diff --git a/CHANGELOG.markdown b/CHANGELOG.markdown
index 4fe70ee312a9377c9fc99add85911b304fc27497..52b3655b4b5bed603b0c8bc55e4cdfa878262c75 100644
--- a/CHANGELOG.markdown
+++ b/CHANGELOG.markdown
@@ -1,3 +1,41 @@
+2.0.0.0-dev42
+=============
+* Application initialization improvements:
+  * Removed application initialization responsibility from `Mage` class
+  * Introduces entry points, which are responsible for different types of requests processing: HTTP, media, cron, indexing, console installing, etc.
+  * New configuration classes are introduced and each of them is responsible for specific section of configuration
+  * Class rewrites functionality removed from `Mage_Core_Model_Config` model. DI configuration should be used for rewriting classes
+* Added ability to configure object manager with array in addition to object and scalar values
+* VDE improvements:
+  * Theme CSS files viewing and uploading/downloading of custom CSS file
+  * Updated styling of VDE Tools panel
+* Refactored various components to an analogous jQuery widget:
+  * Refactored components:
+    * Category navigation
+    * Products management and gallery
+    * Send to friend
+    * Sales components, including orders and returns
+    * Retrieve shipping rates and add/remove coupon in shopping cart
+    * Customer address and address book
+    * Customer wishlist
+    * "Contact Us" form
+    * CAPTCHA
+    * Weee
+  * New tabs widget is used instead of `Varien.Tabs`
+  * Refactored `Varien.dateRangeDate` and `Varien.FileElement`
+  * Replaced `$.mage.constants` with jQuery UI `$.ui.keyCode` for keyboard key codes
+* Refactored configurable attribute, category parent and attribute set selectors to use suggest widget
+* Bug fixes:
+  * Improvements and bug fixes in new backend theme
+  * Image, categories attributes and virtual/downloadable fields are displayed on Update Attributes page, where they shouldn't be present
+  * Undefined config property in `reloadOptionLabels()` function in `configurable.js` (Chrome)
+  * Impossible to edit existing customer/product tax class
+  * Incorrect format of customer's "Date of Birth"
+  * Theme preview images are absent in VDE
+  * Search by backslash doesn't work for Categories field on product creation page
+  * Impossible to assign a category to a product, if category name contains HTML tag
+  * Incorrect URL generated for logo image
+
 2.0.0.0-dev41
 =============
 * All-new look & feel of backend UI -- "Magento 2 backend" theme
diff --git a/app/Mage.php b/app/Mage.php
index 825c050ee57bf87a0b47da71fa8f161da4617265..43bf7ac53d555f420d8f33247528ddf3da41aef8 100644
--- a/app/Mage.php
+++ b/app/Mage.php
@@ -29,17 +29,62 @@
  */
 final class Mage
 {
-    /**#@+
-     * Application initialization options to inject custom request/response objects
-     */
-    const INIT_OPTION_REQUEST  = 'request';
-    const INIT_OPTION_RESPONSE = 'response';
-    /**#@-*/
+    const DEFAULT_ERROR_HANDLER = 'mageCoreErrorHandler';
 
     /**
      * Application initialization option to specify custom product edition label
      */
-    const INIT_OPTION_EDITION = 'edition';
+    const PARAM_EDITION = 'edition';
+
+    /**
+     * Application run code
+     */
+    const PARAM_RUN_CODE = 'MAGE_RUN_CODE';
+
+    /**
+     * Application run type (store|website)
+     */
+    const PARAM_RUN_TYPE = 'MAGE_RUN_TYPE';
+
+    /**
+     * Base directory
+     */
+    const PARAM_BASEDIR = 'base_dir';
+
+    /**
+     * Custom application dirs
+     */
+    const PARAM_APP_DIRS = 'app_dirs';
+
+    /**
+     * Custom application uris
+     */
+    const PARAM_APP_URIS = 'app_uris';
+
+    /**
+     * Allowed modules
+     */
+    const PARAM_ALLOWED_MODULES = 'allowed_modules';
+
+    /**
+     * Caching params
+     */
+    const PARAM_CACHE_OPTIONS = 'cache_options';
+
+    /**
+     * Disallow cache
+     */
+    const PARAM_BAN_CACHE = 'global_ban_use_cache';
+
+    /**
+     * Custom local configuration file name
+     */
+    const PARAM_CUSTOM_LOCAL_FILE = 'custom_local_xml';
+
+    /**
+     * Custom local configuration
+     */
+    const PARAM_CUSTOM_LOCAL_CONFIG = 'custom_local_config';
 
     /**
      * Product edition labels
@@ -77,13 +122,6 @@ final class Mage
      */
     static private $_config;
 
-    /**
-     * Event Collection Object
-     *
-     * @var Varien_Event_Collection
-     */
-    static private $_events;
-
     /**
      * Object manager interface
      *
@@ -148,6 +186,13 @@ final class Mage
      */
     static private $_isSerializable = true;
 
+    /**
+     * Update mode flag
+     *
+     * @var bool
+     */
+    static private $_updateMode = false;
+
     /**
      * Gets the current Magento version string
      * @link http://www.magentocommerce.com/blog/new-community-edition-release-process/
@@ -175,7 +220,7 @@ final class Mage
             'revision'  => '0',
             'patch'     => '0',
             'stability' => 'dev',
-            'number'    => '41',
+            'number'    => '42',
         );
     }
 
@@ -190,6 +235,16 @@ final class Mage
         return self::$_currentEdition;
     }
 
+    /**
+     * Set edition
+     *
+     * @param string $edition
+     */
+    public static function setEdition($edition)
+    {
+        self::$_currentEdition = $edition;
+    }
+
     /**
      * Set all my static data to defaults
      *
@@ -201,7 +256,6 @@ final class Mage
         self::$_appRoot         = null;
         self::$_app             = null;
         self::$_config          = null;
-        self::$_events          = null;
         self::$_objects         = null;
         self::$_isDownloader    = false;
         self::$_isDeveloperMode = false;
@@ -230,6 +284,8 @@ final class Mage
      * @param mixed $value
      * @param bool $graceful
      * @throws Mage_Core_Exception
+     *
+     * @deprecated use Mage_Core_Model_Registry::register
      */
     public static function register($key, $value, $graceful = false)
     {
@@ -246,6 +302,8 @@ final class Mage
      * Unregister a variable from register by key
      *
      * @param string $key
+     *
+     * @deprecated use Mage_Core_Model_Registry::unregister
      */
     public static function unregister($key)
     {
@@ -262,6 +320,8 @@ final class Mage
      *
      * @param string $key
      * @return mixed
+     *
+     * @deprecated use Mage_Core_Model_Registry::registry
      */
     public static function registry($key)
     {
@@ -289,16 +349,6 @@ final class Mage
         return self::$_appRoot;
     }
 
-    /**
-     * Retrieve Events Collection
-     *
-     * @return Varien_Event_Collection $collection
-     */
-    public static function getEvents()
-    {
-        return self::$_events;
-    }
-
     /**
      * Varien Objects Cache
      *
@@ -339,7 +389,7 @@ final class Mage
      */
     public static function getModuleDir($type, $moduleName)
     {
-        return self::getConfig()->getModuleDir($type, $moduleName);
+        return self::getObjectManager()->get('Mage_Core_Model_Config_Modules_Reader')->getModuleDir($type, $moduleName);
     }
 
     /**
@@ -419,36 +469,10 @@ final class Mage
      */
     public static function getConfig()
     {
-        if (self::$_app) {
-            // Usual workflow - act as a proxy, retrieve config from the application
-            return self::$_app->getConfig();
-        } else {
-            // Temp workaround for unit tests only, so there is no urgent need to check and refactor them all
-            if (!self::$_config) {
-                self::$_config = self::getObjectManager()->get('Mage_Core_Model_Config');
-            }
-            return self::$_config;
-        }
-    }
-
-    /**
-     * Add observer to even object
-     *
-     * @param string $eventName
-     * @param callback $callback
-     * @param array $data
-     * @param string $observerName
-     * @param string $observerClass
-     * @return Varien_Event_Collection
-     */
-    public static function addObserver($eventName, $callback, $data = array(), $observerName = '', $observerClass = '')
-    {
-        if ($observerClass == '') {
-            $observerClass = 'Varien_Event_Observer';
+        if (!self::$_config) {
+            self::$_config = self::getObjectManager()->get('Mage_Core_Model_Config');
         }
-        $observer = self::getObjectManager()->create($observerClass);
-        $observer->setName($observerName)->addData($data)->setEventName($eventName)->setCallback($callback);
-        return self::getEvents()->addObserver($observer);
+        return self::$_config;
     }
 
     /**
@@ -459,14 +483,14 @@ final class Mage
      *
      * @param string $name
      * @param array $data
-     * @return Mage_Core_Model_App
+     *
+     * @deprecated use Mage_Core_Model_Event_Manager::dispatch
      */
     public static function dispatchEvent($name, array $data = array())
     {
-        Magento_Profiler::start('EVENT:' . $name, array('group' => 'EVENT', 'name' => $name));
-        $result = self::app()->dispatchEvent($name, $data);
-        Magento_Profiler::stop('EVENT:'.$name);
-        return $result;
+        /** @var $eventManager Mage_Core_Model_Event_Manager */
+        $eventManager = self::$_objectManager->get('Mage_Core_Model_Event_Manager');
+        $eventManager->dispatch($name, $data);
     }
 
     /**
@@ -502,31 +526,27 @@ final class Mage
     }
 
     /**
-     * Initialize object manager with definitions file
+     * Retrieve object manager
      *
      * @static
-     * @param string $definitionsFile
-     * @param Magento_ObjectManager $objectManager
+     * @return Magento_ObjectManager
      */
-    public static function initializeObjectManager(
-        $definitionsFile = null,
-        Magento_ObjectManager $objectManager = null
-    ) {
-        self::$_objectManager = $objectManager ?: new Magento_ObjectManager_Zend($definitionsFile);
+    public static function getObjectManager()
+    {
+        return self::$_objectManager;
     }
 
     /**
-     * Retrieve object manager
-     *
-     * @static
-     * @return Magento_ObjectManager
+     * Set application object manager
+     * @param Magento_ObjectManager $objectManager
      */
-    public static function getObjectManager()
+    public static function setObjectManager(Magento_ObjectManager $objectManager)
     {
         if (!self::$_objectManager) {
-            self::initializeObjectManager();
+            self::$_objectManager = $objectManager;
+        } else {
+            throw new LogicException('Only one object manager can be used in application');
         }
-        return self::$_objectManager;
     }
 
     /**
@@ -587,8 +607,7 @@ final class Mage
 
         $registryKey = '_helper/' . $name;
         if (!self::registry($registryKey)) {
-            $helperClass = self::getConfig()->getHelperClassName($name);
-            self::register($registryKey, self::getObjectManager()->get($helperClass));
+            self::register($registryKey, self::getObjectManager()->get($name));
         }
         return self::registry($registryKey);
     }
@@ -601,7 +620,9 @@ final class Mage
      */
     public static function getResourceHelper($moduleName)
     {
-        $connectionModel = self::getConfig()->getResourceConnectionModel('core');
+        $connectionModel = self::getObjectManager()
+            ->get('Mage_Core_Model_Config_Resource')
+            ->getResourceConnectionModel('core');
 
         $helperClassName = $moduleName . '_Model_Resource_Helper_' . ucfirst($connectionModel);
         $connection = strtolower($moduleName);
@@ -641,99 +662,27 @@ final class Mage
     }
 
     /**
-     * Get initialized application object.
+     * Get application object.
      *
-     * @param array $params
      * @return Mage_Core_Model_App
      */
-    public static function app(array $params = array())
+    public static function app()
     {
         if (null === self::$_app) {
             self::$_app = self::getObjectManager()->get('Mage_Core_Model_App');
-            self::$_events = new Varien_Event_Collection();
-
-            Magento_Profiler::start('self::app::init');
-            self::$_app->init($params);
-            Magento_Profiler::stop('self::app::init');
         }
         return self::$_app;
     }
 
     /**
-     * @static
-     * @param array $params
-     * @param string|array $modules
-     */
-    public static function init(array $params, $modules = array())
-    {
-        try {
-            /** @var $app Mage_Core_Model_App */
-            $app = self::getObjectManager()->create('Mage_Core_Model_App');
-            self::$_app = $app;
-            if (!empty($modules)) {
-                self::$_app->initSpecified($params, $modules);
-            } else {
-                self::$_app->init($params);
-            }
-        } catch (Mage_Core_Model_Session_Exception $e) {
-            header('Location: ' . self::getBaseUrl());
-            die;
-        } catch (Mage_Core_Model_Store_Exception $e) {
-            require_once(self::getBaseDir(Mage_Core_Model_Dir::PUB) . DS . 'errors' . DS . '404.php');
-            die;
-        } catch (Exception $e) {
-            self::printException($e);
-            die;
-        }
-    }
-
-    /**
-     * Front end main entry point
-     *
-     * @param array $params
-     */
-    public static function run(array $params)
-    {
-        try {
-            Magento_Profiler::start('mage');
-            if (isset($params[self::INIT_OPTION_EDITION])) {
-                self::$_currentEdition = $params[self::INIT_OPTION_EDITION];
-            }
-            /** @var $app Mage_Core_Model_App */
-            $app = self::getObjectManager()->create('Mage_Core_Model_App');
-            self::$_app = $app;
-            if (isset($params[self::INIT_OPTION_REQUEST])) {
-                self::$_app->setRequest($params[self::INIT_OPTION_REQUEST]);
-            }
-            if (isset($params[self::INIT_OPTION_RESPONSE])) {
-                self::$_app->setResponse($params[self::INIT_OPTION_RESPONSE]);
-            }
-            self::$_events = new Varien_Event_Collection();
-            self::$_app->run($params);
-            Magento_Profiler::stop('mage');
-        } catch (Mage_Core_Model_Session_Exception $e) {
-            header('Location: ' . self::getBaseUrl());
-        } catch (Mage_Core_Model_Store_Exception $e) {
-            require_once(self::getBaseDir() . '/pub/errors/404.php');
-        } catch (Exception $e) {
-            self::printException($e);
-        }
-    }
-
-    /**
-     * Shortcut for the application "is installed" getter
+     * Check if application is installed
      *
      * @return bool
-     * @throws Magento_Exception
-     *
-     * @todo Remove in favour of Mage_Core_Model_App::isInstalled() as soon as dependencies on application are injected
+     * @deprecated use Mage_Core_Model_App_State::isInstalled()
      */
     public static function isInstalled()
     {
-        if (!self::$_app) {
-            throw new Magento_Exception('Application instance has not been initialized yet.');
-        }
-        return self::$_app->isInstalled();
+       return (bool) self::$_objectManager->get('Mage_Core_Model_Config_Primary')->getInstallDate();
     }
 
     /**
@@ -779,6 +728,8 @@ final class Mage
      *
      * @param bool $mode
      * @return bool
+     *
+     * @deprecated use Mage_Core_Model_App_State::setIsDeveloperMode()
      */
     public static function setIsDeveloperMode($mode)
     {
@@ -790,6 +741,7 @@ final class Mage
      * Retrieve enabled developer mode
      *
      * @return bool
+     * @deprecated use Mage_Core_Model_App_State::isDeveloperMode()
      */
     public static function getIsDeveloperMode()
     {
@@ -898,6 +850,8 @@ final class Mage
      * Set is downloader flag
      *
      * @param bool $flag
+     *
+     * @deprecated use Mage_Core_Model_App_State::setIsDownloader()
      */
     public static function setIsDownloader($flag = true)
     {
@@ -909,6 +863,8 @@ final class Mage
      *
      * @static
      * @param bool $value
+     *
+     * @deprecated use Mage_Core_Model_App_State::setIsSerializable()
      */
     public static function setIsSerializable($value = true)
     {
@@ -920,9 +876,35 @@ final class Mage
      *
      * @static
      * @return bool
+     *
+     * @deprecated use Mage_Core_Model_App_State::getIsSerializable()
      */
     public static function getIsSerializable()
     {
         return self::$_isSerializable;
     }
+
+    /**
+     * Set update mode flag
+     *
+     * @param bool $value
+     *
+     * @deprecated use Mage_Core_Model_App_State::setUpdateMode()
+     */
+    public static function setUpdateMode($value)
+    {
+        self::$_updateMode = $value;
+
+    }
+
+    /**
+     * Get update mode flag
+     * @return bool
+     *
+     * @deprecated use Mage_Core_Model_App_State::setUpdateMode()
+     */
+    public static function getUpdateMode()
+    {
+        return self::$_updateMode;
+    }
 }
diff --git a/app/bootstrap.php b/app/bootstrap.php
index bac5bf5a10db94474c246040d72c85776e8c69a7..d20ee4c1956c84e0236ced3707611fb12a484997 100644
--- a/app/bootstrap.php
+++ b/app/bootstrap.php
@@ -109,8 +109,3 @@ HTML;
         Magento_Profiler::applyConfig($profilerConfig);
     }
 }
-
-$definitionsFile = BP . DS . 'var/di/definitions.php';
-if (file_exists($definitionsFile)) {
-    Mage::initializeObjectManager($definitionsFile);
-}
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/Attributes.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/Attributes.php
index d86749b28a44504467fcb7bdd853571f9812466a..6b1cf55b44b84d6a08e17279fbe4ec1f8de0372c 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/Attributes.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/Attributes.php
@@ -174,8 +174,8 @@ class Mage_Adminhtml_Block_Catalog_Category_Tab_Attributes extends Mage_Adminhtm
     protected function _getAdditionalElementTypes()
     {
         return array(
-            'image' => Mage::getConfig()->getBlockClassName('Mage_Adminhtml_Block_Catalog_Category_Helper_Image'),
-            'textarea' => Mage::getConfig()->getBlockClassName('Mage_Adminhtml_Block_Catalog_Helper_Form_Wysiwyg')
+            'image' => 'Mage_Adminhtml_Block_Catalog_Category_Helper_Image',
+            'textarea' => 'Mage_Adminhtml_Block_Catalog_Helper_Form_Wysiwyg'
         );
     }
 }
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/General.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/General.php
index 889033ea90d8998ecb22c450d19323d0a512dfb0..7b11ecacb792d90a70769816dbf0a3035d8cfc12 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/General.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tab/General.php
@@ -109,9 +109,7 @@ class Mage_Adminhtml_Block_Catalog_Category_Tab_General extends Mage_Adminhtml_B
 
     protected function _getAdditionalElementTypes()
     {
-        return array(
-            'image' => Mage::getConfig()->getBlockClassName('Mage_Adminhtml_Block_Catalog_Category_Helper_Image')
-        );
+        return array('image' => 'Mage_Adminhtml_Block_Catalog_Category_Helper_Image');
     }
 
     protected function _getParentCategoryOptions($node=null, &$options=array())
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tree.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tree.php
index 00cb782c93b322d3fe7a700953f9a40433685a9a..67619d263620db3d03566a55b15b53022892da62 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tree.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Tree.php
@@ -119,7 +119,8 @@ class Mage_Adminhtml_Block_Catalog_Category_Tree extends Mage_Adminhtml_Block_Ca
         $collection = Mage::getModel('Mage_Catalog_Model_Category')->getCollection();
 
         $matchingNamesCollection = clone $collection;
-        $matchingNamesCollection->addAttributeToFilter('name', array('like' => "%{$namePart}%"))
+        $escapedNamePart = Mage::getResourceHelper('Mage_Core')->addLikeEscape($namePart, array('position' => 'any'));
+        $matchingNamesCollection->addAttributeToFilter('name', array('like' => $escapedNamePart))
             ->addAttributeToFilter('entity_id', array('neq' => Mage_Catalog_Model_Category::TREE_ROOT_ID))
             ->addAttributeToSelect('path')
             ->setPageSize((string)Mage::getConfig()->getNode(self::XML_PATH_SUGGESTED_CATEGORIES_LIMIT))
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Edit/Tab/Main.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Edit/Tab/Main.php
index 8945df0ebf13a8df71491466d4fc0a54709e95c2..4fce4c2cdf366d01bff0ddddf8a5d4147a23e7a3 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Edit/Tab/Main.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Edit/Tab/Main.php
@@ -257,8 +257,6 @@ class Mage_Adminhtml_Block_Catalog_Product_Attribute_Edit_Tab_Main extends Mage_
      */
     protected function _getAdditionalElementTypes()
     {
-        return array(
-            'apply' => Mage::getConfig()->getBlockClassName('Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Apply'),
-        );
+        return array('apply' => 'Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Apply');
     }
 }
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/New/Product/Attributes.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/New/Product/Attributes.php
index e1f32c9aa363d5e7cd2a8345dec4bfec121f5c86..93e9298c588ebfd575f59108194e000729a66930 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/New/Product/Attributes.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/New/Product/Attributes.php
@@ -70,12 +70,9 @@ class Mage_Adminhtml_Block_Catalog_Product_Attribute_New_Product_Attributes exte
     protected function _getAdditionalElementTypes()
     {
         $result = array(
-            'price'   => Mage::getConfig()
-                ->getBlockClassName('Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Price'),
-            'image'   => Mage::getConfig()
-                ->getBlockClassName('Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Image'),
-            'boolean' => Mage::getConfig()
-                ->getBlockClassName('Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Boolean')
+            'price'   => 'Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Price',
+            'image'   => 'Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Image',
+            'boolean' => 'Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Boolean',
         );
 
         $response = new Varien_Object();
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit.php
index 1be54193cdc44da39c7526ff541c58020b2dfed8..4b945b28106252a2c57a37b4dd2f0f308d760541 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit.php
@@ -75,18 +75,6 @@ class Mage_Adminhtml_Block_Catalog_Product_Edit extends Mage_Adminhtml_Block_Wid
         }
 
         if (!$this->getProduct()->isReadonly()) {
-            if (!$this->getProduct()->isConfigurable() || !$this->getIsConfigured()) {
-                $this->addChild(
-                    'change_attribute_set_button',
-                    'Mage_Backend_Block_Widget_Button',
-                    array(
-                        'label' => Mage::helper('Mage_Catalog_Helper_Data')->__('Change Attribute Set'),
-                        'onclick' => "jQuery('#attribute-set-info').dialog('open');",
-                        'id' => 'change-attribute-set-button'
-                    )
-                );
-            }
-
             $this->addChild('reset_button', 'Mage_Adminhtml_Block_Widget_Button', array(
                 'label' => Mage::helper('Mage_Catalog_Helper_Data')->__('Reset'),
                 'onclick' => 'setLocation(\'' . $this->getUrl('*/*/*', array('_current' => true)) . '\')'
@@ -131,16 +119,6 @@ class Mage_Adminhtml_Block_Catalog_Product_Edit extends Mage_Adminhtml_Block_Wid
         return $this->getChildHtml('save_button');
     }
 
-    /**
-     * Get Change AttributeSet Button html
-     *
-     * @return string
-     */
-    public function getChangeAttributeSetButtonHtml()
-    {
-        return $this->getChildHtml('change_attribute_set_button');
-    }
-
     public function getSaveAndEditButtonHtml()
     {
         return $this->getChildHtml('save_and_edit_button');
@@ -222,9 +200,6 @@ class Mage_Adminhtml_Block_Catalog_Product_Edit extends Mage_Adminhtml_Block_Wid
         } else {
             $header = Mage::helper('Mage_Catalog_Helper_Data')->__('New Product');
         }
-        if ($setName = $this->getAttributeSetName()) {
-            $header.= ' (' . $setName . ')';
-        }
         return $header;
     }
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Action/Attribute/Tab/Attributes.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Action/Attribute/Tab/Attributes.php
index 0e64b0334367046513b03c87d51d7a83ce37ce3a..44aac052cbb1e9a07d234fe661acd50531a271db 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Action/Attribute/Tab/Attributes.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Action/Attribute/Tab/Attributes.php
@@ -45,13 +45,21 @@ class Mage_Adminhtml_Block_Catalog_Product_Edit_Action_Attribute_Tab_Attributes
     protected function _prepareForm()
     {
         $this->setFormExcludedFieldList(array(
-            'tier_price', 'gallery', 'media_gallery', 'recurring_profile', 'group_price',
-            'quantity_and_stock_status'
+            'category_ids',
+            'gallery',
+            'group_price',
+            'image',
+            'media_gallery',
+            'quantity_and_stock_status',
+            'recurring_profile',
+            'tier_price',
         ));
         Mage::dispatchEvent('adminhtml_catalog_product_form_prepare_excluded_field_list', array('object'=>$this));
 
         $form = new Varien_Data_Form();
-        $fieldset = $form->addFieldset('fields', array('legend'=>Mage::helper('Mage_Catalog_Helper_Data')->__('Attributes')));
+        $fieldset = $form->addFieldset('fields', array(
+            'legend' => Mage::helper('Mage_Catalog_Helper_Data')->__('Attributes'),
+        ));
         $attributes = $this->getAttributes();
         /**
          * Initialize product object as form property
@@ -70,7 +78,8 @@ class Mage_Adminhtml_Block_Catalog_Product_Edit_Action_Attribute_Tab_Attributes
      */
     public function getAttributes()
     {
-        return $this->helper('Mage_Adminhtml_Helper_Catalog_Product_Edit_Action_Attribute')->getAttributes()->getItems();
+        return $this->helper('Mage_Adminhtml_Helper_Catalog_Product_Edit_Action_Attribute')
+            ->getAttributes()->getItems();
     }
 
     /**
@@ -81,15 +90,15 @@ class Mage_Adminhtml_Block_Catalog_Product_Edit_Action_Attribute_Tab_Attributes
     protected function _getAdditionalElementTypes()
     {
         return array(
-            'price' => Mage::getConfig()->getBlockClassName('Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Price'),
-            'weight' => Mage::getConfig()->getBlockClassName('Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Weight'),
-            'image' => Mage::getConfig()->getBlockClassName('Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Image'),
-            'boolean' => Mage::getConfig()->getBlockClassName('Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Boolean')
+            'price' => 'Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Price',
+            'weight' => 'Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Weight',
+            'image' => 'Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Image',
+            'boolean' => 'Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Boolean',
         );
     }
 
     /**
-     * Custom additional elemnt html
+     * Custom additional element html
      *
      * @param Varien_Data_Form_Element_Abstract $element
      * @return string
@@ -97,18 +106,28 @@ class Mage_Adminhtml_Block_Catalog_Product_Edit_Action_Attribute_Tab_Attributes
     protected function _getAdditionalElementHtml($element)
     {
         // Add name attribute to checkboxes that correspond to multiselect elements
-        $nameAttributeHtml = ($element->getExtType() === 'multiple') ? 'name="' . $element->getId() . '_checkbox"'
-            : '';
-        return '<span class="attribute-change-checkbox"><input type="checkbox" id="' . $element->getId()
-             . '-checkbox" ' . $nameAttributeHtml . ' onclick="toogleFieldEditMode(this, \'' . $element->getId()
-             . '\')" /><label for="' . $element->getId() . '-checkbox">' . Mage::helper('Mage_Catalog_Helper_Data')->__('Change')
-             . '</label></span>
-                <script type="text/javascript">initDisableFields(\''.$element->getId().'\')</script>';
+        $nameAttributeHtml = $element->getExtType() === 'multiple' ? 'name="' . $element->getId() . '_checkbox"' : '';
+        $elementId = $element->getId();
+        $checkboxLabel = Mage::helper('Mage_Catalog_Helper_Data')->__('Change');
+        $html = <<<HTML
+<span class="attribute-change-checkbox">
+    <label>
+        <input type="checkbox" $nameAttributeHtml onclick="toogleFieldEditMode(this, '{$elementId}')" />
+        {$checkboxLabel}
+    </label>
+</span>
+<script>initDisableFields("{$elementId}")</script>
+HTML;
+        if ($elementId === 'weight') {
+            $html .= <<<HTML
+<script>jQuery(function($) {
+    $('#weight_and_type_switcher, label[for=weight_and_type_switcher]').hide();
+});</script>
+HTML;
+        }
+        return $html;
     }
 
-    /**
-     * ######################## TAB settings #################################
-     */
     public function getTabLabel()
     {
         return Mage::helper('Mage_Catalog_Helper_Data')->__('Attributes');
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/AttributeSet.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/AttributeSet.php
index 517c73d76d11216bc7418745b8e3fa21b9697a7f..f79a1eb4ab6f403e52ce60c8058678129e7f643a 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/AttributeSet.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/AttributeSet.php
@@ -33,27 +33,22 @@
  */
 class Mage_Adminhtml_Block_Catalog_Product_Edit_AttributeSet extends Mage_Backend_Block_Widget_Form
 {
-    protected function _prepareForm()
-    {
-        $form = new Varien_Data_Form();
-        $fieldset = $form->addFieldset('settings', array());
-
-        $entityType = Mage::registry('product')->getResource()->getEntityType();
 
-        $fieldset->addField('attribute_set_id', 'select', array(
-            'label' => Mage::helper('Mage_Catalog_Helper_Data')->__('Attribute Set'),
-            'title' => Mage::helper('Mage_Catalog_Helper_Data')->__('Attribute Set'),
-            'name'  => 'set',
-            'value' => Mage::registry('product')->getAttributeSetId(),
-            'values'=> Mage::getResourceModel('Mage_Eav_Model_Resource_Entity_Attribute_Set_Collection')
-                ->setEntityTypeFilter($entityType->getId())
-                ->load()
-                ->toOptionArray()
-        ));
-        $fieldset->addField('type_id', 'hidden', array(
-            'name' => 'type_id',
-            'value' => Mage::registry('product')->getTypeId(),
-        ));
-        $this->setForm($form);
+    /**
+     * Get options for suggest widget
+     *
+     * @return array
+     */
+    public function getSelectorOptions()
+    {
+        return array(
+            'source' => $this->getUrl('*/catalog_product/suggestProductTemplates'),
+            'className' => 'category-select',
+            'template' => '#product-template-selector-template',
+            'showRecent' => true,
+            'storageKey' => 'product-template-key',
+            'minLength' => 0,
+            'ajaxData' => array('current_template_id' => Mage::registry('product')->getAttributeSetId()),
+        );
     }
 }
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/NewCategory.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/NewCategory.php
index a7f34206c43beae1d61ac38ee75d02fa87d88792..cffde3ac48c01431c54371f4230f34e3c6d0bf1b 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/NewCategory.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/NewCategory.php
@@ -50,36 +50,46 @@ class Mage_Adminhtml_Block_Catalog_Product_Edit_NewCategory extends Mage_Backend
             'required' => true,
         ));
 
-        $fieldset->addField('new_category_parent', 'text', array(
-            'label'        => Mage::helper('Mage_Catalog_Helper_Data')->__('Parent Category'),
-            'title'        => Mage::helper('Mage_Catalog_Helper_Data')->__('Parent Category'),
-            'autocomplete' => 'off',
-            'required'     => true,
-            'class'        => 'validate-parent-category',
+        $fieldset->addField('new_category_parent', 'select', array(
+            'label'    => Mage::helper('Mage_Catalog_Helper_Data')->__('Parent Category'),
+            'title'    => Mage::helper('Mage_Catalog_Helper_Data')->__('Parent Category'),
+            'required' => true,
+            'options'  => array(),
+            'class'    => 'validate-parent-category',
         ));
 
-        $fieldset->addField('new_category_parent_id', 'hidden', array());
-
         $this->setForm($form);
     }
 
     /**
-     * Category save action URL
-     *
-     * @return string
-     */
-    public function getSaveCategoryUrl()
-    {
-        return $this->getUrl('*/catalog_category/save');
-    }
-
-    /**
-     * Category suggestion action URL
+     * Attach new category dialog widget initialization
      *
      * @return string
      */
-    public function getSuggestCategoryUrl()
+    public function getAfterElementHtml()
     {
-        return $this->getUrl('*/catalog_category/suggestCategories');
+        /** @var $coreHelper Mage_Core_Helper_Data */
+        $coreHelper = Mage::helper('Mage_Core_Helper_Data');
+        $widgetUrl = $coreHelper->jsonEncode($this->getViewFileUrl('Mage_Catalog::js/new-category-dialog.js'));
+        $widgetOptions = $coreHelper->jsonEncode(array(
+            'suggestOptions' => array(
+                'source' => $this->getUrl('*/catalog_category/suggestCategories'),
+                'valueField' => '#new_category_parent',
+                'template' => '#category_ids-template',
+                'control' => 'jstree',
+                'multiselect' => true,
+                'className' => 'category-select',
+            ),
+            'saveCategoryUrl' => $this->getUrl('*/catalog_category/save'),
+        ));
+        return <<<HTML
+<script>
+    head.js($widgetUrl, function () {
+        jQuery(function($) { // waiting for page to load to have '#category_ids-template' available
+            $('#new-category').mage('newCategoryDialog', $widgetOptions);
+        });
+    });
+</script>
+HTML;
     }
 }
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Attributes.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Attributes.php
index 98097ed1090dafd2e140b5502ebde87e5a2f556d..236ebaf9d3fcdbae938c90110209e7932fb66f17 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Attributes.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Attributes.php
@@ -115,10 +115,6 @@ class Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Attributes extends Mage_Admi
                 $fieldset->setHeaderBar($headerBar->toHtml());
             }
 
-            if ($form->getElement('meta_description')) {
-                $form->getElement('meta_description')->setOnkeyup('checkMaxLength(this, 255);');
-            }
-
             $values = $product->getData();
 
             // Set default attribute values for new product or on attribute set change
@@ -155,23 +151,12 @@ class Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Attributes extends Mage_Admi
     protected function _getAdditionalElementTypes()
     {
         $result = array(
-            'price'    => Mage::getConfig()->getBlockClassName(
-                'Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Price'
-            ),
-            'weight'   => Mage::getConfig()->getBlockClassName(
-                'Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Weight'
-            ),
-            'gallery'  => Mage::getConfig()->getBlockClassName(
-                'Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Gallery'
-            ),
-            'image'    => Mage::getConfig()->getBlockClassName(
-                'Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Image'
-            ),
-            'boolean'  => Mage::getConfig()->getBlockClassName(
-                'Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Boolean'),
-            'textarea' => Mage::getConfig()->getBlockClassName(
-                'Mage_Adminhtml_Block_Catalog_Helper_Form_Wysiwyg'
-            )
+            'price'    => 'Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Price',
+            'weight'   => 'Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Weight',
+            'gallery'  => 'Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Gallery',
+            'image'    => 'Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Image',
+            'boolean'  => 'Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Boolean',
+            'textarea' => 'Mage_Adminhtml_Block_Catalog_Helper_Form_Wysiwyg',
         );
 
         $response = new Varien_Object();
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Settings.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Settings.php
index 4e837aa6c0c64cbc1421712db5c55144d396d7d4..410c1f64eb0b18f26b889d218e93aee8d5d30473 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Settings.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Settings.php
@@ -73,7 +73,7 @@ class Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Super_Settings extends Mage_
             'legend' => Mage::helper('Mage_Catalog_Helper_Data')->__('Select Configurable Attributes')
         ));
 
-        $fieldset->addField('attribute-selector', 'text', array(
+        $fieldset->addField('configurable-attribute-selector', 'text', array(
             'label' => 'Select Attribute',
             'title' => 'Select Attribute',
         ));
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Grid.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Grid.php
index 6053b8b782811940da6b3c8ebc40e831e08af4e2..a9041152ac7914cc87ddcd2fcd4281a94a4375d1 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Grid.php
@@ -71,7 +71,7 @@ class Mage_Adminhtml_Block_Catalog_Product_Grid extends Mage_Adminhtml_Block_Wid
         }
         if ($store->getId()) {
             //$collection->setStoreId($store->getId());
-            $adminStore = Mage_Core_Model_App::ADMIN_STORE_ID;
+            $adminStore = Mage_Core_Model_AppInterface::ADMIN_STORE_ID;
             $collection->addStoreFilter($store);
             $collection->joinAttribute(
                 'name',
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/BaseImage.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/BaseImage.php
index edb316cbd43db15d5f3acfabed261000de19b261..a9f3d8ee9235a9b3ac2b801a0285346b185bed4d 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/BaseImage.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/BaseImage.php
@@ -33,20 +33,6 @@
  */
 class Mage_Adminhtml_Block_Catalog_Product_Helper_Form_BaseImage extends Varien_Data_Form_Element_Abstract
 {
-    /**
-     * Maximum file size to upload in bytes.
-     *
-     * @var int
-     */
-    protected $_maxFileSize;
-
-    /**
-     * Media Uploader instance
-     *
-     * @var Mage_Adminhtml_Block_Media_Uploader
-     */
-    protected $_mediaUploader;
-
     /**
      * Model Url instance
      *
@@ -64,6 +50,11 @@ class Mage_Adminhtml_Block_Catalog_Product_Helper_Form_BaseImage extends Varien_
      */
     protected $_catalogHelperData;
 
+    /**
+     * @var Magento_File_Size
+     */
+    protected $_fileConfig;
+
     /**
      * Constructor
      *
@@ -73,28 +64,34 @@ class Mage_Adminhtml_Block_Catalog_Product_Helper_Form_BaseImage extends Varien_
     {
         parent::__construct($attributes);
 
-        $this->_mediaUploader = isset($attributes['mediaUploader']) ? $attributes['mediaUploader']
-            : Mage::getSingleton('Mage_Adminhtml_Block_Media_Uploader');
         $this->_url = isset($attributes['url']) ? $attributes['url']
             : Mage::getModel('Mage_Backend_Model_Url');
         $this->_coreHelper = isset($attributes['coreHelper']) ? $attributes['coreHelper']
             : Mage::helper('Mage_Core_Helper_Data');
         $this->_catalogHelperData = isset($attributes['catalogHelperData']) ? $attributes['catalogHelperData']
             : Mage::helper('Mage_Catalog_Helper_Data');
-
+        $this->_fileConfig = isset($attributes['fileConfig']) ? $attributes['fileConfig'] :
+            Mage::getSingleton('Magento_File_Size');
         $this->_maxFileSize = $this->_getFileMaxSize();
     }
 
-    public function getDefaultHtml()
+    /**
+     * Get label
+     *
+     * @return string
+     */
+    public function getLabel()
     {
-        $html = $this->getData('default_html');
-        if (is_null($html)) {
-            $html = ($this->getNoSpan() === true) ? '' : '<span class="field-row">' . "\n";
-            $html .= $this->getLabelHtml();
-            $html .= $this->getElementHtml();
-            $html .= ($this->getNoSpan() === true) ? '' : '</span>' . "\n";
-        }
-        return $html;
+        return $this->helper('Mage_Catalog_Helper_Data')->__('Images');
+    }
+
+    /**
+     * Translate message
+     *
+     * @param string $message
+     */
+    private function __($message) {
+        return $this->helper('Mage_Catalog_Helper_Data')->__($message);
     }
 
     /**
@@ -107,51 +104,34 @@ class Mage_Adminhtml_Block_Catalog_Product_Helper_Form_BaseImage extends Varien_
         $htmlId = $this->_coreHelper->escapeHtml($this->getHtmlId());
         $uploadUrl = $this->_coreHelper->escapeHtml($this->_getUploadUrl());
         /** @var $product Mage_Catalog_Model_Product */
-        $product = $this->getForm()->getDataObject();
-        $gallery = $product->getMediaGalleryImages();
-        $html = '<input id="' . $htmlId .'-upload" type="file" name="image" '
-            . 'data-url="' . $uploadUrl . '" style="display:none" />'
-            . '<input id="' . $htmlId . '" type="hidden" name="'. $this->getName() .'" />'
-            . '<div id="' . $htmlId  . '-container" class="images" data-main="' .  $this->getEscapedValue() . '" '
-            . 'data-images="' . $this->_coreHelper->escapeHtml(
-            $this->_coreHelper->jsonEncode($gallery ? $gallery->toArray() : array())
-        ) . '">'
-            . '<div class="image image-placeholder" id="' . $htmlId . '-upload-placeholder"><p class="image-placeholder-text">' . $this->helper('Mage_Catalog_Helper_Data')->__('Click here or drag and drop to add images') . '</p></div>'
-            . '<script id="' . $htmlId . '-template" type="text/x-jquery-tmpl">'
-            . '<div class="image" data-image-label="' . $this->helper('Mage_Catalog_Helper_Data')->__('Main') . '">'
-                . '<img class="base-image-uploader" src="${url}" data-position="${position}" alt="${label}" />'
-                . '<div class="actions">'
-                    . '<button class="action-delete" title="' . $this->helper('Mage_Catalog_Helper_Data')->__('Delete image') . '">'
-                        . '<span>' . $this->helper('Mage_Catalog_Helper_Data')->__('Delete image') . '</span>'
-                    . '</button>'
-                    . '<button class="action-make-main" title="' . $this->helper('Mage_Catalog_Helper_Data')->__('Make Main') . '">'
-                        . '<span>' . $this->helper('Mage_Catalog_Helper_Data')->__('Make Main') . '</span>'
-                    . '</button>'
-                    . '<div class="draggable-handle"></div>'
-                . '</div>'
-            . '</div>'
-            . '</script>'
-            . '</div>';
-        $html .= $this->_getJs();
-
+        $html = <<<HTML
+<div id="{$htmlId}-container" class="images"
+    data-mage-init="{baseImage:{}}"
+    data-max-file-size="{$this->_getFileMaxSize()}"
+    >
+    <div class="image image-placeholder">
+        <input type="file" name="image"  data-url="{$uploadUrl}"  />
+        <p class="image-placeholder-text">{$this->__('Click here or drag and drop to add images')}</p>
+    </div>
+    <script id="{$htmlId}-template" class="image-template" type="text/x-jquery-tmpl">
+        <div class="image" data-image-label="{$this->__('Main')}">
+            <img class="base-image-uploader" src="\${url}" data-position="\${position}" alt="\${label}" />
+            <div class="actions">
+                <button class="action-delete" data-role="delete-button" title="{$this->__('Delete image')}">
+                    <span>{$this->__('Delete image')}</span>
+                </button>
+                <button class="action-make-main" data-role="make-main-button" title="{$this->__('Make Main')}">
+                    <span>{$this->__('Make Main')}</span>
+                </button>
+                <div class="draggable-handle"></div>
+            </div>
+        </div>
+    </script>
+</div>
+HTML;
         return $html;
     }
 
-    /**
-     * Get js for image uploader
-     *
-     * @return string
-     */
-    protected function _getJs()
-    {
-        return "<script>/* <![CDATA[ */"
-            . "jQuery(function(){"
-            . "BaseImageUploader({$this->_coreHelper->jsonEncode($this->getHtmlId())}, "
-            . "{$this->_coreHelper->jsonEncode($this->_maxFileSize)});"
-            . " });"
-            . "/*]]>*/</script>";
-    }
-
     /**
      * Get url to upload files
      *
@@ -169,7 +149,7 @@ class Mage_Adminhtml_Block_Catalog_Product_Helper_Form_BaseImage extends Varien_
      */
     protected function _getFileMaxSize()
     {
-        return $this->_mediaUploader->getDataMaxSizeInBytes();
+        return $this->_fileConfig->getMaxFileSize();
     }
 
     /**
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Category.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Category.php
index 16c2065e0d160421238a026ccbc7b8249f390745..38968a24a1d36cc49c962e35f708900dfce809f3 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Category.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Category.php
@@ -68,11 +68,11 @@ class Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Category extends Varien_D
     }
 
     /**
-     * Get html of element
+     * Attach category suggest widget initialization
      *
      * @return string
      */
-    public function getElementHtml()
+    public function getAfterElementHtml()
     {
         /** @var $coreHelper Mage_Core_Helper_Data */
         $coreHelper = Mage::helper('Mage_Core_Helper_Data');
@@ -87,35 +87,50 @@ class Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Category extends Varien_D
             )
         )));
 
-        return parent::getElementHtml() . "\n"
-            . '<input id="' . $this->getHtmlId() . '-suggest" />' . "\n"
-            . '<script id="' . $this->getHtmlId() . '-template" type="text/x-jquery-tmpl">'
-            . '{{if $data.allShown()}}'
-                . '{{if typeof nested === "undefined"}}'
-                . '<div style="display:none;" data-mage-init="' . $treeOptions . '">{{/if}}'
-                . '<ul>{{each items}}'
-                . '<li><a href="#" {{html optionData($value)}}>${$value.label}</a>'
-                . '{{if $value.children && $value.children.length}}'
-                . '{{html renderTreeLevel($value.children)}}'
-                . '{{/if}}'
-                . '</li>{{/each}}</ul>'
-                . '{{if typeof nested === "undefined"}}</div>{{/if}}'
-            . '{{else}}'
-                . '<ul data-mage-init="{&quot;menu&quot;:[]}">'
-                . '{{each items}}'
-                . '<li {{html optionData($value)}}><a href="#"><span class="category-label">${$value.label}<span>'
-                . '<span class="category-path">${$value.path}<span></a></li>'
-                . '{{/each}}</ul>'
-            . '{{/if}}'
-            . '</script>' . "\n"
-            . '<script>//<![CDATA[' . "\n"
-            . 'jQuery(' . $coreHelper->jsonEncode('#' . $this->getHtmlId() . '-suggest') . ').treeSuggest('
-            . $coreHelper->jsonEncode($this->_getSelectorOptions()) . ');' . "\n"
-            . '//]]></script>'
-            . '<button title="' . $coreHelper->__('New Category') . '" type="button"'
-            . ' onclick="jQuery(\'#new-category\').dialog(\'open\')">'
-            . '<span><span><span>' . $coreHelper->__('New Category') . '</span></span></span>'
-            . '</button>';
+        $htmlId = $this->getHtmlId();
+        $suggestPlaceholder = Mage::helper('Mage_Catalog_Helper_Data')->__('start typing to search category');
+        $selectorOptions = $coreHelper->jsonEncode($this->_getSelectorOptions());
+        $newCategoryCaption = Mage::helper('Mage_Catalog_Helper_Data')->__('New Category');
+
+        return <<<HTML
+    <input id="{$htmlId}-suggest" placeholder="$suggestPlaceholder" />
+    <script id="{$htmlId}-template" type="text/x-jquery-tmpl">
+        {{if \$data.allShown()}}
+            {{if typeof nested === "undefined"}}
+                <div style="display:none" data-mage-init="{$treeOptions}">
+            {{/if}}
+            <ul>
+            {{each items}}
+                <li><a href="#" {{html optionData(\$value)}}>\${\$value.label}</a>
+                    {{if \$value.children && \$value.children.length}}
+                        {{html renderTreeLevel(\$value.children)}}
+                    {{/if}}
+                </li>
+            {{/each}}
+            </ul>
+            {{if typeof nested === "undefined"}}
+                </div>
+            {{/if}}
+        {{else}}
+            <ul data-mage-init="{menu:[]}">
+            {{each items}}
+                <li {{html optionData(\$value)}}>
+                    <a href="#">
+                        <span class="category-label">\${\$value.label}</span>
+                        <span class="category-path">\${\$value.path}</span>
+                    </a>
+                </li>
+            {{/each}}
+            </ul>
+        {{/if}}
+    </script>
+    <script>
+        jQuery('#{$htmlId}-suggest').treeSuggest({$selectorOptions});
+    </script>
+    <button title="{$newCategoryCaption}" type="button" onclick="jQuery('#new-category').dialog('open')">
+        <span><span><span>{$newCategoryCaption}</span></span></span>
+    </button>
+HTML;
     }
 
     /**
@@ -126,8 +141,7 @@ class Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Category extends Varien_D
     protected function _getSelectorOptions()
     {
         return array(
-            'source' => Mage::helper('Mage_Backend_Helper_Data')
-                ->getUrl('adminhtml/catalog_category/suggestCategories'),
+            'source' => Mage::helper('Mage_Backend_Helper_Data')->getUrl('*/catalog_category/suggestCategories'),
             'valueField' => '#' . $this->getHtmlId(),
             'template' => '#' . $this->getHtmlId() . '-template',
             'control' => 'jstree',
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Gallery/Content.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Gallery/Content.php
index a5cfe26778744c396d974582f67be32a14247b8d..de1d711625640297e8fa1a4f43d89ec037f6b42a 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Gallery/Content.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Gallery/Content.php
@@ -31,6 +31,8 @@
  * @category   Mage
  * @package    Mage_Adminhtml
  * @author      Magento Core Team <core@magentocommerce.com>
+ *
+ * @method Varien_Data_Form_Element_Abstract getElement()
  */
 class Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Gallery_Content extends Mage_Adminhtml_Block_Widget
 {
@@ -59,6 +61,7 @@ class Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Gallery_Content extends M
         return parent::_prepareLayout();
     }
 
+
     /**
      * Retrive uploader block
      *
@@ -122,7 +125,7 @@ class Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Gallery_Content extends M
     }
 
     /**
-     * Enter description here...
+     * Get image types data
      *
      * @return array
      */
@@ -132,9 +135,11 @@ class Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Gallery_Content extends M
         foreach ($this->getMediaAttributes() as $attribute) {
             /* @var $attribute Mage_Eav_Model_Entity_Attribute */
             $imageTypes[$attribute->getAttributeCode()] = array(
-                'label' => $attribute->getFrontend()->getLabel() . ' '
-                         . Mage::helper('Mage_Catalog_Helper_Data')->__($this->getElement()->getScopeLabel($attribute)),
-                'field' => $this->getElement()->getAttributeFieldName($attribute)
+                'code' => $attribute->getAttributeCode(),
+                'value' => $this->getElement()->getDataObject()->getData($attribute->getAttributeCode()),
+                'label' => $attribute->getFrontend()->getLabel(),
+                'scope' => Mage::helper('Mage_Catalog_Helper_Data')->__($this->getElement()->getScopeLabel($attribute)),
+                'name' => $this->getElement()->getAttributeFieldName($attribute)
             );
         }
         return $imageTypes;
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Account.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Account.php
index 0f177639744e52945f2ef47bf752d59405a79d33..e7d1dc2e46dff798581107faaab089e1fc43f1a3 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Account.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Account.php
@@ -126,9 +126,9 @@ class Mage_Adminhtml_Block_Customer_Edit_Tab_Account extends Mage_Adminhtml_Bloc
     protected function _getAdditionalElementTypes()
     {
         return array(
-            'file'      => Mage::getConfig()->getBlockClassName('Mage_Adminhtml_Block_Customer_Form_Element_File'),
-            'image'     => Mage::getConfig()->getBlockClassName('Mage_Adminhtml_Block_Customer_Form_Element_Image'),
-            'boolean'   => Mage::getConfig()->getBlockClassName('Mage_Adminhtml_Block_Customer_Form_Element_Boolean'),
+            'file'      => 'Mage_Adminhtml_Block_Customer_Form_Element_File',
+            'image'     => 'Mage_Adminhtml_Block_Customer_Form_Element_Image',
+            'boolean'   => 'Mage_Adminhtml_Block_Customer_Form_Element_Boolean',
         );
     }
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Addresses.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Addresses.php
index 3dbcc6d261fd8d9e9205ac039992302fb2cae68b..0ef4dc464d45d43daaa20f9c283ec01f988db5f9 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Addresses.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Addresses.php
@@ -211,9 +211,9 @@ class Mage_Adminhtml_Block_Customer_Edit_Tab_Addresses extends Mage_Adminhtml_Bl
     protected function _getAdditionalElementTypes()
     {
         return array(
-            'file'      => Mage::getConfig()->getBlockClassName('Mage_Adminhtml_Block_Customer_Form_Element_File'),
-            'image'     => Mage::getConfig()->getBlockClassName('Mage_Adminhtml_Block_Customer_Form_Element_Image'),
-            'boolean'   => Mage::getConfig()->getBlockClassName('Mage_Adminhtml_Block_Customer_Form_Element_Boolean'),
+            'file'      => 'Mage_Adminhtml_Block_Customer_Form_Element_File',
+            'image'     => 'Mage_Adminhtml_Block_Customer_Form_Element_Image',
+            'boolean'   => 'Mage_Adminhtml_Block_Customer_Form_Element_Boolean',
         );
     }
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Product/Viewed.php b/app/code/core/Mage/Adminhtml/Block/Report/Product/Viewed.php
index a33d13886225e350231fff4070582d7ccaca4204..d6a72cfbb227fdd41d699da1c0e92b3521d5a82e 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Product/Viewed.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Product/Viewed.php
@@ -45,7 +45,8 @@ class Mage_Adminhtml_Block_Report_Product_Viewed extends Mage_Adminhtml_Block_Wi
         $this->_removeButton('add');
         $this->addButton('filter_form_submit', array(
             'label'     => Mage::helper('Mage_Reports_Helper_Data')->__('Show Report'),
-            'onclick'   => 'filterFormSubmit()'
+            'onclick'   => 'filterFormSubmit()',
+            'class'     => 'primary'
         ));
     }
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Sales/Bestsellers.php b/app/code/core/Mage/Adminhtml/Block/Report/Sales/Bestsellers.php
index 44483c5d083f5f5aac207ef379bbb11f2cda66a7..4fb9b4deb5c7e9d02bf95e54319f24cc79129122 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Sales/Bestsellers.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Sales/Bestsellers.php
@@ -45,7 +45,8 @@ class Mage_Adminhtml_Block_Report_Sales_Bestsellers extends Mage_Adminhtml_Block
         $this->_removeButton('add');
         $this->addButton('filter_form_submit', array(
             'label'     => Mage::helper('Mage_Reports_Helper_Data')->__('Show Report'),
-            'onclick'   => 'filterFormSubmit()'
+            'onclick'   => 'filterFormSubmit()',
+            'class'     => 'primary'
         ));
     }
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Sales/Coupons.php b/app/code/core/Mage/Adminhtml/Block/Report/Sales/Coupons.php
index 51d35cdac910a7716d171ffecb97633387b09b57..3ede6b458d7ef71659a3d2d0682855ecbca4fa1d 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Sales/Coupons.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Sales/Coupons.php
@@ -45,7 +45,8 @@ class Mage_Adminhtml_Block_Report_Sales_Coupons extends Mage_Adminhtml_Block_Wid
         $this->_removeButton('add');
         $this->addButton('filter_form_submit', array(
             'label'     => Mage::helper('Mage_Reports_Helper_Data')->__('Show Report'),
-            'onclick'   => 'filterFormSubmit()'
+            'onclick'   => 'filterFormSubmit()',
+            'class'     => 'primary'
         ));
     }
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Sales/Invoiced.php b/app/code/core/Mage/Adminhtml/Block/Report/Sales/Invoiced.php
index 24e0f87dafdbb44ea2e8ebe8d378afbde27753bb..c9d3ac55441af68389816a7767de4ce346bd11c4 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Sales/Invoiced.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Sales/Invoiced.php
@@ -45,7 +45,8 @@ class Mage_Adminhtml_Block_Report_Sales_Invoiced extends Mage_Adminhtml_Block_Wi
         $this->_removeButton('add');
         $this->addButton('filter_form_submit', array(
             'label'     => Mage::helper('Mage_Reports_Helper_Data')->__('Show Report'),
-            'onclick'   => 'filterFormSubmit()'
+            'onclick'   => 'filterFormSubmit()',
+            'class'     => 'primary'
         ));
     }
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Sales/Refunded.php b/app/code/core/Mage/Adminhtml/Block/Report/Sales/Refunded.php
index 7d461db86a3dbf661331982592320cd68e6d865e..9abef5bd676d9af61324507141ad54b1aecc4447 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Sales/Refunded.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Sales/Refunded.php
@@ -45,7 +45,8 @@ class Mage_Adminhtml_Block_Report_Sales_Refunded extends Mage_Adminhtml_Block_Wi
         $this->_removeButton('add');
         $this->addButton('filter_form_submit', array(
             'label'     => Mage::helper('Mage_Reports_Helper_Data')->__('Show Report'),
-            'onclick'   => 'filterFormSubmit()'
+            'onclick'   => 'filterFormSubmit()',
+            'class'     => 'primary'
         ));
     }
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Sales/Sales.php b/app/code/core/Mage/Adminhtml/Block/Report/Sales/Sales.php
index 1987379dc22a0cb0f5dc330be143ea4841d93b9c..b770a3303ddd3d1c264188a65cb17ef859459348 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Sales/Sales.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Sales/Sales.php
@@ -45,7 +45,8 @@ class Mage_Adminhtml_Block_Report_Sales_Sales extends Mage_Adminhtml_Block_Widge
         $this->_removeButton('add');
         $this->addButton('filter_form_submit', array(
             'label'     => Mage::helper('Mage_Reports_Helper_Data')->__('Show Report'),
-            'onclick'   => 'filterFormSubmit()'
+            'onclick'   => 'filterFormSubmit()',
+            'class'     => 'primary'
         ));
     }
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Sales/Shipping.php b/app/code/core/Mage/Adminhtml/Block/Report/Sales/Shipping.php
index 20ee739781c619cd879284906ef0ba8673efa1d2..bd53cde1b5f240eb99d6e0cc50a5cb8c43acf122 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Sales/Shipping.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Sales/Shipping.php
@@ -46,7 +46,8 @@ class Mage_Adminhtml_Block_Report_Sales_Shipping extends Mage_Adminhtml_Block_Wi
         $this->_removeButton('add');
         $this->addButton('filter_form_submit', array(
             'label'     => Mage::helper('Mage_Reports_Helper_Data')->__('Show Report'),
-            'onclick'   => 'filterFormSubmit()'
+            'onclick'   => 'filterFormSubmit()',
+            'class'     => 'primary'
         ));
     }
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Sales/Tax.php b/app/code/core/Mage/Adminhtml/Block/Report/Sales/Tax.php
index 78b089742dda3710efc0ab343faf3c4da68145b4..a0df7ff0b3ab096c74c4c4a52627541662f5b0e3 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Sales/Tax.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Sales/Tax.php
@@ -46,7 +46,8 @@ class Mage_Adminhtml_Block_Report_Sales_Tax extends Mage_Adminhtml_Block_Widget_
         $this->_removeButton('add');
         $this->addButton('filter_form_submit', array(
             'label'     => Mage::helper('Mage_Reports_Helper_Data')->__('Show Report'),
-            'onclick'   => 'filterFormSubmit()'
+            'onclick'   => 'filterFormSubmit()',
+            'class'     => 'primary'
         ));
     }
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Review/Grid/Renderer/Type.php b/app/code/core/Mage/Adminhtml/Block/Review/Grid/Renderer/Type.php
index 4f6889e57b10f2f01eac60efa3c179b8f9c4af5a..c7ccbb0613627f2d9d5bbc08e4b0568b3695a292 100644
--- a/app/code/core/Mage/Adminhtml/Block/Review/Grid/Renderer/Type.php
+++ b/app/code/core/Mage/Adminhtml/Block/Review/Grid/Renderer/Type.php
@@ -38,7 +38,7 @@ class Mage_Adminhtml_Block_Review_Grid_Renderer_Type extends Mage_Adminhtml_Bloc
     {
 
         if (is_null($row->getCustomerId())) {
-            if ($row->getStoreId() == Mage_Core_Model_App::ADMIN_STORE_ID) {
+            if ($row->getStoreId() == Mage_Core_Model_AppInterface::ADMIN_STORE_ID) {
                 return Mage::helper('Mage_Review_Helper_Data')->__('Administrator');
             } else {
                 return Mage::helper('Mage_Review_Helper_Data')->__('Guest');
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Abstract.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Abstract.php
index 18d9f5b542bcec9a0083dd43562e6bcb3ab9c7a1..08be4de6ceb10571a0581d2da6c053794cd30995 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Abstract.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Abstract.php
@@ -104,9 +104,9 @@ abstract class Mage_Adminhtml_Block_Sales_Order_Create_Form_Abstract
     protected function _getAdditionalFormElementTypes()
     {
         return array(
-            'file'      => Mage::getConfig()->getBlockClassName('Mage_Adminhtml_Block_Customer_Form_Element_File'),
-            'image'     => Mage::getConfig()->getBlockClassName('Mage_Adminhtml_Block_Customer_Form_Element_Image'),
-            'boolean'   => Mage::getConfig()->getBlockClassName('Mage_Adminhtml_Block_Customer_Form_Element_Boolean'),
+            'file'      => 'Mage_Adminhtml_Block_Customer_Form_Element_File',
+            'image'     => 'Mage_Adminhtml_Block_Customer_Form_Element_Image',
+            'boolean'   => 'Mage_Adminhtml_Block_Customer_Form_Element_Boolean',
         );
     }
 
diff --git a/app/code/core/Mage/Adminhtml/Controller/Action.php b/app/code/core/Mage/Adminhtml/Controller/Action.php
index 8a7c8dc94c8442dd68e466ff77fb689a2da6ac74..6a12d22cf47663f896a1411555a21e8c9cff3347 100644
--- a/app/code/core/Mage/Adminhtml/Controller/Action.php
+++ b/app/code/core/Mage/Adminhtml/Controller/Action.php
@@ -49,22 +49,22 @@ class Mage_Adminhtml_Controller_Action extends Mage_Backend_Controller_ActionAbs
     /**
      * @param Mage_Core_Controller_Request_Http $request
      * @param Mage_Core_Controller_Response_Http $response
-     * @param string $areaCode
      * @param Magento_ObjectManager $objectManager
      * @param Mage_Core_Controller_Varien_Front $frontController
      * @param Mage_Core_Model_Layout_Factory $layoutFactory
+     * @param string $areaCode
      * @param array $invokeArgs
      */
     public function __construct(
         Mage_Core_Controller_Request_Http $request,
         Mage_Core_Controller_Response_Http $response,
-        $areaCode = null,
         Magento_ObjectManager $objectManager,
         Mage_Core_Controller_Varien_Front $frontController,
         Mage_Core_Model_Layout_Factory $layoutFactory,
+        $areaCode = null,
         array $invokeArgs = array()
     ) {
-        parent::__construct($request, $response, $areaCode, $objectManager, $frontController, $layoutFactory,
+        parent::__construct($request, $response, $objectManager, $frontController, $layoutFactory, $areaCode,
             $invokeArgs
         );
 
@@ -92,7 +92,7 @@ class Mage_Adminhtml_Controller_Action extends Mage_Backend_Controller_ActionAbs
     protected function _getTranslator()
     {
         if (null === $this->_translator) {
-            $this->_translator = Mage::app()->getTranslator();
+            $this->_translator = $this->_objectManager->get('Mage_Core_Model_Translate');
         }
         return $this->_translator;
     }
diff --git a/app/code/core/Mage/Adminhtml/Helper/Catalog/Product/Edit/Action/Attribute.php b/app/code/core/Mage/Adminhtml/Helper/Catalog/Product/Edit/Action/Attribute.php
index 9ceab88e196989b8512d520fa166b6f43ee68c58..02ab9d87beed538334af0f5f4c2bcfc7a02f277b 100644
--- a/app/code/core/Mage/Adminhtml/Helper/Catalog/Product/Edit/Action/Attribute.php
+++ b/app/code/core/Mage/Adminhtml/Helper/Catalog/Product/Edit/Action/Attribute.php
@@ -101,7 +101,7 @@ class Mage_Adminhtml_Helper_Catalog_Product_Edit_Action_Attribute extends Mage_B
      */
     public function getSelectedStoreId()
     {
-        return (int)$this->_getRequest()->getParam('store', Mage_Core_Model_App::ADMIN_STORE_ID);
+        return (int)$this->_getRequest()->getParam('store', Mage_Core_Model_AppInterface::ADMIN_STORE_ID);
     }
 
     /**
diff --git a/app/code/core/Mage/Adminhtml/Helper/Dashboard/Data.php b/app/code/core/Mage/Adminhtml/Helper/Dashboard/Data.php
index bf9e7bee9d98071e6f9851a5f949a8e7f96304b9..1f80e4284cac47c746e65b38cc37a79ec50b976d 100644
--- a/app/code/core/Mage/Adminhtml/Helper/Dashboard/Data.php
+++ b/app/code/core/Mage/Adminhtml/Helper/Dashboard/Data.php
@@ -86,7 +86,7 @@ class Mage_Adminhtml_Helper_Dashboard_Data extends Mage_Core_Helper_Data
      */
     public function getChartDataHash($data)
     {
-        $secret = (string)Mage::getConfig()->getNode(Mage_Core_Model_App::XML_PATH_INSTALL_DATE);
+        $secret = (string)Mage::getConfig()->getNode(Mage_Core_Model_Config_Primary::XML_PATH_INSTALL_DATE);
         return md5($data . $secret);
     }
 }
diff --git a/app/code/core/Mage/Adminhtml/Helper/Media/Js.php b/app/code/core/Mage/Adminhtml/Helper/Media/Js.php
index e96501876b9a616cfae4d972990255c9c8bf5733..9c522520ef3d22391dbeedf9de8a0fda571a2e06 100644
--- a/app/code/core/Mage/Adminhtml/Helper/Media/Js.php
+++ b/app/code/core/Mage/Adminhtml/Helper/Media/Js.php
@@ -35,16 +35,23 @@
  */
 class Mage_Adminhtml_Helper_Media_Js extends Mage_Core_Helper_Js
 {
+    /**
+     * @param Mage_Core_Model_Translate $translator
+     * @param Mage_Core_Model_Config_Modules_Reader $configReader
+     */
+    public function __construct(
+        Mage_Core_Model_Translate $translator,
+        Mage_Core_Model_Config_Modules_Reader $configReader
+    ) {
+        parent::__construct($translator, $configReader);
 
-    public function __construct()
-    {
-         $this->_translateData = array(
+        $this->_translateData = array(
             'Complete' => $this->__('Complete'),
             'File size should be more than 0 bytes' => $this->__('File size should be more than 0 bytes'),
             'Upload Security Error' => $this->__('Upload Security Error'),
             'Upload HTTP Error'     => $this->__('Upload HTTP Error'),
             'Upload I/O Error'     => $this->__('Upload I/O Error'),
-            'SSL Error: Invalid or self-signed certificate'     => $this->__('SSL Error: Invalid or self-signed certificate'),
+            'SSL Error: Invalid or self-signed certificate' => $this->__('SSL Error: Invalid or self-signed certificate'),
             'Tb' => $this->__('Tb'),
             'Gb' => $this->__('Gb'),
             'Mb' => $this->__('Mb'),
diff --git a/app/code/core/Mage/Adminhtml/Model/Customer/Renderer/Region.php b/app/code/core/Mage/Adminhtml/Model/Customer/Renderer/Region.php
index 402411ca0fe7a14d28022d8b3da562c59e9d2643..20e1a7abb60f988cf51dfa34cead95bb17f83031 100644
--- a/app/code/core/Mage/Adminhtml/Model/Customer/Renderer/Region.php
+++ b/app/code/core/Mage/Adminhtml/Model/Customer/Renderer/Region.php
@@ -46,7 +46,7 @@ class Mage_Adminhtml_Model_Customer_Renderer_Region implements Varien_Data_Form_
 
     public function render(Varien_Data_Form_Element_Abstract $element)
     {
-        $html = '<div class="field field-region">'."\n";
+        $html = '<div class="field field-region required">'."\n";
 
         $countryId = false;
         if ($country = $element->getForm()->getElement('country_id')) {
@@ -85,7 +85,7 @@ class Mage_Adminhtml_Model_Customer_Renderer_Region implements Varien_Data_Form_
 
         if ($regionCollection && count($regionCollection) > 0) {
             $elementClass = $element->getClass();
-            $html.= '<label class="label" for="' . $regionIdHtmlId . '"><span>'.$element->getLabelHtml().'</span><span class="required" style="display:none">*</span></label>';
+            $html.= '<label class="label" for="' . $regionIdHtmlId . '"><span>'.$element->getLabel().'</span><span class="required" style="display:none">*</span></label>';
             $html.= '<div class="control">';
 
             $html .= '<select id="' . $regionIdHtmlId . '" name="' . $regionIdHtmlName . '" '
diff --git a/app/code/core/Mage/Adminhtml/controllers/Catalog/CategoryController.php b/app/code/core/Mage/Adminhtml/controllers/Catalog/CategoryController.php
index 9eb5d4752d54763f6f3dbe083179e6c54836984f..d4c8566e2746965a87f8ffbeeda46bdeb253a2dd 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Catalog/CategoryController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Catalog/CategoryController.php
@@ -524,7 +524,7 @@ class Mage_Adminhtml_Catalog_CategoryController extends Mage_Adminhtml_Controlle
     public function suggestCategoriesAction()
     {
         $this->getResponse()->setBody($this->getLayout()->createBlock('Mage_Adminhtml_Block_Catalog_Category_Tree')
-            ->getSuggestedCategoriesJson($this->getRequest()->getParam('name_part'))
+            ->getSuggestedCategoriesJson($this->getRequest()->getParam('label_part'))
         );
     }
 
diff --git a/app/code/core/Mage/Adminhtml/controllers/Catalog/ProductController.php b/app/code/core/Mage/Adminhtml/controllers/Catalog/ProductController.php
index fa08d7763b7de81cc313d77f432810960c7dd309..b9e4002b1de26fce35e2efc73263cf200ed4da85 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Catalog/ProductController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Catalog/ProductController.php
@@ -1040,6 +1040,16 @@ class Mage_Adminhtml_Catalog_ProductController extends Mage_Adminhtml_Controller
         $this->loadLayout();
         $this->renderLayout();
     }
-}
-
 
+    /**
+     * Action for product template selector
+     */
+    public function suggestProductTemplatesAction()
+    {
+        $this->_initProduct();
+        $this->getResponse()->setBody(Mage::helper('Mage_Core_Helper_Data')->jsonEncode(
+            $this->getLayout()->createBlock('Mage_Catalog_Block_Product_TemplateSelector')
+                ->getSuggestedTemplates($this->getRequest()->getParam('label_part'))
+        ));
+    }
+}
diff --git a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/ShipmentController.php b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/ShipmentController.php
index 73409bcd1ff778176859c0ce924d5041891ed3d2..0e63c5d1753d24bc6ec02d54f6a8da478184e687 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/ShipmentController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/ShipmentController.php
@@ -397,8 +397,7 @@ class Mage_Adminhtml_Sales_Order_ShipmentController extends Mage_Adminhtml_Contr
         }
 
         if ( is_object($response)){
-            $className = Mage::getConfig()->getBlockClassName('Mage_Adminhtml_Block_Template');
-            $block = new $className();
+            $block = $this->_objectManager->create('Mage_Adminhtml_Block_Template');
             $block->setTemplate('sales/order/shipment/tracking/info.phtml');
             $block->setTrackingInfo($response);
 
@@ -715,4 +714,4 @@ class Mage_Adminhtml_Sales_Order_ShipmentController extends Mage_Adminhtml_Contr
                 ->toHtml()
            );
     }
-}
\ No newline at end of file
+}
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/admin.xml b/app/code/core/Mage/Adminhtml/view/adminhtml/admin.xml
index e42ba0570fee8130bafd905597fdf360909d67b8..3dd1faf2bb3c2c9050d3b34fbf8953709c1f88f6 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/admin.xml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/admin.xml
@@ -38,8 +38,8 @@
     </adminhtml_dashboard_index>
     <adminhtml_cache_index>
         <reference name="content">
-            <block type="Mage_Adminhtml_Block_Cache" name="cache"></block>
-            <block type="Mage_Adminhtml_Block_Cache_Additional" name="cache.additional" template="system/cache/additional.phtml"></block>
+            <block type="Mage_Adminhtml_Block_Cache" name="cache" />
+            <block type="Mage_Adminhtml_Block_Cache_Additional" name="cache.additional" template="system/cache/additional.phtml" />
         </reference>
     </adminhtml_cache_index>
 </layout>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog.xml b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog.xml
index 890a1aedcd874c7b45a4ee429aeb07f40d17815a..ce4806b341f5b75ac3db37808420478e8f704b4b 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog.xml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog.xml
@@ -49,18 +49,19 @@
             <action method="addJs"><file>Mage_Adminhtml::jquery/fileUploader/load-image.min.js</file></action>
             <action method="addJs"><file>Mage_Adminhtml::jquery/fileUploader/canvas-to-blob.min.js</file></action>
             <action method="addJs"><file>Mage_Adminhtml::jquery/fileUploader/jquery.fileupload-fp.js</file></action>
+
             <action method="addCss"><file>Mage_Adminhtml::catalog/category-selector.css</file></action>
             <action method="addJs"><file>Mage_Adminhtml::catalog/category-selector.js</file></action>
             <action method="addJs"><file>Mage_Adminhtml::json2.js</file></action>
             <action method="addJs"><file>Mage_Adminhtml::mage/backend/suggest.js</file></action>
-            <action method="addJs"><file>Mage_Adminhtml::mage/backend/multisuggest.js</file></action>
             <action method="addJs"><file>Mage_Adminhtml::jquery/jstree/jquery.hotkeys.js</file></action>
             <action method="addJs"><file>Mage_Adminhtml::jquery/jstree/jquery.jstree.js</file></action>
             <action method="addJs"><file>Mage_Adminhtml::mage/backend/tree-suggest.js</file></action>
             <action method="addJs"><file>Mage_Adminhtml::catalog/type-switcher.js</file></action>
             <action method="addJs"><file>Mage_Adminhtml::catalog/product-variation.js</file></action>
             <action method="addJs"><file>Mage_Adminhtml::catalog/base-image-uploader.js</file></action>
-            <action method="addCss"><file>Mage_Adminhtml::catalog/configurable-product.css</file></action>
+            <action method="addJs"><file>Mage_Catalog::js/product-gallery.js</file></action>
+            <!--<action method="addCss"><file>Mage_Adminhtml::catalog/configurable-product.css</file></action>-->
         </reference>
         <reference name="content">
             <block type="Mage_Adminhtml_Block_Catalog_Product_Edit" name="product_edit">
@@ -78,10 +79,6 @@
             <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tabs" name="product_tabs"/>
         </reference>
         <reference name="js">
-            <block type="Mage_Core_Block_Template" name="change-attribute-set"
-                   template="Mage_Adminhtml::catalog/product/change_attribute_set_widget.phtml"/>
-            <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_NewCategory" name="new-category-js"
-                   template="Mage_Adminhtml::catalog/product/edit/category/new/js.phtml"/>
             <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Js" name="catalog_product_js"
                    template="catalog/product/js.phtml" />
             <block type="Mage_Core_Block_Template" template="Mage_Adminhtml::catalog/wysiwyg/js.phtml"/>
@@ -93,55 +90,9 @@
     </adminhtml_catalog_product_new>
 
     <adminhtml_catalog_product_edit>
-        <update handle="editor"/>
-        <reference name="head">
-            <action method="addCss"><file>Mage_Adminhtml::jquery/fileUploader/css/jquery.fileupload-ui.css</file></action>
-            <action method="addJs"><file>Mage_Adminhtml::jquery/fileUploader/jquery.iframe-transport.js</file></action>
-            <action method="addJs"><file>Mage_Adminhtml::jquery/fileUploader/jquery.fileupload.js</file></action>
-            <action method="addJs"><file>Mage_Adminhtml::jquery/fileUploader/load-image.min.js</file></action>
-            <action method="addJs"><file>Mage_Adminhtml::jquery/fileUploader/canvas-to-blob.min.js</file></action>
-            <action method="addJs"><file>Mage_Adminhtml::jquery/fileUploader/jquery.fileupload-fp.js</file></action>
-            <action method="addCss"><file>Mage_Adminhtml::catalog/category-selector.css</file></action>
-            <action method="addJs"><file>Mage_Adminhtml::catalog/category-selector.js</file></action>
-            <action method="addJs"><file>Mage_Adminhtml::json2.js</file></action>
-            <action method="addJs"><file>Mage_Adminhtml::mage/backend/suggest.js</file></action>
-            <action method="addJs"><file>Mage_Adminhtml::mage/backend/multisuggest.js</file></action>
-            <action method="addJs"><file>Mage_Adminhtml::jquery/jstree/jquery.hotkeys.js</file></action>
-            <action method="addJs"><file>Mage_Adminhtml::jquery/jstree/jquery.jstree.js</file></action>
-            <action method="addJs"><file>Mage_Adminhtml::mage/backend/tree-suggest.js</file></action>
-            <action method="addJs"><file>Mage_Adminhtml::catalog/type-switcher.js</file></action>
-            <action method="addJs"><file>Mage_Adminhtml::catalog/product-variation.js</file></action>
-            <action method="addJs"><file>Mage_Adminhtml::catalog/base-image-uploader.js</file></action>
-            <action method="addCss"><file>Mage_Adminhtml::catalog/configurable-product.css</file></action>
-        </reference>
-        <reference name="content">
-            <block type="Mage_Adminhtml_Block_Catalog_Product_Edit" name="product_edit">
-                <container name="product-type-tabs" label="Tabs">
-                </container>
-            </block>
-            <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_AttributeSet" name="attribute-set-info"
-                   template="Mage_Adminhtml::catalog/product/edit/attribute_set.phtml"/>
-            <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_NewCategory" name="new-category"
-                   template="Mage_Adminhtml::catalog/product/edit/category/new/form.phtml"/>
-            <block type="Mage_Core_Block_Template" name="affected-attribute-set-form"
-                   template="Mage_Catalog::product/configurable/affected-attribute-set-selector/form.phtml"/>
-        </reference>
+        <update handle="adminhtml_catalog_product_new"/>
         <reference name="left">
-            <block type="Mage_Backend_Block_Store_Switcher" name="store_switcher" before="-"/>
-            <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tabs" name="product_tabs"/>
-        </reference>
-        <reference name="js">
-            <block type="Mage_Core_Block_Template" name="change-attribute-set"
-                   template="Mage_Adminhtml::catalog/product/change_attribute_set_widget.phtml"/>
-            <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_NewCategory" name="new-category-js"
-                   template="Mage_Adminhtml::catalog/product/edit/category/new/js.phtml"/>
-            <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Js" name="catalog_product_js"
-                   template="catalog/product/js.phtml" />
-            <block type="Mage_Core_Block_Template" template="Mage_Adminhtml::catalog/wysiwyg/js.phtml"/>
-            <block type="Mage_Catalog_Block_Product_Configurable_AttributeSelector"
-                   template="Mage_Catalog::product/configurable/attribute-selector/js.phtml"/>
-            <block type="Mage_Catalog_Block_Product_Configurable_AttributeSelector"
-                   template="Mage_Catalog::product/configurable/affected-attribute-set-selector/js.phtml"/>
+            <block type="Mage_Backend_Block_Store_Switcher" name="store_switcher" before="-"/>            
         </reference>
     </adminhtml_catalog_product_edit>
 
@@ -431,25 +382,30 @@ Layout handle for grouped products
                     </block>
                     <block type="Mage_Backend_Block_Widget_Grid_Column" as="name">
                         <arguments>
-                            <header translate="true" module="Mage_Sales">Name</header>
+                            <header translate="true" module="Mage_Catalog">Name</header>
+                            <column_css_class>grouped-product-name</column_css_class>
                             <type>text</type>
                             <index>name</index>
                             <editable>1</editable>
                             <sortable>0</sortable>
+                            <escape>1</escape>
                         </arguments>
                     </block>
                     <block type="Mage_Backend_Block_Widget_Grid_Column" as="sku">
                         <arguments>
-                            <header translate="true" module="Mage_Sales">SKU</header>
+                            <header translate="true" module="Mage_Catalog">SKU</header>
+                            <column_css_class>grouped-product-sku</column_css_class>
                             <type>text</type>
                             <index>sku</index>
                             <width>80px</width>
                             <sortable>0</sortable>
+                            <escape>1</escape>
                         </arguments>
                     </block>
                     <block type="Mage_Backend_Block_Widget_Grid_Column" as="price">
                         <arguments>
-                            <header translate="true" module="Mage_Sales">Price</header>
+                            <header translate="true" module="Mage_Catalog">Price</header>
+                            <column_css_class>grouped-product-price</column_css_class>
                             <type>currency</type>
                             <index>price</index>
                             <width>110px</width>
@@ -459,7 +415,8 @@ Layout handle for grouped products
                     </block>
                     <block type="Mage_Backend_Block_Widget_Grid_Column" as="qty">
                         <arguments>
-                            <header translate="true" module="Mage_Sales">Default Qty</header>
+                            <header translate="true" module="Mage_Catalog">Default Qty</header>
+                            <column_css_class>grouped-product-qty</column_css_class>
                             <type>number</type>
                             <index>qty</index>
                             <width>110px</width>
@@ -470,10 +427,10 @@ Layout handle for grouped products
                     </block>
                     <block type="Mage_Backend_Block_Widget_Grid_Column" as="delete">
                         <arguments>
-                            <header translate="true" module="Mage_Sales">Delete</header>
+                            <header translate="true" module="Mage_Catalog">Delete</header>
                             <type>button</type>
                             <button_type>button</button_type>
-                            <column_css_class>product-delete</column_css_class>
+                            <column_css_class>grouped-product-delete</column_css_class>
                             <width>60px</width>
                             <renderer>Mage_Backend_Block_Widget_Grid_Column_Renderer_Button</renderer>
                             <align>right</align>
@@ -525,25 +482,27 @@ Layout handle for grouped products
                     </block>
                     <block type="Mage_Backend_Block_Widget_Grid_Column" as="name">
                         <arguments>
-                            <header translate="true" module="Mage_Sales">Name</header>
+                            <header translate="true" module="Mage_Catalog">Name</header>
                             <column_css_class>associated-product-name</column_css_class>
                             <type>text</type>
                             <index>name</index>
                             <editable>1</editable>
+                            <escape>1</escape>
                         </arguments>
                     </block>
                     <block type="Mage_Backend_Block_Widget_Grid_Column" as="sku">
                         <arguments>
-                            <header translate="true" module="Mage_Sales">SKU</header>
+                            <header translate="true" module="Mage_Catalog">SKU</header>
                             <column_css_class>associated-product-sku</column_css_class>
                             <type>text</type>
                             <index>sku</index>
                             <width>80px</width>
+                            <escape>1</escape>
                         </arguments>
                     </block>
                     <block type="Mage_Backend_Block_Widget_Grid_Column" as="price">
                         <arguments>
-                            <header translate="true" module="Mage_Sales">Price</header>
+                            <header translate="true" module="Mage_Catalog">Price</header>
                             <column_css_class>associated-product-price</column_css_class>
                             <type>currency</type>
                             <index>price</index>
@@ -558,12 +517,12 @@ Layout handle for grouped products
 
     <adminhtml_catalog_product_supergroup>
         <update handle="adminhtml_catalog_product_grouped"/>
-        <container output="1" name="catalog.product.edit.tab.super.grid.container" label="grid"></container>
+        <container output="1" name="catalog.product.edit.tab.super.grid.container" label="grid"/>
     </adminhtml_catalog_product_supergroup>
 
     <adminhtml_catalog_product_supergrouppopup>
         <update handle="adminhtml_catalog_product_grouped"/>
-        <container output="1" name="catalog.product.edit.tab.super.grid.popup.container" label="grid"></container>
+        <container output="1" name="catalog.product.edit.tab.super.grid.popup.container" label="grid"/>
     </adminhtml_catalog_product_supergrouppopup>
 
     <adminhtml_catalog_product_variationsmatrix>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/base-image-uploader.js b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/base-image-uploader.js
index 3e148a98c4e87d9be4661001b6bda157516077a9..8fb8fda72980c66ccd2d5a28b495d541d4b574d7 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/base-image-uploader.js
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/base-image-uploader.js
@@ -22,137 +22,120 @@
  * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
-/*global media_gallery_contentJsObject*/
-// @todo: refactor as widget
-function BaseImageUploader(id, maxFileSize) {
-    (function ($) {
-        var $container = $('#' + id + '-container'),
-            $template = $('#' + id + '-template'),
-            $dropPlaceholder = $('#' + id + '-upload-placeholder'),
-            images = $container.data('images'),
-            mainImage = $container.data('main'),
-            mainClass = 'base-image',
-            currentImageCount = 0,
-            maximumImageCount = 5,
-            isInitialized = false;
+/*jshint jquery:true*/
+/*global alert*/
+(function ($) {
+    "use strict";
+    $.widget('mage.baseImage', {
+        /**
+         * Button creation
+         * @protected
+         */
+        _create: function() {
+            var $container = this.element,
+                $template = this.element.find('.image-template'),
+                $dropPlaceholder = this.element.find('.image-placeholder'),
+                $galleryContainer = $('#media_gallery_content'),
+                mainClass = 'base-image',
+                maximumImageCount = 5;
 
-        $container.on('add', function(event, data) {
-            if (currentImageCount < maximumImageCount) {
-                var $element = $template.tmpl(data);
-                $element.insertBefore($dropPlaceholder)
-                    .data('image', data);
-                if (isInitialized && !currentImageCount) {
-                    $.each('image,small_image,thumbnail'.split(','), function () {
-                        if ($('input[name="product[' + this + ']"][value=no_selection]').is(':checked')) {
-                            media_gallery_contentJsObject.imagesValues[this] = data.file;
-                            if (this == 'image') {
-                                mainImage = data.file;
-                            }
-                        }
-                    });
-                }
-                if (data.file == mainImage) {
-                    $element.addClass(mainClass);
-                }
-                currentImageCount++;
-            }
-            if (currentImageCount >= maximumImageCount) {
-                $dropPlaceholder.hide();
-            }
-            $('input[name="product[name]"]').focus().blur(); // prevent just inserted image selection
-        });
-
-        $container.on('click', '.image', function (event) {
-            $(this).toggleClass('active').siblings().removeClass('active');
-        });
-        $container.on('click', '.action-make-main', function (event) {
-            var $imageContainer = $(this).closest('.image'),
-                image = $imageContainer.data('image');
+            var findElement = function(data) {
+                return $container.find('.image:not(.image-placeholder)').filter(function() {
+                    return $(this).data('image').file === data.file;
+                }).first();
+            };
+            var updateVisibility = function() {
+                var elementsList = $container.find('.image:not(.removed-item)');
+                elementsList.each(function(index) {
+                    $(this)[index < maximumImageCount ? 'show' : 'hide']();
+                });
+                $dropPlaceholder[elementsList.length >= maximumImageCount ? 'hide' : 'show']();
+            };
 
-            $container.find('.image').removeClass(mainClass);
-            $imageContainer.addClass(mainClass);
-            mainImage = image.file;
+            $galleryContainer.on('setImageType', function(event, data) {
+                if (data.type === 'image') {
+                    $container.find('.' + mainClass).removeClass(mainClass);
+                    if (data.imageData) {
+                        findElement(data.imageData).addClass(mainClass);
+                    }
+                }
+            });
 
-            var $galleryContainer = $('#media_gallery_content_grid'),
-                $currentImage = $galleryContainer.find('input[name="product[image]"]:checked'),
-                $currentSmallImage = $galleryContainer.find('input[name="product[small_image]"]:checked'),
-                $currentThumbnail = $galleryContainer.find('input[name="product[thumbnail]"]:checked'),
-                radiosToSwitch = 'input[name="product[image]"]';
-            if ($currentImage.attr('onclick') == $currentSmallImage.attr('onclick')
-                && $currentImage.attr('onclick') == $currentThumbnail.attr('onclick')
-            ) {
-                radiosToSwitch += ',input[name="product[small_image]"],input[name="product[thumbnail]"]';
-            }
-            _getGalleryRowByImage(image).find(radiosToSwitch).trigger('click');
-        });
+            $galleryContainer.on('addItem', function(event, data) {
+                var $element = $template.tmpl(data);
+                $element.data('image', data).insertBefore($dropPlaceholder);
+                updateVisibility();
+            });
 
-        $container.on('click', '.action-delete', function (event) {
-            var $imageContainer = $(this).closest('.image'),
-                image = $imageContainer.data('image'),
-                $galleryRow = _getGalleryRowByImage(image);
+            $galleryContainer.on('removeItem', function(event, image) {
+                findElement(image).addClass('removed-item').hide();
+                updateVisibility();
+            });
 
-            $galleryRow.find('.cell-remove input[type=checkbox]').prop('checked', true).trigger('click');
-            $.each('image,small_image,thumbnail'.split(','), function () {
-                if ($galleryRow.find('input[name="product[' + this + ']"]').is(':checked')) {
-                    $('input[name="product[' + this + ']"][value=no_selection]').prop('checked', true).trigger('click');
+            $galleryContainer.on('moveElement', function(event, data) {
+                var $element = findElement(data.imageData);
+                if (data.position === 0) {
+                    $container.prepend($element);
+                } else {
+                    var $after = $container.find('.image').eq(data.position);
+                    if (!$element.is($after)) {
+                        $element.insertAfter($after);
+                    }
                 }
+                updateVisibility();
             });
-            media_gallery_contentJsObject.updateImages();
-            $imageContainer.remove();
 
-            currentImageCount--;
-            if (currentImageCount < maximumImageCount) {
-                $dropPlaceholder.css('display', 'inline-block');
-            }
-        });
-
-        function _getGalleryRowByImage(image)
-        {
-            var escapedFileName = image.file.replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g, '\\$1');
-            return $('input[onclick*="\'' + escapedFileName + '\'"]').closest('tr');
-        }
+            $container.on('click', '[data-role="make-main-button"]', function(event) {
+                event.preventDefault();
+                var data = $(this.target).closest('.image').data('image');
+                $galleryContainer.productGallery('setMain', data);
+            });
 
-        $container.sortable({
-            axis: 'x',
-            handle: '.image'
-        });
+            $container.on('click', '[data-role="delete-button"]', function(event) {
+                event.preventDefault();
+                $galleryContainer.trigger('removeItem', $(this.target).closest('.image').data('image'));
+            });
 
-        $dropPlaceholder.on('click', function(e) {
-            $('#' + id + '-upload').trigger(e);
-        });
-        $('#' + id + '-upload').fileupload({
-            dataType: 'json',
-            dropZone: $dropPlaceholder,
-            acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
-            maxFileSize: maxFileSize,
-            done: function (event, data) {
-                if (!data.result) {
-                    return;
+            $container.sortable({
+                axis: 'x',
+                items: '.image:not(.image-placeholder)',
+                distance: 8,
+                tolerance: 'pointer',
+                stop: function(event, data) {
+                    $galleryContainer.trigger('setPosition', {
+                        imageData: data.item.data('image'),
+                        position: $container.find('.image').index(data.item)
+                    });
+                    $galleryContainer.trigger('resort');
                 }
-                if (!data.result.error) {
-                    $container.trigger('add', data.result);
-                    if (typeof media_gallery_contentJsObject != 'undefined') {
-                        media_gallery_contentJsObject.handleUploadComplete(data.result);
-                        media_gallery_contentJsObject.updateImages();
+            }).disableSelection();
+
+            this.element.find('input[type="file"]').fileupload({
+                dataType: 'json',
+                dropZone: $dropPlaceholder,
+                acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
+                maxFileSize: this.element.data('maxFileSize'),
+                done: function(event, data) {
+                    $dropPlaceholder.find('.progress-bar').text('').removeClass('in-progress');
+                    if (!data.result) {
+                        return;
                     }
-                } else {
-                    alert(jQuery.mage.__('File extension not known or unsupported type.'));
+                    if (!data.result.error) {
+                        $galleryContainer.trigger('addItem', data.result);
+                    } else {
+                        alert($.mage.__('File extension not known or unsupported type.'));
+                    }
+                },
+                add: function(event, data) {
+                    $(this).fileupload('process', data).done(function() {
+                        data.submit();
+                    });
+                },
+                progress: function(e, data) {
+                    var progress = parseInt(data.loaded / data.total * 100, 10);
+                    $dropPlaceholder.find('.progress-bar').addClass('in-progress').text(progress + '%');
                 }
-            },
-            add: function(event, data) {
-                $(this).fileupload('process', data).done(function () {
-                    data.submit();
-                });
-            }
-        });
-
-        $.each(images.items || [], function() {
-            $container.trigger('add', this);
-        });
-        isInitialized = true;
-
-        if ($('label[for=image]').text() == 'Base Image') {
-            $('label[for=image]').text('Images');
+            });
         }
-    })(jQuery);
-}
+    });
+})(jQuery);
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/category-selector.css b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/category-selector.css
index 797a22a0dea3add4af5f9c67f70a3405bccc9e9f..857ba8ff6d94dc9b253746a6a2c16cc21a845bfd 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/category-selector.css
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/category-selector.css
@@ -23,23 +23,7 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 
-.category-selector-container {
-    position: relative;
-    display: inline-block;
-    vertical-align: top;
-    margin: 0 6px 6px 0;
-    width: 73.6%;
-    padding: 2px;
-    padding-right: 30px;
-    background-color: #fff;
-    border: 1px solid #ccc;
-    border-radius: 3px;
-    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-    -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-}
-
-.category-selector-container:after {
+.mage-suggest.category-select:after {
     position: absolute;
     top: 0;
     right: 5px;
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/category-selector.js b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/category-selector.js
index 6d509ab3880c66830ef71f087e076ebbb4faced3..bf80f782a0999f5c0b0b64fbb4acdcb673772364 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/category-selector.js
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/category-selector.js
@@ -95,7 +95,7 @@
                         url: options.url,
                         context: $input,
                         dataType: 'json',
-                        data: {name_part: request.term},
+                        data: {label_part: request.term},
                         success: function(data) {
                             response(treeToList([], data || [], 0, ''));
                         }
@@ -124,10 +124,10 @@
                     return false;
                 }
             });
-            $input.data('autocomplete')._renderItem = function(ul, item) {
+            $input.data('ui-autocomplete')._renderItem = function(ul, item) {
                 var level = window.parseInt(item.level),
                     $li = $("<li>");
-                $li.data("item.autocomplete", item);
+                $li.data('ui-autocomplete-item', item);
                 $li.append($("<a />", {
                             'data-level': level,
                             'data-ui-id': 'category-selector-' + item.value
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/configurable-product.css b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/configurable-product.css
index 514b8fdd0faff3941969f2e93ccf5b427baf5216..bfd205987ad05faa93b2185ff2ea41bbc60433b3 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/configurable-product.css
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/configurable-product.css
@@ -38,28 +38,29 @@ input.ui-autocomplete-loading {
     background:url('images/spinner.gif') no-repeat 100%, linear-gradient(top, #ffffff 85%, #eeeeee 99%);
 }
 
-#attributes-container {
+#configurable-attributes-container {
     padding-bottom: 15px;
 }
 
-#attributes-container .entry-edit > fieldset {
+#configurable-attributes-container .entry-edit > fieldset {
     margin-bottom: 0;
 }
-#attributes-container  .column-price {
+#configurable-attributes-container  .column-price {
     visibility: hidden;
 }
 
-#attributes-container .have-price .column-price {
+#configurable-attributes-container .have-price .column-price {
     visibility: visible;
 }
 
-#attributes-container .ui-icon-circle-triangle-s, #attributes-container .ui-icon-circle-close {
+#configurable-attributes-container .ui-icon-circle-triangle-s,
+#configurable-attributes-container .ui-icon-circle-close {
     cursor: pointer;
     float: right;
     margin-left: 4px;
 }
 
-#attributes-container tr:hover {
+#configurable-attributes-container tr:hover {
     outline: 1px dotted rgba(128, 128, 128, 0.2);
 }
 
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/form/renderer/fieldset/element.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/form/renderer/fieldset/element.phtml
index a87b8dbc00769cd02e5a55706d767166844f91c1..b236ffefe1e5f9112b4b066bbad213a96f779383 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/form/renderer/fieldset/element.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/form/renderer/fieldset/element.phtml
@@ -51,7 +51,6 @@ $fieldAttributes = $fieldId . ' class="' . $fieldClass . '" '
     $elementToggleCode = $element->getToggleCode() ? $element->getToggleCode()
         : 'toggleValueElements(this, this.parentNode.parentNode.parentNode)';
 ?>
-
 <?php if (!$element->getNoDisplay()): ?>
     <?php if ($element->getType() == 'hidden'): ?>
         <?php echo $element->getElementHtml() ?>
@@ -70,9 +69,16 @@ $fieldAttributes = $fieldId . ' class="' . $fieldClass . '" '
         <?php endif; ?>
         <div class="field-service" value-scope="<?php echo $this->getScopeLabel()?>">
             <?php if ($this->canDisplayUseDefault()): ?>
-                <label for="<?php echo $element->getHtmlId() ?>_default" class="choice action-default">
-                    <input <?php if($element->getReadonly()):?> disabled="disabled"<?php endif; ?> type="checkbox" name="use_default[]" id="<?php echo $element->getHtmlId() ?>_default"<?php if($this->usedDefault()): ?> checked="checked"<?php endif; ?> onclick="<?php echo $elementToggleCode; ?>" value="<?php echo $this->getAttributeCode() ?>"/>
-                    <?php echo $this->__('Use Default Value') ?>
+                <label for="<?php echo $element->getHtmlId() ?>_default" class="choice use-default">
+                    <input <?php if($element->getReadonly()):?> disabled="disabled"<?php endif; ?>
+                            type="checkbox"
+                            name="use_default[]"
+                            class="use-default-control"
+                            id="<?php echo $element->getHtmlId() ?>_default"
+                            <?php if($this->usedDefault()): ?> checked="checked"<?php endif; ?>
+                            onclick="<?php echo $elementToggleCode; ?>"
+                            value="<?php echo $this->getAttributeCode() ?>"/>
+                    <span class="use-default-label"><?php echo $this->__('Use Default Value') ?></span>
                 </label>
             <?php endif; ?>
         </div>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product-variation.js b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product-variation.js
index 7a7050a6097223d64ba8a5d47d65207e9417039d..60ba2b4ea7ba9184834673f011f3ed9e1727e7b2 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product-variation.js
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product-variation.js
@@ -27,38 +27,22 @@
         _create: function () {
             this.element.sortable({
                 axis: 'y',
-                handle: '.ui-icon-grip-dotted-vertical',
+                handle: '.draggable-handle',
                 update: function () {
                     $(this).find('[name$="[position]"]').each(function (index) {
                         $(this).val(index);
                     });
                 }
             });
-
-            var havePriceVariationsCheckboxHandler = function (event) {
-                var $this = $(event.target),
-                    $block = $this.closest('.entry-edit');
-                if ($this.is(':checked')) {
-                    $block.addClass('have-price');
-                } else {
-                    $block.removeClass('have-price');
-                    $block.find('.pricing-value').val('');
-                }
-            };
-            var useDefaultCheckboxHandler = function (event) {
-                var $this = $(event.target);
-                $this.closest('.fieldset-legend').find('.store-label').prop('disabled', $this.is(':checked'));
-            };
             var updateGenerateVariationsButtonAvailability = function () {
-                var isDisabled = $('#attributes-container .entry-edit:not(:has(input.include:checked))').length > 0 ||
-                    !$('#attributes-container .entry-edit').length;
+                var isDisabled =
+                    $('#configurable-attributes-container .entry-edit:not(:has(input.include:checked))').length > 0 ||
+                    !$('#configurable-attributes-container .entry-edit').length;
                 $('#generate-variations-button').prop('disabled', isDisabled).toggleClass('disabled', isDisabled);
             };
 
             this._on({
-                'click input.price-variation': havePriceVariationsCheckboxHandler,
-                'change input.price-variation': havePriceVariationsCheckboxHandler,
-                'click .remove':  function (event) {
+                'click .fieldset-wrapper-title .action-delete':  function (event) {
                     var $entity = $(event.target).closest('.entry-edit');
                     $('#attribute-' + $entity.find('[name$="[code]"]').val() + '-container select').removeAttr('disabled');
                     $entity.remove();
@@ -71,10 +55,15 @@
                 'add': function (event, attribute) {
                     $('#attribute-template').tmpl({attribute: attribute}).appendTo($(event.target));
                     $('#attribute-' + attribute.code + '-container select').prop('disabled', true);
+
+                    $('.collapse')
+                        .collapsable()
+                        .collapse('show');
+
+                    $('[data-store-label]').useDefault();
+
                     updateGenerateVariationsButtonAvailability();
-                },
-                'click .use-default': useDefaultCheckboxHandler,
-                'change .use-default': useDefaultCheckboxHandler
+                }
             });
             updateGenerateVariationsButtonAvailability();
         },
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product.js b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product.js
index ee4e2f5743ad98f1d1d4f8a2b31102278756b96f..e08aea74b42954545bf5426a182737f11adf45d1 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product.js
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product.js
@@ -40,6 +40,7 @@ Product.Gallery.prototype = {
         this.containerId = containerId, this.container = $(this.containerId);
         this.uploader = uploader;
         this.imageTypes = imageTypes;
+
         if (this.uploader) {
             this.uploader.onFilesComplete = this.handleUploadComplete
                     .bind(this);
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/change_attribute_set_widget.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/change_attribute_set_widget.phtml
deleted file mode 100644
index a0315b607695c534522bdf22921a1bbffb6c34f1..0000000000000000000000000000000000000000
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/change_attribute_set_widget.phtml
+++ /dev/null
@@ -1,68 +0,0 @@
-<?php
-/**
- * Magento
- *
- * NOTICE OF LICENSE
- *
- * This source file is subject to the Academic Free License (AFL 3.0)
- * that is bundled with this package in the file LICENSE_AFL.txt.
- * It is also available through the world-wide-web at this URL:
- * http://opensource.org/licenses/afl-3.0.php
- * If you did not receive a copy of the license and are unable to
- * obtain it through the world-wide-web, please send an email
- * to license@magentocommerce.com so we can send you a copy immediately.
- *
- * DISCLAIMER
- *
- * Do not edit or add to this file if you wish to upgrade Magento to newer
- * versions in the future. If you wish to customize Magento for your
- * needs please refer to http://www.magentocommerce.com for more information.
- *
- * @category    design
- * @package     default_default
- * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
- * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
- */
-/* @var $this Mage_Core_Block_Template */
-?>
-<script type="text/javascript">//<[CDATA[
-(function($) {
-    $(function() {
-        $('#product-edit-form').bind('product:changeAttributeSet', function(event, attributeSetId) {
-            if ($('.tab-item-link.ajax.changed').length > 0
-                && !confirm('Some data will be not saved. Perform attribute set change anyway?')
-            ) {
-                return false;
-            }
-            var $form = $(this);
-            var uri = document.location.href.replace(/(\/|&|\?)?\bset(\/|=)\d+/g, '').replace('#', '');
-            uri += /\?/.test(uri) ? '&' : '?';
-            uri += 'set=' + window.encodeURIComponent(attributeSetId);
-            $form.attr('action', uri).addClass('ignore-validate').submit();
-        });
-        $('#attribute-set-info').dialog({
-            title: '<?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Select Attribute Set'); ?>',
-            autoOpen: false,
-            id: '<?php echo $this->getJsId() ?>',
-            minWidth: 560,
-            modal: true,
-            resizable: false,
-            buttons: [{
-                text: '<?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Cancel'); ?>',
-                id: '<?php echo $this->getJsId('close-button') ?>',
-                click: function() {
-                    $(this).dialog("close");
-                }
-            }, {
-                text: '<?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Apply'); ?>',
-                id: '<?php echo $this->getJsId('apply-button') ?>',
-                click: function() {
-                    var $attibuteSetId = $(this).find('#attribute_set_id');
-                    $('#product-edit-form').trigger('product:changeAttributeSet', [$attibuteSetId.val()]);
-                }
-            }]
-        });
-    });
-})(jQuery);
-//]]>
-</script>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit.phtml
index a412f2495ad2ae5a0760e50e1329caaec4137479..239844a6476cf86874186d09e2092e356ff49d1f 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit.phtml
@@ -35,6 +35,16 @@
 -->
 
 <div class="page-actions">
+    <div id="product-template-suggest-container" style="float:left; position: relative;padding: 5px 0 0 10px;">
+        <span class="current-product-template-container" style="cursor: pointer">
+            <span class="current-product-template"><?php echo $this->getAttributeSetName()?></span>
+            <div class="arrow" style="display: inline-block;height: 0;width: 0;border-left:5px solid transparent;border-right: 5px solid transparent;border-top:5px solid #000;"></div>
+        </span>
+        <div class="dropdown-wrapper" style="display: none; position: absolute; background: white; padding: 5px;">
+            <input type="text" id="product-template-suggest" placeholder="start typing to search product template"/>
+        </div>
+    </div>
+
     <div class="switcher" onselectstart='return false;'>
         <label class="switcher-label" for="product-online-switcher" title="Product online status">
             <strong>Product online</strong>
@@ -60,17 +70,17 @@
     <?php echo $this->getBlockHtml('formkey')?>
     <div id="product-edit-form-tabs"></div>
     <?php echo $this->getChildHtml('product-type-tabs') ?>
+    <input type="hidden" id="product_type_id" value="<?php echo $this->getProduct()->getTypeId()?>"/>
 </form>
 <script type="text/javascript">
-    function checkMaxLength(Object, MaxLen)
-    {
-        if (Object.value.length > MaxLen-1) {
-            Object.value = Object.value.substr(0, MaxLen);
-        }
-        return 1;
-    }
 
 jQuery(function($) {
+    $('#meta_description').on('change keyup paste', function () {
+        var maxLength = $(this).data('maxLength') || 255;
+        if ($(this).val().length >= maxLength) {
+            $(this).val($(this).val().substr(0, maxLength));
+        }
+    });
     $('#product-edit-form')
         .mage('form')
         .mage('validation', {validationUrl: '<?php echo $this->getValidationUrl() ?>'});
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/attribute_set.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/attribute_set.phtml
index 683d1b0d393d6f147764e553508fd896b4391d78..d0ff1bf7762c274a8835ec1afd63fd58fa09df05 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/attribute_set.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/attribute_set.phtml
@@ -25,8 +25,39 @@
  */
  /* @var $this Mage_Adminhtml_Block_Catalog_Product_Edit_AttributeSet */
 ?>
-<div id="<?php echo $this->getNameInLayout() ?>" style="display:none">
-    <?php echo $this->getFormHtml();?>
-    <?php echo $this->getChildHtml('form_after');?>
-</div>
-
+<script id="product-template-selector-template" type="text/x-jquery-tmpl">
+{{if !term && items.length && !$data.allShown()}}
+<h2>Recent Items</h2>
+{{/if}}
+<ul data-mage-init="{&quot;menu&quot;:[]}">
+    {{each items}}
+    <li {{html optionData($value)}}><a href="#">${$value.label}</a></li>
+    {{/each}}
+</ul>
+{{if !term && items.length && !$data.allShown()}}
+<div data-mage-init="{actionLink:{event:&quot;showAll&quot;}}" class="show-all">Show all...</div>
+{{/if}}
+</script>
+<script>
+    jQuery(function ($) {
+        $('#product-template-suggest-container .current-product-template-container').off('click.product-template')
+            .on('click.product-template', function () {
+                $(this).next('div').toggle().find('.mage-suggest-dropdown')/*.trigger('showAll')*/;
+            });
+        $('#product-template-suggest').suggest(<?php echo Mage::helper('Mage_Core_Helper_Data')->jsonEncode($this->getSelectorOptions())?>)
+            .on('suggestselect', function (e, selectedItem) {
+                if (selectedItem.id) {
+                    var uri = document.location.href.replace(/(\/|&|\?)?\bset(\/|=)\d+/g, '').replace('#', '');
+                    uri += /\?/.test(uri) ? '&' : '?';
+                    uri += 'set=' + window.encodeURIComponent(selectedItem.id);
+                    var $form = $('#product-edit-form');
+                    $form.attr('action', uri).addClass('ignore-validate').submit();
+                }
+            }).focus();
+        $('body').on('click', function (e) {
+            if (!$(e.target).is('#product-template-suggest-container, #product-template-suggest-container *')) {
+                $('#product-template-suggest-container .dropdown-wrapper').hide();
+            }
+        });
+    });
+</script>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/category/new/form.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/category/new/form.phtml
index 3be91793c89b7e06dae7029f77ef88ec0e4464f4..32e64ef905f308b4caba20d3993f5ce2a2e14340 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/category/new/form.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/category/new/form.phtml
@@ -27,5 +27,5 @@
 ?>
 <div id="<?php echo $this->getNameInLayout() ?>" style="display:none">
     <?php echo $this->getFormHtml();?>
-    <?php echo $this->getChildHtml('form_after');?>
+    <?php echo $this->getAfterElementHtml();?>
 </div>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/category/new/js.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/category/new/js.phtml
deleted file mode 100644
index 30ebed16b6579c532d6f880054aaa41414786708..0000000000000000000000000000000000000000
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/category/new/js.phtml
+++ /dev/null
@@ -1,202 +0,0 @@
-<?php
-/**
- * Magento
- *
- * NOTICE OF LICENSE
- *
- * This source file is subject to the Academic Free License (AFL 3.0)
- * that is bundled with this package in the file LICENSE_AFL.txt.
- * It is also available through the world-wide-web at this URL:
- * http://opensource.org/licenses/afl-3.0.php
- * If you did not receive a copy of the license and are unable to
- * obtain it through the world-wide-web, please send an email
- * to license@magentocommerce.com so we can send you a copy immediately.
- *
- * DISCLAIMER
- *
- * Do not edit or add to this file if you wish to upgrade Magento to newer
- * versions in the future. If you wish to customize Magento for your
- * needs please refer to http://www.magentocommerce.com for more information.
- *
- * @category    design
- * @package     default_default
- * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
- * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
- */
-?>
-<?php /** @var $this Mage_Adminhtml_Block_Catalog_Product_Edit_NewCategory */ ?>
-<script type="text/javascript">//<[CDATA[
-(function($) {
-    'use strict';
-    $(function() {
-        Validation.add('validate-parent-category', 'Choose existing category.', function() {
-            return $('#new_category_parent_id').val() !== '';
-        });
-        var newCategoryForm = new Validation($('#new-category').get(0));
-
-        var treeToList = function(list, nodes, level, path) {
-            $.each(nodes, function() {
-                list.push({
-                    label: this.name,
-                    value: this.id,
-                    level: level,
-                    item: this,
-                    path: path + this.name
-                });
-                if ('children' in this) {
-                    treeToList(list, this.children, level + 1, path + this.name + '/' );
-                }
-            });
-            return list;
-        };
-
-        $('#new_category_parent')
-            .removeClass('validate-parent-category')
-            .addClass('validate-parent-category') // adjusting validation rules order
-            .bind('ajaxSend ajaxComplete', function(e) {
-                e.stopPropagation();
-            })
-            .autocomplete({
-                source: function(request, response) {
-                    $.ajax({
-                        url: '<?php echo $this->getSuggestCategoryUrl()?>',
-                        data: {name_part: request.term},
-                        dataType: 'json',
-                        context: $('#new_category_parent')
-                    }).success(function(data) {
-                        response(treeToList([], data || [], 0, ''));
-                    });
-                },
-                minLength: 0,
-                focus: function(event, ui) {
-                    $(this).val(ui.item.label);
-                    return false;
-                },
-                open: function(event, ui) {
-                    $('#new_category_parent').data('selected-name', '');
-                },
-                select: function(event, ui) {
-                    $('#new_category_parent_id').val(ui.item.value);
-                    $('#new_category_parent').data('selected-name', $('#new_category_parent').val());
-                    $(this).val(ui.item.label);
-
-                    if ($('#new_category_name').val() === '') {
-                        $('#new_category_name').focus();
-                    } else {
-                        $('#<?php echo $this->getJsId('save-button')?>').focus();
-                    }
-
-                    return false;
-                },
-                close: function(event, ui) {
-                    var selectedName = $('#new_category_parent').data('selected-name');
-                    $('#new_category_parent').val(selectedName === '' ? $(this).data('autocomplete').term : selectedName);
-                    return false;
-                }
-            })
-            .focus(function () {
-                var $this = $(this);
-                if (!$this.data('focus-emulated') && $this.val() === '') {
-                    $this.autocomplete('search');
-                }
-                setTimeout(function() { // fix for IE9 in which two focus events are triggered
-                    $this.data('focus-emulated', false);
-                }, 100);
-            })
-            .data('autocomplete')._renderItem = function(ul, item) {
-                var level = window.parseInt(item.level),
-                    $li = $('<li>');
-                $li.data('item.autocomplete', item);
-                $li.append($('<a/>', {
-                    'data-level': level,
-                    'data-ui-id': 'category-selector-' + item.value
-                }).attr('title', item.path)
-                    .addClass('level-' + level)
-                    .text(item.label)
-                    .css({marginLeft: level * 16})
-                );
-                if (window.parseInt(item.item.is_active, 10) == 0) {
-                    $li.addClass('category-disabled');
-                }
-                $li.appendTo(ul);
-
-                return $li;
-            };
-
-        $('#new-category').dialog({
-            title: '<?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Create New Category');?>',
-            autoOpen: false,
-            id: '<?php echo $this->getJsId()?>',
-            minWidth: 560,
-            modal: true,
-            resizable: false,
-            open: function() {
-                var enteredName = $('#category_ids + .category-selector-container .category-selector-input').val();
-                $('#new_category_name').val(enteredName);
-                if (enteredName === '') {
-                    $('#new_category_name').focus();
-                } else {
-                    $('#new_category_parent').data('focus-emulated', true).focus();
-                }
-                $('#new_category_messages').html('');
-            },
-            close: function() {
-                $('#new_category_name, #new_category_parent_id, #new_category_parent').val('');
-                $('#new_category_parent').autocomplete('close');
-                newCategoryForm.reset();
-                $('#category_ids + .category-selector-container .category-selector-input').focus();
-            },
-            buttons: [{
-                text: '<?php echo $this->helper('Mage_Catalog_Helper_Data')->__('Cancel');?>',
-                id: '<?php echo $this->getJsId('close-button')?>',
-                click: function() {
-                    $(this).dialog('close');
-                }
-            }, {
-                text: '<?php echo $this->helper('Mage_Catalog_Helper_Data')->__('Save');?>',
-                id: '<?php echo $this->getJsId('save-button')?>',
-                click: function() {
-                    if ($('#new_category_parent').data('selected-name') != $('#new_category_parent').val()) {
-                        $('#new_category_parent_id').val('');
-                    }
-
-                    if (!newCategoryForm.validate()) {
-                        return;
-                    }
-
-                    $.ajax({
-                        type: 'POST',
-                        url: '<?php echo $this->getSaveCategoryUrl()?>',
-                        data: {
-                            general: {
-                                name: $('#new_category_name').val(),
-                                is_active: 1,
-                                include_in_menu: 0
-                            },
-                            parent: $('#new_category_parent_id').val(),
-                            use_config: ['available_sort_by', 'default_sort_by'],
-                            form_key: '<?php echo $this->getFormKey()?>',
-                            return_session_messages_only: 1
-                        },
-                        dataType: 'json',
-                        context: $('body')
-                    }).success(function (data) {
-                        if (!data.error) {
-                            $('#category_ids').trigger('categorySelector:add', {
-                                text: data.category.name,
-                                value: data.category.entity_id
-                            });
-                            $('#new_category_name, #new_category_parent_id, #new_category_parent').val('');
-                            $('#category_ids + .category-selector-container .category-selector-input').val('');
-                            $('#new-category').dialog('close');
-                        } else {
-                            $('#new_category_messages').html(data.messages);
-                        }
-                    });
-                }
-            }]
-        });
-    });
-})(jQuery);
-//]]>
-</script>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/super/attribute-js-template.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/super/attribute-js-template.phtml
index 3cd2bbdaa9eff6d74ca21daf7f4a6bada51054d3..44eeca21b0dbbd248d20c9135918a06d721b9f20 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/super/attribute-js-template.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/super/attribute-js-template.phtml
@@ -38,76 +38,163 @@
         <input value="${attribute.code}" type="hidden"
             name="product[configurable_attributes_data][${attribute.id}][code]"/>
 
-        <div class="entry-edit-head">
-            <span class="ui-icon ui-icon-grip-dotted-vertical" style="float:left"></span>
-            <h4 class="icon-head head-edit-form fieldset-legend">
-                <input value="${attribute.label}"
-                    name="product[configurable_attributes_data][${attribute.id}][label]"
-                    data-store-label="${attribute.label}"
-                    class="store-label required-entry"/>
-                <label for="attribute-${attribute.id}">
-                    <input value="1"
-                        type="checkbox"
-                        class="use-default"
-                        name="product[configurable_attributes_data][${attribute.id}][use_default]"
-                        id="attribute-${attribute.id}"/>
-                    <?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Use default')?>
-            </h4>
-            <span class="ui-icon ui-icon-circle-close remove"></span>
-            <span class="ui-icon ui-icon-circle-triangle-s toggle"></span>
+        <div class="fieldset-wrapper" id="${attribute.id}-wrapper">
+            <div class="fieldset-wrapper-title">
+                <strong class="title" data-toggle="collapse" data-target="#${attribute.id}-content">
+                    <span>${attribute.label}</span>
+                </strong>
+                <div class="actions">
+                    <button type="button" title="<?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Delete Variations Group')?>" class="action-delete">
+                        <span><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Delete Variations Group')?></span>
+                    </button>
+                </div>
+                <div class="draggable-handle" title="<?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Sort Variations')?>"></div>
+            </div>
+            <div class="fieldset-wrapper-content collapse" id="${attribute.id}-content">
+                <fieldset class="fieldset">
+                    <div class="field field-variation">
+                        <label class="label"><span><?php echo $this->__('Variation Label'); ?></span></label>
+                        <div class="control">
+                            <input type="text" value="${attribute.label}"
+                                   name="product[configurable_attributes_data][${attribute.id}][label]"
+                                   data-store-label="${attribute.label}"
+                                   class="store-label required-entry"/>
+                        </div>
+                        <div class="field-service">
+                            <label for="attribute-${attribute.id}" class="use-default">
+                                <input value="1"
+                                       type="checkbox"
+                                       class="use-default-control"
+                                       name="product[configurable_attributes_data][${attribute.id}][use_default]"
+                                       id="attribute-${attribute.id}"/>
+                                <span class="use-default-label"><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Use Default')?></span>
+                            </label>
+                        </div>
+                    </div>
+                    <div class="field">
+                        <div class="control">
+                            <table class="data-table">
+                                <thead>
+                                    <tr>
+                                        <th class="col-name">
+                                            <?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Label')?>
+                                        </th>
+                                        <th class="col-change-price">
+                                            <?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Change Price')?>
+                                        </th>
+                                        <th class="col-include">
+                                            <?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Include')?>
+                                        </th>
+                                        <th class="col-actions"></th>
+                                    </tr>
+                                </thead>
+                                <tbody>
+                                {{each(index, option) attribute.options}}
+                                <tr>
+                                    <td class="col-name">${option.label}</td>
+                                    <td class="col-change-price">
+                                        <input type="hidden"
+                                               name="product[configurable_attributes_data][${attribute.id}][values][${option.value}][value_index]"
+                                               value="${option.value}">
+
+                                        <div class="field field-change-pricing">
+                                            <div class="control">
+                                                <div class="fields-group-2">
+                                                    <div class="field">
+                                                        <div class="control">
+                                                            <input type="text" class="pricing-value"
+                                                                   name="product[configurable_attributes_data][${attribute.id}][values][${option.value}][pricing_value]"
+                                                                   value="">
+                                                        </div>
+                                                    </div>
+                                                    <div class="field">
+                                                        <div class="control">
+                                                            <select name="product[configurable_attributes_data][${attribute.id}][values][${option.value}][is_percent]">
+                                                                <option value="0"><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Fixed')?>
+                                                                </option>
+                                                                <option value="1"><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Percentage')?>
+                                                                </option>
+                                                            </select>
+                                                        </div>
+                                                    </div>
+                                                </div>
+                                            </div>
+                                        </div>
+                                    </td>
+                                    <td class="col-include">
+                                        <input type="hidden"
+                                               name="product[configurable_attributes_data][${attribute.id}][values][${option.value}][include]"
+                                               value="0"/>
+                                        <div class="field choice">
+                                            <input type="checkbox" class="include"
+                                                   name="product[configurable_attributes_data][${attribute.id}][values][${option.value}][include]"
+                                                   value="1" checked="checked"/>
+                                        </div>
+                                    </td>
+                                    <td class="col-actions">
+                                        <button type="button" class="action-delete" title="<?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Delete')?>">
+                                            <span><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Delete')?></span>
+                                        </button>
+                                    </td>
+                                </tr>
+                                {{/each}}
+                                <tr>
+                                    <td class="col-name">
+                                        <div class="field">
+                                            <div class="control">
+                                                <input type="text" value="" placeholder="<?php echo $this->__('begin typing to add value'); ?>" />
+                                            </div>
+                                        </div>
+                                    </td>
+                                    <td class="col-change-price">
+                                        <input type="hidden"
+                                               name="name[]"
+                                               value="">
+
+                                        <div class="field field-change-pricing">
+                                            <div class="control">
+                                                <div class="fields-group-2">
+                                                    <div class="field">
+                                                        <div class="control">
+                                                            <input type="text" class="pricing-value"
+                                                                   name="pricing_value[]"
+                                                                   value="">
+                                                        </div>
+                                                    </div>
+                                                    <div class="field">
+                                                        <div class="control">
+                                                            <select name="is_percent[]">
+                                                                <option value="0">Fixed</option>
+                                                                <option value="1">Percentage</option>
+                                                            </select>
+                                                        </div>
+                                                    </div>
+                                                </div>
+                                            </div>
+                                        </div>
+                                    </td>
+                                    <td class="col-include">
+                                        <input type="hidden"
+                                               name="include[]"
+                                               value="0"/>
+                                        <div class="field choice">
+                                            <input type="checkbox" class="include"
+                                                   name="include[]"
+                                                   value="1"/>
+                                        </div>
+                                    </td>
+                                    <td class="col-actions">
+                                        <button type="button" class="action-delete" title="<?php echo $this->__('Delete'); ?>" disabled>
+                                            <span><?php echo $this->__('Delete'); ?></span>
+                                        </button>
+                                    </td>
+                                </tr>
+                                </tbody>
+                            </table>
+                        </div>
+                    </div>
+                </fieldset>
+            </div>
         </div>
-        <fieldset>
-            <table style="width:100%">
-                <thead>
-                <tr>
-                    <th>
-                        <?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Option Value')?>
-                    </th>
-                    <th class="column-price">
-                        <?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Change Price')?>
-                    </th>
-                    <th>
-                        <?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Include')?>
-                    </th>
-                </tr>
-                </thead>
-                <tbody>
-                {{each(index, option) attribute.options}}
-                <tr>
-                    <td>${option.label}</td>
-                    <td class="column-price">
-                        <input type="hidden"
-                            name="product[configurable_attributes_data][${attribute.id}][values][${option.value}][value_index]"
-                            value="${option.value}">
-                        <input type="text"
-                            name="product[configurable_attributes_data][${attribute.id}][values][${option.value}][pricing_value]"
-                            value="">
-                        <select
-                            name="product[configurable_attributes_data][${attribute.id}][values][${option.value}][is_percent]">
-                            <option value="0">
-                                <?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Fixed')?>
-                            </option>
-                            <option value="1">
-                                <?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Percentage')?>
-                            </option>
-                        </select>
-                    </td>
-                    <td>
-                        <input type="hidden"
-                            name="product[configurable_attributes_data][${attribute.id}][values][${option.value}][include]"
-                            value="0"/>
-                        <input type="checkbox" class="include"
-                            name="product[configurable_attributes_data][${attribute.id}][values][${option.value}][include]"
-                            value="1" checked="checked"/>
-                    </td>
-                </tr>
-                {{/each}}
-                </tbody>
-            </table>
-            <label>
-                <input type="checkbox" class="price-variation" />
-                <?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Have price variations')?>
-            </label>
-        </fieldset>
     </div>
 </script>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/super/attribute-template.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/super/attribute-template.phtml
index c8ce55442660839cf8c75d27712a0c9c88086846..8e4fecf8e6fee03aa735a35cb860a5d595ba7fdf 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/super/attribute-template.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/super/attribute-template.phtml
@@ -34,6 +34,7 @@ $havePriceVariation = array_reduce(
 );
 $id = $this->escapeHtml($attribute['attribute_id']);
 ?>
+
 <div class="entry-edit
             <?php echo $havePriceVariation ? ' have-price' : '' ?>
             " <?php echo $this->getUiId('attribute-container', $attribute['attribute_code']) ?>>
@@ -48,93 +49,181 @@ $id = $this->escapeHtml($attribute['attribute_id']);
     <input value="<?php echo $this->escapeHtml($attribute['position']); ?>" type="hidden"
         name="product[configurable_attributes_data][<?php echo $id ?>][position]"/>
 
-    <div class="entry-edit-head">
-        <span class="ui-icon ui-icon-grip-dotted-vertical" style="float:left"></span>
-        <h4 class="icon-head head-edit-form fieldset-legend">
-            <input value="<?php echo $this->escapeHtml($attribute['label']); ?>"
-                name="product[configurable_attributes_data][<?php echo $id ?>][label]"
-                data-store-label="<?php echo $this->escapeHtml($attribute['label']); ?>"
-                class="store-label required-entry"/>
-            <label for="attribute-<?php echo $id ?>">
-                <input value="1"
-                    type="checkbox"
-                    class="use-default"
-                    name="product[configurable_attributes_data][<?php echo $id ?>][use_default]"
-                    id="attribute-<?php echo $id ?>"/>
-                <?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Use default')?>
-            </label>
-        </h4>
-        <span class="ui-icon ui-icon-circle-close remove"></span>
-        <span class="ui-icon ui-icon-circle-triangle-s toggle"></span>
+    <div class="fieldset-wrapper" id="<?php echo $id ?>-wrapper">
+        <div class="fieldset-wrapper-title">
+            <strong class="title" data-toggle="collapse" data-target="#<?php echo $id ?>-content">
+                <span><?php echo $this->escapeHtml($attribute['label']); ?></span>
+            </strong>
+            <div class="actions">
+                <button type="button" title="<?php echo $this->__('Delete Variations Group'); ?>" class="action-delete">
+                    <span><?php echo $this->__('Delete Variations Group'); ?></span>
+                </button>
+            </div>
+            <div class="draggable-handle" title="<?php echo $this->__('Sort Variations'); ?>"></div>
+        </div>
+        <div class="fieldset-wrapper-content collapse" id="<?php echo $id ?>-content">
+            <fieldset class="fieldset">
+                <div class="field field-variation">
+                    <label class="label"><span><?php echo $this->__('Variation Label'); ?></span></label>
+                    <div class="control">
+                        <input type="text" value="<?php echo $this->escapeHtml($attribute['label']); ?>"
+                               name="product[configurable_attributes_data][<?php echo $id ?>][label]"
+                               data-store-label="<?php echo $this->escapeHtml($attribute['label']); ?>"
+                               class="store-label required-entry"/>
+                    </div>
+                    <div class="field-service">
+                        <label for="attribute-<?php echo $id ?>" class="use-default">
+                            <input value="1"
+                                   type="checkbox"
+                                   class="use-default-control"
+                                   name="product[configurable_attributes_data][<?php echo $id ?>][use_default]"
+                                   id="attribute-<?php echo $id ?>"/>
+                            <span class="use-default-label"><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Use Default')?></span>
+                        </label>
+                    </div>
+                </div>
+                <div class="field">
+                    <div class="control">
+                        <table class="data-table">
+                            <thead>
+                                <tr>
+                                    <th class="col-name"><?php echo $this->__('Label'); ?></th>
+                                    <th class="col-change-price"><?php echo $this->__('Change Price'); ?></th>
+                                    <th class="col-include"><?php echo $this->__('Include'); ?></th>
+                                    <th class="col-actions"></th>
+                                </tr>
+                            </thead>
+                            <tbody>
+                            <?php
+                            $namePrefix = 'product[configurable_attributes_data][' . $id . '][values]';
+                            foreach ($attribute['options'] as $option) {
+                                ?>
+                                <tr>
+                                    <td class="col-name"><?php echo $this->escapeHtml($option['label']) ?></td>
+                                    <td class="col-price">
+                                        <?php
+                                        $price_value = '';
+                                        $isPercent = false;
+                                        $include = false;
+                                        $valueIndex = $option['value'];
+                                        foreach ($attribute['values'] as $priceValue) {
+                                            if ($valueIndex == $priceValue['value_index']) {
+                                                $price_value = $priceValue['pricing_value'];
+                                                $isPercent = (bool)$priceValue['is_percent'];
+                                                $include = true;
+                                                if (isset($priceValue['include'])) {
+                                                    $include = $include && (bool)$priceValue['include'];
+                                                }
+                                                break;
+                                            }
+                                        }
+                                        ?>
+                                        <input type="hidden"
+                                               name="<?php echo $namePrefix ?>[<?php echo $valueIndex ?>][value_index]"
+                                               value="<?php echo $this->escapeHtml($valueIndex); ?>">
+
+                                        <div class="field field-change-pricing">
+                                            <div class="control">
+                                                <div class="fields-group-2">
+                                                    <div class="field">
+                                                        <div class="control">
+                                                            <input type="text" class="pricing-value"
+                                                                   name="<?php echo $namePrefix ?>[<?php echo $valueIndex ?>][pricing_value]"
+                                                                   value="<?php echo $this->escapeHtml($price_value); ?>">
+                                                        </div>
+                                                    </div>
+                                                    <div class="field">
+                                                        <div class="control">
+                                                            <select name="<?php echo $namePrefix ?>[<?php echo $valueIndex ?>][is_percent]">
+                                                                <option value="0"
+                                                                    <?php echo !$isPercent ? 'selected="selected"' : '' ?>
+                                                                        >Fixed
+                                                                </option>
+                                                                <option value="1"
+                                                                    <?php echo $isPercent ? 'selected="selected"' : '' ?>
+                                                                        >Percentage
+                                                                </option>
+                                                            </select>
+                                                        </div>
+                                                    </div>
+                                                </div>
+                                            </div>
+                                        </div>
+                                    </td>
+                                    <td class="col-include">
+                                        <input type="hidden"
+                                               name="<?php echo $namePrefix ?>[<?php echo $valueIndex ?>][include]"
+                                               value="0"/>
+                                        <div class="field choice">
+                                            <input type="checkbox" class="include"
+                                                   name="<?php echo $namePrefix ?>[<?php echo $valueIndex ?>][include]"
+                                                   value="1" <?php echo $include ? 'checked="checked"' : ''; ?> />
+                                        </div>
+                                    </td>
+                                    <td class="col-actions">
+                                        <button type="button" class="action-delete" title="<?php echo $this->__('Delete'); ?>">
+                                            <span><?php echo $this->__('Delete'); ?></span>
+                                        </button>
+                                    </td>
+                                </tr>
+                                <?php } ?>
+                                <tr>
+                                    <td class="col-name">
+                                        <div class="field">
+                                            <div class="control">
+                                                <input type="text" value="" placeholder="<?php echo $this->__('begin typing to add value'); ?>" />
+                                            </div>
+                                        </div>
+                                    </td>
+                                    <td class="col-change-price">
+                                        <input type="hidden"
+                                               name="name[]"
+                                               value="">
+
+                                        <div class="field field-change-pricing">
+                                            <div class="control">
+                                                <div class="fields-group-2">
+                                                    <div class="field">
+                                                        <div class="control">
+                                                            <input type="text" class="pricing-value"
+                                                                   name="pricing_value[]"
+                                                                   value="">
+                                                        </div>
+                                                    </div>
+                                                    <div class="field">
+                                                        <div class="control">
+                                                            <select name="is_percent[]">
+                                                                <option value="0">Fixed</option>
+                                                                <option value="1">Percentage</option>
+                                                            </select>
+                                                        </div>
+                                                    </div>
+                                                </div>
+                                            </div>
+                                        </div>
+                                    </td>
+                                    <td class="col-include">
+                                        <input type="hidden"
+                                               name="include[]"
+                                               value="0"/>
+                                        <div class="field choice">
+                                            <input type="checkbox" class="include"
+                                                   name="include[]"
+                                                   value="1"/>
+                                        </div>
+                                    </td>
+                                    <td class="col-actions">
+                                        <button type="button" class="action-delete" title="<?php echo $this->__('Delete'); ?>" disabled>
+                                            <span><?php echo $this->__('Delete'); ?></span>
+                                        </button>
+                                    </td>
+                                </tr>
+                            </tbody>
+                        </table>
+                    </div>
+                </div>
+            </fieldset>
+        </div>
     </div>
-    <fieldset>
-        <table style="width:100%">
-            <thead>
-            <tr>
-                <th><?php echo $this->__('Option Value'); ?></th>
-                <th class="column-price"><?php echo $this->__('Change Price'); ?></th>
-                <th><?php echo $this->__('Include'); ?></th>
-            </tr>
-            </thead>
-            <tbody>
-            <?php
-            $namePrefix = 'product[configurable_attributes_data][' . $id . '][values]';
-            foreach ($attribute['options'] as $option) {
-                ?>
-                <tr>
-                    <td><?php echo $this->escapeHtml($option['label']) ?></td>
-                    <td class="column-price">
-                        <?php
-                        $price_value = '';
-                        $isPercent = false;
-                        $include = false;
-                        $valueIndex = $option['value'];
-                        foreach ($attribute['values'] as $priceValue) {
-                            if ($valueIndex == $priceValue['value_index']) {
-                                $price_value = $priceValue['pricing_value'];
-                                $isPercent = (bool)$priceValue['is_percent'];
-                                $include = true;
-                                if (isset($priceValue['include'])) {
-                                    $include = $include && (bool)$priceValue['include'];
-                                }
-                                break;
-                            }
-                        }
-                        ?>
-                        <input type="hidden"
-                            name="<?php echo $namePrefix ?>[<?php echo $valueIndex ?>][value_index]"
-                            value="<?php echo $this->escapeHtml($valueIndex); ?>">
-                        <input type="text" class="pricing-value"
-                            name="<?php echo $namePrefix ?>[<?php echo $valueIndex ?>][pricing_value]"
-                            value="<?php echo $this->escapeHtml($price_value); ?>">
-                        <select name="<?php echo $namePrefix ?>[<?php echo $valueIndex ?>][is_percent]">
-                            <option value="0"
-                                <?php echo !$isPercent ? 'selected="selected"' : '' ?>
-                                >Fixed
-                            </option>
-                            <option value="1"
-                                <?php echo $isPercent ? 'selected="selected"' : '' ?>
-                                >Percentage
-                            </option>
-                        </select>
-                    </td>
-                    <td>
-                        <input type="hidden"
-                            name="<?php echo $namePrefix ?>[<?php echo $valueIndex ?>][include]"
-                            value="0"/>
-                        <input type="checkbox" class="include"
-                            name="<?php echo $namePrefix ?>[<?php echo $valueIndex ?>][include]"
-                            value="1" <?php echo $include ? 'checked="checked"' : ''; ?> />
-                    </td>
-                </tr>
-            <?php } ?>
-            </tbody>
-        </table>
-        <label>
-            <input type="checkbox" class="price-variation"
-                <?php echo $havePriceVariation ? 'checked="checked"' : '' ?> />
-            <?php echo $this->__('Have price variations'); ?>
-        </label>
-    </fieldset>
 </div>
 
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/super/config.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/super/config.phtml
index 1f69e3ab83d0098be2fef3c2047d4ef6d70e725c..8305a64314b7c74fdf953afa1d8fc2cb6143527c 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/super/config.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/super/config.phtml
@@ -25,81 +25,113 @@
  */
  /** @var $this Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Super_Config */
 ?>
-<div class="entry-edit" id="<?php echo $this->getId() ?>">
-    <div class="entry-edit-head">
-        <h4 class="icon-head head-edit-form fieldset-legend">
-            <?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Variations') ?>
-        </h4>
-        <div style="float:right">
-            <input type="checkbox" id="<?php echo $this->getId()?>-checkbox" name="attributes"
-                value=""
-                <?php if ($this->_getProduct()->isConfigurable() || $this->getRequest()->has('attributes')) {
-                    echo ' checked="checked" ';
-                }?>
-            />
-            <label for="<?php echo $this->getId()?>-checkbox">
-                <?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Does this product have variations?') ?>
-            </label>
+<div class="entry-edit form-inline" id="<?php echo $this->getId() ?>">
+    <div class="fieldset-wrapper" id="<?php echo $this->getId() ?>-wrapper">
+        <div class="fieldset-wrapper-title">
+            <strong class="title" data-toggle="collapse" data-target="#<?php echo $this->getId() ?>-content">
+                <span><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Variations') ?></span>
+            </strong>
         </div>
-    </div>
-    <fieldset>
-        <input id="attribute-selector"
-            placeholder="start typing to search attribute"
-            title="Select Attribute" type="text"
-            style="width: 100%; margin: 0px 0px 20px; padding: 5px; box-sizing: border-box; font-size: 1.5em;"
-            class="input-text" autocomplete="off">
-        <div id="attributes-container">
-        <?php echo $this->getChildHtml('template'); ?>
-        <?php
-        foreach ($this->getAttributes() as $attribute) {
-            echo $this->getChildBlock('attribute-renderer')->render(array(
-                'attribute' => $attribute,
-            ));
-        } ?>
-        </div>
-        <?php echo $this->getChildHtml('generate'); ?>
-        <div id="product-variations-matrix" class="grid" style="margin:20px 0">
-            <?php echo $this->getChildHtml('matrix'); ?>
-        </div>
-        <div id="associated-products-container" style="display: none;">
-            <?php echo $this->getGridHtml(); ?>
+
+        <div class="fieldset-wrapper-content collapse" id="<?php echo $this->getId() ?>-content">
+            <fieldset class="fieldset">
+                <div class="field" id="variations-search-field">
+                    <label class="label" for="configurable-attribute-selector"><span>Search</span></label>
+                    <div class="control">
+                        <input id="configurable-attribute-selector" class="input-text" placeholder="start typing to search attribute" title="Select Attribute" type="search" autocomplete="off"/>
+                    </div>
+                </div>
+
+                <!-- Configurable Attributes list -->
+                <div id="configurable-attributes-container">
+                    <?php echo $this->getChildHtml('template'); ?>
+                    <?php
+                    foreach ($this->getAttributes() as $attribute) {
+                        echo $this->getChildBlock('attribute-renderer')->render(array(
+                            'attribute' => $attribute,
+                        ));
+                    } ?>
+                </div>
+
+                <!-- "Generate Variations" button -->
+                <?php echo $this->getChildHtml('generate'); ?>
+
+                <!-- Variations -->
+                <div id="product-variations-matrix">
+                    <?php echo $this->getChildHtml('matrix'); ?>
+                </div>
+
+                <!-- Select Associated Product popup -->
+                <div id="associated-products-container">
+                    <?php echo $this->getGridHtml(); ?>
+                </div>
+
+                <input type="hidden" name="affect_configurable_product_attributes" value="1" />
+            </fieldset>
         </div>
-        <input type="hidden" name="affect_configurable_product_attributes" value="1" />
-</fieldset>
+    </div>
 
 <script type="text/javascript">
 jQuery(function($) {
-    var $variationsContainer = $("#<?php echo $this->getId()?>");
-    $('#attributes-container').variationsAttributes();
-
-    $("#<?php echo $this->getId()?>-checkbox").on('click change', function() {
-        var $fieldset = $("#<?php echo $this->getId()?> > fieldset"),
-            stockAvailabilityField = $('#quantity_and_stock_status'),
-            qtyField = $('#qty');
-        if ($(this).is(':checked')) {
-            $fieldset.show();
-            $('#change-attribute-set-button').attr('disabled', true).addClass('disabled');
-            $variationsContainer.find("input[name='attributes[]']").removeAttr('disabled');
-            qtyField.prop('disabled', true).trigger('change');
-            stockAvailabilityField.prop('disabled', false);
-            $.each($('#attributes-container').variationsAttributes('getAttributes'), function() {
-                $('#attribute-' + this.code + '-container select').attr('disabled', true);
+    'use strict';
+
+    var variationsContainer = $("#<?php echo $this->getId()?>"),
+        collapsableWrapper = $("#<?php echo $this->getId()?>-wrapper"),
+        collapsableArea = $('> .collapse', collapsableWrapper),
+        collapsableControl = $('> .fieldset-wrapper-title > [data-toggle="collapse"]', collapsableWrapper),
+        stockAvailabilityField = $('#quantity_and_stock_status'),
+        qtyField = $('#qty'),
+        currentProductTemplateContainer = $('#product-template-suggest-container .current-product-template-container'),
+        attributesInput = $("input[name='attributes[]']", variationsContainer),
+        hasVariations = <?php echo ($this->_getProduct()->isConfigurable() || $this->getRequest()->has('attributes')) ? 'true' : 'false' ?>;
+
+    $('#configurable-attributes-container').variationsAttributes();
+
+    collapsableArea
+        .collapse(hasVariations ? 'show' : 'hide')
+        .on('show', function() {
+            currentProductTemplateContainer
+                .off('click.product-template')
+                .addClass('disabled');
+
+            attributesInput.prop('disabled', false);
+
+            qtyField
+                .prop('disabled', true)
+                .trigger('change');
+
+            stockAvailabilityField
+                .prop('disabled', false);
+
+            $.each($('#configurable-attributes-container').variationsAttributes('getAttributes'), function() {
+                $('#attribute-' + this.code + '-container select').prop('disabled', true);
             })
-        } else {
-            $('#change-attribute-set-button').removeAttr('disabled').removeClass('disabled');
-            qtyField.prop('disabled', false).trigger('change');
+        })
+        .on('hide', function() {
+            currentProductTemplateContainer
+                .removeClass('disabled')
+                .off('click.product-template')
+                .on('click.product-template', function () {
+                    $(this).next('div').toggle();
+                });
+
+            qtyField
+                .prop('disabled', false)
+                .trigger('change');
+
             if (qtyField.val() == '') {
-                stockAvailabilityField.val(0).trigger('change');
+                stockAvailabilityField
+                    .val(0)
+                    .trigger('change');
+
                 stockAvailabilityField.prop('disabled', true);
             }
-            $variationsContainer.find('.entry-edit').remove();
-            $.each($('#attributes-container').variationsAttributes('getAttributes'), function() {
-                $('#attribute-' + this.code + '-container select').removeAttr('disabled');
+            variationsContainer.find('.entry-edit').remove();
+            $.each($('#configurable-attributes-container').variationsAttributes('getAttributes'), function() {
+                $('#attribute-' + this.code + '-container select').prop('disabled', false);
             });
             $('#product-variations-matrix').trigger('disable');
-            $fieldset.hide();
-        }
-    }).trigger('change');
+        });
 
     var $gridDialog = $('#associated-products-container').dialog({
         title: 'Select Associated Product',
@@ -115,7 +147,7 @@ jQuery(function($) {
                 url: data.url,
                 data: $('#product-edit-form').serialize(),
                 dataType: 'html',
-                context: $variationsContainer,
+                context: variationsContainer,
                 showLoader: true
             }).success(function(data) {
                 $('#product-variations-matrix').html(data);
@@ -127,17 +159,17 @@ jQuery(function($) {
         .on('click', 'input.associated-matrix-product-id', function() {
             $(this).closest('tr').find('input[type!=checkbox]').prop('disabled', !$(this).is(':checked'));
         })
-        .on('click', '.choose-product', function(event) {
+        .on('click', '.action-choose', function(event) {
             event.preventDefault();
             var grid = window.<?php echo $this->getGridJsObject() ?>;
             var $button = $(this);
             var attributeIds = [];
-            $variationsContainer.find("input[name='attributes[]']").each(function () {
+            variationsContainer.find("input[name='attributes[]']").each(function () {
                 attributeIds.push($(this).val());
             });
 
             grid.reloadParams = {
-                'filter': $button.data('attributes'),
+                filter: $button.data('attributes'),
                 'attributes[]': attributeIds
             };
             grid.reload(null, function() {
@@ -150,16 +182,20 @@ jQuery(function($) {
                 }
                 var $gridRow = $(event.target).parents('tr'),
                     associatedClass = '.associated-product-';
+
                 if ($gridRow.find(associatedClass + 'id').length) {
                     var $matrixRow = $button.parents('tr'),
                         matrixClass = '.associated-matrix-product-';
+
                     $.each('name,sku,qty,weight,id'.split(','), function () {
                         var target = $matrixRow.find(matrixClass + this),
                             value = $.trim($gridRow.find(associatedClass + this).text()),
-                            button = target.find('button.choose-product');
+                            button = target.find('.action-choose');
+
                         target[target.is('input[type=checkbox]') ? 'val' : 'text'](value).append(button);
                     });
-                    $matrixRow.find(matrixClass + 'id').attr('checked', true).removeAttr('disabled');
+
+                    $matrixRow.find(matrixClass + 'id').prop({checked: true, disabled: false});
                 }
                 $gridDialog.dialog('close');
             };
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/super/matrix.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/super/matrix.phtml
index 1267e74197b208dde91b253d527db683481bf11b..11d0860e546e0705f563b0a8276e7583621b20c6 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/super/matrix.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/super/matrix.phtml
@@ -33,126 +33,218 @@ if (!$variations) {
 $usedProductAttributes = $this->getUsedAttributes();
 $productByUsedAttributes = $this->getAssociatedProducts();
 ?>
-<table cellspacing="0">
-    <thead>
-    <tr class="headings">
-        <th width="180" class="name <?php echo $this->getAttributeFrontendClass('name'); ?>">
-            <?php echo $this->__('Product Name'); ?> <span class="required">*</span>
-        </th>
-        <th width="180">
-            <?php echo $this->__('Price'); ?>
-        </th>
-        <th width="220" class="sku <?php echo $this->getAttributeFrontendClass('sku'); ?>">
-             <?php echo $this->__('SKU'); ?> <span class="required">*</span>
-        </th>
-        <th width="180" class="qty">
-            <?php echo $this->__('Quantity'); ?>
-        </th>
-        <th width="180" class="weight <?php echo str_replace('required-entry', '', $this->getAttributeFrontendClass('weight')); ?>">
-            <?php echo $this->__('Weight'); ?>
-        </th>
-        <?php
-        foreach ($usedProductAttributes as $attribute) {
-            /** @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
-            echo '<th class="' . $attribute->getAttributeCode() . '">', $attribute->getStoreLabel(), '</th>', PHP_EOL;
-        }
-        ?>
-        <th class="a-center include" width="55">
-            <?php echo $this->__('Include'); ?>
-        </th>
-    </tr>
-    </thead>
-    <tbody>
-<?php
-    $isEven = true;
-    $productPrice = (float)$this->_getProduct()->getPrice();
-    foreach ($variations as $variation) {
-        $attributeValues = array();
-        $attributeLabels = array();
-        $price = $productPrice;
-        foreach ($usedProductAttributes as $attribute) {
-            /** @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
-            $attributeValues[$attribute->getAttributeCode()] = $variation[$attribute->getId()]['value'];
-            $attributeLabels[$attribute->getAttributeCode()] = $variation[$attribute->getId()]['label'];
-            if (isset($variation[$attribute->getId()]['price'])) {
-                $priceInfo = $variation[$attribute->getId()]['price'];
-                $price += ($priceInfo['is_percent'] ? $productPrice / 100.0 : 1.0) * $priceInfo['pricing_value'];
+
+<h3 class="title"><?php echo $this->__('Current Variations'); ?></h3>
+
+<div class="field">
+    <div class="control">
+        <table class="data-table">
+            <thead>
+                <tr>
+                    <th class="col-display">
+                        <?php echo $this->__('Display'); ?>
+                    </th>
+                    <th class="col-image">
+                        <?php echo $this->__('Image'); ?>
+                    </th>
+                    <th class="col-name <?php echo $this->getAttributeFrontendClass('name'); ?>">
+                        <?php echo $this->__('Name'); ?>
+                    </th>
+                    <th class="col-sku <?php echo $this->getAttributeFrontendClass('sku'); ?>">
+                        <?php echo $this->__('SKU'); ?>
+                    </th>
+                    <th class="col-price">
+                        <?php echo $this->__('Price'); ?>
+                    </th>
+                    <th class="col-qty">
+                        <?php echo $this->__('Quantity'); ?>
+                    </th>
+                    <th class="col-weight <?php echo str_replace('required-entry', '', $this->getAttributeFrontendClass('weight')); ?>">
+                        <?php echo $this->__('Weight'); ?>
+                    </th>
+                    <?php
+                    foreach ($usedProductAttributes as $attribute) {
+                        /** @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
+                        echo '<th class="col-' . preg_replace('#[^a-z0-9]+#', '-', strtolower($attribute->getStoreLabel())) . '">', $attribute->getStoreLabel(), '</th>', PHP_EOL;
+                    }
+                    ?>
+                    <th class="col-actions"></th>
+                </tr>
+            </thead>
+            <tbody>
+            <?php
+            $isEven = true;
+            $productPrice = (float)$this->_getProduct()->getPrice();
+            foreach ($variations as $variation) {
+                $attributeValues = array();
+                $attributeLabels = array();
+                $attributeStoreLabels = array();
+                $price = $productPrice;
+                foreach ($usedProductAttributes as $attribute) {
+                    /** @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
+
+                    $attributeValues[$attribute->getAttributeCode()] = $variation[$attribute->getId()]['value'];
+                    $attributeLabels[$attribute->getAttributeCode()] = $variation[$attribute->getId()]['label'];
+
+                    if (isset($variation[$attribute->getId()]['price'])) {
+                        $priceInfo = $variation[$attribute->getId()]['price'];
+                        $price += ($priceInfo['is_percent'] ? $productPrice / 100.0 : 1.0) * $priceInfo['pricing_value'];
+                    }
+                }
+                $attributeLabels = $this->escapeHtml($attributeLabels);
+                $key = implode('-', $attributeValues);
+                if (isset($productByUsedAttributes[$key])) {
+                    $product = $productByUsedAttributes[$key];
+                    ?>
+
+                <tr class="<?php echo $isEven ? 'even' : '' ?>">
+                    <td class="col-display">
+                        <input type="checkbox" name="associated_product_ids[]"
+                               value="<?php echo $product->getId()?>" class="checkbox associated-matrix-product-id"
+                               checked="checked">
+                    </td>
+                    <td class="col-image">
+                        <div class="action-upload">
+                            <span><?php echo $this->__('Upload Image'); ?></span>
+                            <input type="file" name="file[]" title="<?php echo $this->__('Upload Image'); ?>">
+                        </div>
+                    </td>
+                    <td class="col-name associated-matrix-product-name"><a
+                            href="<?php echo $this->getEditProductUrl($product->getId())?>"
+                            target="_blank"><?php echo $this->escapeHtml($product->getName())?></a>
+
+                        <button type="button" class="action-choose" title="<?php echo $this->__('Choose'); ?>"
+                                data-attributes="<?php echo $this->escapeHtml($this->helper('Mage_Core_Helper_Data')->jsonEncode($attributeValues)); ?>">
+                            <span><?php echo $this->__('Choose'); ?></span>
+                        </button>
+                    </td>
+                    <td class="col-sku"><span
+                            class="associated-matrix-product-sku"><?php echo $this->escapeHtml($product->getSku())?></span>
+                    </td>
+                    <td class="col-price associated-matrix-product-price"><?php echo $price ?></td>
+                    <td class="col-qty associated-matrix-product-qty"><?php echo $product->getStockItem()->getQty()?></td>
+                    <td class="col-weight associated-matrix-product-weight"><?php echo $product->getWeight()?></td>
+                    <?php
+                    foreach ($usedProductAttributes as $attribute) {
+                        /** @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
+                        echo '<td class="col-' . preg_replace('#[^a-z0-9]+#', '-', strtolower($attribute->getStoreLabel())) . '">', $variation[$attribute->getId()]['label'], '</td>', PHP_EOL;
+                    }
+                    ?>
+                    <td class="col-actions">
+                        <div class="actions-split">
+                            <button class="action-default">
+                                <span>Edit</span>
+                            </button>
+                            <button class="action-toggle" data-toggle="dropdown">
+                                <span>Select</span>
+                            </button>
+                            <ul class="dropdown-menu">
+                                <li>
+                                    <a href="#">Reset Variation</a>
+                                </li>
+                            </ul>
+                        </div>
+
+                        <script type="text/javascript">
+                            (function ($) {
+                                'use strict';
+
+                                $('.actions-split')
+                                    .on('click.splitDefault', '.action-default', function () {
+                                        $(this).siblings('.dropdown-menu').find('.item-default').trigger('click');
+                                    });
+                            })(window.jQuery);
+                        </script>
+                    </td>
+                </tr>
+                    <?php
+                } else {
+                    $checked = $this->_getProduct()->getId() && !$this->_getProduct()->dataHasChangedFor('type_id') ? '' : ' checked="checked"';
+                    $disabled = $this->_getProduct()->getId() && !$this->_getProduct()->dataHasChangedFor('type_id') ? ' disabled="disabled"' : '';
+                    ?>
+                <tr class="<?php echo $isEven ? 'even' : '' ?>">
+                    <td class="col-display">
+                        <input type="checkbox" name="associated_product_ids[]" value=""
+                               class="checkbox associated-matrix-product-id"<?php echo $checked?> />
+                    </td>
+                    <td class="col-image">
+                        <div class="action-upload">
+                            <span><?php echo $this->__('Upload Image'); ?></span>
+                            <input type="file" name="file[]" title="<?php echo $this->__('Upload Image'); ?>">
+                        </div>
+                    </td>
+                    <td class="col-name associated-matrix-product-name">
+                        <input id="variations-matrix-<?php echo $key?>-name"
+                               name="variations-matrix[<?php echo $key?>][name]"
+                               value="<?php echo $this->escapeHtml($this->_getProduct()->getName()), '-', implode('-', $attributeLabels)?>"
+                               class="<?php echo $this->getAttributeFrontendClass('name'); ?>"<?php echo $disabled?>/>
+                        <input type="hidden" name="variations-matrix[<?php echo $key?>][configurable_attribute]"
+                               value="<?php echo $this->escapeHtml($this->helper('Mage_Core_Helper_Data')->jsonEncode($attributeValues)); ?>"<?php echo $disabled?>/>
+
+                        <button type="button" class="action-choose" title="<?php echo $this->__('Choose'); ?>" data-attributes="<?php echo $this->escapeHtml($this->helper('Mage_Core_Helper_Data')->jsonEncode($attributeValues)); ?>">
+                            <span><?php echo $this->__('Choose'); ?></span>
+                        </button>
+                    </td>
+                    <td class="col-sku associated-matrix-product-sku">
+                        <input id="variations-matrix-<?php echo $key?>-sku"
+                               name="variations-matrix[<?php echo $key?>][sku]"
+                               value="<?php echo $this->escapeHtml($this->_getProduct()->getSku()), '-', implode('-', $attributeLabels)?>"
+                               class="<?php echo $this->getAttributeFrontendClass('sku'); ?>"<?php echo $disabled?>/>
+                    </td>
+                    <td class="col-price associated-matrix-product-price">
+                        <?php echo $price ?>
+                    </td>
+                    <td class="col-qty associated-matrix-product-qty">
+                        <input id="variations-matrix-<?php echo $key?>-qty"
+                               name="variations-matrix[<?php echo $key?>][quantity_and_stock_status][qty]"
+                               class="validate-number"
+                               value=""<?php echo $disabled?>>
+                    </td>
+                    <td class="col-weight associated-matrix-product-weight">
+                        <input id="variations-matrix-<?php echo $key?>-weight"
+                               name="variations-matrix[<?php echo $key?>][weight]"
+                               class="<?php echo str_replace('required-entry', '', $this->getAttributeFrontendClass('weight')); ?>"
+                               value="<?php echo $this->_getProduct()->getWeight()?>"<?php echo $disabled?>>
+                    </td>
+                    <?php
+                    foreach ($usedProductAttributes as $attribute) {
+                        /** @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
+                        echo '<td class="col-' . preg_replace('#[^a-z0-9]+#', '-', strtolower($attribute->getStoreLabel())) . '">', $variation[$attribute->getId()]['label'], '</td>', PHP_EOL;
+                    }
+                    ?>
+                    <td class="col-actions">
+                        <div class="actions-split">
+                            <button class="action-default">
+                                <span>Edit</span>
+                            </button>
+                            <button class="action-toggle" data-toggle="dropdown">
+                                <span>Select</span>
+                            </button>
+                            <ul class="dropdown-menu">
+                                <li>
+                                    <a href="#">Reset Variation</a>
+                                </li>
+                            </ul>
+                        </div>
+
+                        <script type="text/javascript">
+                            (function ($) {
+                                'use strict';
+
+                                $('.actions-split')
+                                        .on('click.splitDefault', '.action-default', function () {
+                                            $(this).siblings('.dropdown-menu').find('.item-default').trigger('click');
+                                        });
+                            })(window.jQuery);
+                        </script>
+                    </td>
+                </tr>
+                    <?php
+                }
+                $isEven = !$isEven;
             }
-        }
-        $attributeLabels = $this->escapeHtml($attributeLabels);
-        $key = implode('-', $attributeValues);
-        if (isset($productByUsedAttributes[$key])) {
-            $product = $productByUsedAttributes[$key];
-            ?>
-            <tr class="<?php echo $isEven ? 'even' : '' ?>">
-                <td class="associated-matrix-product-name"><a
-                        href="<?php echo $this->getEditProductUrl($product->getId())?>"
-                        target="_blank"><?php echo $this->escapeHtml($product->getName())?></a></td>
-                <td class="associated-matrix-product-price"><?php echo $price ?></td>
-                <td><span class="associated-matrix-product-sku"><?php echo $this->escapeHtml($product->getSku())?></span>
-                    <button class="choose-product"
-                        data-attributes="<?php echo $this->escapeHtml($this->helper('Mage_Core_Helper_Data')->jsonEncode($attributeValues)); ?>"
-                        style="float:right">
-                        Choose
-                    </button>
-                </td>
-                <td class="associated-matrix-product-qty"><?php echo $product->getStockItem()->getQty()?></td>
-                <td class="associated-matrix-product-weight"><?php echo $product->getWeight()?></td>
-                <td><?php echo implode('</td><td>', $attributeLabels)?></td>
-                <td class="a-center"><input type="checkbox" name="associated_product_ids[]"
-                    value="<?php echo $product->getId()?>" class="checkbox associated-matrix-product-id"
-                    checked="checked"></td>
-            </tr>
-        <?php
-        } else {
-            $checked = $this->_getProduct()->getId() && !$this->_getProduct()->dataHasChangedFor('type_id') ? '' : ' checked="checked"';
-            $disabled = $this->_getProduct()->getId() && !$this->_getProduct()->dataHasChangedFor('type_id') ? ' disabled="disabled"' : '';
             ?>
-            <tr class="<?php echo $isEven ? 'even' : '' ?>">
-                <td class="associated-matrix-product-name">
-                    <input id="variations-matrix-<?php echo $key?>-name"
-                        name="variations-matrix[<?php echo $key?>][name]"
-                        value="<?php echo $this->escapeHtml($this->_getProduct()->getName()), '-', implode('-', $attributeLabels)?>"
-                        class="<?php echo $this->getAttributeFrontendClass('name'); ?>"<?php echo $disabled?>/>
-                    <input type="hidden" name="variations-matrix[<?php echo $key?>][configurable_attribute]"
-                        value="<?php echo $this->escapeHtml($this->helper('Mage_Core_Helper_Data')->jsonEncode($attributeValues)); ?>"<?php echo $disabled?>/>
-                </td>
-                <td class="associated-matrix-product-price">
-                    <?php echo $price ?>
-                </td>
-                <td class="associated-matrix-product-sku">
-                    <input id="variations-matrix-<?php echo $key?>-sku"
-                        name="variations-matrix[<?php echo $key?>][sku]"
-                        value="<?php echo $this->escapeHtml($this->_getProduct()->getSku()), '-', implode('-', $attributeLabels)?>"
-                        class="<?php echo $this->getAttributeFrontendClass('sku'); ?>"<?php echo $disabled?>/>
-                    <button class="choose-product"
-                        data-attributes="<?php echo $this->escapeHtml($this->helper('Mage_Core_Helper_Data')->jsonEncode($attributeValues)); ?>"
-                        style="float:right">
-                        Choose
-                    </button>
-                </td>
-                <td class="associated-matrix-product-qty">
-                    <input id="variations-matrix-<?php echo $key?>-qty"
-                        name="variations-matrix[<?php echo $key?>][quantity_and_stock_status][qty]"
-                        class="validate-number"
-                        value=""<?php echo $disabled?>>
-                </td>
-                <td class="associated-matrix-product-weight">
-                    <input id="variations-matrix-<?php echo $key?>-weight"
-                        name="variations-matrix[<?php echo $key?>][weight]"
-                        class="<?php echo str_replace('required-entry', '', $this->getAttributeFrontendClass('weight')); ?>"
-                        value="<?php echo $this->_getProduct()->getWeight()?>"<?php echo $disabled?>>
-                </td>
-                <td><?php echo implode('</td><td>', $attributeLabels)?></td>
-                <td class="a-center">
-                    <input type="checkbox" name="associated_product_ids[]" value=""
-                        class="checkbox associated-matrix-product-id"<?php echo $checked?> />
-                </td>
-            </tr>
-    <?php
-        }
-        $isEven = !$isEven;
-    }
-    ?>
-    </tbody>
-</table>
+            </tbody>
+        </table>
+    </div>
+</div>
\ No newline at end of file
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/helper/gallery.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/helper/gallery.phtml
index 5da5b5a3312f689bf9a2d746abef129f4f8c575b..413ce0f960638c72a703453a6fe1b7488fc59ece 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/helper/gallery.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/helper/gallery.phtml
@@ -23,137 +23,94 @@
  * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
+ /** @var $this Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Gallery_Content */
+$elementName = $this->getElement()->getName() . '[images]';
 ?>
-<?php
-/**
- * Template for block Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Gallery_Content
- */
-?>
-<?php
-$_block = $this;
-/* @var $_block Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Gallery_Content */
-?>
-<div id="<?php echo $_block->getHtmlId() ?>">
-    <div class="message message-info">
-        <div class="message-inner">
-            <div class="message-content"><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Image type and information need to be specified for each store view.'); ?></div>
+<div id="<?php echo $this->getHtmlId() ?>"
+     data-mage-init="{'productGallery':{template:'#<?php echo $this->getHtmlId() ?>-template'}}"
+     data-images="<?php echo $this->escapeHtml($this->getImagesJson()) ?>"
+     data-types="<?php echo $this->escapeHtml(
+         $this->helper('Mage_Core_Helper_Data')->jsonEncode($this->getImageTypes())
+     ) ?>"
+     >
+    <?php foreach ($this->getImageTypes() as $typeData) { ?>
+        <input name="<?php echo $this->escapeHtml($typeData['name']) ?>"
+               class="image-<?php echo $this->escapeHtml($typeData['code']) ?>"
+               type="hidden"
+               value="<?php echo $this->escapeHtml($typeData['value']) ?>"/>
+    <?php } ?>
+    <?php
+    if (!$this->getElement()->getReadonly()) {
+        echo $this->getUploaderHtml();
+    }
+    ?>
+    <script id="<?php echo $this->getHtmlId() ?>-template" type="text/x-jquery-tmpl">
+        <div class="image item {{if disabled == 1 }}disabled{{/if}}" data-image-label="<?php echo $this->__('Main') ?>" data-role="image">
+            <input type="hidden" name="<?php echo $elementName ?>[${file_id}][position]" value="${position}" class="position"/>
+            <input type="hidden" name="<?php echo $elementName ?>[${file_id}][file]" value="${file}"/>
+            <input type="hidden" name="<?php echo $elementName ?>[${file_id}][value_id]" value="${value_id}"/>
+            <input type="hidden" name="<?php echo $elementName ?>[${file_id}][label]" value="${label}"/>
+            <input type="hidden" name="<?php echo $elementName ?>[${file_id}][disabled]" value="${disabled}"/>
+            <input type="hidden" name="<?php echo $elementName ?>[${file_id}][removed]" value="" class="is-removed"/>
+            <ul class="type-labels" style="display: none">
+                <?php foreach ($this->getImageTypes() as $typeData) { ?>
+                    <li class="type-<?php echo $this->escapeHtml(
+                        $typeData['code']
+                    ) ?>"><?php echo $this->escapeHtml($typeData['label']) ?></li>
+                <?php } ?>
+            </ul>
+            <img src="${url}" alt="${label}"/>
+            <div class="actions" >
+                <button class="action-delete" data-role="delete-button" title="<?php echo $this->__('Delete image') ?>">
+                     <span> <?php echo $this->__('Delete image') ?></span >
+                </button>
+                <button class="action-make-main" data-role="make-main-button"  title="<?php echo $this->__('Make Main') ?>">
+                    <span><?php echo $this->__('Make Main') ?></span >
+                </button >
+                <div class="draggable-handle" ></div >
+            </div >
+        </div>
+    </script>
+    <script class="dialog-template" type="text/x-jquery-tmpl"  data-title="Image Options">
+        <div style="width: 100%; clear: both; overflow: auto;" data-role="dialog">
+            <div style="width: 50%; float:right">
+                <div>
+                    <label><?php echo $this->__('Description')?></label>
+                    <textarea placeholder="label"
+                              name="<?php echo $elementName ?>[${file_id}][label]">${label}</textarea>
+                </div>
+                <div class="buttons-group widget-button-split">
+                    <label><?php echo $this->__('Role')?></label>
+                    <ul style="float:right; background-color:white; border: 1px solid #666">
+                        <?php foreach ($this->getMediaAttributes() as $attribute) { ?>
+                        <li>
+                            <label>
+                            <?php echo $this->escapeHtml($attribute->getFrontendLabel()) ?>
+                            <input class="image-type"
+                                data-role="type-selector"
+                                type="checkbox"
+                                value="<?php echo $this->escapeHtml($attribute->getAttributeCode()) ?>"
+                            />
+                            </label>
+                        </li>
+                        <?php } ?>
+                    </ul>
+                </div>
+                <div>
+                    <label>
+                        <input type="checkbox"
+                           data-role="visibility-trigger"
+                           value="1"
+                           name="<?php echo $elementName ?>[${file_id}][disabled]"
+                        {{if disabled == 1 }}checked="checked"{{/if}} />
+                        <span><?php echo $this->__('Hide from product page')?></span>
+                    </label>
+                </div>
+            </div>
+            <div style="width: 50%;">
+                <img src="${url}" alt="${label}" style="max-width:90%; max-height:500px" />
+                <span class="remove">&times;</span>
+             </div>
         </div>
-    </div>
-    <div class="grid">
-        <table cellspacing="0" class="data border" id="<?php echo $_block->getHtmlId() ?>_grid" width="100%">
-            <col width="1"/>
-            <col/>
-            <col width="70"/>
-            <?php foreach ($_block->getImageTypes() as $typeId => $type): ?>
-            <col/>
-            <?php endforeach; ?>
-            <col width="70"/>
-            <col width="70"/>
-            <thead>
-            <tr class="headings">
-                <th><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Image') ?></th>
-                <th><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Label') ?></th>
-                <th><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Sort Order') ?></th>
-                <?php foreach ($_block->getImageTypes() as $typeId => $type): ?>
-                <th><?php echo $type['label'] ?></th>
-                <?php endforeach; ?>
-                <th><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Exclude') ?></th>
-                <th class="last"><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Remove') ?></th>
-            </tr>
-            </thead>
-            <tbody id="<?php echo $_block->getHtmlId() ?>_list">
-            <tr id="<?php echo $_block->getHtmlId() ?>_template" class="template no-display">
-                <td class="cell-image">
-                    <div class="place-holder"
-                         onmouseover="<?php echo $_block->getJsObjectName(); ?>.loadImage('__file__')">
-                        <span><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Roll Over for preview') ?></span>
-                    </div>
-                    <img src="<?php echo $this->getViewFileUrl('images/spacer.gif')?>" width="100" style="display:none;"
-                         alt=""/>
-                </td>
-                <td class="cell-label"><input type="text" <?php if ($_block->getElement()->getReadonly()): ?>
-                                              disabled="disabled"<?php endif;?> class="input-text"
-                                              onkeyup="<?php echo $_block->getJsObjectName(); ?>.updateImage('__file__')"
-                                              onchange="<?php echo $_block->getJsObjectName(); ?>.updateImage('__file__')"/>
-                </td>
-                <td class="cell-position"><input type="text" <?php if ($_block->getElement()->getReadonly()): ?>
-                                                 disabled="disabled"<?php endif;?> class="input-text validate-number"
-                                                 onkeyup="<?php echo $_block->getJsObjectName(); ?>.updateImage('__file__')"
-                                                 onchange="<?php echo $_block->getJsObjectName(); ?>.updateImage('__file__')"/>
-                </td>
-                <?php foreach ($_block->getImageTypes() as $typeId => $type): ?>
-                <td class="cell-<?php echo $typeId ?> a-center">
-                    <input <?php if ($_block->getElement()->getAttributeReadonly($typeId)) : ?>
-                            disabled="disabled" <?php endif;?> type="radio" name="<?php echo $type['field'] ?>"
-                            onclick="<?php echo $_block->getJsObjectName(); ?>.setProductImages('__file__')"
-                            value="__file__"/>
-                </td>
-                <?php endforeach; ?>
-                <td class="cell-disable a-center"><input
-                        type="checkbox" <?php if ($_block->getElement()->getReadonly()): ?>
-                        disabled="disabled"<?php endif;?>
-                        onclick="<?php echo $_block->getJsObjectName(); ?>.updateImage('__file__')"/></td>
-                <td class="cell-remove a-center last"><input
-                        type="checkbox" <?php if ($_block->getElement()->getReadonly()): ?>
-                        disabled="disabled"<?php endif;?>
-                        onclick="<?php echo $_block->getJsObjectName(); ?>.updateImage('__file__')"/></td>
-            </tr>
-            <?php if ($_block->hasUseDefault()): ?>
-            <tr id="<?php echo $_block->getHtmlId() ?>_default">
-                <td><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Use Default Value') ?></td>
-                <td>&nbsp;</td>
-                <td>&nbsp;</td>
-                <?php foreach ($_block->getMediaAttributes() as $_attribute): ?>
-                <td class="a-center">
-                    <?php if ($_block->getElement()->canDisplayUseDefault($_attribute)): ?>
-                    <input class="default-checkbox" name="use_default[]"
-                           type="checkbox" <?php if ($_block->getElement()->getAttributeReadonly($_attribute->getAttributeCode())): ?>
-                           disabled="disabled" <?php endif;?>
-                           onclick="<?php echo $_block->getJsObjectName(); ?>.updateUseDefault()" <?php if ($_block->getElement()->usedDefault($_attribute)): ?>checked<?php endif; ?>
-                           value="<?php echo $_attribute->getAttributeCode() ?>"/>
-                    <?php endif ?>
-                </td>
-                <?php endforeach; ?>
-                <td>&nbsp;</td>
-                <td class="last">&nbsp;</td>
-            </tr>
-                <?php endif ?>
-            <tr id="<?php echo $_block->getHtmlId() ?>-image-0">
-                <td class="cell-image"><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('No image') ?></td>
-                <td class="cell-label"><input type="hidden"/>&nbsp;</td>
-                <td class="cell-position"><input type="hidden"/>&nbsp;</td>
-                <?php foreach ($_block->getImageTypes() as $typeId => $type): ?>
-                <td class="cell-<?php echo $typeId ?> a-center"><input
-                        type="radio" <?php if ($_block->getElement()->getAttributeReadonly($typeId)) : ?>
-                        disabled="disabled" <?php endif;?> name="<?php echo $type['field'] ?>"
-                        onclick="<?php echo $_block->getJsObjectName(); ?>.setProductImages('no_selection')"
-                        value="no_selection"/></td>
-                <?php endforeach; ?>
-                <td class="cell-disable"><input type="hidden"/>&nbsp;</td>
-                <td class="cell-remove last"><input type="hidden"/>&nbsp;</td>
-            </tr>
-            </tbody>
-            <?php if (!$_block->getElement()->getReadonly()): ?>
-            <tfoot>
-            <tr>
-                <td colspan="100" class="last" style="padding:8px">
-                    <?php echo $_block->getUploaderHtml() ?>
-                </td>
-            </tr>
-            </tfoot>
-            <?php endif;?>
-        </table>
-    </div>
+    </script>
 </div>
-<input type="hidden" id="<?php echo $_block->getHtmlId() ?>_save"
-       name="<?php echo $_block->getElement()->getName() ?>[images]"
-       value="<?php echo $_block->escapeHtml($_block->getImagesJson()) ?>"/>
-<input type="hidden" id="<?php echo $_block->getHtmlId() ?>_save_image"
-       name="<?php echo $_block->getElement()->getName() ?>[values]"
-       value="<?php echo $_block->escapeHtml($_block->getImagesValuesJson()) ?>"/>
-<script type="text/javascript">
-    //<![CDATA[
-    var <?php echo $_block->getJsObjectName(); ?> =
-    new Product.Gallery('<?php echo $_block->getHtmlId() ?>', null, <?php echo $_block->getImageTypesJson() ?>);
-    //]]>
-</script>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/tab/inventory.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/tab/inventory.phtml
index 68d8c23d72f0b1fbfb34e36d4541f568bcf47532..3a2b818401f346ae367d52922d03528e7d515b8b 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/tab/inventory.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/tab/inventory.phtml
@@ -299,18 +299,18 @@
                 ? $('inventory_enable_qty_increments_default').value
                 : $('inventory_enable_qty_increments').value;
 
-        $('inventory_qty_increments').up('tr')[enableQtyIncrements == 1 ? 'show' : 'hide']();
+        $('inventory_qty_increments').up('.field')[enableQtyIncrements == 1 ? 'show' : 'hide']();
     }
 
     function applyEnableDecimalDivided() {
     <?php if (!$this->isVirtual()) : ?>
-        $('inventory_is_decimal_divided').up('tr').hide();
+        $('inventory_is_decimal_divided').up('.field').hide();
         <?php endif; ?>
         $('inventory_qty_increments').removeClassName('validate-digits').removeClassName('validate-number');
         $('inventory_min_sale_qty').removeClassName('validate-digits').removeClassName('validate-number');
         if ($('inventory_is_qty_decimal').value == 1) {
         <?php if (!$this->isVirtual()) : ?>
-            $('inventory_is_decimal_divided').up('tr').show();
+            $('inventory_is_decimal_divided').up('.field').show();
             <?php endif; ?>
             $('inventory_qty_increments').addClassName('validate-number');
             $('inventory_min_sale_qty').addClassName('validate-number');
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/type-switcher.js b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/type-switcher.js
index 3fb0020093cf11de659f924943d4954c82c6716d..0e43fc0f67ba97f4e261f8a1ac706a787dfe3206 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/type-switcher.js
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/type-switcher.js
@@ -31,7 +31,7 @@
      */
     var TypeSwitcher = function (data) {
         this._data = data;
-        this.$type = $('#type_id');
+        this.$type = $('#product_type_id');
         this.$weight = $('#' + data.weight_id);
         this.$is_virtual = $('#' + data.is_virtual_id);
         this.$tab = $('#' + data.tab_id);
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/customer/tab/addresses.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/customer/tab/addresses.phtml
index 220b0a29561017f0d101a143a2adce5d71d7b4c4..0b00633eabf7ba60aecefb80f94b88c6e8abc194 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/customer/tab/addresses.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/customer/tab/addresses.phtml
@@ -25,88 +25,102 @@
  */
 ?>
 <!-- Addresses list -->
-<div class="fieldset-wrapper">
+<fieldset class="fieldset">
+    <legend class="legend">
+        <span><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Customer Addresses') ?></span>
+    </legend>
+    <br />
 
-<table cellspacing="0" class="form-edit">
-<tr>
-<td class="address-list">
-    <div class="entry-edit-head">
-        <h4 class="icon-head head-customer-address-list"><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Customer Addresses') ?></h4>
-    </div>
-    <div class="sub-btn-set"><?php echo $this->getAddNewButtonHtml() ?></div>
-    <ul id="address_list">
-    <?php $_iterator = 0; ?>
-    <?php if(count($addressCollection)): ?>
-        <?php foreach ($addressCollection as $_address): ?>
-        <li id="address_item_<?php echo $_address->getId() ?>">
+    <ul class="address-list" id="address_list">
+        <?php if(count($addressCollection)): ?>
+        <?php $_iterator = 0; ?>
+            <?php foreach ($addressCollection as $_address): ?>
+
+            <li class="address-list-item" id="address_item_<?php echo $_address->getId() ?>">
+                <?php if (!$this->isReadonly()): ?>
+                <div class="address-list-item-actions">
+                    <button class="action-delete" type="button" title="Remove address" id="delete_button<?php echo ++$_iterator ?>">
+                        <span>Remove address</span>
+                    </button>
+                    <button class="action-edit" type="button" title="Edit address" id="select_button_<?php echo $_address->getId() ?>">
+                        <span>Edit address</span>
+                    </button>
+                </div>
+                <?php endif;?>
+
+                <address>
+                    <?php echo $_address->format('html') ?>
+                </address>
+
+                <div class="field field-address-item-billing choice">
+                    <input type="checkbox" <?php if ($this->isReadonly()):?> disabled="disabled"<?php endif;?> value="<?php echo $_address->getId() ?>" id="address_item_billing<?php echo $_address->getId() ?>" name="account[default_billing]" title="<?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Set as Default Billing Address') ?>"<?php if($_address->getId()==$customer->getDefaultBilling()): ?> checked="checked"<?php endif; ?> />
+                    <label class="label" for="address_item_billing<?php echo $_address->getId() ?>">
+                        <span><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Default Billing Address') ?></span>
+                    </label>
+                </div>
+                <div class="field field-address-item-shipping choice">
+                    <input type="checkbox" <?php if ($this->isReadonly()):?> disabled="disabled"<?php endif;?> value="<?php echo $_address->getId() ?>" id="address_item_shipping<?php echo $_address->getId() ?>" name="account[default_shipping]" title="<?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Set as Default Shipping Address') ?>"<?php if($_address->getId()==$customer->getDefaultShipping()): ?> checked="checked"<?php endif; ?> />
+                    <label class="label" for="address_item_shipping<?php echo $_address->getId() ?>">
+                        <span><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Default Shipping Address') ?></span>
+                    </label>
+                </div>
+
+            </li>
+            <?php endforeach; ?>
+            <?php endif; ?>
+            <li class="adress-list-actions last"><?php echo $this->getAddNewButtonHtml() ?></li>
+        </ul>
+
+        <!-- Template for adding address item to list -->
+        <?php $_templatePrefix = $this->getTemplatePrefix() ?>
+        <div id="address_item_template" class="hidden template">
             <?php if (!$this->isReadonly()): ?>
-            <a href="#" class="btn-remove-address">
-                <img src="<?php echo $this->getViewFileUrl('images/cancel_icon.gif') ?>" alt="Remove address" id="delete_button<?php echo ++$_iterator ?>" />
-            </a>
-            <a href="#" id="select_button_<?php echo $_address->getId() ?>" class="select_button btn-edit-address">
-                <img src="<?php echo $this->getViewFileUrl('images/edit_icon.gif') ?>" alt="Edit address"/>
-            </a>
+            <div class="address-list-item-actions">
+                <button class="action-delete" type="button" title="Remove address" id="delete_button<?php echo ++$_iterator ?>">
+                    <span>Remove address</span>
+                </button>
+                <button class="action-edit" type="button" title="Edit address">
+                    <span>Edit address</span>
+                </button>
+            </div>
             <?php endif;?>
+
             <address>
-                <?php echo $_address->format('html') ?>
+                <?php echo Mage::helper('Mage_Customer_Helper_Data')->__('New Customer Address') ?>
             </address>
-            <div class="address-type">
-                <span class="address-type-line">
-                    <input type="radio" <?php if ($this->isReadonly()):?> disabled="disabled"<?php endif;?> value="<?php echo $_address->getId() ?>" id="address_item_billing<?php echo $_address->getId() ?>" name="account[default_billing]" title="<?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Set as Default Billing Address') ?>"<?php if($_address->getId()==$customer->getDefaultBilling()): ?> checked="checked"<?php endif; ?>/>
-                    &nbsp;<label for="address_item_billing<?php echo $_address->getId() ?>"><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Default Billing Address') ?></label>
-                </span>
-                <span class="address-type-line">
-                    <input type="radio"  <?php if ($this->isReadonly()):?> disabled="disabled"<?php endif;?> value="<?php echo $_address->getId() ?>" id="address_item_shipping<?php echo $_address->getId() ?>" name="account[default_shipping]" title="<?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Set as Default Shipping Address') ?>"<?php if($_address->getId()==$customer->getDefaultShipping()): ?> checked="checked"<?php endif; ?>/>
-                    &nbsp;<label for="address_item_shipping<?php echo $_address->getId() ?>"><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Default Shipping Address') ?></label>
-                </span>
+
+            <div class="field choice field-address-item-billing">
+                    <input type="checkbox" <?php if ($this->isReadonly()):?> disabled="disabled"<?php endif;?> value="<?php echo $_templatePrefix ?>" id="address_item_billing<?php echo $_templatePrefix ?>" name="account[default_billing]" title="<?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Set as Default Billing Address') ?>" />
+                <label class="label" for="address_item_billing<?php echo $_templatePrefix ?>">
+                    <span><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Default Billing Address') ?></span>
+                </label>
+            </div>
+            <div class="field choice field-address-item-shipping">
+                    <input type="checkbox" <?php if ($this->isReadonly()):?> disabled="disabled"<?php endif;?> value="<?php echo $_templatePrefix ?>" id="address_item_shipping<?php echo $_templatePrefix ?>" name="account[default_shipping]" title="<?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Set as Default Shipping Address') ?>"/>
+                <label class="label" for="address_item_shipping<?php echo $_templatePrefix ?>">
+                    <span><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Default Shipping Address') ?></span>
+                </label>
             </div>
-        </li>
-        <?php endforeach; ?>
-    <?php endif; ?>
-    </ul>
-</td>
-<td>
-    <!-- Template for adding address item to list -->
-    <?php $_templatePrefix = $this->getTemplatePrefix() ?>
-    <div id="address_item_template" class="no-display template">
-        <?php if (!$this->isReadonly()): ?>
-        <a href="#" class="btn-remove-address">
-            <img src="<?php echo $this->getViewFileUrl('images/cancel_icon.gif') ?>" alt="Remove address" id="delete_button<?php echo ++$_iterator ?>" />
-        </a>
-        <a href="#" id="select_button_" class="select_button btn-edit-address">
-            <img src="<?php echo $this->getViewFileUrl('images/edit_icon.gif') ?>" alt="Edit address"/>
-        </a>
-        <?php endif;?>
-        <address><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('New Customer Address') ?></address>
-        <div class="address-type">
-            <span class="address-type-line">
-                <input  <?php if ($this->isReadonly()):?> disabled="disabled"<?php endif;?> type="radio" value="<?php echo $_templatePrefix ?>" id="address_item_billing<?php echo $_templatePrefix ?>" name="account[default_billing]" title="<?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Set as Default Billing Address') ?>"/>
-                &nbsp;<label for="address_item_billing<?php echo $_templatePrefix ?>"><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Default Billing Address') ?></label>
-            </span>
-            <span class="address-type-line">
-                <input  <?php if ($this->isReadonly()):?> disabled="disabled"<?php endif;?> type="radio" value="<?php echo $_templatePrefix ?>" id="address_item_shipping<?php echo $_templatePrefix ?>" name="account[default_shipping]" title="<?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Set as Default Shipping Address') ?>"/>
-                &nbsp;<label for="address_item_shipping<?php echo $_templatePrefix ?>"><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Default Shipping Address') ?></label>
-            </span>
         </div>
-    </div>
 
-    <!-- Address form template -->
-    <div id="address_form_template" class="no-display template">
-    <?php
-        // Set form template elements prefix
-        $this->getForm()->setHtmlIdPrefix($_templatePrefix)
-                ->setFieldNameSuffix('address['.$_templatePrefix.']');
-    ?>
-    <?php echo $this->getForm()->getHtml() ?>
-    <?php echo $this->getCancelButtonHtml() ?>
-    </div>
-<!-- -->
+        <!-- Address form template -->
+        <div id="address_form_template" class="no-display template"><!-- Don`t delete class no-display, save customer stops work  -->
+            <?php
+                // Set form template elements prefix
+                $this->getForm()->setHtmlIdPrefix($_templatePrefix)
+                        ->setFieldNameSuffix('address['.$_templatePrefix.']');
+            ?>
+            <?php echo $this->getForm()->getHtml() ?>
+            <div class="address-item-edit-actions"><?php echo $this->getCancelButtonHtml() ?></div>
+        </div>
+
+
 
-<!-- Addresses forms -->
-    <div class="entry-edit" id="address_form_container">
+    <!-- Addresses forms -->
+    <div class="address-item-edit" id="address_form_container">
         <?php if(count($addressCollection)): ?>
             <?php foreach ($addressCollection as $_address): ?>
-            <div id="form_address_item_<?php echo $_address->getId() ?>" style="display:none">
+            <div class="address-item-edit-content" id="form_address_item_<?php echo $_address->getId() ?>" style="display:none">
             <?php
                     $this->getForm()->addValues($_address->getData())
                             ->setHtmlIdPrefix("_item{$_address->getId()}")
@@ -118,10 +132,9 @@
             <input type="hidden" name="address[<?php echo $_address->getId() ?>][_deleted]" id="deleted_address_item_<?php echo $_address->getId() ?>" />
             </div>
             <?php endforeach; ?>
-        <?php else: ?>
-            <div id="no_address_message"><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('This customer has no saved addresses.') ?></div>
         <?php endif; ?>
     </div>
+</fieldset>
 
 <script type="text/javascript">
 //<![CDATA[
@@ -173,14 +186,14 @@ addressesModel.prototype = {
         if( initial ) {
             this.itemCount = this.itemList.length;
         }
-        if(!this.itemList.length){
-            if($('no_address_message')){
-                $('no_address_message').show();
-            }
-            else {
-                this.formContainer.innerHTML+= '<div id="no_address_message"><?php echo addslashes(Mage::helper('Mage_Customer_Helper_Data')->__('This customer has no saved addresses.')) ?></div>'
-            }
-        }
+        // if(!this.itemList.length){
+        //     if($('no_address_message')){
+        //         $('no_address_message').show();
+        //     }
+        //     else {
+        //         this.formContainer.innerHTML+= '<div id="no_address_message"><?php echo addslashes(Mage::helper('Mage_Customer_Helper_Data')->__('This customer has no saved addresses.')) ?></div>'
+        //     }
+        // }
     },
 
     initItem : function(item){
@@ -207,16 +220,16 @@ addressesModel.prototype = {
     addNewAddress : function(event){
         if(this.canCreateNewAddress){
             this.itemCount++;
-            if($('no_address_message')){
-                $('no_address_message').hide();
-            }
+            // if($('no_address_message')){
+            //     $('no_address_message').hide();
+            // }
             // preventing duplication of ids for fields and blocks
             while ($$("div[id='form_address_item_" + this.itemCount + "']").length) {
                 this.itemCount++;
             }
             // create new form elements
             Element.insert(this.formContainer, {bottom:
-                '<div id="' + 'form_' + this.baseItemId + this.itemCount + '">'
+                '<div id="' + 'form_' + this.baseItemId + this.itemCount + '" class="address-item-edit-content">'
                 + this.prepareTemplate(this.formTemplate.innerHTML)
                 + '</div>'
             });
@@ -231,7 +244,7 @@ addressesModel.prototype = {
             deleteButtonId ++;
             template    += this.prepareTemplate(this.itemTemplate.innerHTML).replace('delete_button', 'delete_button'+ deleteButtonId);
             template    += '</li>';
-            Element.insert(this.itemContainer, {bottom: template});
+            Element.insert(this.itemContainer.down('.adress-list-actions'), {before: template});
             var newItem = $(this.baseItemId+this.itemCount);
             newItem.isNewAddress = true;
             newItem.formBlock = newForm;
@@ -287,7 +300,7 @@ addressesModel.prototype = {
         var element = Event.findElement(event, 'li'); // find top item
         var elem = Event.element(event); // exact element clicked
 
-        if ( ((elem.tagName.toUpperCase() == 'A') && elem.id.match(/^delete_button([0-9]*?)$/)) || ((elem.tagName.toUpperCase() == 'IMG') && elem.id.match(/^delete_button([0-9]*?)$/)) ) {
+        if ( ((elem.tagName.toUpperCase() == 'BUTTON') && elem.id.match(/^delete_button([0-9]*?)$/)) && elem.id.match(/^delete_button([0-9]*?)$/) ) {
             this.deleteAddress(element);
             Event.stop(event);
         }
@@ -316,22 +329,22 @@ addressesModel.prototype = {
 
     toggleDeleteButton : function(item, flag){
         if(flag){
-            $(item).select('.btn-remove-address').each(Element.show);
+            $(item).select('.action-delete-address').each(Element.show);
             $(item.formBlock).getElementsBySelector('.delete-address').each(Element.show);
         } else {
-            $(item).select('.btn-remove-address').each(Element.hide);
+            $(item).select('.action-delete-address').each(Element.hide);
             $(item.formBlock).getElementsBySelector('.delete-address').each(Element.hide);
         }
     },
 
     setActiveItem : function(item){
         if(this.activeItem){
-            Element.removeClassName(this.activeItem, 'on');
+            Element.removeClassName(this.activeItem, 'active');
             if($('form_'+this.activeItem.id)){
                 Element.hide($('form_'+this.activeItem.id));
             }
         }
-        Element.addClassName(item, 'on');
+        Element.addClassName(item, 'active');
 
         if(item && $('form_'+item.id)){
             $('form_'+item.id).changeRelation = item;
@@ -637,7 +650,4 @@ addressesModel.prototype = {
 customerAddresses = new addressesModel();
 //]]>
 </script>
-</td>
-</tr>
-</table>
-</div>
+
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/customer/tab/view.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/customer/tab/view.phtml
index 82f565cd3ed6d081b4245b7345c860c23d8f0f78..081c97dcacf1f2c7bca4cbe241304324da292036 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/customer/tab/view.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/customer/tab/view.phtml
@@ -37,45 +37,47 @@ $createDateAdmin    = $this->getCreateDate();
 $createDateStore    = $this->getStoreCreateDate();
 ?>
 
-<div class="entry-edit fieldset-wrapper">
+<div class="fieldset-wrapper customer-iformation">
 
     <div class="fieldset-wrapper-title">
         <span class="title"><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Personal Information') ?></span>
     </div>
 
-    <table cellspacing="2">
-        <tr>
-            <td><strong><?php echo $this->__('Last Logged In:') ?></strong></td>
-            <td><?php echo $lastLoginDateAdmin ?> (<?php echo $this->getCurrentStatus() ?>)</td>
-        </tr>
-        <?php if ($lastLoginDateAdmin != $lastLoginDateStore): ?>
-        <tr>
-            <td><strong><?php echo $this->__('Last Logged In (%s):', $this->getStoreLastLoginDateTimezone()) ?></strong></td>
-            <td><?php echo $lastLoginDateStore ?> (<?php echo $this->getCurrentStatus() ?>)</td>
-        </tr>
-        <?php endif; ?>
-        <tr>
-            <td><strong><?php echo $this->__('Confirmed email:') ?></strong></td>
-            <td><?php echo $this->getIsConfirmedStatus() ?></td>
-        </tr>
-        <tr>
-            <td><strong><?php echo $this->__('Account Created on:') ?></strong></td>
-            <td><?php echo $createDateAdmin ?></td>
-        </tr>
-        <?php if ($createDateAdmin != $createDateStore): ?>
-        <tr>
-            <td><strong><?php echo $this->__('Account Created on (%s):', $this->getStoreCreateDateTimezone()) ?></strong></td>
-            <td><?php echo $createDateStore ?></td>
-        </tr>
-        <?php endif; ?>
-        <tr>
-            <td><strong><?php echo $this->__('Account Created in:') ?></strong></td>
-            <td><?php echo $this->getCreatedInStore() ?></td>
-        </tr>
-        <tr>
-            <td><strong><?php echo $this->__('Customer Group:') ?></strong></td>
-            <td><?php echo $this->getGroupName() ?></td>
-        </tr>
+    <table>
+        <tbody>
+            <tr>
+                <th><?php echo $this->__('Last Logged In:') ?></th>
+                <td><?php echo $lastLoginDateAdmin ?> (<?php echo $this->getCurrentStatus() ?>)</td>
+            </tr>
+            <?php if ($lastLoginDateAdmin != $lastLoginDateStore): ?>
+            <tr>
+                <th><?php echo $this->__('Last Logged In (%s):', $this->getStoreLastLoginDateTimezone()) ?></th>
+                <td><?php echo $lastLoginDateStore ?> (<?php echo $this->getCurrentStatus() ?>)</td>
+            </tr>
+            <?php endif; ?>
+            <tr>
+                <th><?php echo $this->__('Confirmed email:') ?></th>
+                <td><?php echo $this->getIsConfirmedStatus() ?></td>
+            </tr>
+            <tr>
+                <th><?php echo $this->__('Account Created on:') ?></th>
+                <td><?php echo $createDateAdmin ?></td>
+            </tr>
+            <?php if ($createDateAdmin != $createDateStore): ?>
+            <tr>
+                <th><?php echo $this->__('Account Created on (%s):', $this->getStoreCreateDateTimezone()) ?></th>
+                <td><?php echo $createDateStore ?></td>
+            </tr>
+            <?php endif; ?>
+            <tr>
+                <th><?php echo $this->__('Account Created in:') ?></th>
+                <td><?php echo $this->getCreatedInStore() ?></td>
+            </tr>
+            <tr>
+                <th><?php echo $this->__('Customer Group:') ?></th>
+                <td><?php echo $this->getGroupName() ?></td>
+            </tr>
+        </tbody>
     </table>
     <address>
         <strong><?php echo $this->__('Default Billing Address') ?></strong><br/>
@@ -83,4 +85,4 @@ $createDateStore    = $this->getStoreCreateDate();
     </address>
 
 </div>
-<?php echo $this->getChildHtml('', true); ?>
+<?php echo $this->getChildHtml('', true); ?>
\ No newline at end of file
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/customer/tab/view/sales.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/customer/tab/view/sales.phtml
index 69775c400f14e851b0fd954785e690b7fa49bc34..5798ae935794105a88dd82321412d9be87510938 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/customer/tab/view/sales.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/customer/tab/view/sales.phtml
@@ -30,66 +30,65 @@
         <span class="title"><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Sales Statistics') ?></span>
     </div>
 
-    <div class="grid">
-        <table cellspacing="0" class="data">
-            <thead>
-                <tr class="headings">
-                    <?php if (!Mage::app()->isSingleStoreMode()): ?>
-                        <th><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Website') ?></th>
-                        <th><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Store') ?></th>
-                        <th><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Store View') ?></th>
-                    <?php endif; ?>
-                    <th><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Lifetime Sales') ?></th>
-                    <th><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Average Sale') ?></th>
+    <table class="data-table">
+        <thead>
+            <tr>
+                <?php if (!Mage::app()->isSingleStoreMode()): ?>
+                    <th><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Website') ?></th>
+                    <th><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Store') ?></th>
+                    <th><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Store View') ?></th>
+                <?php endif; ?>
+                <th><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Lifetime Sales') ?></th>
+                <th class="last"><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('Average Sale') ?></th>
+            </tr>
+        </thead>
+        <?php if (!Mage::app()->isSingleStoreMode()): ?>
+            <tfoot>
+                <tr>
+                    <td colspan="3"><strong><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('All Store Views') ?></strong></td>
+                    <td class="emph"><strong><?php echo $this->formatCurrency($this->getTotals()->getBaseLifetime()) ?></strong></td>
+                    <td class="emph last"><strong><?php echo $this->formatCurrency($this->getTotals()->getAvgsale()) ?></strong></td>
                 </tr>
-            </thead>
-            <?php if (!Mage::app()->isSingleStoreMode()): ?>
-                <tfoot>
-                    <tr>
-                        <td colspan="3" class="label"><strong><big><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('All Store Views') ?></big></strong></td>
-                        <td class="emph"><strong><big><?php echo $this->formatCurrency($this->getTotals()->getBaseLifetime()) ?></big></strong></td>
-                        <td class="emph"><strong><big><?php echo $this->formatCurrency($this->getTotals()->getAvgsale()) ?></big></strong></td>
-                    </tr>
-                </tfoot>
-            <?php endif; ?>
-            <?php if ($this->getRows()): ?>
-            <tbody>
-                <?php $_i = 0; ?>
-                <?php foreach ($this->getRows() as $_websiteId => $_groups): ?>
-                    <?php $_websiteRow = false; ?>
-                    <?php foreach ($_groups as $_groupId => $_stores): ?>
-                        <?php $_groupRow = false; ?>
-                        <?php foreach ($_stores as $_row): ?>
-                            <?php if (!Mage::app()->isSingleStoreMode()): ?>
-                                <?php if ($_row->getStoreId() == 0): ?>
-                                <td colspan="3" class="label"><?php echo $_row->getStoreName() ?></td>
-                                <?php else: ?>
-                        <tr<?php echo ($_i++ % 2 ? ' class="even"' : '') ?>>
-                                <?php if (!$_websiteRow): ?>
-                            <td rowspan="<?php echo $this->getWebsiteCount($_websiteId) ?>"><?php echo $_row->getWebsiteName() ?></td>
-                                    <?php $_websiteRow = true; ?>
-                                <?php endif; ?>
-                                <?php if (!$_groupRow): ?>
-                            <td rowspan="<?php echo count($_stores) ?>"><?php echo $_row->getGroupName() ?></td>
-                                    <?php $_groupRow = true; ?>
-                                <?php endif; ?>
-                            <td class="label"><?php echo $_row->getStoreName() ?></td>
-                                <?php endif; ?>
+            </tfoot>
+        <?php endif; ?>
+        <?php if ($this->getRows()): ?>
+        <tbody>
+            <?php $_i = 0; ?>
+            <?php foreach ($this->getRows() as $_websiteId => $_groups): ?>
+                <?php $_websiteRow = false; ?>
+                <?php foreach ($_groups as $_groupId => $_stores): ?>
+                    <?php $_groupRow = false; ?>
+                    <?php foreach ($_stores as $_row): ?>
+                        <?php if (!Mage::app()->isSingleStoreMode()): ?>
+                            <?php if ($_row->getStoreId() == 0): ?>
+                            <td colspan="3" class="label"><?php echo $_row->getStoreName() ?></td>
                             <?php else: ?>
-                        <tr>
+                    <tr<?php echo ($_i++ % 2 ? ' class="even"' : '') ?>>
+                            <?php if (!$_websiteRow): ?>
+                        <td rowspan="<?php echo $this->getWebsiteCount($_websiteId) ?>"><?php echo $_row->getWebsiteName() ?></td>
+                                <?php $_websiteRow = true; ?>
+                            <?php endif; ?>
+                            <?php if (!$_groupRow): ?>
+                        <td rowspan="<?php echo count($_stores) ?>"><?php echo $_row->getGroupName() ?></td>
+                                <?php $_groupRow = true; ?>
+                            <?php endif; ?>
+                        <td class="label"><?php echo $_row->getStoreName() ?></td>
                             <?php endif; ?>
-                            <td><?php echo $this->formatCurrency($_row->getLifetime(), $_row->getWebsiteId()) ?></td>
-                            <td><?php echo $this->formatCurrency($_row->getAvgsale(), $_row->getWebsiteId()) ?></td>
-                        </tr>
-                        <?php endforeach; ?>
+                        <?php else: ?>
+                    <tr>
+                        <?php endif; ?>
+                        <td><?php echo $this->formatCurrency($_row->getLifetime(), $_row->getWebsiteId()) ?></td>
+                        <td><?php echo $this->formatCurrency($_row->getAvgsale(), $_row->getWebsiteId()) ?></td>
+                    </tr>
                     <?php endforeach; ?>
                 <?php endforeach; ?>
-            </tbody>
-            <?php else: ?>
-            <tbody>
-                <tr class="no-display"><td colspan="<?php echo !Mage::app()->isSingleStoreMode() ? '5' : '2'; ?>"></td></tr>
-            </tbody>
-            <?php endif; ?>
-        </table>
-    </div>
-</div>
+            <?php endforeach; ?>
+        </tbody>
+        <?php else: ?>
+        <tbody>
+            <tr class="hidden"><td colspan="<?php echo !Mage::app()->isSingleStoreMode() ? '5' : '2'; ?>"></td></tr>
+        </tbody>
+        <?php endif; ?>
+    </table>
+
+</div>
\ No newline at end of file
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/main.xml b/app/code/core/Mage/Adminhtml/view/adminhtml/main.xml
index 3d16204850474e6df511b18f6d8e6948bc2ca3d4..6b55fc2a40667dc60cefd4cf3ed38361c9c2ee5b 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/main.xml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/main.xml
@@ -57,7 +57,7 @@ Supported layout update handles (special):
                 <action method="setTitle" translate="title"><title>Magento Admin</title></action>
                 <action method="addJs"><file>jquery/jquery.min.js</file></action>
                 <action method="addJs"><file>mage/jquery-no-conflict.js</file></action>
-                <action method="addJs"><file>jquery/jquery-ui.custom.min.js</file></action>
+                <action method="addJs"><file>jquery/jquery-ui.js</file></action>
                 <action method="addJs"><file>head.load.min.js</file></action>
                 <action method="addJs"><file>mage/mage.js</file></action>
                 <action method="addJs"><file>jquery/jquery.tmpl.min.js</file></action>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/media/uploader.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/media/uploader.phtml
index 73326a1ae91df181f9175c45606e134b2fbc444c..5c4b6441ad50d85fc237f110f1f03d88226a7e11 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/media/uploader.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/media/uploader.phtml
@@ -23,18 +23,16 @@
  * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
-?>
-<?php
-/**
- * @see Mage_Adminhtml_Block_Media_Uploader
- */
+
+/** @var $this Mage_Adminhtml_Block_Media_Uploader */
 ?>
 
 <div id="<?php echo $this->getHtmlId() ?>" class="uploader">
-    <span class="fileinput-button form-buttons">
+    <div class="fileinput-button form-buttons button">
         <span><?php echo Mage::helper('Mage_Adminhtml_Helper_Data')->__('Browse Files...') ?></span>
-        <input id="fileupload" type="file" name="<?php echo $this->getConfig()->getFileField() ?>" data-url="<?php echo $this->getConfig()->getUrl() ?>" multiple>
-    </span>
+        <input id="fileupload" type="file" name="<?php echo $this->getConfig()->getFileField() ?>"
+            data-url="<?php echo $this->getConfig()->getUrl() ?>" multiple="multiple" />
+    </div>
     <div class="clear"></div>
     <div class="no-display" id="<?php echo $this->getHtmlId() ?>-template">
         <div id="{{id}}" class="file-row">
@@ -53,12 +51,13 @@
     $(function () {
         $('#fileupload').fileupload({
             dataType: 'json',
+            dropZone: '#media_gallery_content',
             sequentialUploads: true,
             acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
             maxFileSize: <?php echo Mage::getObjectManager()->get('Magento_File_Size')->getMaxFileSize() ?>,
             add: function(e, data) {
                 $.each(data.files, function (index, file) {
-                    data.fileId =  Math.random().toString(36).substr(2,9);
+                    data.fileId = Math.random().toString(33).substr(2, 18);
                     var progressTmpl = $('#<?php echo $this->getHtmlId(); ?>-template').children(':first').clone();
                     progressTmpl.attr('id', data.fileId);
                     var fileInfoHtml = progressTmpl.html().replace('{{size}}', byteConvert(file.size))
@@ -73,14 +72,14 @@
                 });
             },
             done: function(e, data) {
-                var progressSelector = '#' + data.fileId + ' .progressbar-container .progressbar';
-                $(progressSelector).css('width','100%');
-                if (data.result && !data.result.hasOwnProperty('errorcode')) {
-                    $(progressSelector).removeClass('upload-progress').addClass('upload-success');
-                    <?php echo $this->getConfig()->getMegiaGallery() ?>.handleUploadComplete(data.result);
+                if (data.result && !data.result.error) {
+                    $('#<?php echo $this->getParentBlock()->getHtmlId() ?>').trigger('addItem', data.result);
                 } else {
-                    $(progressSelector).removeClass('upload-progress').addClass('upload-failure');
+                    $('#' + data.fileId)
+                        .delay(2000)
+                        .hide('highlight');
                 }
+                $('#' + data.fileId).remove();
             },
             progress: function(e, data) {
                 var progress = parseInt(data.loaded / data.total * 100, 10);
@@ -88,16 +87,18 @@
                 $(progressSelector).css('width', progress + '%');
             },
             fail: function(e, data) {
-                var progressSelector = '#' + data.fileId + ' .progressbar-container .progressbar';
-                $(progressSelector).removeClass('upload-progress').addClass('upload-failure');
+                var progressSelector = '#' + data.fileId;
+                $(progressSelector).removeClass('upload-progress').addClass('upload-failure')
+                    .delay(2000)
+                    .hide('highlight')
+                    .remove();
             }
         });
         $('#fileupload').fileupload('option', {
             process: [
                 {
                     action: 'load',
-                    fileTypes: /^image\/(gif|jpeg|png)$/,
-                    maxFileSize: <?php echo Mage::getObjectManager()->get('Magento_File_Size')->getMaxFileSize() ?> * 10
+                    fileTypes: /^image\/(gif|jpeg|png)$/
                 },
                 {
                     action: 'resize',
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/page/js/components.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/page/js/components.phtml
index c52ecf8b104c0df9f07ecdbc56ece97614e40f40..7f634169b23cb6b5f3da5f41e09cb7e1d7d75108 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/page/js/components.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/page/js/components.phtml
@@ -77,10 +77,7 @@
         /**
          * Declaration of resources for components (based on previously defined components)
          */
-        .extend('multisuggest', 'suggest',
-            '<?php echo $this->getViewFileUrl('mage/backend/multisuggest.js') ?>'
-        )
-        .extend('treeSuggest', 'multisuggest', [
+        .extend('treeSuggest', 'suggest', [
             '<?php echo $this->getViewFileUrl('jquery/jstree/jquery.hotkeys.js') ?>',
             '<?php echo $this->getViewFileUrl('jquery/jstree/jquery.jstree.js') ?>',
             '<?php echo $this->getViewFileUrl('mage/backend/tree-suggest.js') ?>'
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/poll/answers/list.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/poll/answers/list.phtml
index 82e9b26f525bfe9d117a2686a3997b9d68f4d349..03c1cfbd124035dafe096e1b1cf417e2969b822e 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/poll/answers/list.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/poll/answers/list.phtml
@@ -31,28 +31,28 @@
             <span class="title"><?php echo Mage::helper('Mage_Poll_Helper_Data')->__('Assigned Answers') ?></span>
         </div>
 
-        <div class="field">
+        <div class="field field-poll_answers_container">
             <div class="control">
                 <table class="data-table">
                     <thead>
                         <tr>
-                            <th><?php echo Mage::helper('Mage_Poll_Helper_Data')->__('Answer Title') ?></th>
-                            <th><?php echo Mage::helper('Mage_Poll_Helper_Data')->__('Votes Count') ?></th>
+                            <th class="col-poll_answer_title"><?php echo Mage::helper('Mage_Poll_Helper_Data')->__('Answer Title') ?></th>
+                            <th class="col-poll_votes_count"><?php echo Mage::helper('Mage_Poll_Helper_Data')->__('Votes Count') ?></th>
                             <th class="col-delete"><?php echo Mage::helper('Mage_Poll_Helper_Data')->__('Action') ?></th>
                         </tr>
                     </thead>
-                    <tbody id="answers_container">
+                    <tbody id="poll_answers_list">
                         <?php foreach($answers->getItems() as $_item): ?>
-                        <tr id="poll_answer_fieldset_<?php echo $_item->getId() ?>">
+                        <tr id="poll_answer_item_<?php echo $_item->getId() ?>">
                             <td>
-                                <input type="text" id="answer_<?php echo $_item->getId() ?>" name="answer[<?php echo $_item->getId() ?>][title]" value="<?php echo $this->escapeHtml($_item->getAnswerTitle()) ?>" class="required-entry" />
+                                <input type="text" name="answer[<?php echo $_item->getId() ?>][title]" value="<?php echo $this->escapeHtml($_item->getAnswerTitle()) ?>" class="required-entry" />
                             </td>
                             <td>
-                                <input type="text" id="answer_votes_<?php echo $_item->getId() ?>" name="answer[<?php echo $_item->getId() ?>][votes]" value="<?php echo $_item->getVotesCount() ?>" class="required-entry validate-not-negative-number" />
+                                <input type="text" name="answer[<?php echo $_item->getId() ?>][votes]" value="<?php echo $_item->getVotesCount() ?>" class="required-entry validate-not-negative-number" />
                             </td>
                             <td>
                                 <?php echo $this->getDeleteButtonHtml() ?>
-                                <input type="hidden" id="id_poll_answer_fieldset_<?php echo $_item->getId() ?>" value="<?php echo $_item->getId() ?>" />
+                                <input type="hidden" id="id_poll_answer_item_<?php echo $_item->getId() ?>" value="<?php echo $_item->getId() ?>" />
                             </td>
                         </tr>
                         <?php endforeach; ?>
@@ -75,16 +75,16 @@
 
 
 <script type="text/template" id="templatePollAnswer">
-    <tr id="poll_answer_fieldset_#{id}">
+    <tr id="poll_answer_item_#{id}">
         <td>
-            <input type="text" id="answer_#{id}" name="answer[#{id}][title]" value="" class="required-entry" />
+            <input type="text" name="answer[#{id}][title]" value="" class="required-entry" />
         </td>
         <td>
-            <input type="text" id="answer_votes_#{id}" name="answer[#{id}][votes]" value="0" class="required-entry validate-not-negative-number" />
+            <input type="text" name="answer[#{id}][votes]" value="0" class="required-entry validate-not-negative-number" />
         </td>
         <td>
             <?php echo $this->getDeleteButtonHtml() ?>
-            <input type="hidden" id="id_poll_answer_fieldset_#{id}" value="#{id}" />
+            <input type="hidden" id="id_poll_answer_item_#{id}" value="#{id}" />
         </td>
     </tr>
 </script>
@@ -92,7 +92,7 @@
 
 
 
-<script type="text/template" id="templatePollHidden">
+<script type="text/template" id="templatePollAnswerId">
     <input type="hidden" name="deleteAnswer[]" value="#{id}" />
 </script>
 
@@ -111,8 +111,8 @@
     
         _init: function() {
             this.templatePollAnswer = new Template($('#templatePollAnswer').html());
-            this.templatePollHidden = new Template($('#templatePollHidden').html());
-            this.container = $('#answers_container');
+            this.templatePollAnswerId = new Template($('#templatePollAnswerId').html());
+            this.container = $('#poll_answers_list');
         },
     
         _create: function() {
@@ -139,13 +139,13 @@
 
         deleteAnswer: function(el) {
             if(confirm('<?php echo Mage::helper('Mage_Poll_Helper_Data')->__('Are you sure you want to delete it?') ?>')) {
-                var fieldset = $(el).closest('tr');
-                var hidden = $('#id_' + fieldset.attr("id"));
+                var item = $(el).closest('tr');
+                var hidden = $('#id_' + item.attr("id"));
                 var id = hidden.attr("value");
-                hidden.after(this.templatePollHidden.evaluate({
+                this.container.closest('table').after(this.templatePollAnswerId.evaluate({
                     id: id
                 }));
-                fieldset.hide();
+                item.remove();
             }
         }
     });
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/promo/fieldset.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/promo/fieldset.phtml
index 7e75e2dcfaa17ec51037db60b5c9d69b26fb9bc6..8023ae83eebb6608067715c760d73f747a0f76c5 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/promo/fieldset.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/promo/fieldset.phtml
@@ -32,7 +32,9 @@
     <?php if ($_element->getComment()): ?>
         <p class="comment"><?php echo $this->escapeHtml($_element->getComment()) ?></p>
     <?php endif; ?>
-    <?php echo $_element->getChildrenHtml() ?>
+    <div class="rule-tree-wrapper">
+        <?php echo $_element->getChildrenHtml() ?>
+    </div>
     </fieldset>
 </div>
 <script type="text/javascript">
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/rating.xml b/app/code/core/Mage/Adminhtml/view/adminhtml/rating.xml
index 93d61d25a4e4ec736624680d3188272953fc0e02..283bd16d6eb99a07da177df0dec4ca815b21f40e 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/rating.xml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/rating.xml
@@ -1,6 +1,6 @@
-<?xml version="1.0"?>
-<!--
-/**
+<?xml version="1.0"?>
+<!--
+/**
  * Magento
  *
  * NOTICE OF LICENSE
@@ -17,75 +17,75 @@
  *
  * Do not edit or add to this file if you wish to upgrade Magento to newer
  * versions in the future. If you wish to customize Magento for your
- * needs please refer to http://www.magentocommerce.com for more information.
- *
- * @category    design
- * @package     default_default
- * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
- * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
- */
--->
-<layout>
-    <adminhtml_rating_index>
-        <update handle="formkey"/>
-        <update handle="adminhtml_rating_block"/>
-        <reference name="content">
-            <block type="Mage_Adminhtml_Block_Rating_Rating" name="adminhtml.rating.container"/>
-        </reference>
-    </adminhtml_rating_index>
-
-    <adminhtml_rating_block>
-        <reference name='adminhtml.rating.container'>
-            <block type="Mage_Backend_Block_Widget_Grid" name='adminhtml.rating.grid' as='grid'>
-                <arguments>
-                    <id>ratingsGrid</id>
-                    <dataSource type="object">Mage_Rating_Model_Resource_Rating_Grid_Collection</dataSource>
-                    <default_sort>rating_code</default_sort>
-                    <default_dir>ASC</default_dir>
-                    <save_parameters_in_session>1</save_parameters_in_session>
-                </arguments>
-                <block type='Mage_Backend_Block_Widget_Grid_ColumnSet' name='adminhtml.rating.grid.columnSet' as='grid.columnSet'>
-                    <arguments>
-                        <rowUrl>
-                            <path>*/*/edit</path>
-                            <extraParamsTemplate>
-                                <id>getId</id>
-                            </extraParamsTemplate>
-                        </rowUrl>
-                    </arguments>
-                    <block type='Mage_Backend_Block_Widget_Grid_Column' as='rating_id'>
-                        <arguments>
-                            <header translate='true' module='Mage_Rating'>ID</header>
-                            <align>right</align>
-                            <width>50px</width>
-                            <index>rating_id</index>
-                        </arguments>
-                    </block>
-                    <block type='Mage_Backend_Block_Widget_Grid_Column' as='rating_code'>
-                        <arguments>
-                            <header translate='true' module='Mage_Rating'>Rating Name</header>
-                            <index>rating_code</index>
-                        </arguments>
-                    </block>
-                    <block type='Mage_Backend_Block_Widget_Grid_Column' as='position'>
-                        <arguments>
-                            <header translate='true' module='Mage_Rating'>Sort Order</header>
-                            <align>left</align>
-                            <width>100px</width>
-                            <index>position</index>
-                        </arguments>
-                    </block>
-                    <block type='Mage_Backend_Block_Widget_Grid_Column' as='is_active'>
-                        <arguments>
-                            <header translate='true' module='Mage_Rating'>Is Active</header>
-                            <align>left</align>
-                            <index>is_active</index>
-                            <type>options</type>
-                            <options type="options">Mage_Rating_Model_Resource_Rating_Grid_Statuses</options>
-                        </arguments>
-                    </block>
-                </block>
-            </block>
-        </reference>
-    </adminhtml_rating_block>
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    design
+ * @package     default_default
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<layout>
+    <adminhtml_rating_index>
+        <update handle="formkey"/>
+        <update handle="adminhtml_rating_block"/>
+        <reference name="content">
+            <block type="Mage_Adminhtml_Block_Rating_Rating" name="adminhtml.rating.container"/>
+        </reference>
+    </adminhtml_rating_index>
+
+    <adminhtml_rating_block>
+        <reference name='adminhtml.rating.container'>
+            <block type="Mage_Backend_Block_Widget_Grid" name='adminhtml.rating.grid' as='grid'>
+                <arguments>
+                    <id>ratingsGrid</id>
+                    <dataSource type="object">Mage_Rating_Model_Resource_Rating_Grid_Collection</dataSource>
+                    <default_sort>rating_code</default_sort>
+                    <default_dir>ASC</default_dir>
+                    <save_parameters_in_session>1</save_parameters_in_session>
+                </arguments>
+                <block type='Mage_Backend_Block_Widget_Grid_ColumnSet' name='adminhtml.rating.grid.columnSet' as='grid.columnSet'>
+                    <arguments>
+                        <rowUrl>
+                            <path>*/*/edit</path>
+                            <extraParamsTemplate>
+                                <id>getId</id>
+                            </extraParamsTemplate>
+                        </rowUrl>
+                    </arguments>
+                    <block type='Mage_Backend_Block_Widget_Grid_Column' as='rating_id'>
+                        <arguments>
+                            <header translate='true' module='Mage_Rating'>ID</header>
+                            <align>right</align>
+                            <width>50px</width>
+                            <index>rating_id</index>
+                        </arguments>
+                    </block>
+                    <block type='Mage_Backend_Block_Widget_Grid_Column' as='rating_code'>
+                        <arguments>
+                            <header translate='true' module='Mage_Rating'>Rating Name</header>
+                            <index>rating_code</index>
+                        </arguments>
+                    </block>
+                    <block type='Mage_Backend_Block_Widget_Grid_Column' as='position'>
+                        <arguments>
+                            <header translate='true' module='Mage_Rating'>Sort Order</header>
+                            <align>left</align>
+                            <width>100px</width>
+                            <index>position</index>
+                        </arguments>
+                    </block>
+                    <block type='Mage_Backend_Block_Widget_Grid_Column' as='is_active'>
+                        <arguments>
+                            <header translate='true' module='Mage_Rating'>Is Active</header>
+                            <align>left</align>
+                            <index>is_active</index>
+                            <type>options</type>
+                            <options type="options">Mage_Rating_Model_Resource_Rating_Grid_Statuses</options>
+                        </arguments>
+                    </block>
+                </block>
+            </block>
+        </reference>
+    </adminhtml_rating_block>
 </layout>
\ No newline at end of file
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/rating/detailed.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/rating/detailed.phtml
index b728072f8b3436195618ce6426198ad7a41e8ff6..6d20564ac7598d634a9dac6e4fc09663c4cac200 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/rating/detailed.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/rating/detailed.phtml
@@ -25,37 +25,25 @@
  */
 ?>
 <?php if( $this->getRating() && $this->getRating()->getSize()): ?>
-    <div class="product-review-box">
-        <table cellspacing="0" id="product-review-table">
-            <thead>
-                <tr>
-                    <th>&nbsp;</th>
-                    <th><span class="nobr"><?php echo Mage::helper('Mage_Rating_Helper_Data')->__('1 star') ?></span></th>
-                    <th><span class="nobr"><?php echo Mage::helper('Mage_Rating_Helper_Data')->__('2 stars') ?></span></th>
-                    <th><span class="nobr"><?php echo Mage::helper('Mage_Rating_Helper_Data')->__('3 stars') ?></span></th>
-                    <th><span class="nobr"><?php echo Mage::helper('Mage_Rating_Helper_Data')->__('4 stars') ?></span></th>
-                    <th><span class="nobr"><?php echo Mage::helper('Mage_Rating_Helper_Data')->__('5 stars') ?></span></th>
-                </tr>
-            </thead>
-        <?php $_oddIterator = 1; ?>
-            <tbody>
-            <?php foreach ($this->getRating() as $_rating): ?>
-                <tr class="odd<?php if($_oddIterator == $this->getRating()->getSize()): $_oddIterator = 0; ?> last<?php endif; ?>">
-                    <td class="label"><?php echo $this->escapeHtml($_rating->getRatingCode()) ?></td>
-                <?php $_iterator = 1; ?>
-                <?php $_options = ( $_rating->getRatingOptions() ) ? $_rating->getRatingOptions() : $_rating->getOptions() ?>
-                <?php foreach ($_options as $_option): ?>
-                    <td<?php if($_iterator == 5): ?> class="last"<?php endif; ?>><input type="radio" name="ratings[<?php echo ( $_rating->getVoteId() ) ? $_rating->getVoteId() : $_rating->getId() ?>]" id="<?php echo $this->escapeHtml($_rating->getRatingCode()) ?>_<?php echo $_option->getValue() ?>" value="<?php echo $_option->getId() ?>" <?php if( $this->isSelected($_option, $_rating)): ?>checked="checked"<?php endif; ?> /></td>
-                <?php $_iterator++ ?>
-                <?php endforeach; ?>
-                </tr>
-            <?php $_oddIterator ++; ?>
+    <div class="nested">
+        <?php foreach ($this->getRating() as $_rating): ?>
+        <div class="field field-rating">
+            <label class="label"><span><?php echo $this->escapeHtml($_rating->getRatingCode()) ?></span></label>
+            <?php $_iterator = 1; ?>
+            <?php $_options = ( $_rating->getRatingOptions() ) ? $_rating->getRatingOptions() : $_rating->getOptions() ?>
+            <div class="control">
+            <?php foreach (array_reverse($_options) as $_option): ?>
+                <input type="radio" name="ratings[<?php echo ( $_rating->getVoteId() ) ? $_rating->getVoteId() : $_rating->getId() ?>]" id="<?php echo $this->escapeHtml($_rating->getRatingCode()) ?>_<?php echo $_option->getValue() ?>" value="<?php echo $_option->getId() ?>" <?php if( $this->isSelected($_option, $_rating)): ?>checked="checked"<?php endif; ?> />
+                <label for="<?php echo $this->escapeHtml($_rating->getRatingCode()) ?>_<?php echo $_option->getValue() ?>"><?php echo Mage::helper('Mage_Rating_Helper_Data')->__('%s %s', $_iterator, $_iterator > 1 ? 'stars' : 'star') ?></label>
+            <?php $_iterator++ ?>
             <?php endforeach; ?>
-            </tbody>
-        </table>
+            </div>
+        </div>
+        <?php endforeach; ?>
         <input type="hidden" name="validate_rating" class="validate-rating" value="" />
     </div>
 <script type="text/javascript">
+//@TODO: Fix validation
 //<![CDATA[
     Validation.addAllThese(
     [
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/report/grid/container.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/report/grid/container.phtml
index 7d744da71d16c33c71d15c3a0041d6ce63f5e151..5237b38cac636d551e3994b489b1f5ffe2d221b7 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/report/grid/container.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/report/grid/container.phtml
@@ -24,16 +24,17 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 ?>
-<div class="page-actions"><?php echo $this->getButtonsHtml() ?></div>
-<div>
+<div class="reports-title">
+    <div class="page-actions"><?php echo $this->getButtonsHtml() ?></div>
     <?php echo $this->getChildHtml('store.switcher') ?>
 </div>
-<div>
+
+<div class="reports-content">
     <?php echo $this->getChildHtml('grid.filter.form') ?>
 </div>
-<div>
-    <?php echo $this->getGridHtml() ?>
-</div>
+
+<?php echo $this->getGridHtml() ?>
+
 <script type="text/javascript">
 //<![CDATA[
     jQuery('#filter_form').mage('validation', {errorClass: 'mage-error'});
diff --git a/app/code/core/Mage/Api/Model/Config.php b/app/code/core/Mage/Api/Model/Config.php
index 2abff6da50ec3bc3477fcad7bde54d20b7a25033..18bf0de468533200c5a0fde4bf1114d6fa0cb77d 100644
--- a/app/code/core/Mage/Api/Model/Config.php
+++ b/app/code/core/Mage/Api/Model/Config.php
@@ -62,7 +62,7 @@ class Mage_Api_Model_Config extends Varien_Simplexml_Config
             }
         }
 
-        $config = Mage::getConfig()->loadModulesConfiguration('api.xml');
+        $config = Mage::getSingleton('Mage_Core_Model_Config_Modules_Reader')->loadModulesConfiguration('api.xml');
         $this->setXml($config->getNode('api'));
 
         if (Mage::app()->useCache('config_api')) {
diff --git a/app/code/core/Mage/Api/Model/Wsdl/Config.php b/app/code/core/Mage/Api/Model/Wsdl/Config.php
index b9a5e525cd26de949572229d28b34f97aecb1308..2c14bde8981e04156ad282fb8fe809f0119fa3c1 100644
--- a/app/code/core/Mage/Api/Model/Wsdl/Config.php
+++ b/app/code/core/Mage/Api/Model/Wsdl/Config.php
@@ -114,11 +114,13 @@ class Mage_Api_Model_Wsdl_Config extends Mage_Api_Model_Wsdl_Config_Base
 
             $baseWsdlFile = Mage::getConfig()->getModuleDir('etc', "Mage_Api") . DS . 'wsi.xml';
             $this->loadFile($baseWsdlFile);
-            Mage::getConfig()->loadModulesConfiguration('wsi.xml', $this, $mergeWsdl);
+            Mage::getSingleton('Mage_Core_Model_Config_Modules_Reader')
+                ->loadModulesConfiguration('wsi.xml', $this, $mergeWsdl);
         } else {
             $baseWsdlFile = Mage::getConfig()->getModuleDir('etc', "Mage_Api") . DS . 'wsdl.xml';
             $this->loadFile($baseWsdlFile);
-            Mage::getConfig()->loadModulesConfiguration('wsdl.xml', $this, $mergeWsdl);
+            Mage::getSingleton('Mage_Core_Model_Config_Modules_Reader')
+                ->loadModulesConfiguration('wsdl.xml', $this, $mergeWsdl);
         }
 
         if (Mage::app()->useCache('config')) {
diff --git a/app/code/core/Mage/Backend/Block/System/Config/Form.php b/app/code/core/Mage/Backend/Block/System/Config/Form.php
index 513d5d98775ddf69b3a0ed9a69c3295fb301f76c..8c106444c9532c5fe56e351bf63d583c848c7a0b 100644
--- a/app/code/core/Mage/Backend/Block/System/Config/Form.php
+++ b/app/code/core/Mage/Backend/Block/System/Config/Form.php
@@ -645,16 +645,11 @@ class Mage_Backend_Block_System_Config_Form extends Mage_Backend_Block_Widget_Fo
     protected function _getAdditionalElementTypes()
     {
         return array(
-            'export' => $this->_coreConfig
-                ->getBlockClassName('Mage_Backend_Block_System_Config_Form_Field_Export'),
-            'import' => $this->_coreConfig
-                 ->getBlockClassName('Mage_Backend_Block_System_Config_Form_Field_Import'),
-            'allowspecific' => $this->_coreConfig
-                ->getBlockClassName('Mage_Backend_Block_System_Config_Form_Field_Select_Allowspecific'),
-            'image' => $this->_coreConfig
-                ->getBlockClassName('Mage_Backend_Block_System_Config_Form_Field_Image'),
-            'file' => $this->_coreConfig
-                ->getBlockClassName('Mage_Backend_Block_System_Config_Form_Field_File')
+            'export' => 'Mage_Backend_Block_System_Config_Form_Field_Export',
+            'import' => 'Mage_Backend_Block_System_Config_Form_Field_Import',
+            'allowspecific' => 'Mage_Backend_Block_System_Config_Form_Field_Select_Allowspecific',
+            'image' => 'Mage_Backend_Block_System_Config_Form_Field_Image',
+            'file' => 'Mage_Backend_Block_System_Config_Form_Field_File',
         );
     }
 
diff --git a/app/code/core/Mage/Backend/Block/Template.php b/app/code/core/Mage/Backend/Block/Template.php
index 5a125de297a06141ffb1850c55c364e299644e7c..55e281952c53ed5f5aaebae417fa00caf9372b5e 100644
--- a/app/code/core/Mage/Backend/Block/Template.php
+++ b/app/code/core/Mage/Backend/Block/Template.php
@@ -32,7 +32,6 @@
  * @author     Magento Core Team <core@magentocommerce.com>
  *
  * @SuppressWarnings(PHPMD.NumberOfChildren)
- * @SuppressWarnings(PHPMD.numberOfChildren)
  * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  */
 class Mage_Backend_Block_Template extends Mage_Core_Block_Template
diff --git a/app/code/core/Mage/Backend/Block/Widget.php b/app/code/core/Mage/Backend/Block/Widget.php
index 84f65111337d8342cf640f0172acc6e97c4bb5a8..ccd8a3158df5fce272689cd6db0a90dc228fdbf6 100644
--- a/app/code/core/Mage/Backend/Block/Widget.php
+++ b/app/code/core/Mage/Backend/Block/Widget.php
@@ -30,13 +30,15 @@
  * @category   Mage
  * @package    Mage_Backend
  * @author     Magento Core Team <core@magentocommerce.com>
+ *
+ * @SuppressWarnings(PHPMD.NumberOfChildren)
  */
 class Mage_Backend_Block_Widget extends Mage_Backend_Block_Template
 {
     public function getId()
     {
-        if ($this->getData('id')===null) {
-            $this->setData('id', $this->_helperFactory->get('Mage_Core_Helper_Data')->uniqHash('id_'));
+        if (null === $this->getData('id')) {
+            $this->setData('id', $this->helper('Mage_Core_Helper_Data')->uniqHash('id_'));
         }
         return $this->getData('id');
     }
diff --git a/app/code/core/Mage/Backend/Block/Widget/Form.php b/app/code/core/Mage/Backend/Block/Widget/Form.php
index 7b413bcfbaa2591cb36c7db2eb2a3adff928f8c8..edb4438cb2e2b2213b453362c2cd32fd07b7a7b6 100644
--- a/app/code/core/Mage/Backend/Block/Widget/Form.php
+++ b/app/code/core/Mage/Backend/Block/Widget/Form.php
@@ -28,7 +28,6 @@
  * Backend form widget
  *
  * @SuppressWarnings(PHPMD.NumberOfChildren)
- * @SuppressWarnings(PHPMD.numberOfChildren)
  */
 class Mage_Backend_Block_Widget_Form extends Mage_Backend_Block_Widget
 {
diff --git a/app/code/core/Mage/Backend/Controller/ActionAbstract.php b/app/code/core/Mage/Backend/Controller/ActionAbstract.php
index c052f7eef6b0f911a8a8596ebba0c34e12f49fe5..3c3bb27625a181f4adba8e5413d2bbf843214e63 100644
--- a/app/code/core/Mage/Backend/Controller/ActionAbstract.php
+++ b/app/code/core/Mage/Backend/Controller/ActionAbstract.php
@@ -66,22 +66,22 @@ abstract class Mage_Backend_Controller_ActionAbstract extends Mage_Core_Controll
     /**
      * @param Mage_Core_Controller_Request_Http $request
      * @param Mage_Core_Controller_Response_Http $response
-     * @param string $areaCode
      * @param Magento_ObjectManager $objectManager
      * @param Mage_Core_Controller_Varien_Front $frontController
      * @param Mage_Core_Model_Layout_Factory $layoutFactory
+     * @param string $areaCode
      * @param array $invokeArgs
      */
     public function __construct(
         Mage_Core_Controller_Request_Http $request,
         Mage_Core_Controller_Response_Http $response,
-        $areaCode = null,
         Magento_ObjectManager $objectManager,
         Mage_Core_Controller_Varien_Front $frontController,
         Mage_Core_Model_Layout_Factory $layoutFactory,
+        $areaCode = null,
         array $invokeArgs = array()
     ) {
-        parent::__construct($request, $response, $areaCode, $objectManager, $frontController, $layoutFactory);
+        parent::__construct($request, $response, $objectManager, $frontController, $layoutFactory, $areaCode);
 
         $this->_helper = isset($invokeArgs['helper']) ?
             $invokeArgs['helper'] :
@@ -516,7 +516,7 @@ abstract class Mage_Backend_Controller_ActionAbstract extends Mage_Core_Controll
         $args = func_get_args();
         $expr = new Mage_Core_Model_Translate_Expr(array_shift($args), $this->_getRealModuleName());
         array_unshift($args, $expr);
-        return Mage::app()->getTranslator()->translate($args);
+        return $this->_objectManager->get('Mage_Core_Model_Translate')->translate($args);
     }
 
     /**
diff --git a/app/code/core/Mage/Backend/Controller/Router/Default.php b/app/code/core/Mage/Backend/Controller/Router/Default.php
index e7c11d8133f6b1a2d08bc0b86b1c3dbbddf18701..558105ba9bad44b596121cfe60eaaf270edfbf16 100644
--- a/app/code/core/Mage/Backend/Controller/Router/Default.php
+++ b/app/code/core/Mage/Backend/Controller/Router/Default.php
@@ -49,6 +49,7 @@ class Mage_Backend_Controller_Router_Default extends Mage_Core_Controller_Varien
     /**
      * @param Mage_Core_Controller_Varien_Action_Factory $controllerFactory
      * @param Magento_Filesystem $filesystem
+     * @param Mage_Core_Model_App $app
      * @param string $areaCode
      * @param string $baseController
      * @throws InvalidArgumentException
@@ -56,10 +57,11 @@ class Mage_Backend_Controller_Router_Default extends Mage_Core_Controller_Varien
     public function __construct(
         Mage_Core_Controller_Varien_Action_Factory $controllerFactory,
         Magento_Filesystem $filesystem,
+        Mage_Core_Model_App $app,
         $areaCode,
         $baseController
     ) {
-        parent::__construct($controllerFactory, $filesystem, $areaCode, $baseController);
+        parent::__construct($controllerFactory, $filesystem, $app, $areaCode, $baseController);
 
         $this->_areaFrontName = Mage::helper('Mage_Backend_Helper_Data')->getAreaFrontName();
         if (empty($this->_areaFrontName)) {
@@ -153,7 +155,7 @@ class Mage_Backend_Controller_Router_Default extends Mage_Core_Controller_Varien
     protected function _shouldBeSecure($path)
     {
         return substr((string)Mage::getConfig()->getNode('default/web/unsecure/base_url'), 0, 5) === 'https'
-            || Mage::getStoreConfigFlag('web/secure/use_in_adminhtml', Mage_Core_Model_App::ADMIN_STORE_ID)
+            || Mage::getStoreConfigFlag('web/secure/use_in_adminhtml', Mage_Core_Model_AppInterface::ADMIN_STORE_ID)
                 && substr((string)Mage::getConfig()->getNode('default/web/secure/base_url'), 0, 5) === 'https';
     }
 
@@ -165,7 +167,7 @@ class Mage_Backend_Controller_Router_Default extends Mage_Core_Controller_Varien
      */
     protected function _getCurrentSecureUrl($request)
     {
-        return Mage::app()->getStore(Mage_Core_Model_App::ADMIN_STORE_ID)
+        return Mage::app()->getStore(Mage_Core_Model_AppInterface::ADMIN_STORE_ID)
             ->getBaseUrl('link', true) . ltrim($request->getPathInfo(), '/');
     }
 
diff --git a/app/code/core/Mage/Backend/Controller/System/ConfigAbstract.php b/app/code/core/Mage/Backend/Controller/System/ConfigAbstract.php
index 55b3d89cc9f0ccea92a77aa75f1f91dd12308543..59991cc170e0a846ddc11643c6bda401856eb36f 100644
--- a/app/code/core/Mage/Backend/Controller/System/ConfigAbstract.php
+++ b/app/code/core/Mage/Backend/Controller/System/ConfigAbstract.php
@@ -55,13 +55,13 @@ abstract class Mage_Backend_Controller_System_ConfigAbstract extends Mage_Backen
     /**
      * @param Mage_Core_Controller_Request_Http $request
      * @param Mage_Core_Controller_Response_Http $response
-     * @param string $areaCode
      * @param Magento_ObjectManager $objectManager
      * @param Mage_Core_Controller_Varien_Front $frontController
      * @param Mage_Core_Model_Authorization $authorization
      * @param Mage_Backend_Model_Config_Structure $configStructure
      * @param Mage_Backend_Model_Auth_StorageInterface $authSession
      * @param Mage_Core_Model_Layout_Factory $layoutFactory
+     * @param string $areaCode
      * @param array $invokeArgs
      *
      * @SuppressWarnings(PHPMD.ExcessiveParameterList)
@@ -69,16 +69,16 @@ abstract class Mage_Backend_Controller_System_ConfigAbstract extends Mage_Backen
     public function __construct(
         Mage_Core_Controller_Request_Http $request,
         Mage_Core_Controller_Response_Http $response,
-        $areaCode = null,
         Magento_ObjectManager $objectManager,
         Mage_Core_Controller_Varien_Front $frontController,
         Mage_Core_Model_Authorization $authorization,
         Mage_Backend_Model_Config_Structure $configStructure,
         Mage_Backend_Model_Auth_StorageInterface $authSession,
         Mage_Core_Model_Layout_Factory $layoutFactory,
+        $areaCode = null,
         array $invokeArgs = array()
     ) {
-        parent::__construct($request, $response, $areaCode, $objectManager, $frontController, $layoutFactory,
+        parent::__construct($request, $response, $objectManager, $frontController, $layoutFactory, $areaCode,
             $invokeArgs
         );
 
diff --git a/app/code/core/Mage/Backend/Helper/Data.php b/app/code/core/Mage/Backend/Helper/Data.php
index e7ceb57f646bd8c3d4b39ea1e20e81fdc207bd7c..fd803f30581b3d35e88836ef47352b7bfe453e9b 100644
--- a/app/code/core/Mage/Backend/Helper/Data.php
+++ b/app/code/core/Mage/Backend/Helper/Data.php
@@ -42,10 +42,12 @@ class Mage_Backend_Helper_Data extends Mage_Core_Helper_Abstract
     protected $_areaFrontName = null;
 
     /**
-     * @param array $data
+     * @param Mage_Core_Model_Config $applicationConfig
+     * @param Mage_Core_Model_Translate $translator
      */
-    public function __construct(Mage_Core_Model_Config $applicationConfig)
+    public function __construct(Mage_Core_Model_Config $applicationConfig, Mage_Core_Model_Translate $translator)
     {
+        parent::__construct($translator);
         $this->_config = $applicationConfig;
     }
 
diff --git a/app/code/core/Mage/Backend/Model/Acl/Config.php b/app/code/core/Mage/Backend/Model/Acl/Config.php
index d43d69db13b438c1ece2c75a451c7b3abca8d959..e5418fcc29a06070a820ceb55cd03d8cc0f0efb8 100644
--- a/app/code/core/Mage/Backend/Model/Acl/Config.php
+++ b/app/code/core/Mage/Backend/Model/Acl/Config.php
@@ -53,10 +53,26 @@ class Mage_Backend_Model_Acl_Config implements Mage_Core_Model_Acl_Config_Config
      */
     protected $_reader;
 
-    public function __construct(array $args = array())
-    {
-        $this->_config = isset($args['config']) ? $args['config'] : Mage::getConfig();
-        $this->_cache  = isset($args['cache']) ? $args['cache'] : Mage::app()->getCacheInstance();
+    /**
+     * Module configuration reader
+     *
+     * @var Mage_Core_Model_Config_Modules_Reader
+     */
+    protected $_moduleReader;
+
+    /**
+     * @param Mage_Core_Model_Config $config
+     * @param Mage_Core_Model_Cache $cache
+     * @param Mage_Core_Model_Config_Modules_Reader $moduleReader
+     */
+    public function __construct(
+        Mage_Core_Model_Config $config,
+        Mage_Core_Model_Cache $cache,
+        Mage_Core_Model_Config_Modules_Reader $moduleReader
+    ) {
+        $this->_config = $config;
+        $this->_cache  = $cache;
+        $this->_moduleReader = $moduleReader;
     }
 
     /**
@@ -66,7 +82,7 @@ class Mage_Backend_Model_Acl_Config implements Mage_Core_Model_Acl_Config_Config
      */
     protected function _getAclResourceFiles()
     {
-        $files = $this->_config
+        $files = $this->_moduleReader
             ->getModuleConfigurationFiles('adminhtml' . DIRECTORY_SEPARATOR . 'acl.xml');
         return (array) $files;
     }
diff --git a/app/code/core/Mage/Backend/Model/Config/Backend/Admin/Custom.php b/app/code/core/Mage/Backend/Model/Config/Backend/Admin/Custom.php
index 35bd4cb13144016ee6effe0bbc108c3587ae7ca5..8e8f236e9a4a89ebb3858c95d62d7c0e05faed4b 100644
--- a/app/code/core/Mage/Backend/Model/Config/Backend/Admin/Custom.php
+++ b/app/code/core/Mage/Backend/Model/Config/Backend/Admin/Custom.php
@@ -42,6 +42,33 @@ class Mage_Backend_Model_Config_Backend_Admin_Custom extends Mage_Core_Model_Con
     const XML_PATH_UNSECURE_BASE_LINK_URL   = 'web/unsecure/base_link_url';
     const XML_PATH_SECURE_BASE_LINK_URL     = 'web/secure/base_link_url';
 
+    /**
+     * Writer of configuration storage
+     *
+     * @var Mage_Core_Model_Config_Storage_WriterInterface
+     */
+    protected $_configWriter;
+
+    /**
+     * @param Mage_Core_Model_Event_Manager $eventDispatcher
+     * @param Mage_Core_Model_Cache $cacheManager
+     * @param Mage_Core_Model_Config_Storage_WriterInterface $configWriter
+     * @param Mage_Core_Model_Resource_Abstract $resource
+     * @param Varien_Data_Collection_Db $resourceCollection
+     * @param array $data
+     */
+    public function __construct(
+        Mage_Core_Model_Event_Manager $eventDispatcher,
+        Mage_Core_Model_Cache $cacheManager,
+        Mage_Core_Model_Config_Storage_WriterInterface $configWriter,
+        Mage_Core_Model_Resource_Abstract $resource = null,
+        Varien_Data_Collection_Db $resourceCollection = null,
+        array $data = array()
+    ) {
+        $this->_configWriter = $configWriter;
+        parent::__construct($eventDispatcher, $cacheManager, $resource, $resourceCollection, $data);
+    }
+
     /**
      * Validate value before save
      *
@@ -74,13 +101,13 @@ class Mage_Backend_Model_Config_Backend_Admin_Custom extends Mage_Core_Model_Con
         }
 
         if ($useCustomUrl == 1) {
-            Mage::getConfig()->saveConfig(
+            $this->_configWriter->save(
                 self::XML_PATH_SECURE_BASE_URL,
                 $value,
                 self::CONFIG_SCOPE,
                 self::CONFIG_SCOPE_ID
             );
-            Mage::getConfig()->saveConfig(
+            $this->_configWriter->save(
                 self::XML_PATH_UNSECURE_BASE_URL,
                 $value,
                 self::CONFIG_SCOPE,
diff --git a/app/code/core/Mage/Backend/Model/Config/Backend/Admin/Usecustom.php b/app/code/core/Mage/Backend/Model/Config/Backend/Admin/Usecustom.php
index 2b75f9a50f607d44f57404b1a2ab905864d69e0b..9f801cefdf04137d20a3dc66333c5c3bfcec29b4 100644
--- a/app/code/core/Mage/Backend/Model/Config/Backend/Admin/Usecustom.php
+++ b/app/code/core/Mage/Backend/Model/Config/Backend/Admin/Usecustom.php
@@ -34,6 +34,34 @@
  */
 class Mage_Backend_Model_Config_Backend_Admin_Usecustom extends Mage_Core_Model_Config_Data
 {
+    /**
+     * Writer of configuration storage
+     *
+     * @var Mage_Core_Model_Config_Storage_WriterInterface
+     */
+    protected $_configWriter;
+
+    /**
+     * @param Mage_Core_Model_Event_Manager $eventDispatcher
+     * @param Mage_Core_Model_Cache $cacheManager
+     * @param Mage_Core_Model_Resource_Abstract $resource
+     * @param Varien_Data_Collection_Db $resourceCollection
+     * @param Mage_Core_Model_Config_Storage_WriterInterface $configWriter
+     * @param array $data
+     */
+    public function __construct(
+        Mage_Core_Model_Event_Manager $eventDispatcher,
+        Mage_Core_Model_Cache $cacheManager,
+        Mage_Core_Model_Config_Storage_WriterInterface $configWriter,
+        Mage_Core_Model_Resource_Abstract $resource = null,
+        Varien_Data_Collection_Db $resourceCollection = null,
+        array $data = array()
+    ) {
+        $this->_configWriter = $configWriter;
+        parent::__construct($eventDispatcher, $cacheManager, $resource, $resourceCollection, $data);
+    }
+
+
     /**
      * Validate custom url
      *
@@ -64,12 +92,12 @@ class Mage_Backend_Model_Config_Backend_Admin_Usecustom extends Mage_Core_Model_
         $value = $this->getValue();
 
         if (!$value) {
-            Mage::getConfig()->deleteConfig(
+            $this->_configWriter->delete(
                 Mage_Backend_Model_Config_Backend_Admin_Custom::XML_PATH_SECURE_BASE_URL,
                 Mage_Backend_Model_Config_Backend_Admin_Custom::CONFIG_SCOPE,
                 Mage_Backend_Model_Config_Backend_Admin_Custom::CONFIG_SCOPE_ID
             );
-            Mage::getConfig()->deleteConfig(
+            $this->_configWriter->delete(
                 Mage_Backend_Model_Config_Backend_Admin_Custom::XML_PATH_UNSECURE_BASE_URL,
                 Mage_Backend_Model_Config_Backend_Admin_Custom::CONFIG_SCOPE,
                 Mage_Backend_Model_Config_Backend_Admin_Custom::CONFIG_SCOPE_ID
diff --git a/app/code/core/Mage/Backend/Model/Config/Structure/Reader.php b/app/code/core/Mage/Backend/Model/Config/Structure/Reader.php
index 93402a16b893d4ee4938ddc4cb3cf9cebefb657c..b44e7435bbaec55759923b3c8763b4abe11a2ef2 100644
--- a/app/code/core/Mage/Backend/Model/Config/Structure/Reader.php
+++ b/app/code/core/Mage/Backend/Model/Config/Structure/Reader.php
@@ -45,37 +45,42 @@ class Mage_Backend_Model_Config_Structure_Reader extends Magento_Config_XmlAbstr
     protected $_runtimeValidation;
 
     /**
+     * Structure converter
+     *
      * @var Mage_Backend_Model_Config_Structure_Converter
      */
     protected $_converter;
 
     /**
-     * @var Mage_Core_Model_Config
+     * Module configuration reader
+     *
+     * @var Mage_Core_Model_Config_Modules_Reader
      */
-    protected $_config;
+    protected $_modulesReader;
 
     /**
-     * @param Mage_Core_Model_Config $config
      * @param Mage_Core_Model_Cache $cache
+     * @param Mage_Core_Model_Config_Modules_Reader $moduleReader
      * @param Mage_Backend_Model_Config_Structure_Converter $structureConverter
      * @param bool $runtimeValidation
      */
     public function __construct(
-        Mage_Core_Model_Config $config,
         Mage_Core_Model_Cache $cache,
+        Mage_Core_Model_Config_Modules_Reader $moduleReader,
         Mage_Backend_Model_Config_Structure_Converter $structureConverter,
         $runtimeValidation = true
     ) {
+        $this->_modulesReader = $moduleReader;
         $this->_runtimeValidation = $runtimeValidation;
         $this->_converter = $structureConverter;
-        $this->_config = $config;
 
         if ($cache->canUse('config')
             && ($cachedData = $cache->load(self::CACHE_SYSTEM_CONFIGURATION_STRUCTURE))) {
             $this->_data = unserialize($cachedData);
         } else {
-            $fileNames = $this->_config
-                ->getModuleConfigurationFiles('adminhtml' . DIRECTORY_SEPARATOR . 'system.xml');
+            $fileNames = $this->_modulesReader->getModuleConfigurationFiles(
+                'adminhtml' . DIRECTORY_SEPARATOR . 'system.xml'
+            );
             parent::__construct($fileNames);
 
             if ($cache->canUse('config')) {
@@ -95,7 +100,7 @@ class Mage_Backend_Model_Config_Structure_Reader extends Magento_Config_XmlAbstr
      */
     public function getSchemaFile()
     {
-        return $this->_config->getModuleDir('etc', 'Mage_Backend') . DIRECTORY_SEPARATOR . 'system.xsd';
+        return $this->_modulesReader->getModuleDir('etc', 'Mage_Backend') . DIRECTORY_SEPARATOR . 'system.xsd';
     }
 
     /**
@@ -105,7 +110,7 @@ class Mage_Backend_Model_Config_Structure_Reader extends Magento_Config_XmlAbstr
      */
     public function getPerFileSchemaFile()
     {
-        return $this->_config->getModuleDir('etc', 'Mage_Backend') . DIRECTORY_SEPARATOR . 'system_file.xsd';
+        return $this->_modulesReader->getModuleDir('etc', 'Mage_Backend') . DIRECTORY_SEPARATOR . 'system_file.xsd';
     }
 
     /**
diff --git a/app/code/core/Mage/Backend/Model/Menu/Config.php b/app/code/core/Mage/Backend/Model/Menu/Config.php
index 7ddb751f55fcd45378bb7acf16bd29036de59caa..8d9e0c4d2b4e9e1c60dcc6c048dafc60f14e8a00 100644
--- a/app/code/core/Mage/Backend/Model/Menu/Config.php
+++ b/app/code/core/Mage/Backend/Model/Menu/Config.php
@@ -39,9 +39,9 @@ class Mage_Backend_Model_Menu_Config
     protected $_factory;
 
     /**
-     * @var Mage_Core_Model_Config
+     * @var Mage_Core_Model_Config_Modules_Reader
      */
-    protected $_appConfig;
+    protected $_moduleReader;
 
     /**
      * @var Mage_Core_Model_Event_Manager
@@ -67,7 +67,7 @@ class Mage_Backend_Model_Menu_Config
     /**
      * @param Mage_Core_Model_Cache $cache
      * @param Magento_ObjectManager $factory
-     * @param Mage_Core_Model_Config $config
+     * @param Mage_Core_Model_Config_Modules_Reader $moduleReader
      * @param Mage_Core_Model_Event_Manager $eventManager
      * @param Mage_Core_Model_Logger $logger
      * @param Mage_Backend_Model_Menu_Factory $menuFactory
@@ -75,14 +75,14 @@ class Mage_Backend_Model_Menu_Config
     public function __construct(
         Mage_Core_Model_Cache $cache,
         Magento_ObjectManager $factory,
-        Mage_Core_Model_Config $config,
+        Mage_Core_Model_Config_Modules_Reader $moduleReader,
         Mage_Core_Model_Event_Manager $eventManager,
         Mage_Core_Model_Logger $logger,
         Mage_Backend_Model_Menu_Factory $menuFactory
     ) {
         $this->_cache = $cache;
         $this->_factory = $factory;
-        $this->_appConfig = $config;
+        $this->_moduleReader = $moduleReader;
         $this->_eventManager = $eventManager;
         $this->_logger = $logger;
         $this->_menuFactory = $menuFactory;
@@ -204,7 +204,7 @@ class Mage_Backend_Model_Menu_Config
      */
     public function getMenuConfigurationFiles()
     {
-        $files = $this->_appConfig
+        $files = $this->_moduleReader
             ->getModuleConfigurationFiles('adminhtml' . DIRECTORY_SEPARATOR . 'menu.xml');
         return (array) $files;
     }
diff --git a/app/code/core/Mage/Backend/controllers/Adminhtml/System/Config/SaveController.php b/app/code/core/Mage/Backend/controllers/Adminhtml/System/Config/SaveController.php
index b7f402ec1a1c98b244678a580a0973e86e39dfce..c8607e0aab5249ec9af49cf5d646e2adc101032d 100644
--- a/app/code/core/Mage/Backend/controllers/Adminhtml/System/Config/SaveController.php
+++ b/app/code/core/Mage/Backend/controllers/Adminhtml/System/Config/SaveController.php
@@ -68,7 +68,6 @@ class Mage_Backend_Adminhtml_System_Config_SaveController extends Mage_Backend_C
      *
      * @param Mage_Core_Controller_Request_Http $request
      * @param Mage_Core_Controller_Response_Http $response
-     * @param string $areaCode
      * @param Magento_ObjectManager $objectManager
      * @param Mage_Core_Controller_Varien_Front $frontController
      * @param Mage_Core_Model_Authorization $authorization
@@ -79,6 +78,7 @@ class Mage_Backend_Adminhtml_System_Config_SaveController extends Mage_Backend_C
      * @param Mage_Core_Model_App $app
      * @param Mage_Backend_Model_Auth_StorageInterface $authSession
      * @param Mage_Core_Model_Layout_Factory $layoutFactory
+     * @param string $areaCode
      * @param array $invokeArgs
      *
      * @SuppressWarnings(PHPMD.ExcessiveParameterList)
@@ -86,7 +86,6 @@ class Mage_Backend_Adminhtml_System_Config_SaveController extends Mage_Backend_C
     public function __construct(
         Mage_Core_Controller_Request_Http $request,
         Mage_Core_Controller_Response_Http $response,
-        $areaCode = null,
         Magento_ObjectManager $objectManager,
         Mage_Core_Controller_Varien_Front $frontController,
         Mage_Core_Model_Authorization $authorization,
@@ -97,10 +96,11 @@ class Mage_Backend_Adminhtml_System_Config_SaveController extends Mage_Backend_C
         Mage_Core_Model_App $app,
         Mage_Backend_Model_Auth_StorageInterface $authSession,
         Mage_Core_Model_Layout_Factory $layoutFactory,
+        $areaCode = null,
         array $invokeArgs = array()
     ) {
-        parent::__construct($request, $response, $areaCode, $objectManager, $frontController,
-            $authorization, $configStructure, $authSession, $layoutFactory, $invokeArgs
+        parent::__construct($request, $response, $objectManager, $frontController,
+            $authorization, $configStructure, $authSession, $layoutFactory, $areaCode, $invokeArgs
         );
 
         $this->_authorization = $authorization;
diff --git a/app/code/core/Mage/Backend/etc/config.xml b/app/code/core/Mage/Backend/etc/config.xml
index d68026f3566e609f3ef20ddef52101e29ae52aa2..e29d1f3a5598f3c95a594b10779a8b149dffb8bb 100644
--- a/app/code/core/Mage/Backend/etc/config.xml
+++ b/app/code/core/Mage/Backend/etc/config.xml
@@ -75,6 +75,7 @@
             <preferences>
                 <Mage_Backend_Model_Auth_StorageInterface>Mage_Backend_Model_Auth_Session</Mage_Backend_Model_Auth_StorageInterface>
                 <Mage_Backend_Model_Config_Structure_SearchInterface>Mage_Backend_Model_Config_Structure</Mage_Backend_Model_Config_Structure_SearchInterface>
+                <Mage_Core_Model_Config_Storage_WriterInterface>Mage_Core_Model_Config_Storage_Writer_Db</Mage_Core_Model_Config_Storage_WriterInterface>
             </preferences>
             <Mage_Backend_Model_Config_Structure_Element_Iterator_Tab>
                 <shared>0</shared>
diff --git a/app/code/core/Mage/Backend/view/adminhtml/admin/login.phtml b/app/code/core/Mage/Backend/view/adminhtml/admin/login.phtml
index 909a5e6905e87f446125442663eb3eb4fd220159..27c957ca37eef7021ef128a55ad1f5b1815f4cbd 100644
--- a/app/code/core/Mage/Backend/view/adminhtml/admin/login.phtml
+++ b/app/code/core/Mage/Backend/view/adminhtml/admin/login.phtml
@@ -45,7 +45,7 @@
 
     <script src="<?php echo $this->getViewFileUrl('jquery/jquery.min.js') ?>"></script>
     <script src="<?php echo $this->getViewFileUrl('mage/jquery-no-conflict.js') ?>"></script>
-    <script src="<?php echo $this->getViewFileUrl('jquery/jquery-ui.custom.min.js') ?>"></script>
+    <script src="<?php echo $this->getViewFileUrl('jquery/jquery-ui.js') ?>"></script>
     <script src="<?php echo $this->getViewFileUrl('jquery/jquery.tmpl.min.js') ?>"></script>
     <script src="<?php echo $this->getViewFileUrl('jquery/jquery.validate.js') ?>"></script>
     <script src="<?php echo $this->getViewFileUrl('mage/validation.js') ?>"></script>
diff --git a/app/code/core/Mage/Backend/view/adminhtml/widget/grid/column_set.phtml b/app/code/core/Mage/Backend/view/adminhtml/widget/grid/column_set.phtml
index a9d0f925bef5b99505d0789e008b02b5efbc63b8..51b2daf56b4da6dbf0b47b29889cea373828be15 100644
--- a/app/code/core/Mage/Backend/view/adminhtml/widget/grid/column_set.phtml
+++ b/app/code/core/Mage/Backend/view/adminhtml/widget/grid/column_set.phtml
@@ -106,7 +106,7 @@ $numColumns = sizeof($this->getColumns());
                                 <?php echo (($_html = $_column->getRowField($_item)) != '' ? $_html : '&nbsp;') ?>
                             </td>
                             <?php if ($this->shouldRenderEmptyCell($_item, $_column)):?>
-                                <td colspan="<?php echo $this->getEmptyCellColspan($_item)?>" class="empty-text <?php echo $this->getEmptyTextClass() ?> last"><?php echo $this->getEmptyCellLabel()?></td>
+                                <td colspan="<?php echo $this->getEmptyCellColspan($_item)?>" class="col-no-records <?php echo $this->getEmptyTextClass() ?> last"><?php echo $this->getEmptyCellLabel()?></td>
                             <?php endif;?>
                         <?php endif;?>
                     <?php endforeach; ?>
diff --git a/app/code/core/Mage/Backend/view/adminhtml/widget/grid/container.phtml b/app/code/core/Mage/Backend/view/adminhtml/widget/grid/container.phtml
index 214639b1f07570755979af0970c28c48a87dbc96..f0dc11cb27519a5632d935b4a5fd83231845213d 100644
--- a/app/code/core/Mage/Backend/view/adminhtml/widget/grid/container.phtml
+++ b/app/code/core/Mage/Backend/view/adminhtml/widget/grid/container.phtml
@@ -24,5 +24,7 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 ?>
+<?php if ($this->getButtonsHtml()): ?>
 <div class="page-actions"><?php echo $this->getButtonsHtml() ?></div>
+<?php endif; ?>
 <?php echo $this->getGridHtml() ?>
diff --git a/app/code/core/Mage/Backup/Helper/Data.php b/app/code/core/Mage/Backup/Helper/Data.php
index 241ec496a839f7f1fd780b6eef9d45efa9656472..c15972f140cddf7ed63dc90abb4a556389084d4f 100644
--- a/app/code/core/Mage/Backup/Helper/Data.php
+++ b/app/code/core/Mage/Backup/Helper/Data.php
@@ -60,10 +60,12 @@ class Mage_Backup_Helper_Data extends Mage_Core_Helper_Abstract
     protected $_filesystem;
 
     /**
+     * @param Mage_Core_Model_Translate $translator
      * @param Magento_Filesystem $filesystem
      */
-    public function __construct(Magento_Filesystem $filesystem)
+    public function __construct(Mage_Core_Model_Translate $translator, Magento_Filesystem $filesystem)
     {
+        parent::__construct($translator);
         $this->_filesystem = $filesystem;
     }
 
diff --git a/app/code/core/Mage/Bundle/Block/Catalog/Product/View/Type/Bundle/Option.php b/app/code/core/Mage/Bundle/Block/Catalog/Product/View/Type/Bundle/Option.php
index 85b25f33035691b547b730558d822d55e874524b..d0207e52c364e1a1a52d3519a827e239e3fd15a5 100644
--- a/app/code/core/Mage/Bundle/Block/Catalog/Product/View/Type/Bundle/Option.php
+++ b/app/code/core/Mage/Bundle/Block/Catalog/Product/View/Type/Bundle/Option.php
@@ -235,10 +235,7 @@ class Mage_Bundle_Block_Catalog_Product_View_Type_Bundle_Option extends Mage_Bun
      */
     public function setValidationContainer($elementId, $containerId)
     {
-        return '<script type="text/javascript">
-            $(\'' . $elementId . '\').advaiceContainer = \'' . $containerId . '\';
-            $(\'' . $elementId . '\').callbackFunction  = \'bundle.validationCallback\';
-            </script>';
+        return;
     }
 
     /**
diff --git a/app/code/core/Mage/Bundle/view/adminhtml/js/bundle-product.js b/app/code/core/Mage/Bundle/view/adminhtml/js/bundle-product.js
index c3decb6dbf3029a33df02d10fbe994cbd8efb833..c8ec34d3060aede49434ecbed01abb2b6aec1ce8 100644
--- a/app/code/core/Mage/Bundle/view/adminhtml/js/bundle-product.js
+++ b/app/code/core/Mage/Bundle/view/adminhtml/js/bundle-product.js
@@ -25,7 +25,9 @@
 /*jshint browser:true jquery:true*/
 /*global FORM_KEY*/
 /*global bSelection*/
+/*global $H*/
 (function($) {
+    "use strict";
     $.widget('mage.bundleProduct', {
         _create: function () {
             this._initOptionBoxes();
@@ -97,7 +99,8 @@
                 $selectionGrid.dialog({
                     title: $optionBox.find('input[name$="[title]"]').val() === '' ?
                         'Add Products to New Option' :
-                        'Add Products to Option "' + $optionBox.find('input[name$="[title]"]').val() + '"',
+                        'Add Products to Option "' +
+                            $('<div>').text($optionBox.find('input[name$="[title]"]').val()).html() + '"',
                     autoOpen: false,
                     minWidth: 980,
                     modal: true,
@@ -126,7 +129,7 @@
                             bSelection.gridRemoval.each(
                                 function(pair) {
                                     $optionBox.find('.product-sku').filter(function () {
-                                        return $.trim($(this).text()) == pair.key; // find row by SKU
+                                        return $.trim($(this).text()) === pair.key; // find row by SKU
                                     }).closest('tr').find('button.delete').trigger('click');
                                 }
                             );
diff --git a/app/code/core/Mage/Bundle/view/frontend/bundle.js b/app/code/core/Mage/Bundle/view/frontend/bundle.js
index d223d8aabc370a39fa82ebe9e2bf51bed7bde924..7bcde99b579fe419af7bd5ace199d85cda0f12b3 100644
--- a/app/code/core/Mage/Bundle/view/frontend/bundle.js
+++ b/app/code/core/Mage/Bundle/view/frontend/bundle.js
@@ -100,11 +100,9 @@
                     selected.push(element.val());
                     config.selected[parts[2]] = selected;
                 } else if (element.is('input')) {
-                    if (element.is(":radio")) {
-                        if (element.is(":checked")) {
+                    if (element.is(":radio:checked")) {
                             selected.push(element.val());
                             config.selected[parts[2]] = selected;
-                        }
                     }
                     if (element.is(":checkbox")) {
                         if (element.is(":checked")) {
diff --git a/app/code/core/Mage/Bundle/view/frontend/catalog/product/view/price.phtml b/app/code/core/Mage/Bundle/view/frontend/catalog/product/view/price.phtml
index 038e757e29c9749b2adedc1e188976cd598aa25f..f44199185df02dd79ab541d0a6cc89293e6655ec 100644
--- a/app/code/core/Mage/Bundle/view/frontend/catalog/product/view/price.phtml
+++ b/app/code/core/Mage/Bundle/view/frontend/catalog/product/view/price.phtml
@@ -107,8 +107,10 @@ $canApplyMAP  = Mage::helper('Mage_Catalog_Helper_Data')->canApplyMsrp($_product
 <?php endif; ?>
 <?php if($_product->isSaleable()): ?>
 <script type="text/javascript">
-document.observe("dom:loaded", function() {
-    bundle.reloadPrice();
-});
+        (function ($) {
+            head.js("<?php echo $this->getViewFileUrl('Mage_Bundle::bundle.js') ?>", function () {
+                $('#product_addtocart_form').bundleOption({'optionConfig':<?php echo $this->getJsonConfig()?>});
+            });
+        })(jQuery);
 </script>
 <?php endif; ?>
diff --git a/app/code/core/Mage/Bundle/view/frontend/catalog/product/view/type/bundle.phtml b/app/code/core/Mage/Bundle/view/frontend/catalog/product/view/type/bundle.phtml
index e3730fdf9959542f8cb015d1bfc20a7d1c42f37e..d95356056a9974ecfdd99021a65273173cbab450 100644
--- a/app/code/core/Mage/Bundle/view/frontend/catalog/product/view/type/bundle.phtml
+++ b/app/code/core/Mage/Bundle/view/frontend/catalog/product/view/type/bundle.phtml
@@ -32,10 +32,10 @@
     (function ($) {
         head.js("<?php echo $this->getViewFileUrl('Mage_Bundle::/bundle.js') ?>", function() {
             $('#product_addtocart_form').bundleOption({
-                "bundleConfig": <?php echo $this->getJsonConfig() ?>,
-                "bundleOptionQtyPrefix": "#bundle-option-",
-                "bundleOptionQtySuffix": "-qty-input",
-                "priceSelectors": {
+                bundleConfig: <?php echo $this->getJsonConfig() ?>,
+                bundleOptionQtyPrefix: "#bundle-option-",
+                bundleOptionQtySuffix: "-qty-input",
+                priceSelectors: {
                     "product-price": "#product-price-<?php echo $_product->getId()?>",
                     "bundle-price": "#bundle-price-<?php echo $_product->getId()?>",
                     "price-including-tax": "#price-including-tax-<?php echo $_product->getId()?>",
diff --git a/app/code/core/Mage/Bundle/view/frontend/catalog/product/view/type/bundle/option/checkbox.phtml b/app/code/core/Mage/Bundle/view/frontend/catalog/product/view/type/bundle/option/checkbox.phtml
index 15a25d8ec2ac18c6f8814a9fb93cd232c18e3e2f..bf8793f1b5863931fcae12008aeb8e6258aaf68a 100644
--- a/app/code/core/Mage/Bundle/view/frontend/catalog/product/view/type/bundle/option/checkbox.phtml
+++ b/app/code/core/Mage/Bundle/view/frontend/catalog/product/view/type/bundle/option/checkbox.phtml
@@ -40,9 +40,6 @@
         <?php foreach($_selections as $_selection): ?>
             <li><input class="change-container-classname checkbox bundle-option-<?php echo $_option->getId() ?> product-bundle-option" id="bundle-option-<?php echo $_option->getId() ?>-<?php echo $_selection->getSelectionId() ?>" type="checkbox" <?php if ($_option->getRequired()) echo 'data-validate = {"validate-one-required-by-name":true}'?> name="bundle_option[<?php echo $_option->getId() ?>][]"<?php if ($this->_isSelected($_selection)) echo ' checked="checked"' ?><?php if (!$_selection->isSaleable()) echo ' disabled="disabled"' ?> value="<?php echo $_selection->getSelectionId() ?>"/>
                 <span class="label"><label for="bundle-option-<?php echo $_option->getId() ?>-<?php echo $_selection->getSelectionId() ?>"><?php echo $this->getSelectionQtyTitlePrice($_selection) ?></label></span>
-                <?php if($_option->getRequired()): ?>
-                    <?php echo $this->setValidationContainer('bundle-option-'.$_option->getId().'-'.$_selection->getSelectionId(), 'bundle-option-'.$_option->getId().'-container') ?>
-                <?php endif; ?>
             </li>
         <?php endforeach; ?>
         </ul>
diff --git a/app/code/core/Mage/Bundle/view/frontend/catalog/product/view/type/bundle/option/radio.phtml b/app/code/core/Mage/Bundle/view/frontend/catalog/product/view/type/bundle/option/radio.phtml
index 52a97a731b4ce6612580c23f9254606cba207c8b..b8109820a4360f1d376d63e7c9b35654cb22fdc9 100644
--- a/app/code/core/Mage/Bundle/view/frontend/catalog/product/view/type/bundle/option/radio.phtml
+++ b/app/code/core/Mage/Bundle/view/frontend/catalog/product/view/type/bundle/option/radio.phtml
@@ -50,9 +50,6 @@
         <?php foreach ($_selections as $_selection): ?>
             <li><input type="radio" class="radio change-container-classname product-bundle-option" id="bundle-option-<?php echo $_option->getId() ?>-<?php echo $_selection->getSelectionId() ?>" <?php if ($_option->getRequired()) echo 'data-validate = {"validate-one-required-by-name":true}'?>  name="bundle_option[<?php echo $_option->getId() ?>]"<?php if ($this->_isSelected($_selection)) echo ' checked="checked"' ?><?php if (!$_selection->isSaleable()) echo ' disabled="disabled"' ?>value="<?php echo $_selection->getSelectionId() ?>"/>
             <span class="label"><label for="bundle-option-<?php echo $_option->getId() ?>-<?php echo $_selection->getSelectionId() ?>"><?php echo $this->getSelectionTitlePrice($_selection) ?></label></span>
-            <?php if ($_option->getRequired()): ?>
-                <?php echo $this->setValidationContainer('bundle-option-'.$_option->getId().'-'.$_selection->getSelectionId(), 'bundle-option-'.$_option->getId().'-container') ?>
-            <?php endif; ?>
             </li>
         <?php endforeach; ?>
         </ul>
diff --git a/app/code/core/Mage/Bundle/view/frontend/sales/order/creditmemo/items/renderer.phtml b/app/code/core/Mage/Bundle/view/frontend/sales/order/creditmemo/items/renderer.phtml
index 50c4f6df4dc5380f68d9e1ba324008883cb22d5e..89da8eee76da15cdd23063f3602197675c9f8f3c 100644
--- a/app/code/core/Mage/Bundle/view/frontend/sales/order/creditmemo/items/renderer.phtml
+++ b/app/code/core/Mage/Bundle/view/frontend/sales/order/creditmemo/items/renderer.phtml
@@ -78,7 +78,7 @@
                     <?php endif; ?>
                 <?php endif; ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -115,7 +115,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($this->getItem()->getPrice()+$this->getItem()->getWeeeTaxAppliedAmount()+$this->getItem()->getWeeeTaxDisposition()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -136,7 +136,7 @@
                 <?php endif; ?>
                 <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getPriceInclTax($this->getItem()); ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -173,7 +173,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total Incl. Tax'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($_incl+$this->getItem()->getWeeeTaxAppliedAmount()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -205,7 +205,7 @@
                         <?php endif; ?>
                     <?php endif; ?>
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                     <?php else: ?>
                         <span class="cart-price">
                     <?php endif; ?>
@@ -242,7 +242,7 @@
                         </span>
 
                         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                            <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                            <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                                 <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($this->getItem()->getRowTotal()+$this->getItem()->getWeeeTaxAppliedRowAmount()+$this->getItem()->getWeeeTaxRowDisposition()); ?></span>
                             </span>
                         <?php endif; ?>
diff --git a/app/code/core/Mage/Bundle/view/frontend/sales/order/invoice/items/renderer.phtml b/app/code/core/Mage/Bundle/view/frontend/sales/order/invoice/items/renderer.phtml
index 608a7a38c42c2ff3636b966c37548c1cd6f498e1..2e9aa7a507f45f102901f712dbf1c1ff3c768095 100644
--- a/app/code/core/Mage/Bundle/view/frontend/sales/order/invoice/items/renderer.phtml
+++ b/app/code/core/Mage/Bundle/view/frontend/sales/order/invoice/items/renderer.phtml
@@ -75,7 +75,7 @@
                     <?php endif; ?>
                 <?php endif; ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -112,7 +112,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($this->getItem()->getPrice()+$this->getItem()->getWeeeTaxAppliedAmount()+$this->getItem()->getWeeeTaxDisposition()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -133,7 +133,7 @@
                 <?php endif; ?>
                 <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getPriceInclTax($this->getItem()); ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -170,7 +170,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($_incl+$this->getItem()->getWeeeTaxAppliedAmount()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -202,7 +202,7 @@
                     <?php endif; ?>
                 <?php endif; ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -239,7 +239,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($this->getItem()->getRowTotal()+$this->getItem()->getWeeeTaxAppliedRowAmount()+$this->getItem()->getWeeeTaxRowDisposition()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -260,7 +260,7 @@
                 <?php endif; ?>
                 <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getSubtotalInclTax($this->getItem()); ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -296,7 +296,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($_incl+$this->getItem()->getWeeeTaxAppliedRowAmount()); ?></span>
                         </span>
                     <?php endif; ?>
diff --git a/app/code/core/Mage/Bundle/view/frontend/sales/order/items/renderer.phtml b/app/code/core/Mage/Bundle/view/frontend/sales/order/items/renderer.phtml
index f2487579274eb28a8c9cfd308bb4c1b68972f368..c2a8461bba75f24286ed42ca368e3277099adce6 100644
--- a/app/code/core/Mage/Bundle/view/frontend/sales/order/items/renderer.phtml
+++ b/app/code/core/Mage/Bundle/view/frontend/sales/order/items/renderer.phtml
@@ -74,7 +74,7 @@
                     <?php endif; ?>
                 <?php endif; ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -111,7 +111,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($this->getItem()->getPrice()+$this->getItem()->getWeeeTaxAppliedAmount()+$this->getItem()->getWeeeTaxDisposition()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -132,7 +132,7 @@
                 <?php endif; ?>
                 <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getPriceInclTax($this->getItem()); ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -169,7 +169,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($_incl+$this->getItem()->getWeeeTaxAppliedAmount()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -217,7 +217,7 @@
                     <?php endif; ?>
                 <?php endif; ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -254,7 +254,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($this->getItem()->getRowTotal()+$this->getItem()->getWeeeTaxAppliedRowAmount()+$this->getItem()->getWeeeTaxRowDisposition()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -275,7 +275,7 @@
                 <?php endif; ?>
                 <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getSubtotalInclTax($this->getItem()); ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -311,7 +311,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total Incl. Tax'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($_incl+$this->getItem()->getWeeeTaxAppliedRowAmount()); ?></span>
                         </span>
                     <?php endif; ?>
diff --git a/app/code/core/Mage/Captcha/Block/Captcha/Zend.php b/app/code/core/Mage/Captcha/Block/Captcha/Default.php
similarity index 95%
rename from app/code/core/Mage/Captcha/Block/Captcha/Zend.php
rename to app/code/core/Mage/Captcha/Block/Captcha/Default.php
index 42a9534a3ad8ac21026d3d1e9def4feb266876ad..88dbdb37b93be839cfe1e06308a0c63616f5560e 100755
--- a/app/code/core/Mage/Captcha/Block/Captcha/Zend.php
+++ b/app/code/core/Mage/Captcha/Block/Captcha/Default.php
@@ -31,9 +31,9 @@
  * @package    Mage_Captcha
  * @author     Magento Core Team <core@magentocommerce.com>
  */
-class Mage_Captcha_Block_Captcha_Zend extends Mage_Core_Block_Template
+class Mage_Captcha_Block_Captcha_Default extends Mage_Core_Block_Template
 {
-    protected $_template = 'zend.phtml';
+    protected $_template = 'default.phtml';
 
     /**
      * @var string
diff --git a/app/code/core/Mage/Captcha/Helper/Data.php b/app/code/core/Mage/Captcha/Helper/Data.php
index 34131609db0ff2e1d12c9979677cb927e1750119..875388ed137b829035b5a65cae0617688db2f37c 100755
--- a/app/code/core/Mage/Captcha/Helper/Data.php
+++ b/app/code/core/Mage/Captcha/Helper/Data.php
@@ -89,17 +89,21 @@ class Mage_Captcha_Helper_Data extends Mage_Core_Helper_Abstract
      * @param Mage_Core_Model_App $app
      * @param Mage_Core_Model_Config $config
      * @param Magento_Filesystem $filesystem
+     * @param Mage_Core_Model_Translate $translator
      */
     public function __construct(
         Mage_Core_Model_Dir $dirs,
         Mage_Core_Model_App $app,
         Mage_Core_Model_Config $config,
-        Magento_Filesystem $filesystem
+        Magento_Filesystem $filesystem,
+        Mage_Core_Model_Translate $translator
     ) {
+    
         $this->_dirs = $dirs;
         $this->_app = $app;
         $this->_config = $config;
         $this->_filesystem = $filesystem;
+        parent::__construct($translator);
     }
 
     /**
diff --git a/app/code/core/Mage/Captcha/Model/Zend.php b/app/code/core/Mage/Captcha/Model/Default.php
similarity index 98%
rename from app/code/core/Mage/Captcha/Model/Zend.php
rename to app/code/core/Mage/Captcha/Model/Default.php
index 2d177c897376c29dbdac526920f0463ee74ca2a7..5ec89fa683f1f1c3a5b4269278df6c3c2abd38ce 100755
--- a/app/code/core/Mage/Captcha/Model/Zend.php
+++ b/app/code/core/Mage/Captcha/Model/Default.php
@@ -31,7 +31,7 @@
  * @package    Mage_Captcha
  * @author     Magento Core Team <core@magentocommerce.com>
  */
-class Mage_Captcha_Model_Zend extends Zend_Captcha_Image implements Mage_Captcha_Model_Interface
+class Mage_Captcha_Model_Default extends Zend_Captcha_Image implements Mage_Captcha_Model_Interface
 {
     /**
      * Key in session for captcha code
@@ -120,7 +120,7 @@ class Mage_Captcha_Model_Zend extends Zend_Captcha_Image implements Mage_Captcha
      */
     public function getBlockName()
     {
-        return 'Mage_Captcha_Block_Captcha_Zend';
+        return 'Mage_Captcha_Block_Captcha_Default';
     }
 
 
@@ -336,7 +336,7 @@ class Mage_Captcha_Model_Zend extends Zend_Captcha_Image implements Mage_Captcha
      * log Attempt
      *
      * @param string $login
-     * @return Mage_Captcha_Model_Zend
+     * @return Mage_Captcha_Model_Default
      */
     public function logAttempt($login)
     {
diff --git a/app/code/core/Mage/Captcha/etc/config.xml b/app/code/core/Mage/Captcha/etc/config.xml
index 9dfceb9e55efaa325f9c36d405d3323b55d42622..b6df2889aca4a7a150a5f1728b3602b286f86772 100755
--- a/app/code/core/Mage/Captcha/etc/config.xml
+++ b/app/code/core/Mage/Captcha/etc/config.xml
@@ -185,7 +185,7 @@
         </system>
         <admin>
             <captcha>
-                <type>zend</type>
+                <type>default</type>
                 <enable>0</enable>
                 <font>linlibertine</font>
                 <mode>after_fail</mode>
@@ -203,7 +203,7 @@
         </admin>
         <customer>
             <captcha>
-                <type>zend</type>
+                <type>default</type>
                 <enable>0</enable>
                 <font>linlibertine</font>
                 <mode>after_fail</mode>
diff --git a/app/code/core/Mage/Captcha/view/adminhtml/zend.phtml b/app/code/core/Mage/Captcha/view/adminhtml/default.phtml
similarity index 97%
rename from app/code/core/Mage/Captcha/view/adminhtml/zend.phtml
rename to app/code/core/Mage/Captcha/view/adminhtml/default.phtml
index 4c8ead547c4c7c9dc82fa979d2548344f1dc0872..3aa9f35c7f19b595ffa59a5f8099e43e52975180 100644
--- a/app/code/core/Mage/Captcha/view/adminhtml/zend.phtml
+++ b/app/code/core/Mage/Captcha/view/adminhtml/default.phtml
@@ -25,7 +25,7 @@
  */
 ?>
 <?php $captcha = $this->getCaptchaModel() ?>
-<?php /* @var $this Mage_Core_Block_Captcha_Zend */ ?>
+<?php /* @var $this Mage_Core_Block_Captcha_Default */ ?>
 <div class="clear"></div>
 <div class="captcha">
     <div class="captcha-input input-box input-left">
diff --git a/app/code/core/Mage/Captcha/view/frontend/captcha.js b/app/code/core/Mage/Captcha/view/frontend/captcha.js
index 9a64912705fb1de5b5a3641954c9037c8760d188..dd6ef9edd81b5c94c59c88535642286c1cc33bb1 100644
--- a/app/code/core/Mage/Captcha/view/frontend/captcha.js
+++ b/app/code/core/Mage/Captcha/view/frontend/captcha.js
@@ -23,30 +23,45 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 /*jshint browser:true jquery:true*/
-(function ($, undefined) {
+(function($, undefined) {
+    "use strict";
     $.widget('mage.captcha', {
         options: {
-            refreshClass: 'refreshing'
+            refreshClass: 'refreshing',
+            reloadSelector: '.captcha-reload',
+            imageSelector: '.captcha-img'
         },
-        _create: function () {
-            this.element.on('click', $.proxy(this.refresh, this));
+
+        /**
+         * Method binds click event to reload image
+         * @private
+         */
+        _create: function() {
+            this.element.on('click', this.options.reloadSelector, $.proxy(this.refresh, this));
         },
-        refresh: function () {
-            this.element.addClass(this.options.refreshClass);
+
+        /**
+         * Method triggeres an AJAX request to refresh the CAPTCHA image
+         * @param e - Event
+         */
+        refresh: function(e) {
+            var reloadImage = $(e.currentTarget);
+            reloadImage.addClass(this.options.refreshClass);
             $.ajax({
                 url: this.options.url,
                 type: 'post',
                 dataType: 'json',
                 context: this,
-                data: {'formId': this.options.formSelector.replace(/^(#|.)/, "")},
+                data: {
+                    'formId': this.options.type
+                },
                 success: function (response) {
                     if (response.imgSrc) {
-                        $(this.options.formSelector).attr('src', response.imgSrc);
+                        this.element.find(this.options.imageSelector).attr('src', response.imgSrc);
                     }
-                    this.element.removeClass(this.options.refreshClass);
                 },
-                error: function () {
-                    this.element.removeClass(this.options.refreshClass);
+                complete: function() {
+                    reloadImage.removeClass(this.options.refreshClass);
                 }
             });
         }
diff --git a/app/code/core/Mage/Captcha/view/frontend/zend.phtml b/app/code/core/Mage/Captcha/view/frontend/default.phtml
similarity index 74%
rename from app/code/core/Mage/Captcha/view/frontend/zend.phtml
rename to app/code/core/Mage/Captcha/view/frontend/default.phtml
index b10b0172c2737e811b3259ca9bb65fae3c3a3535..13c56a091cf2951d491eca92774eda782ea0e9b5 100644
--- a/app/code/core/Mage/Captcha/view/frontend/zend.phtml
+++ b/app/code/core/Mage/Captcha/view/frontend/default.phtml
@@ -24,20 +24,20 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 ?>
-<?php /* @var $this Mage_Core_Block_Captcha_Zend */ ?>
+<?php /* @var $this Mage_Core_Block_Captcha_Default */ ?>
 
-<?php /* @var $captcha Mage_Core_Model_Captcha_Zend */ ?>
+<?php /* @var $captcha Mage_Core_Model_Captcha_Default */ ?>
 <?php $captcha = $this->getCaptchaModel() ?>
-<li id="captcha-input-box-<?php echo $this->getFormId()?>">
+<li role="<?php echo $this->getFormId()?>">
     <label for="captcha_<?php echo $this->getFormId() ?>" class="required"><em>*</em><?php echo $this->__('Please type the letters below')?></label>
     <div class="input-box captcha">
         <input name="<?php echo Mage_Captcha_Helper_Data::INPUT_NAME_FIELD_VALUE ?>[<?php echo $this->getFormId()?>]" type="text" class="input-text required-entry" data-validate="{required:true}" id="captcha_<?php echo $this->getFormId() ?>" />
     </div>
 </li>
-<li id="captcha-image-box-<?php echo $this->getFormId()?>">
+<li role="<?php echo $this->getFormId()?>" id="captcha-container-<?php echo $this->getFormId()?>">
     <div class="captcha-image">
-        <img id="captcha-reload" class="captcha-reload" src="<?php echo $this->getViewFileUrl('Mage_Captcha::reload.png') ?>" alt="<?php echo $this->__('Reload captcha') ?>">
-        <img id="<?php echo $this->getFormId() ?>" class="captcha-img" height="<?php echo $this->getImgHeight() ?>" src="<?php echo $captcha->getImgSrc() ?>"/>
+        <img class="captcha-reload" src="<?php echo $this->getViewFileUrl('Mage_Captcha::reload.png') ?>" alt="<?php echo $this->__('Reload captcha') ?>">
+        <img class="captcha-img" height="<?php echo $this->getImgHeight() ?>" src="<?php echo $captcha->getImgSrc() ?>"/>
         <?php if ($captcha->isCaseSensitive()) :?>
         <div class="captcha-note">
             <?php echo $this->__('<strong>Attention</strong>: Captcha is case sensitive.') ?>
@@ -47,9 +47,9 @@
     <script type="text/javascript">//<![CDATA[
     (function ($) {
         head.js("<?php echo $this->getViewFileUrl('Mage_Captcha::captcha.js') ?>",function() {
-            $('#captcha-reload').captcha({
+            $('#captcha-container-<?php echo $this->getFormId()?>').captcha({
                 url: '<?php echo $this->getRefreshUrl()?>',
-                formSelector: '#<?php echo $this->getFormId()?>'
+                type: '<?php echo $this->getFormId() ?>'
             });
         });
     })(jQuery);
diff --git a/app/code/core/Mage/Captcha/view/frontend/onepage.js b/app/code/core/Mage/Captcha/view/frontend/onepage.js
index 679744983840317421f09c29e02967d2b8381d56..b4b8675feb9e0ad73e218b53281d8f7cff83b70a 100644
--- a/app/code/core/Mage/Captcha/view/frontend/onepage.js
+++ b/app/code/core/Mage/Captcha/view/frontend/onepage.js
@@ -17,42 +17,42 @@
  * versions in the future. If you wish to customize Magento for your
  * needs please refer to http://www.magentocommerce.com for more information.
  *
- * @category    design
- * @package     base_default
+ * @category    mage
+ * @package     captcha
  * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
-document.observe('billing-request:completed', function(event) {
-    if (typeof window.checkout != 'undefined') {
-        if (window.checkout.method == 'guest' && $('guest_checkout')){
-            $('guest_checkout').captcha.refresh()
-        }
-        if (window.checkout.method == 'register' && $('register_during_checkout')){
-            $('register_during_checkout').captcha.refresh()
-        }
-    }
-});
+/*jshint browser:true jquery:true*/
+(function($, window, document, undefined) {
+    "use strict";
 
+    $(document).on("login:setMethod", function() {
+        $("[role='guest_checkout'], [role='register_during_checkout']").hide();
+        var type = ($("#login\\:guest").is(':checked')) ? 'guest_checkout' : 'register_during_checkout';
+        $("[role='" + type + "']").show();
+    });
 
-document.observe('login:setMethod', function(event) {
-    var switchCaptchaElement = function(shown, hidden) {
-        var inputPrefix = 'captcha-input-box-', imagePrefix = 'captcha-image-box-';
-        if ($(inputPrefix + hidden)) {
-            $(inputPrefix + hidden).hide();
-            $(imagePrefix + hidden).hide();
+    $(document).on('billing-request:completed', function() {
+        if (typeof window.checkout !== 'undefined') {
+            $(".captcha-reload:visible").trigger("click");
         }
-        if ($(inputPrefix + shown)) {
-            $(inputPrefix + shown).show();
-            $(imagePrefix + shown).show();
-        }
-    };
+    });
+})(jQuery, window, document);
 
-    switch (event.memo.method) {
-        case 'guest':
-            switchCaptchaElement('guest_checkout', 'register_during_checkout');
-            break;
-        case 'register':
-            switchCaptchaElement('register_during_checkout', 'guest_checkout');
-            break;
-    }
+/**
+ * Need to remove when we refactor onepage checkout
+ * @deprecated
+ */
+document.observe('login:setMethod', function() {
+    "use strict";
+    jQuery(document).trigger('login:setMethod');
 });
+
+/**
+ * Need to remove when we refactor onepage checkout
+ * @deprecated
+ */
+document.observe('billing-request:completed', function() {
+    "use strict";
+    jQuery(document).trigger('billing-request:completed');
+});
\ No newline at end of file
diff --git a/app/code/core/Mage/Catalog/Block/Product/Configurable/AttributeSelector.php b/app/code/core/Mage/Catalog/Block/Product/Configurable/AttributeSelector.php
index 64a19f28e944fbd6496ea128bd6c1e7361f3eb89..07590add4a86e845daad35f6337000a5982593ad 100644
--- a/app/code/core/Mage/Catalog/Block/Product/Configurable/AttributeSelector.php
+++ b/app/code/core/Mage/Catalog/Block/Product/Configurable/AttributeSelector.php
@@ -71,22 +71,27 @@ class Mage_Catalog_Block_Product_Configurable_AttributeSelector extends Mage_Bac
     }
 
     /**
-     * Configurable attribute suggestion action URL
+     * Attribute set creation action URL
      *
      * @return string
      */
-    public function getSuggestUrl()
+    public function getAttributeSetCreationUrl()
     {
-        return $this->getUrl('*/catalog_product_attribute/suggestConfigurableAttributes');
+        return $this->getUrl('*/catalog_product_set/save');
     }
 
     /**
-     * Attribute set creation action URL
+     * Get options for suggest widget
      *
-     * @return string
+     * @return array
      */
-    public function getAttributeSetCreationUrl()
+    public function getSuggestWidgetOptions()
     {
-        return $this->getUrl('*/catalog_product_set/save');
+        return array(
+            'source' => $this->getUrl('*/catalog_product_attribute/suggestConfigurableAttributes'),
+            'template' => '#configurable-attribute-selector-template',
+            'minLength' => 0,
+            'className' => 'category-select',
+        );
     }
 }
diff --git a/app/code/core/Mage/Catalog/Block/Product/TemplateSelector.php b/app/code/core/Mage/Catalog/Block/Product/TemplateSelector.php
new file mode 100644
index 0000000000000000000000000000000000000000..530fba93a0815c35791a2da6e507209d38322062
--- /dev/null
+++ b/app/code/core/Mage/Catalog/Block/Product/TemplateSelector.php
@@ -0,0 +1,62 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_Catalog
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Product gallery
+ *
+ * @category   Mage
+ * @package    Mage_Catalog
+ * @author     Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_Catalog_Block_Product_TemplateSelector extends Mage_Core_Block_Template
+{
+    /**
+     * Retrieve list of product templates with search part contained in label
+     *
+     * @param string $labelPart
+     * @return array
+     */
+    public function getSuggestedTemplates($labelPart)
+    {
+        $product = Mage::registry('product');
+        $entityType = $product->getResource()->getEntityType();
+        $labelPart = Mage::getResourceHelper('Mage_Core')->addLikeEscape($labelPart, array('position' => 'any'));
+        $collection = Mage::getResourceModel('Mage_Eav_Model_Resource_Entity_Attribute_Set_Collection')
+            ->setEntityTypeFilter($entityType->getId())
+            ->addFieldToFilter('attribute_set_name', array('like' => $labelPart))
+            ->addFieldToSelect('attribute_set_id', 'id')
+            ->addFieldToSelect('attribute_set_name', 'label')
+            ->setOrder('attribute_set_name', Mage_Eav_Model_Resource_Entity_Attribute_Set_Collection::SORT_ORDER_ASC);
+        $result = $collection->getData();
+        foreach ($result as $key => $set) {
+            if ($set['id'] == $this->getRequest()->getParam('current_template_id')) {
+                unset($result[$key]);
+                break;
+            }
+        }
+        return $result;
+    }
+}
diff --git a/app/code/core/Mage/Catalog/Helper/Output.php b/app/code/core/Mage/Catalog/Helper/Output.php
index 0a2b08e0ae7ca1114b8f285bd8c958bacae4bebc..1c2c76a77ba9ba72f0b442ffd6bcb233db1ec3e2 100644
--- a/app/code/core/Mage/Catalog/Helper/Output.php
+++ b/app/code/core/Mage/Catalog/Helper/Output.php
@@ -41,10 +41,11 @@ class Mage_Catalog_Helper_Output extends Mage_Core_Helper_Abstract
     protected $_templateProcessor = null;
 
     /**
-     * Constructor
+     * @param Mage_Core_Model_Translate $translator
      */
-    public function __construct()
+    public function __construct(Mage_Core_Model_Translate $translator)
     {
+        parent::__construct($translator);
         Mage::dispatchEvent('catalog_helper_output_construct', array('helper'=>$this));
     }
 
diff --git a/app/code/core/Mage/Catalog/Helper/Product/Url.php b/app/code/core/Mage/Catalog/Helper/Product/Url.php
index 557f1c13dbcd48b66d0efde5a8af375394e0de6c..0e38fec0ce8c514cf644d6afefc7a03d781463c0 100644
--- a/app/code/core/Mage/Catalog/Helper/Product/Url.php
+++ b/app/code/core/Mage/Catalog/Helper/Product/Url.php
@@ -97,10 +97,14 @@ class Mage_Catalog_Helper_Product_Url extends Mage_Core_Helper_Url
 
     /**
      * Check additional instruction for convertation table in configuration
+     *
+     * @param Mage_Core_Model_Translate $translator
+     * @param Mage_Core_Model_Config $config
      */
-    public function __construct()
+    public function __construct(Mage_Core_Model_Translate $translator, Mage_Core_Model_Config $config)
     {
-        $convertNode = Mage::getConfig()->getNode('default/url/convert');
+        parent::__construct($translator);
+        $convertNode = $config->getNode('default/url/convert');
         if ($convertNode) {
             foreach ($convertNode->children() as $node) {
                 $this->_convertTable[strval($node->from)] = strval($node->to);
diff --git a/app/code/core/Mage/Catalog/Helper/Product/View.php b/app/code/core/Mage/Catalog/Helper/Product/View.php
index 0289f89c3a5ad193a76c645895f89bc7e69643ea..6a47172a86c0bd2ae6fa5e6359c50e1dd0664143 100644
--- a/app/code/core/Mage/Catalog/Helper/Product/View.php
+++ b/app/code/core/Mage/Catalog/Helper/Product/View.php
@@ -50,17 +50,17 @@ class Mage_Catalog_Helper_Product_View extends Mage_Core_Helper_Abstract
     protected $_config;
 
     /**
-     * Constructor dependency injection
-     *
+     * @param Mage_Core_Model_Translate $translator
+     * @param Mage_Core_Model_Config $config
      * @param array $data
      */
-    public function __construct(array $data = array())
-    {
-        if (isset($data['config'])) {
-            $this->_config = $data['config'];
-        } else {
-            $this->_config = Mage::getConfig();
-        }
+    public function __construct(
+        Mage_Core_Model_Translate $translator,
+        Mage_Core_Model_Config $config,
+        array $data = array()
+    ) {
+        parent::__construct($translator);
+        $this->_config = $config;
     }
 
     /**
diff --git a/app/code/core/Mage/Catalog/Model/Category.php b/app/code/core/Mage/Catalog/Model/Category.php
index 1f4a8b9b7eb9024cf955f37670be21b42215f6c4..7087ad97a8c54bc5319132b7a2bd57787e2e65f8 100644
--- a/app/code/core/Mage/Catalog/Model/Category.php
+++ b/app/code/core/Mage/Catalog/Model/Category.php
@@ -383,13 +383,13 @@ class Mage_Catalog_Model_Category extends Mage_Catalog_Model_Abstract
     /**
      * Set store id
      *
-     * @param integer $storeId
+     * @param int|string $storeId
      * @return Mage_Catalog_Model_Category
      */
     public function setStoreId($storeId)
     {
         if (!is_numeric($storeId)) {
-            $storeId = Mage::app($storeId)->getStore()->getId();
+            $storeId = Mage::app()->getStore($storeId)->getId();
         }
         $this->setData('store_id', $storeId);
         $this->getResource()->setStoreId($storeId);
diff --git a/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Media.php b/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Media.php
index c04904896e8b4516172561bbe9175c949b850035..4ea23e340a438df96963b2701d406f7c4f1bb126 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Media.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Attribute/Backend/Media.php
@@ -179,7 +179,7 @@ class Mage_Catalog_Model_Product_Attribute_Backend_Media extends Mage_Eav_Model_
             foreach ($value['images'] as &$image) {
                 if (!empty($image['removed'])) {
                     $clearImages[] = $image['file'];
-                } elseif (!isset($image['value_id'])) {
+                } else if (empty($image['value_id'])) {
                     $newFile                   = $this->_moveImageFromTmp($image['file']);
                     $image['new_file'] = $newFile;
                     $newImages[$image['file']] = $image;
@@ -193,7 +193,7 @@ class Mage_Catalog_Model_Product_Attribute_Backend_Media extends Mage_Eav_Model_
             // For duplicating we need copy original images.
             $duplicate = array();
             foreach ($value['images'] as &$image) {
-                if (!isset($image['value_id'])) {
+                if (empty($image['value_id'])) {
                     continue;
                 }
                 $duplicate[$image['value_id']] = $this->_copyImage($image['file']);
@@ -259,7 +259,7 @@ class Mage_Catalog_Model_Product_Attribute_Backend_Media extends Mage_Eav_Model_
         $storeId = $object->getStoreId();
 
         $storeIds = $object->getStoreIds();
-        $storeIds[] = Mage_Core_Model_App::ADMIN_STORE_ID;
+        $storeIds[] = Mage_Core_Model_AppInterface::ADMIN_STORE_ID;
 
         // remove current storeId
         $storeIds = array_flip($storeIds);
@@ -278,13 +278,13 @@ class Mage_Catalog_Model_Product_Attribute_Backend_Media extends Mage_Eav_Model_
         $filesToValueIds = array();
         foreach ($value['images'] as &$image) {
             if (!empty($image['removed'])) {
-                if (isset($image['value_id']) && !isset($picturesInOtherStores[$image['file']])) {
+                if (!empty($image['value_id']) && !isset($picturesInOtherStores[$image['file']])) {
                     $toDelete[] = $image['value_id'];
                 }
                 continue;
             }
 
-            if (!isset($image['value_id'])) {
+            if (empty($image['value_id'])) {
                 $data = array();
                 $data['entity_id']      = $object->getId();
                 $data['attribute_id']   = $this->getAttribute()->getId();
diff --git a/app/code/core/Mage/Catalog/Model/Product/Type.php b/app/code/core/Mage/Catalog/Model/Product/Type.php
index 25dd3d938f52adac05d1ecb2ca01b7628a5b7156..37914bf62650ee2ac64e30bdd592f8d87cf99374 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Type.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Type.php
@@ -26,14 +26,10 @@
 
 /**
  * Product type model
- *
- * @category    Mage
- * @package     Mage_Catalog
- * @author      Magento Core Team <core@magentocommerce.com>
  */
 class Mage_Catalog_Model_Product_Type
 {
-    /**
+    /**#@+
      * Available product types
      */
     const TYPE_SIMPLE       = 'simple';
@@ -41,14 +37,49 @@ class Mage_Catalog_Model_Product_Type
     const TYPE_CONFIGURABLE = 'configurable';
     const TYPE_GROUPED      = 'grouped';
     const TYPE_VIRTUAL      = 'virtual';
+    /**#@-*/
 
+    /**
+     * Default product type
+     */
     const DEFAULT_TYPE      = 'simple';
+
+    /**
+     * Default product type model
+     */
     const DEFAULT_TYPE_MODEL    = 'Mage_Catalog_Model_Product_Type_Simple';
+
+    /**
+     * Default price model
+     */
     const DEFAULT_PRICE_MODEL   = 'Mage_Catalog_Model_Product_Type_Price';
 
+    /**
+     * Product types
+     *
+     * @var array|string
+     */
     static protected $_types;
+
+    /**
+     * Composite product type Ids
+     *
+     * @var array
+     */
     static protected $_compositeTypes;
+
+    /**
+     * Price models
+     *
+     * @var array
+     */
     static protected $_priceModels;
+
+    /**
+     * Product types by type indexing priority
+     *
+     * @var array
+     */
     static protected $_typesPriority;
 
     /**
@@ -99,6 +130,11 @@ class Mage_Catalog_Model_Product_Type
         return self::$_priceModels[$productType];
     }
 
+    /**
+     * Get product type labels array
+     *
+     * @return array
+     */
     static public function getOptionArray()
     {
         $options = array();
@@ -109,17 +145,27 @@ class Mage_Catalog_Model_Product_Type
         return $options;
     }
 
+    /**
+     * Get product type labels array with empty value
+     *
+     * @return array
+     */
     static public function getAllOption()
     {
         $options = self::getOptionArray();
-        array_unshift($options, array('value'=>'', 'label'=>''));
+        array_unshift($options, array('value' => '', 'label' => ''));
         return $options;
     }
 
+    /**
+     * Get product type labels array with empty value for option element
+     *
+     * @return array
+     */
     static public function getAllOptions()
     {
         $res = array();
-        $res[] = array('value'=>'', 'label'=>'');
+        $res[] = array('value' => '', 'label' => '');
         foreach (self::getOptionArray() as $index => $value) {
             $res[] = array(
                'value' => $index,
@@ -129,6 +175,11 @@ class Mage_Catalog_Model_Product_Type
         return $res;
     }
 
+    /**
+     * Get product type labels array for option element
+     *
+     * @return array
+     */
     static public function getOptions()
     {
         $res = array();
@@ -141,16 +192,28 @@ class Mage_Catalog_Model_Product_Type
         return $res;
     }
 
+    /**
+     * Get product type label
+     *
+     * @param string $optionId
+     * @return null|string
+     */
     static public function getOptionText($optionId)
     {
         $options = self::getOptionArray();
         return isset($options[$optionId]) ? $options[$optionId] : null;
     }
 
+    /**
+     * Get product types
+     *
+     * @return array
+     */
     static public function getTypes()
     {
         if (is_null(self::$_types)) {
-            $productTypes = Mage::getConfig()->getNode('global/catalog/product/type')->asArray();
+            $config = Mage::getObjectManager()->get('Mage_Core_Model_Config_Modules');
+            $productTypes = $config->getNode('global/catalog/product/type')->asArray();
             foreach ($productTypes as $productKey => $productConfig) {
                 $moduleName = 'Mage_Catalog_Helper_Data';
                 if (isset($productConfig['@']['module'])) {
@@ -175,7 +238,7 @@ class Mage_Catalog_Model_Product_Type
         if (is_null(self::$_compositeTypes)) {
             self::$_compositeTypes = array();
             $types = self::getTypes();
-            foreach ($types as $typeId=>$typeInfo) {
+            foreach ($types as $typeId => $typeInfo) {
                 if (array_key_exists('composite', $typeInfo) && $typeInfo['composite']) {
                     self::$_compositeTypes[] = $typeId;
                 }
@@ -193,26 +256,26 @@ class Mage_Catalog_Model_Product_Type
     {
         if (is_null(self::$_typesPriority)) {
             self::$_typesPriority = array();
-            $a = array();
-            $b = array();
+            $simplePriority = array();
+            $compositePriority = array();
 
             $types = self::getTypes();
             foreach ($types as $typeId => $typeInfo) {
                 $priority = isset($typeInfo['index_priority']) ? abs(intval($typeInfo['index_priority'])) : 0;
                 if (!empty($typeInfo['composite'])) {
-                    $b[$typeId] = $priority;
+                    $compositePriority[$typeId] = $priority;
                 } else {
-                    $a[$typeId] = $priority;
+                    $simplePriority[$typeId] = $priority;
                 }
             }
 
-            asort($a, SORT_NUMERIC);
-            asort($b, SORT_NUMERIC);
+            asort($simplePriority, SORT_NUMERIC);
+            asort($compositePriority, SORT_NUMERIC);
 
-            foreach (array_keys($a) as $typeId) {
+            foreach (array_keys($simplePriority) as $typeId) {
                 self::$_typesPriority[$typeId] = $types[$typeId];
             }
-            foreach (array_keys($b) as $typeId) {
+            foreach (array_keys($compositePriority) as $typeId) {
                 self::$_typesPriority[$typeId] = $types[$typeId];
             }
         }
diff --git a/app/code/core/Mage/Catalog/Model/Product/Type/Configurable.php b/app/code/core/Mage/Catalog/Model/Product/Type/Configurable.php
index 1309196453742114b41a5ca566257a7971f8f94c..6864255500d9d6b285068abf6ca8dd04c93728c4 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Type/Configurable.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Type/Configurable.php
@@ -979,7 +979,7 @@ class Mage_Catalog_Model_Product_Type_Configurable extends Mage_Catalog_Model_Pr
         Mage_Catalog_Model_Product $parentProduct,
         $postData
     ) {
-        $product->setStoreId(Mage_Core_Model_App::ADMIN_STORE_ID)
+        $product->setStoreId(Mage_Core_Model_AppInterface::ADMIN_STORE_ID)
             ->setTypeId($postData['weight']
                 ? Mage_Catalog_Model_Product_Type::TYPE_SIMPLE
                 : Mage_Catalog_Model_Product_Type::TYPE_VIRTUAL
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Category/Flat.php b/app/code/core/Mage/Catalog/Model/Resource/Category/Flat.php
index 5b1243ee60949520547ae7abaa1162e0cbfaa7f8..a62cd8d614c0362b06874e40de315855d8022cda 100755
--- a/app/code/core/Mage/Catalog/Model/Resource/Category/Flat.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Category/Flat.php
@@ -438,7 +438,7 @@ class Mage_Catalog_Model_Resource_Category_Flat extends Mage_Index_Model_Resourc
         if ($this->_isBuilt === null) {
             $defaultStoreView = Mage::app()->getDefaultStoreView();
             if ($defaultStoreView === null) {
-                $defaultStoreId = Mage_Core_Model_App::ADMIN_STORE_ID;
+                $defaultStoreId = Mage_Core_Model_AppInterface::ADMIN_STORE_ID;
             } else {
                 $defaultStoreId = $defaultStoreView->getId();
             }
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Category/Tree.php b/app/code/core/Mage/Catalog/Model/Resource/Category/Tree.php
index ace02926bd3758712452087e72225bd3801d2a60..639ecb35997b510914ee05473ce1b3a8f12ba4e4 100755
--- a/app/code/core/Mage/Catalog/Model/Resource/Category/Tree.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Category/Tree.php
@@ -602,7 +602,7 @@ class Mage_Catalog_Model_Resource_Category_Tree extends Varien_Data_Tree_Dbp
                         array($tableDefault => $attribute->getBackend()->getTable()),
                         sprintf('%1$s.entity_id=e.entity_id AND %1$s.attribute_id=%2$d'
                             . ' AND %1$s.entity_type_id=e.entity_type_id AND %1$s.store_id=%3$d',
-                            $tableDefault, $attribute->getId(), Mage_Core_Model_App::ADMIN_STORE_ID),
+                            $tableDefault, $attribute->getId(), Mage_Core_Model_AppInterface::ADMIN_STORE_ID),
                         array($attributeCode => 'value'))
                     ->joinLeft(
                         array($tableStore => $attribute->getBackend()->getTable()),
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Flat/Indexer.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Flat/Indexer.php
index 3ea964bf15d43c09d6268b7474e65fde68d67c50..d65f9ad3ece73868e467c181adb7760fbd8ed05f 100755
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Flat/Indexer.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Flat/Indexer.php
@@ -799,7 +799,7 @@ class Mage_Catalog_Model_Resource_Product_Flat_Indexer extends Mage_Index_Model_
                 array())
             ->where('t1.entity_type_id = :entity_type_id')
             ->where('t1.attribute_id = :attribute_id')
-            ->where('t1.store_id = ?', Mage_Core_Model_App::ADMIN_STORE_ID)
+            ->where('t1.store_id = ?', Mage_Core_Model_AppInterface::ADMIN_STORE_ID)
             ->where("{$fieldExpr} = ?", Mage_Catalog_Model_Product_Status::STATUS_ENABLED);
         foreach ($this->getAttributes() as $attributeCode => $attribute) {
             /** @var $attribute Mage_Eav_Model_Entity_Attribute */
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Status.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Status.php
index 1c1d487469f5d3c0f121cb5047e83bded9fc2d2a..b4dbdeffe7f9dadd19fe9292d350f2799348b49b 100755
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Status.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Status.php
@@ -195,7 +195,7 @@ class Mage_Catalog_Model_Resource_Product_Status extends Mage_Core_Model_Resourc
                     't1.entity_id = t2.entity_id AND t1.attribute_id = t2.attribute_id AND t2.store_id = ' . (int)$storeId,
                     array('t1.entity_id')
                 )
-                ->where('t1.store_id = ?', Mage_Core_Model_App::ADMIN_STORE_ID)
+                ->where('t1.store_id = ?', Mage_Core_Model_AppInterface::ADMIN_STORE_ID)
                 ->where('t1.attribute_id = ?', $attribute->getAttributeId())
                 ->where('t1.entity_id IN(?)', $productIds);
             $rows = $adapter->fetchPairs($select);
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable.php
index 3cc8512e8f998a24ccf9ab913213da32c9dd2365..795a926b65c14c5692e7b9b579cf37b254cd0833 100755
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Type/Configurable.php
@@ -204,7 +204,7 @@ class Mage_Catalog_Model_Resource_Product_Type_Configurable extends Mage_Core_Mo
                     ),
                     implode(' AND ', array(
                         'option_value.option_id = entity_value.value',
-                        'option_value.store_id = ' . Mage_Core_Model_App::ADMIN_STORE_ID,
+                        'option_value.store_id = ' . Mage_Core_Model_AppInterface::ADMIN_STORE_ID,
                     )),
                     array()
                 )->joinLeft(
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Setup.php b/app/code/core/Mage/Catalog/Model/Resource/Setup.php
index 9f99684ce73de07a306131b93f1c053834e2dca9..c72d5bdc6065df36ad420a146b45ad72d649c2b7 100755
--- a/app/code/core/Mage/Catalog/Model/Resource/Setup.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Setup.php
@@ -35,13 +35,22 @@
 class Mage_Catalog_Model_Resource_Setup extends Mage_Eav_Model_Entity_Setup
 {
     /**
-     * Add Minimal attribute set id to exclude list
-     *
-     * @param string $resourceName
+     * @param Mage_Core_Model_Config_Resource $resourcesConfig
+     * @param Mage_Core_Model_Config_Modules $modulesConfig
+     * @param Mage_Core_Model_Resource $resource
+     * @param Mage_Core_Model_Config_Modules_Reader $modulesReader
+     * @param Mage_Core_Model_Cache $cache
+     * @param $resourceName
      */
-    public function __construct($resourceName)
-    {
-        parent::__construct($resourceName);
+    public function __construct(
+        Mage_Core_Model_Config_Resource $resourcesConfig,
+        Mage_Core_Model_Config_Modules $modulesConfig,
+        Mage_Core_Model_Resource $resource,
+        Mage_Core_Model_Config_Modules_Reader $modulesReader,
+        Mage_Core_Model_Cache $cache,
+        $resourceName
+    ) {
+        parent::__construct($resourcesConfig, $modulesConfig, $resource, $modulesReader, $cache, $resourceName);
         $entityTypeForMinimal = $this->getEntityType('Minimal', 'entity_type_id');
         if (is_numeric($entityTypeForMinimal)) {
             $minimalAttributeSetId = $this->getAttributeSet(
diff --git a/app/code/core/Mage/Catalog/view/adminhtml/js/grouped-product.js b/app/code/core/Mage/Catalog/view/adminhtml/js/grouped-product.js
index 950855a5f0ac8f78e3222fa0a8a48b0a9627ac0f..38812a6d236e79f2fd859cc1ac393f86c9f2dc32 100644
--- a/app/code/core/Mage/Catalog/view/adminhtml/js/grouped-product.js
+++ b/app/code/core/Mage/Catalog/view/adminhtml/js/grouped-product.js
@@ -24,6 +24,7 @@
  */
 /*jshint browser:true jquery:true*/
 (function($) {
+    'use strict';
     $.widget('mage.groupedProduct', {
         _create: function () {
             this.$grid = this.element.find('#grouped_grid');
@@ -75,13 +76,13 @@
                 $('#grouped-product-popup').dialog('open');
                 return false;
             });
-            this.$grid.on('click', '.product-delete button', function (event) {
+            this.$grid.on('click', '.product-delete button', function () {
                 $(this).closest('tr').hide().addClass('ignore-validate');
                 widget._updatePopupGrid();
                 widget._updateHiddenField(widget._getSelectedIds());
                 widget._updateGridVisibility();
             });
-            this.$grid.on('change keyup', 'input[type="text"]', function (event) {
+            this.$grid.on('change keyup', 'input[type="text"]', function () {
                 widget._updateHiddenField(widget._getSelectedIds());
             });
             this.options.grid.rowClickCallback = function () {};
diff --git a/app/code/core/Mage/Catalog/view/adminhtml/js/new-category-dialog.js b/app/code/core/Mage/Catalog/view/adminhtml/js/new-category-dialog.js
new file mode 100644
index 0000000000000000000000000000000000000000..6ba6a4466c59f52c80cefd2f05cac7004f479c22
--- /dev/null
+++ b/app/code/core/Mage/Catalog/view/adminhtml/js/new-category-dialog.js
@@ -0,0 +1,129 @@
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_Catalog
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+/*jshint browser:true jquery:true*/
+/*global FORM_KEY*/
+/*global Validation*/
+(function($) {
+    'use strict';
+    $.widget('mage.treeSuggestOneChoice', $.mage.treeSuggest, {
+        /**
+         * @override
+         * @todo refactor parent widget to make this possible without method overriding
+         */
+        _selectItem: function() {
+            $(this.elementWrapper).siblings('.category-selector-search-choice').trigger('removeOption');
+            this._superApply(arguments);
+            this._hideDropdown();
+        }
+    });
+
+    $.widget('mage.newCategoryDialog', {
+        _create: function () {
+            var widget = this;
+            $('#new_category_parent').after($('<input>', {
+                id: 'new_category_parent-suggest',
+                placeholder: 'start typing to search category'
+            }));
+            $('#new_category_parent-suggest').treeSuggestOneChoice(this.options.suggestOptions);
+
+            /* @todo rewrite using jQuery validation */
+            Validation.add('validate-parent-category', 'Choose existing category.', function() {
+                return $('#new_category_parent').val() || $('#new_category_parent-suggest').val() === '';
+            });
+            var newCategoryForm = new Validation(this.element.get(0));
+
+            this.element.dialog({
+                title: 'Create New Category',
+                autoOpen: false,
+                minWidth: 560,
+                dialogClass: 'mage-new-category-dialog',
+                modal: true,
+                multiselect: true,
+                resizable: false,
+                open: function() {
+                    var enteredName = $('#category_ids + .category-selector-container .category-selector-input').val();
+                    $('#new_category_name').val(enteredName);
+                    if (enteredName === '') {
+                        $('#new_category_name').focus();
+                    }
+                    $('#new_category_messages').html('');
+                },
+                close: function() {
+                    $('#new_category_name, #new_category_parent').val('');
+                    newCategoryForm.reset();
+                    $('#category_ids + .category-selector-container .category-selector-input').focus();
+                },
+                buttons: [{
+                    text: 'Cancel',
+                    id: 'mage-new-category-dialog-close-button',
+                    click: function() {
+                        $(this).dialog('close');
+                    }
+                }, {
+                    text: 'Save',
+                    id: 'mage-new-category-dialog-save-button',
+                    click: function() {
+                        if (!newCategoryForm.validate()) {
+                            return;
+                        }
+
+                        $.ajax({
+                            type: 'POST',
+                            url: widget.options.saveCategoryUrl,
+                            data: {
+                                general: {
+                                    name: $('#new_category_name').val(),
+                                    is_active: 1,
+                                    include_in_menu: 0
+                                },
+                                parent: $('#new_category_parent').val(),
+                                use_config: ['available_sort_by', 'default_sort_by'],
+                                form_key: FORM_KEY,
+                                return_session_messages_only: 1
+                            },
+                            dataType: 'json',
+                            context: $('body')
+                        })
+                            .success(
+                                function (data) {
+                                    if (!data.error) {
+                                        $('#category_ids-suggest').treeSuggest('selectItem', {
+                                            id: data.category.entity_id,
+                                            label: data.category.name
+                                        });
+                                        $('#new_category_name, #new_category_parent').val('');
+                                        $('#category_ids + .category-selector-container .category-selector-input').val('');
+                                        widget.element.dialog('close');
+                                    } else {
+                                        $('#new_category_messages').html(data.messages);
+                                    }
+                                }
+                            );
+                    }
+                }]
+            });
+        }
+    });
+})(jQuery);
diff --git a/app/code/core/Mage/Catalog/view/adminhtml/js/product-gallery.js b/app/code/core/Mage/Catalog/view/adminhtml/js/product-gallery.js
new file mode 100644
index 0000000000000000000000000000000000000000..c314f82de3f3674c7c586af1f6a236c7bddfee7e
--- /dev/null
+++ b/app/code/core/Mage/Catalog/view/adminhtml/js/product-gallery.js
@@ -0,0 +1,328 @@
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    mage
+ * @package     mage
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+/*jshint jquery:true*/
+(function($) {
+    "use strict";
+    /**
+     * Product gallery widget
+     */
+    $.widget('mage.productGallery', {
+        options: {
+            imageSelector: '[data-role="image"]',
+            template: '.image-template',
+            types: null,
+            initialized: false
+        },
+
+        /**
+         * Gallery creation
+         * @protected
+         */
+        _create: function() {
+            this.options.types = this.options.types || this.element.data('types');
+            this.options.images = this.options.images || this.element.data('images');
+            this.$template = this.element.find(this.options.template);
+            this._bind();
+            $.each(this.options.images, $.proxy(function(index, imageData) {
+                this.element.trigger('addItem', imageData);
+            }, this));
+            this.options.initialized = true;
+        },
+
+        /**
+         * Bind handler to elements
+         * @protected
+         */
+        _bind: function() {
+            var events = {
+                addItem: '_addItem',
+                removeItem: '_removeItem',
+                setImageType: '_setImageType',
+                setPosition: '_setPosition',
+                resort: '_resort',
+                'click [data-role="delete-button"]': function(event) {
+                    event.preventDefault();
+                    var $imageContainer = $(event.currentTarget).closest(this.options.imageSelector);
+                    this.element.trigger('removeItem', $imageContainer.data('imageData'));
+                },
+                'click [data-role="make-main-button"]': function(event) {
+                    event.preventDefault();
+                    var $imageContainer = $(event.currentTarget).closest(this.options.imageSelector);
+                    var imageData = $imageContainer.data('imageData');
+                    this.setMain(imageData);
+                },
+                'change [data-role="type-selector"]': '_changeType',
+                'change [data-role="visibility-trigger"]': '_changeVisibility'
+            };
+            events['click ' + this.options.imageSelector] = function() {
+                $(event.currentTarget).toggleClass('active');
+            };
+            this._on(events);
+
+            this.element.sortable({
+                distance: 8,
+                items: this.options.imageSelector,
+                tolerance: "pointer",
+                cancel: 'input, button, .ui-dialog, .uploader',
+                update: $.proxy(function() {
+                    this.element.trigger('resort');
+                }, this)
+            });
+        },
+
+        /**
+         * Change visibility
+         *
+         * @param event
+         * @private
+         */
+        _changeVisibility: function(event) {
+            var $checkbox = $(event.currentTarget);
+            var $imageContainer = $checkbox.closest(this.options.imageSelector);
+            $imageContainer.toggleClass('disabled', $checkbox.is(':checked'));
+        },
+
+        /**
+         * Set image as main
+         * @param {Object} imageData
+         * @private
+         */
+        setMain: function(imageData) {
+            var baseImage = this.options.types.image;
+            var sameImages = $.grep(
+                $.map(this.options.types, function(el) {
+                    return el;
+                }),
+                function(el) {
+                    return el.value == baseImage.value;
+                }
+            );
+
+            $.each(sameImages, $.proxy(function(index, image) {
+                this.element.trigger('setImageType', {
+                    type: image.code,
+                    imageData: imageData
+                });
+            }, this));
+        },
+
+        /**
+         * Set image
+         * @param event
+         * @private
+         */
+        _changeType: function(event) {
+            var $checkbox = $(event.currentTarget);
+            var $imageContainer = $checkbox.closest(this.options.imageSelector);
+            this.element.trigger('setImageType', {
+                type: $checkbox.val(),
+                imageData: $checkbox.is(':checked') ? $imageContainer.data('imageData') : null
+            });
+        },
+
+        /**
+         * Find element by fileName
+         * @param {Object} data
+         * @returns {Element}
+         */
+        findElement: function(data) {
+            return this.element.find(this.options.imageSelector).filter(function() {
+                return $(this).data('imageData').file == data.file;
+            }).first();
+        },
+
+        /**
+         * Add image
+         * @param event
+         * @param imageData
+         * @private
+         */
+        _addItem: function(event, imageData) {
+            var count = this.element.find(this.options.imageSelector).length;
+            imageData = $.extend({
+                file_id: Math.random().toString(33).substr(2, 18),
+                disabled: 0,
+                position: count + 1
+            }, imageData);
+
+            var element = this.$template.tmpl(imageData).data('imageData', imageData);
+            if (count === 0) {
+                element.prependTo(this.element);
+            } else {
+                element.insertAfter(this.element.find(this.options.imageSelector + ':last'));
+            }
+
+            if (!this.options.initialized && this.options.images.length === 0 ||
+                this.options.initialized && this.element.find(this.options.imageSelector + ':not(.removed)').length == 1
+            ) {
+                this.setMain(imageData);
+            }
+            $.each(this.options.types, $.proxy(function(index, image) {
+                if (imageData.file == image.value) {
+                    this.element.trigger('setImageType', {
+                        type: image.code,
+                        imageData: imageData
+                    });
+                }
+            }, this));
+        },
+
+        /**
+         * Remove Image
+         * @param {jQuery.Event} event
+         * @param imageData
+         * @private
+         */
+        _removeItem: function(event, imageData) {
+            var $imageContainer = this.findElement(imageData);
+            $imageContainer.addClass('removed').hide().find('.is-removed').val(1);
+        },
+
+        /**
+         * Set image type
+         * @param event
+         * @param data
+         * @private
+         */
+        _setImageType: function(event, data){
+            this.element.find('.type-' + data.type).hide();
+            if (data.imageData) {
+                this.options.types[data.type].value = data.imageData.file;
+                this.findElement(data.imageData).find('.type-' + data.type).show();
+            } else {
+                this.options.types[data.type].value = null;
+            }
+            this.element.find('.image-' + data.type).val(this.options.types[data.type].value || 'no_selection');
+        },
+
+        /**
+         * Resort images
+         * @private
+         */
+        _resort: function() {
+            this.element.find('.position').each($.proxy(function(index, element) {
+                var value = $(element).val();
+                if (value != index) {
+                    this.element.trigger('moveElement', {
+                        imageData: $(element).closest(this.options.imageSelector).data('imageData'),
+                        position: index
+                    });
+                    $(element).val(index);
+                }
+            }, this));
+        },
+
+        /**
+         * Set image position
+         * @param event
+         * @param data
+         * @private
+         */
+        _setPosition: function(event, data) {
+            var $element = this.findElement(data.imageData);
+            var curIndex = this.element.find(this.options.imageSelector).index($element);
+            var newPosition = data.position + (curIndex > data.position ? -1 : 0);
+            if (data.position != curIndex) {
+                if (data.position === 0) {
+                    this.element.prepend($element);
+                } else {
+                    $element.insertAfter(
+                        this.element.find(this.options.imageSelector).eq(newPosition)
+                    );
+                }
+                this.element.trigger('resort');
+            }
+        }
+    });
+
+    // Extension for mage.productGallery - Add advanced settings dialog
+    $.widget('mage.productGallery', $.mage.productGallery, {
+        options: {
+            dialogTemplate: '.dialog-template'
+        },
+
+        /**
+         * Bind handler to elements
+         * @protected
+         */
+        _bind: function() {
+            this._super();
+            var events = {
+                'click [data-role="delete-button"]': function() {
+                    this.element.find('[data-role="dialog"]').trigger('close');
+                }
+            };
+            events['dblclick ' + this.options.imageSelector] = function(event) {
+                this._showDialog($(event.currentTarget).data('imageData'));
+            };
+            this._on(events);
+            this.element.on('sortstart', $.proxy(function() {
+                this.element.find('[data-role="dialog"]').trigger('close');
+            }, this));
+
+        },
+
+        /**
+         * Show dialog
+         * @param imageData
+         * @private
+         */
+        _showDialog: function(imageData) {
+            var $imageContainer = this.findElement(imageData);
+            var dialogElement = $imageContainer.data('dialog');
+            if ($imageContainer.is('.removed')) {
+                return;
+            }
+
+            if (!dialogElement) {
+                var $template = this.element.find(this.options.dialogTemplate);
+                var imageCountInLine = 6;
+                dialogElement = $template.tmpl(imageData);
+
+                dialogElement.on("open", $.proxy(function(event) {
+                    var imagesList = this.element.find(this.options.imageSelector + ':not(.removed)');
+                    var index = imagesList.index($imageContainer);
+                    var positionIndex = Math.floor(index / imageCountInLine + 1) * imageCountInLine - 1;
+                    if (positionIndex > imagesList.length - 1) {
+                        positionIndex = imagesList.length - 1;
+                    }
+                    var afterElement = imagesList.get(positionIndex);
+                    $(event.target).insertAfter(afterElement);
+                    $imageContainer.find('[data-role="type-selector"]').each($.proxy(function(index, checkbox) {
+                        var $checkbox = $(checkbox);
+                        $checkbox.prop('checked', this.options.types[$checkbox.val()].value == imageData.file);
+                    }, this));
+                    $(event.target).show();
+                }, this));
+                dialogElement.on("close", function(event) {
+                    $(event.target).hide();
+                });
+                $imageContainer.data('dialog', dialogElement);
+            }
+            dialogElement.trigger('open');
+
+        }
+    });
+})(jQuery);
diff --git a/app/code/core/Mage/Catalog/view/adminhtml/product/configurable/affected-attribute-set-selector/js.phtml b/app/code/core/Mage/Catalog/view/adminhtml/product/configurable/affected-attribute-set-selector/js.phtml
index 96cc136ac72c3611955420360fca3b431171aee6..efbf4dc24d2d8ee0cd344d2e442c45b842387a39 100644
--- a/app/code/core/Mage/Catalog/view/adminhtml/product/configurable/affected-attribute-set-selector/js.phtml
+++ b/app/code/core/Mage/Catalog/view/adminhtml/product/configurable/affected-attribute-set-selector/js.phtml
@@ -115,7 +115,7 @@ jQuery(function($) {
                     return; // affected attribute set was already chosen
                 }
                 var extendingAttributes = [];
-                $.each($('#attributes-container').variationsAttributes('getAttributes'), function () {
+                $.each($('#configurable-attributes-container').variationsAttributes('getAttributes'), function () {
                     if (!$('#attribute-' + this.code + '-container').length) {
                         extendingAttributes.push(this.id);
                     }
diff --git a/app/code/core/Mage/Catalog/view/adminhtml/product/configurable/attribute-selector/js.phtml b/app/code/core/Mage/Catalog/view/adminhtml/product/configurable/attribute-selector/js.phtml
index 1a4897bbb90c9d221145ccfd5ba5b9266f749062..059d72730a6326e27ea70a792db4a29ead0e265a 100644
--- a/app/code/core/Mage/Catalog/view/adminhtml/product/configurable/attribute-selector/js.phtml
+++ b/app/code/core/Mage/Catalog/view/adminhtml/product/configurable/attribute-selector/js.phtml
@@ -26,46 +26,36 @@
 
 /** @var $this Mage_Catalog_Block_Product_Configurable_AttributeSelector */
 ?>
+<script id="configurable-attribute-selector-template" type="text/x-jquery-tmpl">
+    <ul data-mage-init="{menu:[]}">
+        {{each items}}
+        <li {{html optionData($value)}}><a href="#">${$value.label}</a></li>
+        {{/each}}
+    </ul>
+</script>
 <script type="text/javascript">
-(function($) {
-    'use strict';
-    $(function() {
-        $('#attribute-selector')
-            .autocomplete({
-                minLength: 0,
-                appendTo: '#config_super_product',
-                source: function(request, response) {
-                    $.ajax({
-                        url: '<?php echo $this->getSuggestUrl()?>',
-                        data: {label_part: request.term},
-                        dataType: 'json',
-                        context: '<div>'
-                    })
-                    .success(function(data) {
-                        var list = [];
-                        $.each(data, function(id, item) {
-                            if (!$('#configurable_attribute_' + id ).length) {
-                                list.push(item);
-                            }
-                        });
-                        response(list);
-                    });
-                },
-                focus: function(event, ui) {
-                    return false;
-                },
-                select: function(event, ui) {
-                    var attribute = ui.item;
-                    if (attribute.id) {
-                        $('#attributes-container').trigger('add', attribute);
-                    }
-                    $(this).val('').blur();
-                    return false;
+jQuery(function($) {
+    var options = <?php echo $this->helper('Mage_Core_Helper_Data')->jsonEncode($this->getSuggestWidgetOptions())?>;
+    $.extend(options, {
+        response: function(data) {
+            var list = [];
+            $.each(data, function(id, item) {
+                if (!$('#configurable_attribute_' + id ).length) {
+                    list.push(item);
                 }
-            })
-            .on('focus', function () {
-                $(this).autocomplete('search');
             });
+            return list;
+        }
     });
-})(jQuery);
+
+    $('#configurable-attribute-selector')
+        .suggest(options)
+        .on('suggestselect', function (event, selectedItem) {
+            if (selectedItem.id) {
+                $('#configurable-attributes-container').trigger('add', selectedItem);
+            }
+            $(this).val('');
+            return false;
+        });
+});
 </script>
diff --git a/app/code/core/Mage/Catalog/view/adminhtml/product/product.css b/app/code/core/Mage/Catalog/view/adminhtml/product/product.css
index 8061349713854ec9e1d3a4e526a995400cca0b2c..5068880ed710b3df6e50f4cbceeb0696e2b2a6a7 100644
--- a/app/code/core/Mage/Catalog/view/adminhtml/product/product.css
+++ b/app/code/core/Mage/Catalog/view/adminhtml/product/product.css
@@ -1062,3 +1062,13 @@
     text-align: center;
     vertical-align: middle;
 }
+.ui-dialog.mage-new-category-dialog,
+.ui-dialog.mage-new-category-dialog .ui-dialog-content,
+.ui-dialog.mage-new-category-dialog .hor-scroll,
+.ui-dialog.mage-new-category-dialog .mage-suggest-dropdown {
+    overflow: visible;
+}
+
+#new_category_parent-suggest, #category_ids-suggest {
+    width: 180px;
+}
diff --git a/app/code/core/Mage/Catalog/view/frontend/js/gallery.js b/app/code/core/Mage/Catalog/view/frontend/js/gallery.js
new file mode 100644
index 0000000000000000000000000000000000000000..960fdfc4c651c09d68ee52ab21c805c0c29e9744
--- /dev/null
+++ b/app/code/core/Mage/Catalog/view/frontend/js/gallery.js
@@ -0,0 +1,55 @@
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    catalog product gallery image
+ * @package     mage
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+/*jshint browser:true, jquery:true*/
+(function($, window) {
+    "use strict";
+    $.widget('mage.gallery', {
+        options: {
+            minWidth: 300, // Minimum width of the gallery image.
+            widthOffset: 90, // Offset added to the width of the gallery image.
+            heightOffset: 210, // Offset added to the height of the gallery image.
+            closeWindow: "div.buttons-set a[role='close-window']" // Selector for closing the gallery popup window.
+        },
+
+        /**
+         * Bind click handler for closing the popup window and resize the popup based on the image size.
+         * @private
+         */
+        _create: function() {
+            $(this.options.closeWindow).on('click', function() { window.close(); });
+            this._resizeWindow();
+        },
+
+        /**
+         * Resize the gallery image popup window based on the image's dimensions.
+         * @private
+         */
+        _resizeWindow: function() {
+            var img = this.element,
+                width = img.width() < this.options.minWidth ? this.options.minWidth : img.width();
+            window.resizeTo(width + this.options.widthOffset, img.height() + this.options.heightOffset);
+        }
+    });
+})(jQuery, window);
diff --git a/app/code/core/Mage/Catalog/view/frontend/js/msrp.js b/app/code/core/Mage/Catalog/view/frontend/js/msrp.js
index 950f395d0db687bffd4d433eb7c771e123452c22..091190ac128fe7c7dadd90891b486f1fddb0567a 100644
--- a/app/code/core/Mage/Catalog/view/frontend/js/msrp.js
+++ b/app/code/core/Mage/Catalog/view/frontend/js/msrp.js
@@ -35,27 +35,18 @@
                 this._addToCartSubmit();
             }, this));
 
-            if (this.element.parents(this.options.groupedProductContainer).length > 0) {
-                this.options.clickUpdate = true;
-            }
-
-            if (!$('#map-popup-price').html() && this.options.realPrice && !this.options.clickUpdate) {
-                $('#map-popup-price').html($(this.options.realPrice));
-                $('#map-popup-msrp').html(this.options.msrpPrice);
-            }
-
             $(this.options.popupId).on('click', $.proxy(function(e) {
                 if (this.options.submitUrl) {
                     location.href = this.options.submitUrl;
                 } else {
+                    $(this.options.popupCartButtonId).off('click');
                     $(this.options.popupCartButtonId).on('click', $.proxy(function() {
                         this._addToCartSubmit();
                     }, this));
                     $('#map-popup-heading').text(this.options.productName);
-                    if (this.options.clickUpdate) {
-                        $('#map-popup-price').html($(this.options.realPrice));
-                        $('#map-popup-msrp').html(this.options.msrpPrice);
-                    }
+                    $('#map-popup-price').html($(this.options.realPrice));
+                    $('#map-popup-msrp').html(this.options.msrpPrice);
+                    this.element.trigger('reloadPrice');
                     var width = $('#map-popup').width();
                     var offsetX = e.pageX - (width / 2) + "px";
                     $('#map-popup').css({left: offsetX, top: e.pageY}).show();
@@ -85,6 +76,7 @@
         },
 
         _addToCartSubmit: function() {
+            this.element.trigger('addToCart', this.element);
             if (this.options.addToCartUrl) {
                 $('#map-popup').hide();
                 if (opener !== null) {
diff --git a/app/code/core/Mage/Catalog/view/frontend/js/related-products.js b/app/code/core/Mage/Catalog/view/frontend/js/related-products.js
new file mode 100644
index 0000000000000000000000000000000000000000..d1d03bb8069bc2ad5e5ce0b7e19aab263acc53b8
--- /dev/null
+++ b/app/code/core/Mage/Catalog/view/frontend/js/related-products.js
@@ -0,0 +1,76 @@
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    frontend related products
+ * @package     mage
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+/*jshint jquery:true*/
+(function($) {
+    "use strict";
+    $.widget('mage.relatedProducts', {
+        options: {
+            relatedCheckbox: '.related-checkbox', // Class name for a related product's input checkbox.
+            relatedProductsCheckFlag: false, // Related products checkboxes are initially unchecked.
+            relatedProductsField: '#related-products-field', // Hidden input field that stores related products.
+            selectAllMessage: $.mage.__('select all'),
+            unselectAllMessage: $.mage.__('unselect all')
+        },
+
+        /**
+         * Bind events to the appropriate handlers.
+         * @private
+         */
+        _create: function() {
+            this.element.on('click', $.proxy(this._selectAllRelated, this));
+            $(this.options.relatedCheckbox).on('click', $.proxy(this._addRelatedToProduct, this));
+        },
+
+        /**
+         * This method either checks all checkboxes for a product's set of related products (select all)
+         * or unchecks them (unselect all).
+         * @private
+         * @param e - Click event on either the "select all" link or the "unselect all" link.
+         * @return {Boolean} - Prevent default event action and event propagation.
+         */
+        _selectAllRelated: function(e) {
+            var innerHTML = this.options.relatedProductsCheckFlag ?
+                this.options.selectAllMessage : this.options.unselectAllMessage;
+            $(e.target).html(innerHTML);
+            $(this.options.relatedCheckbox).attr('checked',
+                this.options.relatedProductsCheckFlag = !this.options.relatedProductsCheckFlag);
+            this._addRelatedToProduct();
+            return false;
+        },
+
+        /**
+         * This method iterates through each checkbox for all related products and collects only those products
+         * whose checkbox has been checked. The selected related products are stored in a hidden input field.
+         * @private
+         */
+        _addRelatedToProduct: function() {
+            $(this.options.relatedProductsField).val(
+                $(this.options.relatedCheckbox + ':checked').map(function() {
+                    return this.value;
+                }).get().join(',')
+            );
+        }
+    });
+})(jQuery);
diff --git a/app/code/core/Mage/Catalog/view/frontend/js/tier-price.js b/app/code/core/Mage/Catalog/view/frontend/js/tier-price.js
new file mode 100644
index 0000000000000000000000000000000000000000..f91bf0f44966ddd5004087d544a38e723e7222ef
--- /dev/null
+++ b/app/code/core/Mage/Catalog/view/frontend/js/tier-price.js
@@ -0,0 +1,74 @@
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    frontend product tier price
+ * @package     mage
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+
+/*jshint evil:true browser:true jquery:true*/
+(function($) {
+    $.widget('mage.tierPrice', {
+        options: {
+            popupHeading: '#map-popup-heading',
+            popupPrice: '#map-popup-price',
+            popupMsrp: '#map-popup-msrp',
+            popup: '#map-popup',
+            popupContent: '#map-popup-content',
+            popupText: '#map-popup-text',
+            popupOnlyText: 'map-popup-only-text',
+            popupTextWhatThis: '#map-popup-text-what-this',
+            popupCartButtonId: '#map-popup-button'
+        },
+
+        _create: function() {
+            this.element.on('click', '[data-tier-price]', $.proxy(this._showTierPrice, this));
+        },
+
+        /**
+         * Show tier price popup on gesture
+         * @private
+         * @param e - element got the clicked on
+         * @return {Boolean}
+         */
+        _showTierPrice: function(e) {
+            var json = eval('(' + $(e.target).data('tier-price') + ')');
+            $(this.options.popupCartButtonId).off('click');
+            $(this.options.popupCartButtonId).on('click', $.proxy(function() {
+                this.element.find(this.options.inputQty).val(json.qty);
+                this.element.submit();
+            }, this));
+            $(this.options.popupHeading).text(json.name);
+            $(this.options.popupPrice).html($(json.price)).find('[id^="product-price-"]').attr('id', function() {
+                // change price element id, so price option won't update the tier price
+                return 'tier' + $(this).attr('id');
+            });
+            $(this.options.popupMsrp).html(json.msrp);
+            var width = $(this.options.popup).width();
+            var offsetX = e.pageX - (width / 2) + "px";
+            $(this.options.popup).css({left: offsetX, top: e.pageY}).show();
+            $(this.options.popupContent).show();
+            $(this.options.popupText).addClass(this.options.popupOnlyText).show();
+            $(this.options.popupTextWhatThis).hide();
+            return false;
+        }
+    });
+})(jQuery);
+
diff --git a/app/code/core/Mage/Catalog/view/frontend/msrp.xml b/app/code/core/Mage/Catalog/view/frontend/msrp.xml
index 2eaef2dd119af6faa7eebb6b3369cf55dbc1cef9..a84ff1cd9e9bb95f085801fd3edc306ce2e5c639 100644
--- a/app/code/core/Mage/Catalog/view/frontend/msrp.xml
+++ b/app/code/core/Mage/Catalog/view/frontend/msrp.xml
@@ -57,6 +57,10 @@ Default layout, loads most of the pages
         <update handle="MAP_popup" />
         <update handle="MAP_price_msrp_wishlist_item" />
     </wishlist_shared_index>
+    <wishlist_search_view>
+        <update handle="MAP_popup" />
+        <update handle="MAP_price_msrp_wishlist_item" />
+    </wishlist_search_view>
     <review_product_list>
         <update handle="MAP_popup" />
         <update handle="MAP_price_msrp_item" />
diff --git a/app/code/core/Mage/Catalog/view/frontend/product/compare/list.phtml b/app/code/core/Mage/Catalog/view/frontend/product/compare/list.phtml
index de404c6e46e9fae7c21afa17acbec68b500b7f25..3c305874d21d89e36c7b2152517dd5e98e16f05a 100644
--- a/app/code/core/Mage/Catalog/view/frontend/product/compare/list.phtml
+++ b/app/code/core/Mage/Catalog/view/frontend/product/compare/list.phtml
@@ -138,8 +138,10 @@
             <img src="<?php echo $this->getViewFileUrl('images/opc-ajax-loader.gif') ?>" alt="<?php echo $this->__('Please wait...') ?>" title="<?php echo $this->__('Please wait...') ?>" class="v-middle" /> <?php echo $this->__('Please wait...') ?>
         </span>
 </div>
+<?php endif; ?>
 <script type="text/javascript">
-    (function($) {
+    (function($, window) {
+    <?php if ($_total): ?>
         head.js("<?php echo $this->getViewFileUrl('Mage_Catalog::js/list.js')?>", function() {
             $('#product-comparison').compareList({
                 productRemoveSelector: 'a.btn-remove',
@@ -154,8 +156,8 @@
                 }
             });
         });
-    })(jQuery);
+    <?php else: ?>
+        window.close();
+    <?php endif; ?>
+    })(jQuery, window);
 </script>
-<?php else: ?>
-<script type="text/javascript">window.close();</script>
-<?php endif; ?>
diff --git a/app/code/core/Mage/Catalog/view/frontend/product/gallery.phtml b/app/code/core/Mage/Catalog/view/frontend/product/gallery.phtml
index 9353b0aba86aa1613f7cf3df17ee35f4bc983ee4..b3a239431ceea87abd7f159510bc81c88a3c0e46 100644
--- a/app/code/core/Mage/Catalog/view/frontend/product/gallery.phtml
+++ b/app/code/core/Mage/Catalog/view/frontend/product/gallery.phtml
@@ -24,9 +24,9 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 ?>
-<?php $_width=$this->getImageWidth() ?>
+<?php $_width = $this->getImageWidth(); ?>
 <div class="product-image-popup" style="width:<?php echo $_width; ?>px;">
-    <div class="buttons-set"><a href="#" onclick="window.close(); return false;" class="button"><span><?php echo $this->__('Close Window') ?></span></a></div>
+    <div class="buttons-set"><a href="#" class="button" role="close-window"><span><?php echo $this->__('Close Window') ?></span></a></div>
     <?php if($this->getPreviusImageUrl() || $this->getNextImageUrl()): ?>
         <div class="nav">
           <?php if($_prevUrl = $this->getPreviusImageUrl()): ?>
@@ -41,7 +41,7 @@
         <h1 class="image-label"><?php echo $_imageTitle ?></h1>
     <?php endif; ?>
     <img src="<?php echo $this->helper('Mage_Catalog_Helper_Image')->init($this->getProduct(), 'image', $this->getImageFile()); ?>"<?php if($_width): ?> width="<?php echo $_width ?>"<?php endif; ?> alt="<?php echo $this->escapeHtml($this->getCurrentImage()->getLabel()) ?>" title="<?php echo $this->escapeHtml($this->getCurrentImage()->getLabel()) ?>" id="product-gallery-image" class="image" />
-    <div class="buttons-set"><a href="#" onclick="window.close(); return false;" class="button"><span><?php echo $this->__('Close Window') ?></span></a></div>
+    <div class="buttons-set"><a href="#" class="button" role="close-window"><span><?php echo $this->__('Close Window') ?></span></a></div>
     <?php if($this->getPreviusImageUrl() || $this->getNextImageUrl()): ?>
         <div class="nav">
           <?php if($_prevUrl = $this->getPreviusImageUrl()): ?>
@@ -54,13 +54,9 @@
     <?php endif; ?>
 </div>
 <script type="text/javascript">
-//<![CDATA[
-Event.observe(window, 'load', function(){
-    var demensions = $('product-gallery-image').getDimensions();
-    if (demensions.width < 300) {
-        demensions.width = 300
-    }
-    window.resizeTo(demensions.width+90, demensions.height+210);
-});
-//]]>
+    window.onload = function() {
+        head.js("<?php echo $this->getViewFileUrl('Mage_Catalog::js/gallery.js');?>", function() {
+            jQuery('#product-gallery-image').gallery();
+        });
+    };
 </script>
diff --git a/app/code/core/Mage/Catalog/view/frontend/product/list/related.phtml b/app/code/core/Mage/Catalog/view/frontend/product/list/related.phtml
index 4f71521b09067bd214df30d59c19cfcc4aef2e2c..0e38a45d9042b53e6812649bc5b45376993cf1ee 100644
--- a/app/code/core/Mage/Catalog/view/frontend/product/list/related.phtml
+++ b/app/code/core/Mage/Catalog/view/frontend/product/list/related.phtml
@@ -30,7 +30,7 @@
         <strong><span><?php echo $this->__('Related Products') ?></span></strong>
     </div>
     <div class="block-content">
-        <p class="block-subtitle"><?php echo $this->__('Check items to add to the cart or') ?>&nbsp;<a href="#" onclick="selectAllRelated(this); return false;"><?php echo $this->__('select all') ?></a></p>
+        <p class="block-subtitle"><?php echo $this->__('Check items to add to the cart or') ?>&nbsp;<a href="#" role="select-all"><?php echo $this->__('select all') ?></a></p>
         <ol class="mini-products-list" id="block-related">
         <?php foreach($this->getItems() as $_item): ?>
             <li class="item">
@@ -52,43 +52,12 @@
             </li>
         <?php endforeach ?>
         </ol>
-        <script type="text/javascript">(function($) {$('#block-related').decorate('list', false)})(jQuery)</script>
+        <script type="text/javascript">jQuery('#block-related').decorate('list', false);</script>
     </div>
     <script type="text/javascript">
-    //<![CDATA[
-    $$('.related-checkbox').each(function(elem){
-        Event.observe(elem, 'click', addRelatedToProduct)
-    });
-
-    var relatedProductsCheckFlag = false;
-    function selectAllRelated(txt){
-        if (relatedProductsCheckFlag == false) {
-            $$('.related-checkbox').each(function(elem){
-                elem.checked = true;
-            });
-            relatedProductsCheckFlag = true;
-            txt.innerHTML="<?php echo $this->__('unselect all') ?>";
-        } else {
-            $$('.related-checkbox').each(function(elem){
-                elem.checked = false;
-            });
-            relatedProductsCheckFlag = false;
-            txt.innerHTML="<?php echo $this->__('select all') ?>";
-        }
-        addRelatedToProduct();
-    }
-
-    function addRelatedToProduct(){
-        var checkboxes = $$('.related-checkbox');
-        var values = [];
-        for(var i=0;i<checkboxes.length;i++){
-            if(checkboxes[i].checked) values.push(checkboxes[i].value);
-        }
-        if($('related-products-field')){
-            $('related-products-field').value = values.join(',');
-        }
-    }
-    //]]>
+        head.js("<?php echo $this->getViewFileUrl('Mage_Catalog::js/related-products.js');?>", function() {
+            jQuery(".block-related a[role='select-all']").relatedProducts();
+        });
     </script>
 </div>
 <?php endif ?>
diff --git a/app/code/core/Mage/Catalog/view/frontend/product/price_msrp.phtml b/app/code/core/Mage/Catalog/view/frontend/product/price_msrp.phtml
index cf648ae5de1cdc5d4d836de67347fcff1b36c27e..9cd5940ecfa8831760d035f2225fde04c0f58928 100644
--- a/app/code/core/Mage/Catalog/view/frontend/product/price_msrp.phtml
+++ b/app/code/core/Mage/Catalog/view/frontend/product/price_msrp.phtml
@@ -60,8 +60,7 @@
                         priceElementId: '<?php echo $priceElementId ?>',
                         closeButtonId: '#map-popup-close',
                         popupCartButtonId: "#map-popup-button",
-                        addToCartUrl: "<?php echo $this->getAddToCartUrl($_product) ?>",
-                        clickUpdate: true
+                        addToCartUrl: "<?php echo $this->getAddToCartUrl($_product) ?>"
                     });
                 <?php else: ?>
                     $('#<?php echo($popupId);?>').addToCart({
diff --git a/app/code/core/Mage/Catalog/view/frontend/product/view/tierprices.phtml b/app/code/core/Mage/Catalog/view/frontend/product/view/tierprices.phtml
index 5518ff0bf19dff129d3bb314b4ef2ff67cab621f..f9d261ff700a415370ee128b951fda63be5078dc 100644
--- a/app/code/core/Mage/Catalog/view/frontend/product/view/tierprices.phtml
+++ b/app/code/core/Mage/Catalog/view/frontend/product/view/tierprices.phtml
@@ -192,41 +192,29 @@ if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_product, array(1,2,4)
 
         <?php if ($_catalogHelper->isShowPriceOnGesture($_product)):?>
             <?php $popupId = 'msrp-popup-' . $_product->getId() . $this->helper('Mage_Core_Helper_Data')->getRandomString(20); ?>
-            <a href="#" id="<?php echo($popupId);?>"><?php echo $this->__('Click for price'); ?></a>
-            <script type="text/javascript">
             <?php
-                    $addToCartUrl = $this->getProduct()->isSalable()
-                        ? $this->getAddToCartUrl($_product, array('qty' => $_price['price_qty']))
-                        : '';
+            $addToCartUrl = $this->getProduct()->isSalable()
+                ? $this->getAddToCartUrl($_product, array('qty' => $_price['price_qty']))
+                : '';
             ?>
-            <?php if (!$this->getInGrouped()): ?>
-                var newLink = {
-                    url: "<?php echo $addToCartUrl; ?>",
-                    qty: "<?php echo $_price['price_qty']?>"
-                };
-            <?php else: ?>
-                var newLink = {
-                    url: "<?php echo $addToCartUrl; ?>",
-                    notUseForm: true
-                };
-            <?php endif ?>
-                Catalog.Map.addHelpLink(
-                    $('<?php echo $popupId ?>'),
-                    "<?php echo $_product->getName() ?>",
-                    <?php echo json_encode($_price['real_price_html']) ?>,
-                    "<?php echo $this->helper('Mage_Core_Helper_Data')->currency($_product->getMsrp(),true,false) ?>",
-                    newLink
-                );
-            </script>
+            <a href="#" id="<?php echo($popupId);?>" data-tier-price='{addToCartUrl:"<?php echo $addToCartUrl; ?>", name:"<?php echo $_product->getName() ?>", price:<?php echo json_encode($_price['real_price_html']) ?>, msrp:"<?php echo $this->helper('Mage_Core_Helper_Data')->currency($_product->getMsrp(),true,false) ?>"<?php if (!$this->getInGrouped()): ?>, qty:"<?php echo $_price['price_qty']?>"<?php endif ?>}'><?php echo $this->__('Click for price'); ?></a>
         <?php else: ?>
             <span class="msrp-price-hide-message">
                 <?php echo $_catalogHelper->getMsrpPriceMessage($_product) ?>
             </span>
         <?php endif; ?>
-
-
         </li>
-
     <?php endforeach ?>
     </ul>
-<?php endif;?>
+    <?php if ($_catalogHelper->isShowPriceOnGesture($_product)):?>
+        <script type="text/javascript">
+            (function($) {
+                head.js("<?php echo $this->getViewFileUrl('Mage_Catalog::js/tier-price.js') ?>", function () {
+                    $('#product_addtocart_form').tierPrice({
+                        inputQty: '#qty'
+                    });
+                });
+            })(jQuery);
+        </script>
+    <?php endif;?>
+<?php endif;?>
\ No newline at end of file
diff --git a/app/code/core/Mage/CatalogInventory/view/frontend/stockqty/composite.phtml b/app/code/core/Mage/CatalogInventory/view/frontend/stockqty/composite.phtml
index e66bc82aeff8bc4e9ee05f6d8c0169effa63b1ba..68412c7929ee0904db0d40cca3f0612155b806f4 100644
--- a/app/code/core/Mage/CatalogInventory/view/frontend/stockqty/composite.phtml
+++ b/app/code/core/Mage/CatalogInventory/view/frontend/stockqty/composite.phtml
@@ -30,7 +30,8 @@
 ?>
 <?php if($this->isMsgVisible()): ?>
     <p class="availability-only">
-        <a href="#" id="<?php echo $this->getPlaceholderId() ?>" title="<?php echo $this->__('Only %s left', ($this->getStockQty())) ?>"><?php echo $this->__('Only %s left', "<strong>{$this->getStockQty()}</strong>") ?></a>
+        <a href="#" data-mage-init="{toggleAdvanced:[]}" data-selectors-toggle-class="no-display" data-base-toggle-class="expanded" data-toggle-selectors="#<?php echo $this->getDetailsPlaceholderId() ?>"
+           id="<?php echo $this->getPlaceholderId() ?>" title="<?php echo $this->__('Only %s left', ($this->getStockQty())) ?>"><?php echo $this->__('Only %s left', "<strong>{$this->getStockQty()}</strong>") ?></a>
     </p>
     <table id="<?php echo $this->getDetailsPlaceholderId() ?>" class="availability-only-details no-display">
         <col />
@@ -54,13 +55,6 @@
         </tbody>
     </table>
     <script type="text/javascript">
-    //<![CDATA[
-    $('<?php echo $this->getPlaceholderId() ?>').observe('click', function(event){
-        this.toggleClassName('expanded');
-        $('<?php echo $this->getDetailsPlaceholderId() ?>').toggleClassName('no-display');
-        event.stop();
-        decorateTable('<?php echo $this->getDetailsPlaceholderId() ?>');
-    });
-    //]]>
+        jQuery('#<?php echo $this->getDetailsPlaceholderId() ?>').decorate('table');
     </script>
 <?php endif ?>
diff --git a/app/code/core/Mage/CatalogRule/Model/Resource/Rule.php b/app/code/core/Mage/CatalogRule/Model/Resource/Rule.php
index 5047e433645bdde80626a7469226004affa17c7a..47ab182309a5358ed3cd9f3fb46836e7be3bbe49 100755
--- a/app/code/core/Mage/CatalogRule/Model/Resource/Rule.php
+++ b/app/code/core/Mage/CatalogRule/Model/Resource/Rule.php
@@ -325,7 +325,7 @@ class Mage_CatalogRule_Model_Resource_Rule extends Mage_Rule_Model_Resource_Abst
 
         $select->join(
             array('pp_default'=>$priceTable),
-            sprintf($joinCondition, 'pp_default', Mage_Core_Model_App::ADMIN_STORE_ID),
+            sprintf($joinCondition, 'pp_default', Mage_Core_Model_AppInterface::ADMIN_STORE_ID),
             array('default_price'=>'pp_default.value')
         );
 
@@ -335,7 +335,7 @@ class Mage_CatalogRule_Model_Resource_Rule extends Mage_Rule_Model_Resource_Abst
             if ($defaultGroup instanceof Mage_Core_Model_Store_Group) {
                 $storeId = $defaultGroup->getDefaultStoreId();
             } else {
-                $storeId = Mage_Core_Model_App::ADMIN_STORE_ID;
+                $storeId = Mage_Core_Model_AppInterface::ADMIN_STORE_ID;
             }
 
             $select->joinInner(
@@ -360,7 +360,7 @@ class Mage_CatalogRule_Model_Resource_Rule extends Mage_Rule_Model_Resource_Abst
                 if ($defaultGroup instanceof Mage_Core_Model_Store_Group) {
                     $storeId = $defaultGroup->getDefaultStoreId();
                 } else {
-                    $storeId = Mage_Core_Model_App::ADMIN_STORE_ID;
+                    $storeId = Mage_Core_Model_AppInterface::ADMIN_STORE_ID;
                 }
 
                 $tableAlias = 'pp' . $websiteId;
diff --git a/app/code/core/Mage/CatalogSearch/view/frontend/form-mini.js b/app/code/core/Mage/CatalogSearch/view/frontend/form-mini.js
index fecbed30b49adb1f225ca533d530d1920e6bf3aa..33d501634ae5c24ddcaf39549d58cc192f2e1cb9 100644
--- a/app/code/core/Mage/CatalogSearch/view/frontend/form-mini.js
+++ b/app/code/core/Mage/CatalogSearch/view/frontend/form-mini.js
@@ -24,8 +24,8 @@
  */
 /*jshint browser:true jquery:true*/
 (function ($) {
+    "use strict";
     $.widget('mage.catalogSearch', {
-
         options: {
             autocomplete: 'off',
             minSearchLength: 2,
@@ -64,16 +64,16 @@
         },
 
         /**
-         * @return {Element} The first element in the suggestion list.
          * @private
+         * @return {Element} The first element in the suggestion list.
          */
         _getFirstVisibleElement: function() {
             return this.responseList.indexList ? this.responseList.indexList.first() : false;
         },
 
         /**
-         * @return {Element} The last element in the suggestion list.
          * @private
+         * @return {Element} The last element in the suggestion list.
          */
         _getLastElement: function() {
             return this.responseList.indexList ? this.responseList.indexList.last() : false;
@@ -81,8 +81,8 @@
 
         /**
          * Clears the item selected from the suggestion list and resets the suggestion list.
-         * @param {boolean} all Controls whether to clear the suggestion list.
          * @private
+         * @param {boolean} all Controls whether to clear the suggestion list.
          */
         _resetResponseList: function(all) {
             this.responseList.selected = null;
@@ -94,8 +94,8 @@
         /**
          * Executes when the search box is submitted. Sets the search input field to the
          * value of the selected item.
-         * @param {Event} e The submit event
          * @private
+         * @param {Event} e The submit event
          */
         _onSubmit: function(e) {
             if (this.element.val() === this.options.placeholder || this.element.val() === '') {
@@ -109,21 +109,21 @@
         /**
          * Executes when keys are pressed in the search input field. Performs specific actions
          * depending on which keys are pressed.
+         * @private
          * @param {Event} e The key down event
          * @return {Boolean} Default return type for any unhandled keys
-         * @private
          */
-        _onKeyDown: function (e) {
+        _onKeyDown: function(e) {
             var keyCode = e.keyCode || e.which;
             switch (keyCode) {
-                case $.mage.constant.KEY_ESC:
+                case $.ui.keyCode.ESCAPE:
                     this._resetResponseList(true);
                     this.autoComplete.hide();
                     break;
-                case $.mage.constant.KEY_TAB:
+                case $.ui.keyCode.TAB:
                     this.searchForm.trigger('submit');
                     break;
-                case $.mage.constant.KEY_DOWN:
+                case $.ui.keyCode.DOWN:
                     if (this.responseList.indexList) {
                         if (!this.responseList.selected) {
                             this._getFirstVisibleElement().addClass(this.options.selectClass);
@@ -138,7 +138,7 @@
                         }
                     }
                     break;
-                case $.mage.constant.KEY_UP:
+                case $.ui.keyCode.UP:
                     if (this.responseList.indexList !== null) {
                         if (!this._getFirstVisibleElement().hasClass(this.options.selectClass)) {
                             this.responseList.selected = this.responseList.selected.removeClass(this.options.selectClass).prev().addClass(this.options.selectClass);
@@ -161,14 +161,14 @@
          * and mouseout events on the populated suggestion list dropdown.
          * @private
          */
-        _onPropertyChange: function () {
-            var searchField = this.element;
-            var clonePosition = {
-                position: 'absolute',
-                left: searchField.offset().left,
-                top: searchField.offset().top + searchField.outerHeight(),
-                width: searchField.outerWidth()
-            };
+        _onPropertyChange: function() {
+            var searchField = this.element,
+                clonePosition = {
+                    position: 'absolute',
+                    left: searchField.offset().left,
+                    top: searchField.offset().top + searchField.outerHeight(),
+                    width: searchField.outerWidth()
+                };
             if (searchField.val().length >= parseInt(this.options.minSearchLength, 10)) {
                 $.get(this.options.url, {q: searchField.val()}, $.proxy(function (data) {
                     this.responseList.indexList = this.autoComplete.html(data)
@@ -195,6 +195,5 @@
                 this.autoComplete.hide();
             }
         }
-
     });
 })(jQuery);
diff --git a/app/code/core/Mage/Checkout/view/frontend/cart/item/default.phtml b/app/code/core/Mage/Checkout/view/frontend/cart/item/default.phtml
index ec2998775f00b609aec3bd1ec7f7c20356d0610f..121a6556071ba73beb1e3e6aaf6487225defe1b8 100644
--- a/app/code/core/Mage/Checkout/view/frontend/cart/item/default.phtml
+++ b/app/code/core/Mage/Checkout/view/frontend/cart/item/default.phtml
@@ -96,7 +96,7 @@ $canApplyMsrp = Mage::helper('Mage_Catalog_Helper_Data')->canApplyMsrp($_item->g
         <?php if ($this->helper('Mage_Tax_Helper_Data')->displayCartPriceExclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()): ?>
         <td class="a-right">
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $_item->getId(); ?>"}'>
             <?php else: ?>
                 <span class="cart-price">
             <?php endif; ?>
@@ -128,7 +128,7 @@ $canApplyMsrp = Mage::helper('Mage_Catalog_Helper_Data')->canApplyMsrp($_item->g
                 </div>
 
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                    <div class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $_item->getId(); ?>"}'>
                         <span class="weee"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>: <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_item->getCalculationPrice()+$_item->getWeeeTaxAppliedAmount()+$_item->getWeeeTaxDisposition()); ?></span>
                     </div>
                 <?php endif; ?>
@@ -139,7 +139,7 @@ $canApplyMsrp = Mage::helper('Mage_Catalog_Helper_Data')->canApplyMsrp($_item->g
         <td>
             <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getPriceInclTax($_item); ?>
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $_item->getId(); ?>"}'>
             <?php else: ?>
                 <span class="cart-price">
             <?php endif; ?>
@@ -170,7 +170,7 @@ $canApplyMsrp = Mage::helper('Mage_Catalog_Helper_Data')->canApplyMsrp($_item->g
                 </div>
 
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                    <div class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $_item->getId(); ?>"}'>
                         <span class="weee"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>: <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_incl+$_item->getWeeeTaxAppliedAmount()); ?></span>
                     </div>
                 <?php endif; ?>
@@ -179,12 +179,12 @@ $canApplyMsrp = Mage::helper('Mage_Catalog_Helper_Data')->canApplyMsrp($_item->g
         <?php endif; ?>
     <?php endif; ?>
     <td class="a-center">
-        <input name="cart[<?php echo $_item->getId() ?>][qty]" value="<?php echo $this->getQty() ?>" size="4" title="<?php echo $this->__('Qty') ?>" class="input-text qty" maxlength="12" data-validate="{required:true,digits:true}"/>
+        <input name="cart[<?php echo $_item->getId() ?>][qty]" value="<?php echo $this->getQty() ?>" size="4" title="<?php echo $this->__('Qty') ?>" class="input-text qty" maxlength="12" data-validate="{required:true,'validate-greater-than-zero':true}"/>
     </td>
     <?php if (($this->helper('Mage_Tax_Helper_Data')->displayCartPriceExclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()) && !$_item->getNoSubtotal()): ?>
     <td class="a-right">
         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-            <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+            <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
         <?php else: ?>
             <span class="cart-price">
         <?php endif; ?>
@@ -219,7 +219,7 @@ $canApplyMsrp = Mage::helper('Mage_Catalog_Helper_Data')->canApplyMsrp($_item->g
             </div>
 
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <div class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
                     <span class="weee"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>: <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_item->getRowTotal()+$_item->getWeeeTaxAppliedRowAmount()+$_item->getWeeeTaxRowDisposition()); ?></span>
                 </div>
             <?php endif; ?>
@@ -230,7 +230,7 @@ $canApplyMsrp = Mage::helper('Mage_Catalog_Helper_Data')->canApplyMsrp($_item->g
     <td>
         <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getSubtotalInclTax($_item); ?>
         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-            <span class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+            <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
         <?php else: ?>
             <span class="cart-price">
         <?php endif; ?>
@@ -267,7 +267,7 @@ $canApplyMsrp = Mage::helper('Mage_Catalog_Helper_Data')->canApplyMsrp($_item->g
             </div>
 
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <div class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
                     <span class="weee"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>: <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_incl+$_item->getWeeeTaxAppliedRowAmount()); ?></span>
                 </div>
             <?php endif; ?>
diff --git a/app/code/core/Mage/Checkout/view/frontend/js/checkout-topcart.js b/app/code/core/Mage/Checkout/view/frontend/js/checkout-topcart.js
deleted file mode 100644
index 4c4cdcf9b472c4bf64f9c90afbac7dff399c5389..0000000000000000000000000000000000000000
--- a/app/code/core/Mage/Checkout/view/frontend/js/checkout-topcart.js
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * Magento
- *
- * NOTICE OF LICENSE
- *
- * This source file is subject to the Academic Free License (AFL 3.0)
- * that is bundled with this package in the file LICENSE_AFL.txt.
- * It is also available through the world-wide-web at this URL:
- * http://opensource.org/licenses/afl-3.0.php
- * If you did not receive a copy of the license and are unable to
- * obtain it through the world-wide-web, please send an email
- * to license@magentocommerce.com so we can send you a copy immediately.
- *
- * DISCLAIMER
- *
- * Do not edit or add to this file if you wish to upgrade Magento to newer
- * versions in the future. If you wish to customize Magento for your
- * needs please refer to http://www.magentocommerce.com for more information.
- *
- * @category    mage product view
- * @package     mage
- * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
- * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
- */
-/*jshint browser:true jquery:true*/
-(function ($) {
-    $.widget('mage.topCart', {
-        options: {
-            intervalDuration: 4000
-        },
-
-        _create: function(){
-            this.element.find(this.options.closeSelector)
-                .on('click', $.proxy(this.hide, this));
-            this.element.parent()
-                .on('mouseleave', $.proxy(this._onMouseleave, this))
-                .on('mouseenter', $.proxy(this._stopTimer, this));
-            this.element.prev().on('click', $.proxy(function () {
-                this.element.slideToggle('slow');
-            }, this));
-        },
-
-        /**
-         * Hide (slide up) the checkout top-cart.
-         */
-        hide: function(){
-            this.element.slideUp('slow', $.proxy(this._stopTimer, this));
-        },
-
-        /**
-         * Clear (stop) the timer that controls the show/hide of the checkout top-cart.
-         * @private
-         */
-        _stopTimer: function() {
-            clearTimeout(this.timer);
-        },
-
-        /**
-         * Executes when the mouse leaves the top-cart area. Initiates hiding of the top-cart
-         * after a set interval duration.
-         * @private
-         */
-        _onMouseleave: function() {
-            this._stopTimer();
-            this.timer = setTimeout($.proxy(this.hide, this), this.options.intervalDuration);
-        }
-    });
-})(jQuery);
\ No newline at end of file
diff --git a/app/code/core/Mage/Checkout/view/frontend/js/region-updater.js b/app/code/core/Mage/Checkout/view/frontend/js/region-updater.js
index 81d7fcf19b24bf7cd79d8c13399cff53fb5b8e36..de303097038c02574a5fdff3e5ab9ae9c8eb0d42 100644
--- a/app/code/core/Mage/Checkout/view/frontend/js/region-updater.js
+++ b/app/code/core/Mage/Checkout/view/frontend/js/region-updater.js
@@ -26,7 +26,10 @@
 (function($) {
     $.widget('mage.regionUpdater', {
         options: {
-            regionTemplate: '<option value="${value}" title="${title}" {{if isSelected}}selected="selected"{{/if}}>${title}</option>'
+            regionTemplate: '<option value="${value}" title="${title}" {{if isSelected}}selected="selected"{{/if}}>${title}</option>',
+            isRegionRequired: true,
+            isZipRequired: true,
+            isCountryRequired: true
         },
 
         _create: function() {
@@ -34,7 +37,16 @@
             this.element.on('change', $.proxy(function(e) {
                 this._updateRegion($(e.target).val());
             }, this));
-            this.element.addClass('required');
+            if (this.isCountryRequired) {
+                this.element.addClass('required-entry');
+            }
+            $(this.options.regionListId).on('change', $.proxy(function(e) {
+                this.setOption = false;
+                this.currentRegionOption = $(e.target).val();
+            }, this));
+            $(this.options.regionInputId).on('focusout', $.proxy(function() {
+                this.setOption = true;
+            }, this));
         },
 
         /**
@@ -43,8 +55,10 @@
          * @private
          */
         _removeSelectOptions: function(selectElement) {
-            selectElement.find('option').each(function (index){
-                index && $(this).remove();
+            selectElement.find('option').each(function(index) {
+                if (index) {
+                    $(this).remove();
+                }
             });
         },
 
@@ -66,6 +80,22 @@
             }, this));
         },
 
+        /**
+         * Takes clearError callback function as first option
+         * If no form is passed as option, look up the closest form and call clearError method.
+         * @private
+         */
+        _clearError: function() {
+            if (this.options.clearError && typeof(this.options.clearError) === "function") {
+                this.options.clearError.call(this);
+            } else {
+                if (!this.options.form) {
+                    this.options.form = this.element.closest('form').length ? $(this.element.closest('form')[0]) : null;
+                }
+                this.options.form && this.options.form.data('validation') && this.options.form.validation('clearError',
+                    this.options.regionListId, this.options.regionInputId, this.options.postcodeId);
+            }
+        },
         /**
          * Update dropdown list based on the country selected
          * @param {string} country - 2 uppercase letter for country code
@@ -77,15 +107,25 @@
                 regionInput = $(this.options.regionInputId),
                 postcode = $(this.options.postcodeId),
                 requiredLabel = regionList.parent().siblings('label').children('em');
-            this.options.form && this.options.form.validation('clearError',
-                this.options.regionListId, this.options.regionInputId, this.options.postcodeId);
+            this._clearError();
             // Populate state/province dropdown list if available or use input box
             if (this.options.regionJson[country]) {
                 this._removeSelectOptions(regionList);
                 $.each(this.options.regionJson[country], $.proxy(function(key, value) {
                     this._renderSelectOption(regionList, key, value);
                 }, this));
-                regionList.addClass('required-entry').show();
+                if (this.currentRegionOption) {
+                    regionList.val(this.currentRegionOption);
+                }
+                if (this.setOption) {
+                    regionList.find("option").filter(function() {
+                        return this.text === regionInput.val();
+                    }).attr('selected', true);
+                }
+                if (this.options.isRegionRequired) {
+                    regionList.addClass('required-entry');
+                }
+                regionList.show();
                 regionInput.hide();
                 requiredLabel.show();
             } else {
@@ -94,9 +134,11 @@
                 requiredLabel.hide();
             }
             // If country is in optionalzip list, make postcode input not required
-            $.inArray(country, this.options.countriesWithOptionalZip) >= 0 ?
-                postcode.removeClass('required-entry').parent().siblings('label').children('em').hide() :
-                postcode.addClass('required-entry').parent().siblings('label').children('em').show();
+            if (this.options.isZipRequired) {
+                $.inArray(country, this.options.countriesWithOptionalZip) >= 0 ?
+                    postcode.removeClass('required-entry').parent().siblings('label').children('em').hide() :
+                    postcode.addClass('required-entry').parent().siblings('label').children('em').show();
+            }
             // Add defaultvalue attribute to state/province select element
             regionList.attr('defaultvalue', this.options.defaultRegion);
         }
diff --git a/app/code/core/Mage/Checkout/view/frontend/multishipping/overview/item.phtml b/app/code/core/Mage/Checkout/view/frontend/multishipping/overview/item.phtml
index c13223fef12bcd544bcf2ea7b024910ae7a98fa9..23308b55ed4800c6aeed856de4ff38fe1f3b8ce6 100644
--- a/app/code/core/Mage/Checkout/view/frontend/multishipping/overview/item.phtml
+++ b/app/code/core/Mage/Checkout/view/frontend/multishipping/overview/item.phtml
@@ -39,7 +39,7 @@
     <?php if ($this->helper('Mage_Tax_Helper_Data')->displayCartPriceExclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()): ?>
     <td class="a-right">
         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-            <div class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+            <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $_item->getId(); ?>"}'>
         <?php else: ?>
             <div class="cart-price">
         <?php endif; ?>
@@ -76,7 +76,7 @@
             </div>
 
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <div class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $_item->getId(); ?>"}'>
                     <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_item->getCalculationPrice()+$_item->getWeeeTaxAppliedAmount()+$_item->getWeeeTaxDisposition()); ?></span>
                 </div>
             <?php endif; ?>
@@ -90,7 +90,7 @@
     <td>
         <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getPriceInclTax($_item); ?>
         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-            <div class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+            <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $_item->getId(); ?>"}'>
         <?php else: ?>
             <div class="cart-price">
         <?php endif; ?>
@@ -125,7 +125,7 @@
             </div>
 
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <div class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $_item->getId(); ?>"}'>
                     <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_incl+$_item->getWeeeTaxAppliedAmount()); ?></span>
                 </div>
             <?php endif; ?>
@@ -141,7 +141,7 @@
     <?php if ($this->helper('Mage_Tax_Helper_Data')->displayCartPriceExclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()): ?>
     <td class="a-right">
         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-            <div class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+            <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
         <?php else: ?>
             <div class="cart-price">
         <?php endif; ?>
@@ -176,7 +176,7 @@
             </div>
 
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <div class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
                     <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_item->getRowTotal()+$_item->getWeeeTaxAppliedRowAmount()+$_item->getWeeeTaxRowDisposition()); ?></span>
                 </div>
             <?php endif; ?>
@@ -190,7 +190,7 @@
     <td>
         <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getSubtotalInclTax($_item); ?>
         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-            <div class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+            <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
         <?php else: ?>
             <div class="cart-price">
         <?php endif; ?>
@@ -227,7 +227,7 @@
             </div>
 
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <div class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
                     <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_incl+$_item->getWeeeTaxAppliedRowAmount()); ?></span>
                 </div>
             <?php endif; ?>
diff --git a/app/code/core/Mage/Checkout/view/frontend/onepage/billing.phtml b/app/code/core/Mage/Checkout/view/frontend/onepage/billing.phtml
index a4f356b0b89357011f226e74ceb21a7afb1a6ee5..d9f03af15161913b81bbd5c7a6e6cda345434179 100644
--- a/app/code/core/Mage/Checkout/view/frontend/onepage/billing.phtml
+++ b/app/code/core/Mage/Checkout/view/frontend/onepage/billing.phtml
@@ -92,11 +92,6 @@
                             <select id="billing:region_id" name="billing[region_id]" title="<?php echo $this->__('State/Province') ?>" class="validate-select" style="display:none;">
                                 <option value=""><?php echo $this->__('Please select region, state or province') ?></option>
                             </select>
-                            <script type="text/javascript">
-                            //<![CDATA[
-                                $('billing:region_id').setAttribute('defaultValue',  "<?php echo $this->getAddress()->getRegionId() ?>");
-                            //]]>
-                            </script>
                             <input type="text" id="billing:region" name="billing[region]" value="<?php echo $this->escapeHtml($this->getAddress()->getRegion()) ?>"  title="<?php echo $this->__('State/Province') ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('region') ?>" style="display:none;" />
                         </div>
                     </div>
@@ -207,10 +202,28 @@
 //<![CDATA[
     var billing = new Billing('co-billing-form', '<?php echo $this->getUrl('checkout/onepage/getAddress') ?>address/', '<?php echo $this->getUrl('checkout/onepage/saveBilling') ?>');
     var billingForm = new VarienForm('co-billing-form');
-
-    //billingForm.setElementsRelation('billing:country_id', 'billing:region', '<?php echo $this->getUrl('directory/json/childRegion') ?>', '<?php echo $this->__('Select State/Province...') ?>');
     $('billing-address-select') && billing.newAddress(!$('billing-address-select').value);
-
-    var billingRegionUpdater = new RegionUpdater('billing:country_id', 'billing:region', 'billing:region_id', <?php echo $this->helper('Mage_Directory_Helper_Data')->getRegionJson() ?>, undefined, 'billing:postcode');
 //]]>
 </script>
+<script type="text/javascript">
+    (function($) {
+        head.js(
+            "<?php echo $this->getViewFileUrl('Mage_Checkout::js/region-updater.js') ?>",
+            function() {
+                $('#billing\\:country_id').regionUpdater({
+                    regionListId: '#billing\\:region_id',
+                    regionInputId: '#billing\\:region',
+                    postcodeId: '#billing\\:postcode',
+                    regionJson: <?php echo $this->helper('Mage_Directory_Helper_Data')->getRegionJson() ?>,
+                    defaultRegion: "<?php echo $this->getAddress()->getRegionId() ?>",
+                    countriesWithOptionalZip: <?php echo $this->helper('Mage_Directory_Helper_Data')->getCountriesWithOptionalZip(true) ?>,
+                    clearError: function() {
+                        var selectorArr = ['#billing\\:region_id', '#billing\\:region', '#billing\\:postcode'];
+                        for (var i = 0; i < selectorArr.length; i++) {
+                            $(selectorArr[i]).removeClass('validation-failed').next("div.validation-advice").remove();
+                        }
+                    }
+                });
+            });
+    })(jQuery);
+</script>
diff --git a/app/code/core/Mage/Checkout/view/frontend/onepage/review/item.phtml b/app/code/core/Mage/Checkout/view/frontend/onepage/review/item.phtml
index 95fc93ab72fb28293ec96c74ab77f033a8f4d546..a1b88afe87134d090a88d1ae44a212a434414269 100644
--- a/app/code/core/Mage/Checkout/view/frontend/onepage/review/item.phtml
+++ b/app/code/core/Mage/Checkout/view/frontend/onepage/review/item.phtml
@@ -52,7 +52,7 @@
     <?php if ($this->helper('Mage_Tax_Helper_Data')->displayCartPriceExclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()): ?>
     <td class="a-right">
         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-            <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+            <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $_item->getId(); ?>"}'>
         <?php else: ?>
             <span class="cart-price">
         <?php endif; ?>
@@ -89,7 +89,7 @@
             </div>
 
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <div class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $_item->getId(); ?>"}'>
                     <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_item->getCalculationPrice()+$_item->getWeeeTaxAppliedAmount()+$_item->getWeeeTaxDisposition()); ?></span>
                 </div>
             <?php endif; ?>
@@ -100,7 +100,7 @@
     <td>
         <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getPriceInclTax($_item); ?>
         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-            <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+            <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $_item->getId(); ?>"}'>
         <?php else: ?>
             <span class="cart-price">
         <?php endif; ?>
@@ -135,7 +135,7 @@
             </div>
 
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <div class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $_item->getId(); ?>"}'>
                     <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_incl+$_item->getWeeeTaxAppliedAmount()); ?></span>
                 </div>
             <?php endif; ?>
@@ -146,7 +146,7 @@
     <?php if ($this->helper('Mage_Tax_Helper_Data')->displayCartPriceExclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()): ?>
     <td class="a-right">
         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-            <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+            <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
         <?php else: ?>
             <span class="cart-price">
         <?php endif; ?>
@@ -181,7 +181,7 @@
             </div>
 
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <div class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
                     <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_item->getRowTotal()+$_item->getWeeeTaxAppliedRowAmount()+$_item->getWeeeTaxRowDisposition()); ?></span>
                 </div>
             <?php endif; ?>
@@ -192,7 +192,7 @@
     <td>
         <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getSubtotalInclTax($_item); ?>
         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-            <span class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+            <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
         <?php else: ?>
             <span class="cart-price">
         <?php endif; ?>
@@ -229,7 +229,7 @@
             </div>
 
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <div class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
                     <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_incl+$_item->getWeeeTaxAppliedRowAmount()); ?></span>
                 </div>
             <?php endif; ?>
diff --git a/app/code/core/Mage/Checkout/view/frontend/onepage/shipping.phtml b/app/code/core/Mage/Checkout/view/frontend/onepage/shipping.phtml
index d1bd71a07cc579c5ba724975acf593c65d30bf72..7104b52555d240fd44b3ba8421de15b3d9eae87a 100644
--- a/app/code/core/Mage/Checkout/view/frontend/onepage/shipping.phtml
+++ b/app/code/core/Mage/Checkout/view/frontend/onepage/shipping.phtml
@@ -83,11 +83,6 @@
                                 <select id="shipping:region_id" name="shipping[region_id]" title="<?php echo $this->__('State/Province') ?>" class="validate-select" style="display:none;">
                                     <option value=""><?php echo $this->__('Please select region, state or province') ?></option>
                                 </select>
-                                <script type="text/javascript">
-                                //<![CDATA[
-                                    $('shipping:region_id').setAttribute('defaultValue',  "<?php echo $this->getAddress()->getRegionId() ?>");
-                                //]]>
-                                </script>
                                 <input type="text" id="shipping:region" name="shipping[region]" value="<?php echo $this->escapeHtml($this->getAddress()->getRegion()) ?>" title="<?php echo $this->__('State/Province') ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('region') ?>" style="display:none;" />
                             </div>
                         </div>
@@ -148,9 +143,29 @@
         '<?php echo $this->getUrl('checkout/onepage/shippingMethod') ?>');
     var shippingForm = new VarienForm('co-shipping-form');
     shippingForm.extraChildParams = ' onchange="shipping.setSameAsBilling(false);"';
-    //shippingForm.setElementsRelation('shipping:country_id', 'shipping:region', '<?php echo $this->getUrl('directory/json/childRegion') ?>', '<?php echo $this->__('Select State/Province...') ?>');
     $('shipping-address-select') && shipping.newAddress(!$('shipping-address-select').value);
-
-    var shippingRegionUpdater = new RegionUpdater('shipping:country_id', 'shipping:region', 'shipping:region_id', <?php echo $this->helper('Mage_Directory_Helper_Data')->getRegionJson() ?>, undefined, 'shipping:postcode');
 //]]>
 </script>
+<script type="text/javascript">
+    (function($) {
+        head.js(
+            "<?php echo $this->getViewFileUrl('Mage_Checkout::js/region-updater.js') ?>",
+            function() {
+                $('#shipping\\:country_id').regionUpdater({
+                    regionListId: '#shipping\\:region_id',
+                    regionInputId: '#shipping\\:region',
+                    postcodeId: '#shipping\\:postcode',
+                    regionJson: <?php echo $this->helper('Mage_Directory_Helper_Data')->getRegionJson() ?>,
+                    defaultRegion: "<?php echo $this->getAddress()->getRegionId() ?>",
+                    countriesWithOptionalZip: <?php echo $this->helper('Mage_Directory_Helper_Data')->getCountriesWithOptionalZip(true) ?>,
+                    clearError: function() {
+                        var selectorArr = ['#shipping\\:region_id', '#shipping\\:region', '#shipping\\:postcode'];
+                        for (var i = 0; i < selectorArr.length; i++) {
+                            $(selectorArr[i]).removeClass('validation-failed').next("div.validation-advice").remove();
+                        }
+                    }
+                });
+            });
+    })(jQuery);
+</script>
+
diff --git a/app/code/core/Mage/Checkout/view/frontend/opcheckout.js b/app/code/core/Mage/Checkout/view/frontend/opcheckout.js
index e338f1977067c53943e1c8aecfa34d6bbf636aff..d475446b3440cebda3f59dd1f8ad1780f8b08053 100644
--- a/app/code/core/Mage/Checkout/view/frontend/opcheckout.js
+++ b/app/code/core/Mage/Checkout/view/frontend/opcheckout.js
@@ -346,10 +346,11 @@ Billing.prototype = {
             if ((typeof response.message) == 'string') {
                 alert(response.message);
             } else {
-                if (window.billingRegionUpdater) {
+                /*if (window.billingRegionUpdater) {
                     billingRegionUpdater.update();
-                }
-
+                }*/
+                // billingRegionUpdater is replaced with jQuery regionUpdater widget which use change event to call update
+                jQuery('#billing\\:country_id').trigger('change');
                 alert(response.message.join("\n"));
             }
 
@@ -458,7 +459,10 @@ Shipping.prototype = {
                 }
             }
             //$('shipping:country_id').value = $('billing:country_id').value;
-            shippingRegionUpdater.update();
+            //shippingRegionUpdater.update();
+            // shippingRegionUpdater is replaced with jQuery regionUpdater widget which use change event to call update
+            jQuery('#shipping\\:country_id').trigger('change');
+            $('shipping:same_as_billing').checked = true;
             $('shipping:region_id').value = $('billing:region_id').value;
             $('shipping:region').value = $('billing:region').value;
             //shippingForm.elementChildLoad($('shipping:country_id'), this.setRegionValue.bind(this));
@@ -506,9 +510,11 @@ Shipping.prototype = {
             if ((typeof response.message) == 'string') {
                 alert(response.message);
             } else {
-                if (window.shippingRegionUpdater) {
+                /*if (window.shippingRegionUpdater) {
                     shippingRegionUpdater.update();
-                }
+                }*/
+                // shippingRegionUpdater is replaced with jQuery regionUpdater widget which use change event to call update
+                jQuery('#shipping\\:country_id').trigger('change');
                 alert(response.message.join("\n"));
             }
 
diff --git a/app/code/core/Mage/Cms/Controller/Router.php b/app/code/core/Mage/Cms/Controller/Router.php
index a5d787f15c1b48254d990a01eb1cb1cf74a72b6d..6a1da845a108a11c67fe75097cc816d895569e5f 100644
--- a/app/code/core/Mage/Cms/Controller/Router.php
+++ b/app/code/core/Mage/Cms/Controller/Router.php
@@ -35,6 +35,8 @@
 class Mage_Cms_Controller_Router extends Mage_Core_Controller_Varien_Router_Abstract
 {
     /**
+     * Event manager
+     *
      * @var Mage_Core_Model_Event_Manager
      */
     protected $_eventManager;
@@ -95,7 +97,7 @@ class Mage_Cms_Controller_Router extends Mage_Core_Controller_Varien_Router_Abst
         $identifier = $condition->getIdentifier();
 
         if ($condition->getRedirectUrl()) {
-            Mage::app()->getFrontController()->getResponse()
+            Mage::getSingleton('Mage_Core_Controller_Response_Http')
                 ->setRedirect($condition->getRedirectUrl())
                 ->sendResponse();
             $request->setDispatched(true);
diff --git a/app/code/core/Mage/Cms/Model/Resource/Block.php b/app/code/core/Mage/Cms/Model/Resource/Block.php
index d767cecf404d27d86c750f8fc10d1b052e03008c..97ee06a384e83a7c50d528da9e642cf1b21b7521 100755
--- a/app/code/core/Mage/Cms/Model/Resource/Block.php
+++ b/app/code/core/Mage/Cms/Model/Resource/Block.php
@@ -169,7 +169,7 @@ class Mage_Cms_Model_Resource_Block extends Mage_Core_Model_Resource_Db_Abstract
         if ($object->getStoreId()) {
             $stores = array(
                 (int) $object->getStoreId(),
-                Mage_Core_Model_App::ADMIN_STORE_ID,
+                Mage_Core_Model_AppInterface::ADMIN_STORE_ID,
             );
 
             $select->join(
@@ -194,7 +194,7 @@ class Mage_Cms_Model_Resource_Block extends Mage_Core_Model_Resource_Db_Abstract
     public function getIsUniqueBlockToStores(Mage_Core_Model_Abstract $object)
     {
         if (Mage::app()->hasSingleStore()) {
-            $stores = array(Mage_Core_Model_App::ADMIN_STORE_ID);
+            $stores = array(Mage_Core_Model_AppInterface::ADMIN_STORE_ID);
         } else {
             $stores = (array)$object->getData('stores');
         }
diff --git a/app/code/core/Mage/Cms/Model/Resource/Block/Collection.php b/app/code/core/Mage/Cms/Model/Resource/Block/Collection.php
index a3838d05139506a00902c57d14789ccd7fba5123..fee5697693c32c452638d609882515a0022d4f8e 100755
--- a/app/code/core/Mage/Cms/Model/Resource/Block/Collection.php
+++ b/app/code/core/Mage/Cms/Model/Resource/Block/Collection.php
@@ -72,7 +72,7 @@ class Mage_Cms_Model_Resource_Block_Collection extends Mage_Core_Model_Resource_
         }
 
         if ($withAdmin) {
-            $store[] = Mage_Core_Model_App::ADMIN_STORE_ID;
+            $store[] = Mage_Core_Model_AppInterface::ADMIN_STORE_ID;
         }
 
         $this->addFilter('store', array('in' => $store), 'public');
diff --git a/app/code/core/Mage/Cms/Model/Resource/Page.php b/app/code/core/Mage/Cms/Model/Resource/Page.php
index 60a5ec522f7cde12df5bb4769682a2ad30440f61..c2f2c0b2bf257a13b4ab8b96bfbebbaab70ed97a 100755
--- a/app/code/core/Mage/Cms/Model/Resource/Page.php
+++ b/app/code/core/Mage/Cms/Model/Resource/Page.php
@@ -198,7 +198,7 @@ class Mage_Cms_Model_Resource_Page extends Mage_Core_Model_Resource_Db_Abstract
         $select = parent::_getLoadSelect($field, $value, $object);
 
         if ($object->getStoreId()) {
-            $storeIds = array(Mage_Core_Model_App::ADMIN_STORE_ID, (int)$object->getStoreId());
+            $storeIds = array(Mage_Core_Model_AppInterface::ADMIN_STORE_ID, (int)$object->getStoreId());
             $select->join(
                 array('cms_page_store' => $this->getTable('cms_page_store')),
                 $this->getMainTable() . '.page_id = cms_page_store.page_id',
@@ -247,7 +247,7 @@ class Mage_Cms_Model_Resource_Page extends Mage_Core_Model_Resource_Db_Abstract
     public function getIsUniquePageToStores(Mage_Core_Model_Abstract $object)
     {
         if (Mage::app()->hasSingleStore() || !$object->hasStores()) {
-            $stores = array(Mage_Core_Model_App::ADMIN_STORE_ID);
+            $stores = array(Mage_Core_Model_AppInterface::ADMIN_STORE_ID);
         } else {
             $stores = (array)$object->getData('stores');
         }
@@ -301,7 +301,7 @@ class Mage_Cms_Model_Resource_Page extends Mage_Core_Model_Resource_Db_Abstract
      */
     public function checkIdentifier($identifier, $storeId)
     {
-        $stores = array(Mage_Core_Model_App::ADMIN_STORE_ID, $storeId);
+        $stores = array(Mage_Core_Model_AppInterface::ADMIN_STORE_ID, $storeId);
         $select = $this->_getLoadByIdentifierSelect($identifier, $stores, 1);
         $select->reset(Zend_Db_Select::COLUMNS)
             ->columns('cp.page_id')
@@ -319,7 +319,7 @@ class Mage_Cms_Model_Resource_Page extends Mage_Core_Model_Resource_Db_Abstract
      */
     public function getCmsPageTitleByIdentifier($identifier)
     {
-        $stores = array(Mage_Core_Model_App::ADMIN_STORE_ID);
+        $stores = array(Mage_Core_Model_AppInterface::ADMIN_STORE_ID);
         if ($this->_store) {
             $stores[] = (int)$this->getStore()->getId();
         }
diff --git a/app/code/core/Mage/Cms/Model/Resource/Page/Collection.php b/app/code/core/Mage/Cms/Model/Resource/Page/Collection.php
index 54dcd825cb17fcb7bdfd0e67b55c9bfcfa3f3673..8330482998b3feca87f1a16e0eb95a0d86e28658 100755
--- a/app/code/core/Mage/Cms/Model/Resource/Page/Collection.php
+++ b/app/code/core/Mage/Cms/Model/Resource/Page/Collection.php
@@ -150,7 +150,7 @@ class Mage_Cms_Model_Resource_Page_Collection extends Mage_Core_Model_Resource_D
             }
 
             if ($withAdmin) {
-                $store[] = Mage_Core_Model_App::ADMIN_STORE_ID;
+                $store[] = Mage_Core_Model_AppInterface::ADMIN_STORE_ID;
             }
 
             $this->addFilter('store', array('in' => $store), 'public');
diff --git a/app/code/core/Mage/Connect/Helper/Data.php b/app/code/core/Mage/Connect/Helper/Data.php
index 18d8c10882847fbd499b1a4a6dbde17272eab2ed..b40a1937ace373885c11c85b46e8af1333650a9a 100644
--- a/app/code/core/Mage/Connect/Helper/Data.php
+++ b/app/code/core/Mage/Connect/Helper/Data.php
@@ -39,10 +39,16 @@ class Mage_Connect_Helper_Data extends Mage_Core_Helper_Data
     protected $_filesystem;
 
     /**
+     * @param Mage_Core_Model_Translate $translator
+     * @param Mage_Core_Model_Config_Modules $modulesConfig
      * @param Magento_Filesystem $filesystem
      */
-    public function __construct(Magento_Filesystem $filesystem)
-    {
+    public function __construct(
+        Mage_Core_Model_Translate $translator,
+        Mage_Core_Model_Config_Modules $modulesConfig,
+        Magento_Filesystem $filesystem
+    ) {
+        parent::__construct($translator, $modulesConfig);
         $this->_filesystem = $filesystem;
     }
 
diff --git a/app/code/core/Mage/Contacts/view/frontend/form.phtml b/app/code/core/Mage/Contacts/view/frontend/form.phtml
index 27ad0bbfa303830cf9da4c1c4070ec3e4a7121a9..1c424121995dd05ea399dd012d4c93c6d618c6a1 100644
--- a/app/code/core/Mage/Contacts/view/frontend/form.phtml
+++ b/app/code/core/Mage/Contacts/view/frontend/form.phtml
@@ -28,7 +28,7 @@
 <div class="page-title">
     <h1><?php echo Mage::helper('Mage_Contacts_Helper_Data')->__('Contact Us') ?></h1>
 </div>
-<form action="<?php echo $this->getFormAction(); ?>" id="contactForm" method="post">
+<form action="<?php echo $this->getFormAction(); ?>" id="contact-form" method="post">
     <div class="fieldset">
         <h2 class="legend"><?php echo Mage::helper('Mage_Contacts_Helper_Data')->__('Contact Information') ?></h2>
         <ul class="form-list">
@@ -36,13 +36,13 @@
                 <div class="field">
                     <label for="name" class="required"><em>*</em><?php echo Mage::helper('Mage_Contacts_Helper_Data')->__('Name') ?></label>
                     <div class="input-box">
-                        <input name="name" id="name" title="<?php echo Mage::helper('Mage_Contacts_Helper_Data')->__('Name') ?>" value="<?php echo $this->escapeHtml($this->helper('Mage_Contacts_Helper_Data')->getUserName()) ?>" class="input-text required-entry" type="text" />
+                        <input name="name" id="name" title="<?php echo Mage::helper('Mage_Contacts_Helper_Data')->__('Name') ?>" value="<?php echo $this->escapeHtml($this->helper('Mage_Contacts_Helper_Data')->getUserName()) ?>" class="input-text" type="text" data-validate="{required:true}"/>
                     </div>
                 </div>
                 <div class="field">
                     <label for="email" class="required"><em>*</em><?php echo Mage::helper('Mage_Contacts_Helper_Data')->__('Email') ?></label>
                     <div class="input-box">
-                        <input name="email" id="email" title="<?php echo Mage::helper('Mage_Contacts_Helper_Data')->__('Email') ?>" value="<?php echo $this->escapeHtml($this->helper('Mage_Contacts_Helper_Data')->getUserEmail()) ?>" class="input-text required-entry validate-email" type="text" />
+                        <input name="email" id="email" title="<?php echo Mage::helper('Mage_Contacts_Helper_Data')->__('Email') ?>" value="<?php echo $this->escapeHtml($this->helper('Mage_Contacts_Helper_Data')->getUserEmail()) ?>" class="input-text" type="text" data-validate="{required:true, 'validate-email':true}"/>
                     </div>
                 </div>
             </li>
@@ -55,7 +55,7 @@
             <li class="wide">
                 <label for="comment" class="required"><em>*</em><?php echo Mage::helper('Mage_Contacts_Helper_Data')->__('Comment') ?></label>
                 <div class="input-box">
-                    <textarea name="comment" id="comment" title="<?php echo Mage::helper('Mage_Contacts_Helper_Data')->__('Comment') ?>" class="required-entry input-text" cols="5" rows="3"></textarea>
+                    <textarea name="comment" id="comment" title="<?php echo Mage::helper('Mage_Contacts_Helper_Data')->__('Comment') ?>" class="input-text" cols="5" rows="3" data-validate="{required:true}"></textarea>
                 </div>
             </li>
         </ul>
@@ -67,7 +67,12 @@
     </div>
 </form>
 <script type="text/javascript">
-//<![CDATA[
-    var contactForm = new VarienForm('contactForm', true);
-//]]>
+    (function($) {
+        head.js("<?php echo $this->getViewFileUrl('jquery/jquery.validate.js')?>",
+            "<?php echo $this->getViewFileUrl('jquery/jquery.metadata.js')?>",
+            "<?php echo $this->getViewFileUrl('mage/validation.js')?>",
+            "<?php echo $this->getViewFileUrl('mage/validation/validation.js')?>", function() {
+                $('#contact-form').validation();
+            });
+    })(jQuery);
 </script>
diff --git a/app/code/core/Mage/Core/Block/Abstract.php b/app/code/core/Mage/Core/Block/Abstract.php
index 4b960fbf74cf493e9038e93d6e998594188a1e82..d47303833cf5e4547bda338d80f9eb186d5b911f 100644
--- a/app/code/core/Mage/Core/Block/Abstract.php
+++ b/app/code/core/Mage/Core/Block/Abstract.php
@@ -128,7 +128,7 @@ abstract class Mage_Core_Block_Abstract extends Varien_Object
      * @param Mage_Core_Model_Translate $translator
      * @param Mage_Core_Model_Cache $cache
      * @param Mage_Core_Model_Design_Package $designPackage
-     * @param Mage_Core_Model_Session $session
+     * @param Mage_Core_Model_Session_Abstract $session
      * @param Mage_Core_Model_Store_Config $storeConfig
      * @param Mage_Core_Controller_Varien_Front $frontController
      * @param Mage_Core_Model_Factory_Helper $helperFactory
@@ -144,7 +144,7 @@ abstract class Mage_Core_Block_Abstract extends Varien_Object
         Mage_Core_Model_Translate $translator,
         Mage_Core_Model_Cache $cache,
         Mage_Core_Model_Design_Package $designPackage,
-        Mage_Core_Model_Session $session,
+        Mage_Core_Model_Session_Abstract $session,
         Mage_Core_Model_Store_Config $storeConfig,
         Mage_Core_Controller_Varien_Front $frontController,
         Mage_Core_Model_Factory_Helper $helperFactory,
diff --git a/app/code/core/Mage/Core/Block/Messages.php b/app/code/core/Mage/Core/Block/Messages.php
index 7dc7d9ff2416847ec0e86403eac400aeda82e955..9d339b8e0cf128a4a2b226977df2e020563a8c3b 100644
--- a/app/code/core/Mage/Core/Block/Messages.php
+++ b/app/code/core/Mage/Core/Block/Messages.php
@@ -73,16 +73,36 @@ class Mage_Core_Block_Messages extends Mage_Core_Block_Template
      *
      * @var array
      */
-    protected $_usedStorageTypes = array('Mage_Core_Model_Session');
+    protected $_usedStorageTypes = array();
 
+    /**
+     * Grouped message types
+     *
+     * @var array
+     */
+    protected $_messageTypes = array(
+        Mage_Core_Model_Message::ERROR,
+        Mage_Core_Model_Message::WARNING,
+        Mage_Core_Model_Message::NOTICE,
+        Mage_Core_Model_Message::SUCCESS
+    );
+
+    /**
+     * Preparing global layout
+     *
+     * @return Mage_Core_Block_Messages
+     */
     public function _prepareLayout()
     {
-        $this->addMessages(Mage::getSingleton('Mage_Core_Model_Session')->getMessages(true));
+        $this->addStorageType(get_class($this->_session));
+        $this->addMessages($this->_session->getMessages(true));
         parent::_prepareLayout();
+        return $this;
     }
 
     /**
      * Set message escape flag
+     *
      * @param bool $flag
      * @return Mage_Core_Block_Messages
      */
@@ -221,6 +241,16 @@ class Mage_Core_Block_Messages extends Mage_Core_Block_Template
         return $html;
     }
 
+    /**
+     * Return grouped message types
+     *
+     * @return array
+     */
+    protected function _getMessageTypes()
+    {
+        return $this->_messageTypes;
+    }
+
     /**
      * Retrieve messages in HTML format grouped by type
      *
@@ -228,22 +258,16 @@ class Mage_Core_Block_Messages extends Mage_Core_Block_Template
      */
     public function getGroupedHtml()
     {
-        $types = array(
-            Mage_Core_Model_Message::ERROR,
-            Mage_Core_Model_Message::WARNING,
-            Mage_Core_Model_Message::NOTICE,
-            Mage_Core_Model_Message::SUCCESS
-        );
         $html = '';
-        foreach ($types as $type) {
-            if ( $messages = $this->getMessages($type) ) {
-                if ( !$html ) {
+        foreach ($this->_getMessageTypes() as $type) {
+            if ($messages = $this->getMessages($type)) {
+                if (!$html) {
                     $html .= '<' . $this->_messagesFirstLevelTagName . ' class="messages">';
                 }
                 $html .= '<' . $this->_messagesSecondLevelTagName . ' class="' . $type . '-msg">';
                 $html .= '<' . $this->_messagesFirstLevelTagName . '>';
 
-                foreach ( $messages as $message ) {
+                foreach ($messages as $message) {
                     $html.= '<' . $this->_messagesSecondLevelTagName . '>';
                     $html.= '<' . $this->_messagesContentWrapperTagName .  $this->getUiId('message', $type) .  '>';
                     $html.= ($this->_escapeMessageFlag) ? $this->escapeHtml($message->getText()) : $message->getText();
@@ -254,15 +278,25 @@ class Mage_Core_Block_Messages extends Mage_Core_Block_Template
                 $html .= '</' . $this->_messagesSecondLevelTagName . '>';
             }
         }
-        if ( $html) {
+        if ($html) {
             $html .= '</' . $this->_messagesFirstLevelTagName . '>';
         }
         return $html;
     }
 
+    /**
+     * Render block HTML
+     *
+     * @return string
+     */
     protected function _toHtml()
     {
-        return $this->getGroupedHtml();
+        if ($this->getTemplate()) {
+            $html = parent::_toHtml();
+        } else {
+            $html = $this->getGroupedHtml();
+        }
+        return $html;
     }
 
     /**
diff --git a/app/code/core/Mage/Core/Block/Template.php b/app/code/core/Mage/Core/Block/Template.php
index c68abf106657af6cfba41ab2f86cf3b5647115a6..e2539658faf2d9671e847a51ffd3aa102bfb05c3 100644
--- a/app/code/core/Mage/Core/Block/Template.php
+++ b/app/code/core/Mage/Core/Block/Template.php
@@ -90,7 +90,7 @@ class Mage_Core_Block_Template extends Mage_Core_Block_Abstract
      * @param Mage_Core_Model_Translate $translator
      * @param Mage_Core_Model_Cache $cache
      * @param Mage_Core_Model_Design_Package $designPackage
-     * @param Mage_Core_Model_Session $session
+     * @param Mage_Core_Model_Session_Abstract $session
      * @param Mage_Core_Model_Store_Config $storeConfig
      * @param Mage_Core_Controller_Varien_Front $frontController
      * @param Mage_Core_Model_Factory_Helper $helperFactory
@@ -109,7 +109,7 @@ class Mage_Core_Block_Template extends Mage_Core_Block_Abstract
         Mage_Core_Model_Translate $translator,
         Mage_Core_Model_Cache $cache,
         Mage_Core_Model_Design_Package $designPackage,
-        Mage_Core_Model_Session $session,
+        Mage_Core_Model_Session_Abstract $session,
         Mage_Core_Model_Store_Config $storeConfig,
         Mage_Core_Controller_Varien_Front $frontController,
         Mage_Core_Model_Factory_Helper $helperFactory,
diff --git a/app/code/core/Mage/Core/Controller/Front/Action.php b/app/code/core/Mage/Core/Controller/Front/Action.php
index 311c5d9298e817e7fc0f8618edaf275e07543292..14fdb1c738eb08e4b8979a111d4c15bf762338cf 100755
--- a/app/code/core/Mage/Core/Controller/Front/Action.php
+++ b/app/code/core/Mage/Core/Controller/Front/Action.php
@@ -72,6 +72,6 @@ class Mage_Core_Controller_Front_Action extends Mage_Core_Controller_Varien_Acti
         $args = func_get_args();
         $expr = new Mage_Core_Model_Translate_Expr(array_shift($args), $this->_getRealModuleName());
         array_unshift($args, $expr);
-        return Mage::app()->getTranslator()->translate($args);
+        return $this->_objectManager->get('Mage_Core_Model_Translate')->translate($args);
     }
 }
diff --git a/app/code/core/Mage/Core/Controller/Response/Http.php b/app/code/core/Mage/Core/Controller/Response/Http.php
index 0122b989dbd3fe1e4f57d64ba76cfa8b4e14b318..00d323b8999f7c93243af64db6c0be81e6eabcbc 100644
--- a/app/code/core/Mage/Core/Controller/Response/Http.php
+++ b/app/code/core/Mage/Core/Controller/Response/Http.php
@@ -79,7 +79,6 @@ class Mage_Core_Controller_Response_Http extends Zend_Controller_Response_Http
 
     public function sendResponse()
     {
-        Mage::dispatchEvent('http_response_send_before', array('response'=>$this));
         return parent::sendResponse();
     }
 
diff --git a/app/code/core/Mage/Core/Controller/Varien/Action.php b/app/code/core/Mage/Core/Controller/Varien/Action.php
index bf4916b90b967c3dc3cea4bfcd465626c29eca69..12714ed595faf07f0079e9837acf7832ac033d77 100755
--- a/app/code/core/Mage/Core/Controller/Varien/Action.php
+++ b/app/code/core/Mage/Core/Controller/Varien/Action.php
@@ -144,18 +144,18 @@ abstract class Mage_Core_Controller_Varien_Action extends Mage_Core_Controller_V
      *
      * @param Mage_Core_Controller_Request_Http $request
      * @param Mage_Core_Controller_Response_Http $response
-     * @param string $areaCode
      * @param Magento_ObjectManager $objectManager
      * @param Mage_Core_Controller_Varien_Front $frontController
      * @param Mage_Core_Model_Layout_Factory $layoutFactory
+     * @param string $areaCode
      */
     public function __construct(
         Mage_Core_Controller_Request_Http $request,
-        Mage_Core_Controller_Response_Http $response,
-        $areaCode = null,
+        Mage_Core_Controller_Response_Http $response,        
         Magento_ObjectManager $objectManager,
         Mage_Core_Controller_Varien_Front $frontController,
-        Mage_Core_Model_Layout_Factory $layoutFactory
+        Mage_Core_Model_Layout_Factory $layoutFactory,
+        $areaCode = null
     ) {
         parent::__construct($request, $response, $areaCode);
 
diff --git a/app/code/core/Mage/Core/Controller/Varien/Front.php b/app/code/core/Mage/Core/Controller/Varien/Front.php
index 84394705bdf56bd9e22a4b61c113d3c7d4e6cfc1..bf58920df50c8f78f329b87005ab4f5c27a49e72 100644
--- a/app/code/core/Mage/Core/Controller/Varien/Front.php
+++ b/app/code/core/Mage/Core/Controller/Varien/Front.php
@@ -217,6 +217,7 @@ class Mage_Core_Controller_Varien_Front extends Varien_Object implements Mage_Co
         // This event gives possibility to launch something before sending output (allow cookie setting)
         Mage::dispatchEvent('controller_front_send_response_before', array('front'=>$this));
         Magento_Profiler::start('send_response');
+        Mage::dispatchEvent('http_response_send_before', array('response'=>$this));
         $this->getResponse()->sendResponse();
         Magento_Profiler::stop('send_response');
         Mage::dispatchEvent('controller_front_send_response_after', array('front'=>$this));
diff --git a/app/code/core/Mage/Core/Controller/Varien/Router/Base.php b/app/code/core/Mage/Core/Controller/Varien/Router/Base.php
index d714be5457f095b0443546e204b1179b64e2e2e6..9ec6c39662a16784bd3291fe564a3a4539774bfe 100644
--- a/app/code/core/Mage/Core/Controller/Varien/Router/Base.php
+++ b/app/code/core/Mage/Core/Controller/Varien/Router/Base.php
@@ -55,9 +55,15 @@ class Mage_Core_Controller_Varien_Router_Base extends Mage_Core_Controller_Varie
      */
     protected $_baseController;
 
+    /**
+     * @var Mage_Core_Model_App
+     */
+    protected $_app;
+
     /**
      * @param Mage_Core_Controller_Varien_Action_Factory $controllerFactory
      * @param Magento_Filesystem $filesystem
+     * @param Mage_Core_Model_App $app
      * @param string $areaCode
      * @param string $baseController
      * @throws InvalidArgumentException
@@ -65,11 +71,13 @@ class Mage_Core_Controller_Varien_Router_Base extends Mage_Core_Controller_Varie
     public function __construct(
         Mage_Core_Controller_Varien_Action_Factory $controllerFactory,
         Magento_Filesystem $filesystem,
+        Mage_Core_Model_App $app,
         $areaCode,
         $baseController
     ) {
         parent::__construct($controllerFactory);
 
+        $this->_app            = $app;
         $this->_filesystem     = $filesystem;
         $this->_areaCode       = $areaCode;
         $this->_baseController = $baseController;
@@ -170,6 +178,8 @@ class Mage_Core_Controller_Varien_Router_Base extends Mage_Core_Controller_Varie
             return null;
         }
 
+        $this->_app->loadAreaPart($this->_areaCode, Mage_Core_Model_App_Area::PART_CONFIG);
+
         return $this->_matchController($request, $params);
     }
 
diff --git a/app/code/core/Mage/Core/Helper/Abstract.php b/app/code/core/Mage/Core/Helper/Abstract.php
index 2ef160537cb81c7e6e2c0739ee31bb5c58656b4b..4495454f7af2a23af3b28bcc45b8181553d8e232 100755
--- a/app/code/core/Mage/Core/Helper/Abstract.php
+++ b/app/code/core/Mage/Core/Helper/Abstract.php
@@ -50,6 +50,21 @@ abstract class Mage_Core_Helper_Abstract
      */
     protected $_layout;
 
+    /**
+     * Translator model
+     *
+     * @var Mage_Core_Model_Translate
+     */
+    protected $_translator;
+
+    /**
+     * @param Mage_Core_Model_Translate $translator
+     */
+    public function __construct(Mage_Core_Model_Translate $translator)
+    {
+        $this->_translator = $translator;
+    }
+
     /**
      * Retrieve request object
      *
@@ -58,7 +73,7 @@ abstract class Mage_Core_Helper_Abstract
     protected function _getRequest()
     {
         if (!$this->_request) {
-            $this->_request = Mage::app()->getRequest();
+            $this->_request = Mage::getObjectManager()->get('Mage_Core_Controller_Request_Http');
         }
         return $this->_request;
     }
@@ -183,7 +198,7 @@ abstract class Mage_Core_Helper_Abstract
         $args = func_get_args();
         $expr = new Mage_Core_Model_Translate_Expr(array_shift($args), $this->_getModuleName());
         array_unshift($args, $expr);
-        return Mage::app()->getTranslator()->translate($args);
+        return $this->_translator->translate($args);
     }
 
     /**
diff --git a/app/code/core/Mage/Core/Helper/Cookie.php b/app/code/core/Mage/Core/Helper/Cookie.php
index 4b8f408a04f018e92df535c32fb7ee168498cab3..52628789c08668d1b18e1370a6dd41f87cd67525 100644
--- a/app/code/core/Mage/Core/Helper/Cookie.php
+++ b/app/code/core/Mage/Core/Helper/Cookie.php
@@ -64,10 +64,13 @@ class Mage_Core_Helper_Cookie extends Mage_Core_Helper_Abstract
     protected $_website;
 
     /**
+     * @param Mage_Core_Model_Translate $translator
      * @param array $data
+     * @throws InvalidArgumentException
      */
-    public function __construct(array $data = array())
+    public function __construct(Mage_Core_Model_Translate $translator, array $data = array())
     {
+        parent::__construct($translator);
         $this->_currentStore = isset($data['current_store']) ? $data['current_store'] : Mage::app()->getStore();
 
         if (!($this->_currentStore instanceof Mage_Core_Model_Store)) {
diff --git a/app/code/core/Mage/Core/Helper/Data.php b/app/code/core/Mage/Core/Helper/Data.php
index 523d5a5097229b335246fe5a64b95e3e44ce9a8d..595a7628e18e274e69fbcae3031918bec2fa30c2 100644
--- a/app/code/core/Mage/Core/Helper/Data.php
+++ b/app/code/core/Mage/Core/Helper/Data.php
@@ -81,6 +81,20 @@ class Mage_Core_Helper_Data extends Mage_Core_Helper_Abstract
         Mage_Core_Model_Locale::FORMAT_TYPE_SHORT
     );
 
+    /**
+     * @var Mage_Core_Model_Config_Modules
+     */
+    protected $_config;
+
+    /**
+     * @param Mage_Core_Model_Translate $translator
+     * @param Mage_Core_Model_Config_Modules $config
+     */
+    public function __construct(Mage_Core_Model_Translate $translator, Mage_Core_Model_Config_Modules $config)
+    {
+        parent::__construct($translator);
+        $this->_config = $config;
+    }
 
     /**
      * @return Mage_Core_Model_Encryption
@@ -88,11 +102,13 @@ class Mage_Core_Helper_Data extends Mage_Core_Helper_Abstract
     public function getEncryptor()
     {
         if ($this->_encryptor === null) {
-            $encryptionModel = (string)Mage::getConfig()->getNode(self::XML_PATH_ENCRYPTION_MODEL);
-            if (empty($encryptionModel)) {
+            $encryptionModel = (string)$this->_config->getNode(self::XML_PATH_ENCRYPTION_MODEL);
+
+            if (!$encryptionModel) {
                 $encryptionModel = 'Mage_Core_Model_Encryption';
             }
-            $this->_encryptor = Mage::getModel($encryptionModel);
+
+            $this->_encryptor = Mage::getObjectManager()->create($encryptionModel);
 
             $this->_encryptor->setHelper($this);
         }
@@ -741,9 +757,10 @@ XML;
      */
     public function useDbCompatibleMode()
     {
-        $connType = (string) Mage::getConfig()->getNode(self::XML_PATH_CONNECTION_TYPE);
-        $path = 'global/resource/connection/types/' . $connType . '/compatibleMode';
-        $value = (string) Mage::getConfig()->getNode($path);
+        /** @var $resourceConfig Mage_Core_Model_Config_Resource */
+        $resourceConfig = Mage::getSingleton('Mage_Core_Model_Config_Resource');
+        $connType = (string) $resourceConfig->getResourceConnectionConfig('default_setup')->type;
+        $value = (string) $resourceConfig->getResourceTypeConfig($connType)->compatibleMode;
         return (bool) $value;
     }
 
diff --git a/app/code/core/Mage/Core/Helper/Js.php b/app/code/core/Mage/Core/Helper/Js.php
index 075392f462e9953b84cd68fc4c81e4152300c472..1fec738297ba33201a5ee0ddc5027e72f832dbc9 100644
--- a/app/code/core/Mage/Core/Helper/Js.php
+++ b/app/code/core/Mage/Core/Helper/Js.php
@@ -55,6 +55,25 @@ class Mage_Core_Helper_Js extends Mage_Core_Helper_Abstract
      */
     protected $_config = null;
 
+    /**
+     * Modules configuration reader
+     *
+     * @var Mage_Core_Model_Config_Modules_Reader
+     */
+    protected $_configReader;
+
+    /**
+     * @param Mage_Core_Model_Translate $translator
+     * @param Mage_Core_Model_Config_Modules_Reader $configReader
+     */
+    public function __construct(
+        Mage_Core_Model_Translate $translator,
+        Mage_Core_Model_Config_Modules_Reader $configReader
+    ) {
+        parent::__construct($translator);
+        $this->_configReader = $configReader;
+    }
+
     /**
      * Retrieve JSON of JS sentences translation
      *
@@ -142,7 +161,7 @@ class Mage_Core_Helper_Js extends Mage_Core_Helper_Abstract
             } else {
                 $xmlConfig = new Varien_Simplexml_Config();
                 $xmlConfig->loadString('<?xml version="1.0"?><jstranslator></jstranslator>');
-                Mage::getConfig()->loadModulesConfiguration(self::JAVASCRIPT_TRANSLATE_CONFIG_FILENAME, $xmlConfig);
+                $this->_configReader->loadModulesConfiguration(self::JAVASCRIPT_TRANSLATE_CONFIG_FILENAME, $xmlConfig);
 
                 if ($canUsaCache) {
                     Mage::app()->saveCache($xmlConfig->getXmlString(), self::JAVASCRIPT_TRANSLATE_CONFIG_KEY,
diff --git a/app/code/core/Mage/Core/Helper/Theme.php b/app/code/core/Mage/Core/Helper/Theme.php
new file mode 100644
index 0000000000000000000000000000000000000000..bcc626f007cfb3b657389fb79f3eecb6bc184a46
--- /dev/null
+++ b/app/code/core/Mage/Core/Helper/Theme.php
@@ -0,0 +1,398 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_Core
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Theme data helper
+ */
+class Mage_Core_Helper_Theme extends Mage_Core_Helper_Abstract
+{
+    /**
+     * XPath selector to get CSS files from layout added for HEAD block directly
+     */
+    const XPATH_SELECTOR_BLOCKS =
+        '//block[@type="Mage_Page_Block_Html_Head"]/action[@method="addCss" or @method="addCssIe"]/*[1]';
+
+    /**
+     * XPath selector to get CSS files from layout added for HEAD block using reference
+     */
+    const XPATH_SELECTOR_REFS =
+        '//reference[@name="head"]/action[@method="addCss" or @method="addCssIe"]/*[1]';
+
+    /**
+     * Design model
+     *
+     * @var Mage_Core_Model_Design_Package
+     */
+    protected $_design;
+
+    /**
+     * Directories
+     *
+     * @var Mage_Core_Model_Dir
+     */
+    protected $_dirs;
+
+    /**
+     * Layout merge factory
+     *
+     * @var Mage_Core_Model_Layout_Merge_Factory
+     */
+    protected $_layoutMergeFactory;
+
+    /**
+     * Theme collection model
+     *
+     * @var Mage_Core_Model_Resource_Theme_Collection
+     */
+    protected $_themeCollection;
+
+    /**
+     * Constructor
+     *
+     * @param Mage_Core_Model_Design_Package $design
+     * @param Mage_Core_Model_Dir $dirs
+     * @param Mage_Core_Model_Layout_Merge_Factory $layoutMergeFactory
+     * @param Mage_Core_Model_Resource_Theme_Collection $themeCollection
+     * @param Mage_Core_Model_Translate $translator
+     */
+    public function __construct(
+        Mage_Core_Model_Design_Package $design,
+        Mage_Core_Model_Dir $dirs,
+        Mage_Core_Model_Layout_Merge_Factory $layoutMergeFactory,
+        Mage_Core_Model_Resource_Theme_Collection $themeCollection,
+        Mage_Core_Model_Translate $translator
+    ) {
+        $this->_design = $design;
+        $this->_dirs = $dirs;
+        $this->_layoutMergeFactory = $layoutMergeFactory;
+        $this->_themeCollection = $themeCollection;
+        parent::__construct($translator);
+    }
+
+    /**
+     * Get CSS files of a given theme
+     *
+     * Returned array has a structure
+     * array(
+     *   'Mage_Catalog::widgets.css' => 'http://mage2.com/pub/media/theme/frontend/_theme15/en_US/Mage_Cms/widgets.css'
+     * )
+     *
+     * @param Mage_Core_Model_Theme $theme
+     * @return array
+     */
+    public function getCssFiles($theme)
+    {
+        $arguments = array(
+            'area'  => $theme->getArea(),
+            'theme' => $theme->getThemeId()
+        );
+        /** @var $layoutMerge Mage_Core_Model_Layout_Merge */
+        $layoutMerge = $this->_layoutMergeFactory->create(array('arguments' => $arguments));
+        $layoutElement = $layoutMerge->getFileLayoutUpdatesXml();
+
+        $elements = array_merge(
+            $layoutElement->xpath(self::XPATH_SELECTOR_REFS),
+            $layoutElement->xpath(self::XPATH_SELECTOR_BLOCKS)
+        );
+
+        $params = array(
+            'area'       => $theme->getArea(),
+            'themeModel' => $theme,
+            'skipProxy'  => true
+        );
+
+        $basePath = $this->_dirs->getDir(Mage_Core_Model_Dir::ROOT);
+        $files = array();
+        foreach ($elements as $fileId) {
+            $fileId = (string)$fileId;
+            $path = $this->_design->getViewFile($fileId, $params);
+            $file = array(
+                'id'       => $fileId,
+                'path'     => Magento_Filesystem::fixSeparator($path),
+             );
+            $file['safePath'] = $this->getSafePath($file['path'], $basePath);
+
+            //keys are used also to remove duplicates
+            $files[$fileId] = $file;
+        }
+
+        return $files;
+    }
+
+    /**
+     * Get CSS files by group
+     *
+     * @param Mage_Core_Model_Theme $theme
+     * @return array
+     * @throws Mage_Core_Exception
+     */
+    public function getGroupedCssFiles($theme)
+    {
+        $jsDir = $this->_dirs->getDir(Mage_Core_Model_Dir::PUB_LIB);
+        $codeDir = $this->_dirs->getDir(Mage_Core_Model_Dir::MODULES);
+        $designDir = $this->_dirs->getDir(Mage_Core_Model_Dir::THEMES);
+
+        $groups = array();
+        $themes = array();
+        foreach ($this->getCssFiles($theme) as $file) {
+            $this->_detectTheme($file, $designDir);
+            $this->_detectGroup($file);
+
+            if (isset($file['theme']) && $file['theme']->getThemeId()) {
+                $themes[$file['theme']->getThemeId()] = $file['theme'];
+            }
+
+            if (!isset($file['group'])) {
+                Mage::throwException(
+                    $this->__('Group is missed for file "%s"', $file['safePath'])
+                );
+            }
+            $group = $file['group'];
+            unset($file['theme']);
+            unset($file['group']);
+
+            if (!isset($groups[$group])) {
+                $groups[$group] = array();
+            }
+            $groups[$group][] = $file;
+        }
+
+        if (count($themes) > 1) {
+            $themes = $this->_sortThemesByHierarchy($themes);
+        }
+
+        $order = array_merge(array($codeDir, $jsDir), array_map(function ($fileTheme) {
+            /** @var $fileTheme Mage_Core_Model_Theme */
+            return $fileTheme->getThemeId();
+        }, $themes));
+        $groups = $this->_sortArrayByArray($groups, $order);
+
+        $labels = $this->_getGroupLabels($themes, $jsDir, $codeDir);
+        foreach ($groups as $key => $group) {
+            usort($group, array($this, '_sortGroupFilesCallback'));
+            $groups[$labels[$key]] = $group;
+            unset($groups[$key]);
+        }
+        return $groups;
+    }
+
+    /**
+     * Detect theme view file belongs to and set it to file data under "theme" key
+     *
+     * @param array $file
+     * @param string $designDir
+     * @return Mage_Theme_Helper_Data
+     * @throws Mage_Core_Exception
+     */
+    protected function _detectTheme(&$file, $designDir)
+    {
+        //TODO use cache here, so files of the same theme share one model
+
+        $isInsideDesignDir = substr($file['path'], 0, strlen($designDir)) == $designDir;
+        if (!$isInsideDesignDir) {
+            return $this;
+        }
+
+        $relativePath = substr($file['path'], strlen($designDir));
+
+        $area = strtok($relativePath, Magento_Filesystem::DIRECTORY_SEPARATOR);
+        $package = strtok(Magento_Filesystem::DIRECTORY_SEPARATOR);
+        $theme = strtok(Magento_Filesystem::DIRECTORY_SEPARATOR);
+
+        if ($area === false || $package === false || $theme === false) {
+            Mage::throwException($this->__('Theme path "%s/%s/%s" is incorrect', $area, $package, $theme));
+        }
+        $themeModel = $this->_themeCollection->getThemeByFullPath($area . '/' . $package . '/' . $theme);
+
+        if (!$themeModel || !$themeModel->getThemeId()) {
+            Mage::throwException($this->__('Invalid theme loaded by theme path "%s/%s/%s"', $area, $package, $theme));
+        }
+
+        $file['theme'] = $themeModel;
+
+        return $this;
+    }
+
+    /**
+     * Detect group where file should be placed and set it to file data under "group" key
+     *
+     * @param array $file
+     * @return Mage_Theme_Helper_Data
+     * @throws Mage_Core_Exception
+     */
+    protected function _detectGroup(&$file)
+    {
+        $jsDir = $this->_dirs->getDir(Mage_Core_Model_Dir::PUB_LIB);
+        $codeDir = $this->_dirs->getDir(Mage_Core_Model_Dir::MODULES);
+        $designDir = $this->_dirs->getDir(Mage_Core_Model_Dir::THEMES);
+
+        $group = null;
+        if (substr($file['path'], 0, strlen($designDir)) == $designDir) {
+            if (!isset($file['theme']) || !$file['theme']->getThemeId()) {
+                Mage::throwException(
+                    $this->__('Theme is missed for file "%s"', $file['safePath'])
+                );
+            }
+            $group = $file['theme']->getThemeId();
+        } elseif (substr($file['path'], 0, strlen($jsDir)) == $jsDir) {
+            $group = $jsDir;
+        } elseif (substr($file['path'], 0, strlen($codeDir)) == $codeDir) {
+            $group = $codeDir;
+        } else {
+            Mage::throwException(
+                $this->__('Invalid view file directory "%s"', $file['safePath'])
+            );
+        }
+        $file['group'] = $group;
+
+        return $this;
+    }
+
+    /**
+     * Sort themes according to their hierarchy
+     *
+     * @param array $themes
+     * @return array
+     */
+    protected function _sortThemesByHierarchy(array $themes)
+    {
+        uasort($themes, array($this, '_sortThemesByHierarchyCallback'));
+        return $themes;
+    }
+
+    /**
+     * Sort one associative array according to another array
+     *
+     * $groups = array(
+     *     b => item2,
+     *     a => item1,
+     *     c => item3,
+     * );
+     * $order = array(a,b,c);
+     * result: array(
+     *     a => item1,
+     *     b => item2,
+     *     c => item3,
+     * )
+     *
+     * @param array $groups
+     * @param array $order
+     * @return array
+     */
+    protected function _sortArrayByArray(array $groups, array $order)
+    {
+        $ordered = array();
+        foreach ($order as $key) {
+            if (array_key_exists($key, $groups)) {
+                $ordered[$key] = $groups[$key];
+                unset($groups[$key]);
+            }
+        }
+        return $ordered + $groups;
+    }
+
+    /**
+     * Get group labels
+     *
+     * @param array $themes
+     * @param string $jsDir
+     * @param string $codeDir
+     * @return array
+     */
+    protected function _getGroupLabels(array $themes, $jsDir, $codeDir)
+    {
+        $labels = array(
+            $jsDir => $this->__('Library files'),
+            $codeDir => $this->__('Framework files')
+        );
+        foreach ($themes as $theme) {
+            /** @var $theme Mage_Core_Model_Theme */
+            $labels[$theme->getThemeId()] = $this->__('"%s" Theme files', $theme->getThemeTitle());
+        }
+        return $labels;
+    }
+
+    /**
+     * Callback for sorting files inside group
+     *
+     * Return "1" if $firstFile should go before $secondFile, otherwise return "-1"
+     *
+     * @param array $firstFile
+     * @param array $secondFile
+     * @return int
+     */
+    protected function _sortGroupFilesCallback(array $firstFile, array $secondFile)
+    {
+        $hasContextFirst = strpos($firstFile['id'], '::') !== false;
+        $hasContextSecond = strpos($secondFile['id'], '::') !== false;
+
+        if ($hasContextFirst && $hasContextSecond) {
+            $result = strcmp($firstFile['id'], $secondFile['id']);
+        } elseif (!$hasContextFirst && !$hasContextSecond) {
+            $result = strcmp($firstFile['id'], $secondFile['id']);
+        } elseif ($hasContextFirst) {
+            //case when first item has module context and second item doesn't
+            $result = 1;
+        } else {
+            //case when second item has module context and first item doesn't
+            $result = -1;
+        }
+        return $result;
+    }
+
+    /**
+     * Sort themes by hierarchy callback
+     *
+     * @param Mage_Core_Model_Theme $firstTheme
+     * @param Mage_Core_Model_Theme $secondTheme
+     * @return int
+     */
+    protected function _sortThemesByHierarchyCallback($firstTheme, $secondTheme)
+    {
+        $parentTheme = $firstTheme->getParentTheme();
+        while ($parentTheme) {
+            if ($parentTheme->getThemeId() == $secondTheme->getThemeId()) {
+                return -1;
+            }
+            $parentTheme = $parentTheme->getParentTheme();
+        }
+        return 1;
+    }
+
+    /**
+     * Get relative file path cut to be safe for public sharing
+     *
+     * Path is considered from the base Magento directory
+     *
+     * @param string $filePath
+     * @param string $basePath
+     * @return string
+     */
+    public function getSafePath($filePath, $basePath)
+    {
+        return ltrim(str_ireplace($basePath, '', $filePath), '\\/');
+    }
+}
diff --git a/app/code/core/Mage/Core/Helper/Translate.php b/app/code/core/Mage/Core/Helper/Translate.php
index 6154c7c68efe0096f974911394aa652380b1e101..3e6262137fa8c4f32ab02295482efd54aa4e685f 100644
--- a/app/code/core/Mage/Core/Helper/Translate.php
+++ b/app/code/core/Mage/Core/Helper/Translate.php
@@ -51,28 +51,4 @@ class Mage_Core_Helper_Translate extends Mage_Core_Helper_Abstract
             return $returnType == 'json' ? "{error:true,message:'" . $e->getMessage() . "'}" : false;
         }
     }
-
-    /**
-     * Compose locale inheritance hierarchy based on given config
-     *
-     * @param array $localeConfig assoc array where key is a code of locale and value is a code of its parent locale
-     * @return array
-     */
-    public function composeLocaleHierarchy(array $localeConfig)
-    {
-        $localeHierarchy = array();
-        foreach ($localeConfig as $locale => $localeParent) {
-            $localeParents = array($localeParent);
-            while (isset($localeConfig[$localeParent]) && !in_array($localeConfig[$localeParent], $localeParents)
-                && $locale != $localeConfig[$localeParent]
-            ) {
-                // inheritance chain starts with the deepest parent
-                array_unshift($localeParents, $localeConfig[$localeParent]);
-                $localeParent = $localeConfig[$localeParent];
-            }
-            // store hierarchy for current locale
-            $localeHierarchy[$locale] = $localeParents;
-        }
-        return $localeHierarchy;
-    }
 }
diff --git a/app/code/core/Mage/Core/Helper/Url.php b/app/code/core/Mage/Core/Helper/Url.php
index 7a3db68709a45babb71e7ba7e6799c9c935b5181..97b1a1c8bd24b6e0a4dadac3020439dee081352b 100644
--- a/app/code/core/Mage/Core/Helper/Url.php
+++ b/app/code/core/Mage/Core/Helper/Url.php
@@ -33,6 +33,13 @@
  */
 class Mage_Core_Helper_Url extends Mage_Core_Helper_Abstract
 {
+    /**
+     * @param Mage_Core_Model_Translate $translate
+     */
+    public function __construct(Mage_Core_Model_Translate $translate)
+    {
+        parent::__construct($translate);
+    }
 
     /**
      * Retrieve current url
@@ -41,8 +48,8 @@ class Mage_Core_Helper_Url extends Mage_Core_Helper_Abstract
      */
     public function getCurrentUrl()
     {
-        $request = Mage::app()->getRequest();
-        $port = $request->getServer('SERVER_PORT');
+        $request = $this->_getRequest();
+        $port = $this->_getRequest()->getServer('SERVER_PORT');
         if ($port) {
             $defaultPorts = array(
                 Mage_Core_Controller_Request_Http::DEFAULT_HTTP_PORT,
@@ -52,7 +59,6 @@ class Mage_Core_Helper_Url extends Mage_Core_Helper_Abstract
         }
         $url = $request->getScheme() . '://' . $request->getHttpHost() . $port . $request->getServer('REQUEST_URI');
         return $url;
-//        return $this->_getUrl('*/*/*', array('_current' => true, '_use_rewrite' => true));
     }
 
     /**
@@ -65,7 +71,7 @@ class Mage_Core_Helper_Url extends Mage_Core_Helper_Abstract
         return $this->urlEncode($this->getCurrentUrl());
     }
 
-    public function getEncodedUrl($url=null)
+    public function getEncodedUrl($url = null)
     {
         if (!$url) {
             $url = $this->getCurrentUrl();
@@ -125,9 +131,9 @@ class Mage_Core_Helper_Url extends Mage_Core_Helper_Abstract
 
     /**
      * Remove request parameter from url
-     *
      * @param string $url
      * @param string $paramKey
+     * @param bool $caseSensitive
      * @return string
      */
     public function removeRequestParam($url, $paramKey, $caseSensitive = false)
diff --git a/app/code/core/Mage/Core/Model/Abstract.php b/app/code/core/Mage/Core/Model/Abstract.php
index 0c709a43a491b0eda128df9e4f81bb807bdf090d..43b0af61b0d27cd288810395daa9c1b9f17b20e0 100644
--- a/app/code/core/Mage/Core/Model/Abstract.php
+++ b/app/code/core/Mage/Core/Model/Abstract.php
@@ -28,9 +28,7 @@
 /**
  * Abstract model class
  *
- * @category    Mage
- * @package     Mage_Core
- * @author      Magento Core Team <core@magentocommerce.com>
+ * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  */
 abstract class Mage_Core_Model_Abstract extends Varien_Object
 {
@@ -75,14 +73,14 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
      *
      * @var string
      */
-    protected $_resourceCollectionName;
+    protected $_collectionName;
 
     /**
      * Model cache tag for clear cache in after save and after delete
      *
      * When you use true - all cache will be clean
      *
-     * @var string || true
+     * @var string|array|true
      */
     protected $_cacheTag = false;
 
@@ -161,7 +159,6 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
      * Standard model initialization
      *
      * @param string $resourceModel
-     * @param string $idFieldName
      * @return Mage_Core_Model_Abstract
      */
     protected function _init($resourceModel)
@@ -190,26 +187,26 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
     public function __wakeup()
     {
         if (Mage::getIsSerializable()) {
-            $this->_eventDispatcher = Mage::getObjectManager()->get('Mage_Core_Model_Event_Manager');
-            $this->_cacheManager    = Mage::getObjectManager()->get('Mage_Core_Model_Cache');
+            $this->_eventDispatcher = Mage::getSingleton('Mage_Core_Model_Event_Manager');
+            $this->_cacheManager    = Mage::getSingleton('Mage_Core_Model_Cache');
         }
     }
 
     /**
      * Set resource names
      *
-     * If collection name is ommited, resource name will be used with _collection appended
+     * If collection name is omitted, resource name will be used with _collection appended
      *
      * @param string $resourceName
-     * @param string|null $resourceCollectionName
+     * @param string|null $collectionName
      */
-    protected function _setResourceModel($resourceName, $resourceCollectionName = null)
+    protected function _setResourceModel($resourceName, $collectionName = null)
     {
         $this->_resourceName = $resourceName;
-        if (is_null($resourceCollectionName)) {
-            $resourceCollectionName = $resourceName . '_Collection';
+        if (is_null($collectionName)) {
+            $collectionName = $resourceName . '_Collection';
         }
-        $this->_resourceCollectionName = $resourceCollectionName;
+        $this->_collectionName = $collectionName;
     }
 
     /**
@@ -243,14 +240,14 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
      */
     public function getResourceCollection()
     {
-        if (empty($this->_resourceCollectionName) &&  empty($this->_resourceCollection)) {
+        if (empty($this->_resourceCollection) && empty($this->_collectionName)) {
             Mage::throwException(
                 Mage::helper('Mage_Core_Helper_Data')->__('Model collection resource name is not defined.')
             );
         }
         return $this->_resourceCollection ?
             clone $this->_resourceCollection :
-            Mage::getResourceModel($this->_resourceCollectionName, array('resource' => $this->_getResource()));
+            Mage::getResourceModel($this->_collectionName, array('resource' => $this->_getResource()));
     }
 
     /**
@@ -266,13 +263,14 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
     /**
      * Load object data
      *
-     * @param   integer $id
-     * @return  Mage_Core_Model_Abstract
+     * @param integer $modelId
+     * @param null|string $field
+     * @return Mage_Core_Model_Abstract
      */
-    public function load($id, $field=null)
+    public function load($modelId, $field = null)
     {
-        $this->_beforeLoad($id, $field);
-        $this->_getResource()->load($this, $id, $field);
+        $this->_beforeLoad($modelId, $field);
+        $this->_getResource()->load($this, $modelId, $field);
         $this->_afterLoad();
         $this->setOrigData();
         $this->_hasDataChanges = false;
@@ -280,7 +278,7 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
     }
 
     /**
-     * Get array of objects transfered to default events processing
+     * Get array of objects transferred to default events processing
      *
      * @return array
      */
@@ -295,14 +293,16 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
     /**
      * Processing object before load data
      *
+     * @param int $modelId
+     * @param null|string $field
      * @return Mage_Core_Model_Abstract
      */
-    protected function _beforeLoad($id, $field = null)
+    protected function _beforeLoad($modelId, $field = null)
     {
-        $params = array('object' => $this, 'field' => $field, 'value'=> $id);
+        $params = array('object' => $this, 'field' => $field, 'value' => $modelId);
         $this->_eventDispatcher->dispatch('model_load_before', $params);
         $params = array_merge($params, $this->_getEventData());
-        $this->_eventDispatcher->dispatch($this->_eventPrefix.'_load_before', $params);
+        $this->_eventDispatcher->dispatch($this->_eventPrefix . '_load_before', $params);
         return $this;
     }
 
@@ -313,8 +313,8 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
      */
     protected function _afterLoad()
     {
-        $this->_eventDispatcher->dispatch('model_load_after', array('object'=>$this));
-        $this->_eventDispatcher->dispatch($this->_eventPrefix.'_load_after', $this->_getEventData());
+        $this->_eventDispatcher->dispatch('model_load_after', array('object' => $this));
+        $this->_eventDispatcher->dispatch($this->_eventPrefix . '_load_after', $this->_getEventData());
         return $this;
     }
 
@@ -346,6 +346,7 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
      * Save object data
      *
      * @return Mage_Core_Model_Abstract
+     * @throws Exception
      */
     public function save()
     {
@@ -384,21 +385,21 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
      */
     public function afterCommitCallback()
     {
-        $this->_eventDispatcher->dispatch('model_save_commit_after', array('object'=>$this));
-        $this->_eventDispatcher->dispatch($this->_eventPrefix.'_save_commit_after', $this->_getEventData());
+        $this->_eventDispatcher->dispatch('model_save_commit_after', array('object' => $this));
+        $this->_eventDispatcher->dispatch($this->_eventPrefix . '_save_commit_after', $this->_getEventData());
         return $this;
     }
 
     /**
      * Check object state (true - if it is object without id on object just created)
      * This method can help detect if object just created in _afterSave method
-     * problem is what in after save onject has id and we can't detect what object was
+     * problem is what in after save object has id and we can't detect what object was
      * created in this transaction
      *
-     * @param bool $flag
+     * @param bool|null $flag
      * @return bool
      */
-    public function isObjectNew($flag=null)
+    public function isObjectNew($flag = null)
     {
         if ($flag !== null) {
             $this->_isObjectNew = $flag;
@@ -419,7 +420,7 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
         if (!$this->getId()) {
             $this->isObjectNew(true);
         }
-        $this->_eventDispatcher->dispatch('model_save_before', array('object'=>$this));
+        $this->_eventDispatcher->dispatch('model_save_before', array('object' => $this));
         $this->_eventDispatcher->dispatch($this->_eventPrefix . '_save_before', $this->_getEventData());
         return $this;
     }
@@ -476,7 +477,7 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
             $validator = new Zend_Validate();
             $validator->addValidator($modelRules);
             $validator->addValidator($resourceRules);
-        } else if ($modelRules) {
+        } elseif ($modelRules) {
             $validator = $modelRules;
         } else {
             $validator = $resourceRules;
@@ -499,7 +500,7 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
      * Get list of cache tags applied to model object.
      * Return false if cache tags are not supported by model
      *
-     * @return array | false
+     * @return array|false
      */
     public function getCacheTags()
     {
@@ -523,7 +524,7 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
     }
 
     /**
-     * Get cahce tags associated with object id
+     * Get cache tags associated with object id
      *
      * @return array
      */
@@ -534,17 +535,17 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
             $tags = array();
             if (is_array($this->_cacheTag)) {
                 foreach ($this->_cacheTag as $_tag) {
-                    $tags[] = $_tag.'_'.$this->getId();
+                    $tags[] = $_tag . '_' . $this->getId();
                 }
             } else {
-                $tags[] = $this->_cacheTag.'_'.$this->getId();
+                $tags[] = $this->_cacheTag . '_' . $this->getId();
             }
         }
         return $tags;
     }
 
     /**
-     * Remove model onject related cache
+     * Remove model object related cache
      *
      * @return Mage_Core_Model_Abstract
      */
@@ -565,8 +566,8 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
     protected function _afterSave()
     {
         $this->cleanModelCache();
-        $this->_eventDispatcher->dispatch('model_save_after', array('object'=>$this));
-        $this->_eventDispatcher->dispatch($this->_eventPrefix.'_save_after', $this->_getEventData());
+        $this->_eventDispatcher->dispatch('model_save_after', array('object' => $this));
+        $this->_eventDispatcher->dispatch($this->_eventPrefix . '_save_after', $this->_getEventData());
         return $this;
     }
 
@@ -574,6 +575,7 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
      * Delete object from database
      *
      * @return Mage_ Core_Model_Abstract
+     * @throws Exception
      */
     public function delete()
     {
@@ -585,8 +587,7 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
 
             $this->_getResource()->commit();
             $this->_afterDeleteCommit();
-        }
-        catch (Exception $e){
+        } catch (Exception $e) {
             $this->_getResource()->rollBack();
             throw $e;
         }
@@ -594,14 +595,14 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
     }
 
     /**
-     * Processing object before delete datac
+     * Processing object before delete data
      *
      * @return Mage_Core_Model_Abstract
      */
     protected function _beforeDelete()
     {
-        $this->_eventDispatcher->dispatch('model_delete_before', array('object'=>$this));
-        $this->_eventDispatcher->dispatch($this->_eventPrefix.'_delete_before', $this->_getEventData());
+        $this->_eventDispatcher->dispatch('model_delete_before', array('object' => $this));
+        $this->_eventDispatcher->dispatch($this->_eventPrefix . '_delete_before', $this->_getEventData());
         $this->cleanModelCache();
         return $this;
     }
@@ -617,7 +618,8 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
             return;
         }
         if (!Mage::app()->getStore()->isAdmin()) {
-            Mage::throwException(Mage::helper('Mage_Core_Helper_Data')->__('Cannot complete this operation from non-admin area.'));
+            Mage::throwException(Mage::helper('Mage_Core_Helper_Data')
+                ->__('Cannot complete this operation from non-admin area.'));
         }
     }
 
@@ -628,8 +630,8 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
      */
     protected function _afterDelete()
     {
-        $this->_eventDispatcher->dispatch('model_delete_after', array('object'=>$this));
-        $this->_eventDispatcher->dispatch($this->_eventPrefix.'_delete_after', $this->_getEventData());
+        $this->_eventDispatcher->dispatch('model_delete_after', array('object' => $this));
+        $this->_eventDispatcher->dispatch($this->_eventPrefix . '_delete_after', $this->_getEventData());
         return $this;
     }
 
@@ -640,8 +642,8 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
      */
     protected function _afterDeleteCommit()
     {
-         $this->_eventDispatcher->dispatch('model_delete_commit_after', array('object'=>$this));
-         $this->_eventDispatcher->dispatch($this->_eventPrefix.'_delete_commit_after', $this->_getEventData());
+         $this->_eventDispatcher->dispatch('model_delete_commit_after', array('object' => $this));
+         $this->_eventDispatcher->dispatch($this->_eventPrefix . '_delete_commit_after', $this->_getEventData());
          return $this;
     }
 
@@ -673,7 +675,7 @@ abstract class Mage_Core_Model_Abstract extends Varien_Object
     final public function clearInstance()
     {
         $this->_clearReferences();
-        $this->_eventDispatcher->dispatch($this->_eventPrefix.'_clear', $this->_getEventData());
+        $this->_eventDispatcher->dispatch($this->_eventPrefix . '_clear', $this->_getEventData());
         $this->_clearData();
         return $this;
     }
diff --git a/app/code/core/Mage/Core/Model/App.php b/app/code/core/Mage/Core/Model/App.php
index c8393e2e8a92f07ae561a8c80e0912e17d7dd3dc..f58e013eb2bcdee1994520fdbc5a958b93f40a60 100644
--- a/app/code/core/Mage/Core/Model/App.php
+++ b/app/code/core/Mage/Core/Model/App.php
@@ -33,84 +33,8 @@
  * @package     Mage_Core
  * @author      Magento Core Team <core@magentocommerce.com>
  */
-class Mage_Core_Model_App
+class Mage_Core_Model_App implements Mage_Core_Model_AppInterface
 {
-    /**
-     * Scope code initialization option
-     */
-    const INIT_OPTION_SCOPE_CODE = 'MAGE_RUN_CODE';
-
-    /**
-     * Scope type initialization option
-     */
-    const INIT_OPTION_SCOPE_TYPE = 'MAGE_RUN_TYPE';
-
-    /**
-     * Custom directory paths initialization option
-     */
-    const INIT_OPTION_URIS = 'app_uris';
-
-    /**
-     * Custom directory absolute paths initialization option
-     */
-    const INIT_OPTION_DIRS = 'app_dirs';
-
-    /**#@+
-     * Available scope types
-     */
-    const SCOPE_TYPE_STORE   = 'store';
-    const SCOPE_TYPE_GROUP   = 'group';
-    const SCOPE_TYPE_WEBSITE = 'website';
-    /**#@-*/
-
-    /**
-     * Xml path install date
-     */
-    const XML_PATH_INSTALL_DATE = 'global/install/date';
-
-    /**
-     * Xml path: global skip modules update
-     */
-    const XML_PATH_SKIP_PROCESS_MODULES_UPDATES = 'global/skip_process_modules_updates';
-
-    /**
-     * if this node set to true, we will ignore Developer Mode for applying updates
-     */
-    const XML_PATH_IGNORE_DEV_MODE = 'global/skip_process_modules_updates_ignore_dev_mode';
-
-    /**
-     * Default error handler
-     */
-    const DEFAULT_ERROR_HANDLER = 'mageCoreErrorHandler';
-
-    /**
-     * Default application locale
-     */
-    const DISTRO_LOCALE_CODE = 'en_US';
-
-    /**
-     * Cache tag for all cache data exclude config cache
-     *
-     */
-    const CACHE_TAG = 'MAGE';
-
-    /**
-     * Default store Id (for install)
-     */
-    const DISTRO_STORE_ID = 1;
-
-    /**
-     * Default store code (for install)
-     *
-     */
-    const DISTRO_STORE_CODE = Mage_Core_Model_Store::DEFAULT_CODE;
-
-    /**
-     * Admin store Id
-     *
-     */
-    const ADMIN_STORE_ID = 0;
-
     /**
      * Application loaded areas array
      *
@@ -118,20 +42,6 @@ class Mage_Core_Model_App
      */
     protected $_areas = array();
 
-    /**
-     * Application store object
-     *
-     * @var Mage_Core_Model_Store
-     */
-    protected $_store;
-
-    /**
-     * Application website object
-     *
-     * @var Mage_Core_Model_Website
-     */
-    protected $_website;
-
     /**
      * Application location object
      *
@@ -139,20 +49,6 @@ class Mage_Core_Model_App
      */
     protected $_locale;
 
-    /**
-     * Application translate object
-     *
-     * @var Mage_Core_Model_Translate
-     */
-    protected $_translator;
-
-    /**
-     * Initialization parameters
-     *
-     * @var array
-     */
-    protected $_initParams = null;
-
     /**
      * Application configuration object
      *
@@ -181,53 +77,6 @@ class Mage_Core_Model_App
      */
     protected $_cache;
 
-    /**
-     * Use Cache
-     *
-     * @var array
-     */
-    protected $_useCache;
-
-    /**
-     * Websites cache
-     *
-     * @var array
-     */
-    protected $_websites = array();
-
-    /**
-     * Groups cache
-     *
-     * @var array
-     */
-    protected $_groups = array();
-
-    /**
-     * Stores cache
-     *
-     * @var array
-     */
-    protected $_stores = array();
-
-    /**
-     * Flag that shows that system has only one store view
-     *
-     * @var bool
-     */
-    protected $_hasSingleStore;
-
-    /**
-     * @var bool
-     */
-    protected $_isSingleStoreAllowed = true;
-
-    /**
-     * Default store code
-     *
-     * @var string
-     */
-    protected $_currentStore;
-
     /**
      * Request object
      *
@@ -242,20 +91,6 @@ class Mage_Core_Model_App
      */
     protected $_response;
 
-    /**
-     * Events cache
-     *
-     * @var array
-     */
-    protected $_events = array();
-
-    /**
-     * Update process run flag
-     *
-     * @var bool
-     */
-    protected $_updateMode = false;
-
     /**
      * Use session in URL flag
      *
@@ -271,13 +106,6 @@ class Mage_Core_Model_App
      */
     protected $_useSessionVar = false;
 
-    /**
-     * Cache locked flag
-     *
-     * @var bool
-     */
-    protected $_isCacheLocked;
-
     /**
      * Object manager
      *
@@ -286,161 +114,79 @@ class Mage_Core_Model_App
     protected $_objectManager;
 
     /**
-     * Constructor
+     * Data base updater object
+     *
+     * @var Mage_Core_Model_Db_UpdaterInterface
      */
-    public function __construct(
-        Mage_Core_Controller_Varien_Front $frontController,
-        Magento_ObjectManager $objectManager
-    ) {
-        $this->_frontController = $frontController;
-        $this->_objectManager = $objectManager;
-    }
+    protected $_dbUpdater;
 
     /**
-     * Initialize application without request processing
-     *
-     * @param  array $params
-     * @return Mage_Core_Model_App
+     * Store list manager
+     * 
+     * @var Mage_Core_Model_StoreManager
      */
-    public function init(array $params)
-    {
-        $this->_initEnvironment();
-        $this->_initParams = $params;
-        $this->_initFilesystem();
-        $logger = $this->_initLogger();
-
-        Magento_Profiler::start('init_config');
-        /** @var $config Mage_Core_Model_Config */
-        $config = $this->_objectManager->create('Mage_Core_Model_Config');
-        $this->_config = $config;
-        $this->_initBaseConfig();
-        $this->_initCache();
-        $this->_config->init();
-        $this->loadAreaPart(Mage_Core_Model_App_Area::AREA_GLOBAL, Mage_Core_Model_App_Area::PART_EVENTS);
-        Magento_Profiler::stop('init_config');
-
-        if (Mage::isInstalled()) {
-            $this->_initCurrentStore(
-                $this->getInitParam(self::INIT_OPTION_SCOPE_CODE),
-                $this->getInitParam(self::INIT_OPTION_SCOPE_TYPE) ?: self::SCOPE_TYPE_STORE
-            );
-            $logger->initForStore($this->_store, $this->_config);
-            $this->_initRequest();
-        }
-        return $this;
-    }
+    protected $_storeManager;
 
     /**
-     * Common logic for all run types
-     *
-     * @param  array $params
-     * @return Mage_Core_Model_App
+     * @var Mage_Core_Model_App_State
      */
-    public function baseInit(array $params)
-    {
-        $this->_initEnvironment();
-        $this->_initParams = $params;
-        $this->_initFilesystem();
-        $this->_initLogger();
-
-        /** @var $config Mage_Core_Model_Config */
-        $config = $this->_objectManager->get('Mage_Core_Model_Config');
-        $this->_config = $config;
-        $this->_initBaseConfig();
-        $this->_initCache($this->getInitParam(Mage_Core_Model_Cache::APP_INIT_PARAM) ?: array());
-
-        return $this;
-    }
+    protected $_appState;
 
     /**
-     * Run light version of application with specified modules support
-     *
-     * @see Mage_Core_Model_App->run()
-     *
-     * @param  array $params
-     * @param  string|array $modules
-     * @return Mage_Core_Model_App
+     * @var Mage_Core_Model_Event_Manager
      */
-    public function initSpecified(array $params, $modules = array())
-    {
-        $this->baseInit($params);
+    protected $_eventManager;
 
-        if (!empty($modules)) {
-            $this->_config->addAllowedModules($modules);
-        }
-        $this->_initModules();
-        $this->_initCurrentStore(
-            $this->getInitParam(self::INIT_OPTION_SCOPE_CODE),
-            $this->getInitParam(self::INIT_OPTION_SCOPE_TYPE) ?: self::SCOPE_TYPE_STORE
-        );
-
-        return $this;
+    /**
+     * @param Mage_Core_Model_Config $config
+     * @param Mage_Core_Controller_Varien_Front $frontController
+     * @param Mage_Core_Model_Cache $cache
+     * @param Magento_ObjectManager $objectManager
+     * @param Mage_Core_Model_Db_UpdaterInterface $dbUpdater
+     * @param Mage_Core_Model_StoreManager $storeManager
+     * @param Mage_Core_Model_Event_Manager $eventManager
+     * @param Mage_Core_Model_App_State $appState
+     */
+    public function __construct(
+        Mage_Core_Model_Config $config,
+        Mage_Core_Controller_Varien_Front $frontController,
+        Mage_Core_Model_Cache $cache,
+        Magento_ObjectManager $objectManager,
+        Mage_Core_Model_Db_UpdaterInterface $dbUpdater,
+        Mage_Core_Model_StoreManager $storeManager,
+        Mage_Core_Model_Event_Manager $eventManager,
+        Mage_Core_Model_App_State $appState
+    ) {
+        $this->_config = $config;
+        $this->_cache = $cache;
+        $this->_objectManager = $objectManager;
+        $this->_storeManager = $storeManager;
+        $this->_dbUpdater = $dbUpdater;
+        $this->_frontController = $frontController;
+        $this->_appState = $appState;
+        $this->_eventManager = $eventManager;
     }
 
     /**
      * Run application. Run process responsible for request processing and sending response.
      *
-     * @param array $params
      * @return Mage_Core_Model_App
      */
-    public function run(array $params)
+    public function run()
     {
         Magento_Profiler::start('init');
 
-        $this->baseInit($params);
+        $this->_initRequest();
+        $this->_dbUpdater->updateData();
 
+        $controllerFront = $this->getFrontController();
         Magento_Profiler::stop('init');
 
-        if ($this->_cache->processRequest($this->getResponse())) {
-            $this->getResponse()->sendResponse();
-        } else {
-            Magento_Profiler::start('init');
-
-            $this->_initModules();
-            $this->loadAreaPart(Mage_Core_Model_App_Area::AREA_GLOBAL, Mage_Core_Model_App_Area::PART_EVENTS);
-
-            if ($this->_config->isLocalConfigLoaded()) {
-                $this->_initCurrentStore(
-                    $this->getInitParam(self::INIT_OPTION_SCOPE_CODE),
-                    $this->getInitParam(self::INIT_OPTION_SCOPE_TYPE) ?: self::SCOPE_TYPE_STORE
-                );
-                /** @var $logger Mage_Core_Model_Logger */
-                $logger = $this->_objectManager->get('Mage_Core_Model_Logger');
-                $logger->initForStore($this->_store, $this->_config);
-                $this->_initRequest();
-                Mage_Core_Model_Resource_Setup::applyAllDataUpdates();
-            }
+        $controllerFront->dispatch();
 
-            $controllerFront = $this->getFrontController();
-            Magento_Profiler::stop('init');
-            $controllerFront->dispatch();
-        }
         return $this;
     }
 
-    /**
-     * Get initialization parameter
-     *
-     * Returns false if key does not exist in array or the value is null
-     *
-     * @param string $key
-     * @return mixed|bool
-     */
-    public function getInitParam($key)
-    {
-        return isset($this->_initParams[$key]) ? $this->_initParams[$key] : false;
-    }
-
-    /**
-     * Whether the application has been installed or not
-     *
-     * @return bool
-     */
-    public function isInstalled()
-    {
-        return (bool)$this->_config->getInstallDate();
-    }
-
     /**
      * Throw an exception, if the application has not been installed yet
      *
@@ -448,130 +194,11 @@ class Mage_Core_Model_App
      */
     public function requireInstalledInstance()
     {
-        if (!$this->isInstalled()) {
+        if (false == $this->_appState->isInstalled()) {
             throw new Magento_Exception('Application is not installed yet, please complete the installation first.');
         }
     }
 
-    /**
-     * Initialize PHP environment
-     *
-     * @return Mage_Core_Model_App
-     */
-    protected function _initEnvironment()
-    {
-        $this->setErrorHandler(self::DEFAULT_ERROR_HANDLER);
-        date_default_timezone_set(Mage_Core_Model_Locale::DEFAULT_TIMEZONE);
-        return $this;
-    }
-
-    /**
-     * Create necessary directories in the file system
-     */
-    protected function _initFileSystem()
-    {
-        $customDirs = $this->getInitParam(self::INIT_OPTION_URIS) ?: array();
-        $customPaths = $this->getInitParam(self::INIT_OPTION_DIRS) ?: array();
-        $dirs = new Mage_Core_Model_Dir(BP, $customDirs, $customPaths);
-        $this->_objectManager->addSharedInstance($dirs, 'Mage_Core_Model_Dir');
-        foreach (Mage_Core_Model_Dir::getWritableDirCodes() as $code) {
-            $path = $dirs->getDir($code);
-            if ($path && !is_dir($path)) {
-                mkdir($path);
-            }
-        }
-    }
-
-    /**
-     * Initialize base system configuration (local.xml and config.xml files).
-     * Base configuration provide ability initialize DB connection and cache backend
-     *
-     * @return Mage_Core_Model_App
-     */
-    protected function _initBaseConfig()
-    {
-        Magento_Profiler::start('init_system_config');
-        $this->_config->loadBase();
-        Magento_Profiler::stop('init_system_config');
-        return $this;
-    }
-
-    /**
-     * Initialize application cache instance
-     *
-     * @param array $cacheInitOptions
-     * @return Mage_Core_Model_App
-     */
-    protected function _initCache(array $cacheInitOptions = array())
-    {
-        $this->_isCacheLocked = true;
-        $options = $this->_config->getNode('global/cache');
-        if ($options) {
-            $options = $options->asArray();
-        } else {
-            $options = array();
-        }
-        $options = array_merge($options, $cacheInitOptions);
-        $this->_cache = $this->_objectManager->create('Mage_Core_Model_Cache', array('options' => $options), false);
-        $this->_objectManager->addSharedInstance($this->_cache, 'Mage_Core_Model_Cache');
-        $this->_isCacheLocked = false;
-        return $this;
-    }
-
-    /**
-     * Initialize configuration of active modules and locales
-     *
-     * @return Mage_Core_Model_App
-     */
-    protected function _initModules()
-    {
-        if (!$this->_config->loadModulesCache()) {
-            $this->_config->loadModules();
-            if ($this->_config->isLocalConfigLoaded() && !$this->_shouldSkipProcessModulesUpdates()) {
-                Magento_Profiler::start('apply_db_schema_updates');
-                Mage_Core_Model_Resource_Setup::applyAllUpdates();
-                Magento_Profiler::stop('apply_db_schema_updates');
-            }
-            $this->_config->loadDb();
-            $this->_config->loadLocales();
-            $this->_config->saveCache();
-        }
-        return $this;
-    }
-
-    /**
-     * Initialize logging of system messages and errors
-     *
-     * @return Mage_Core_Model_Logger
-     */
-    protected function _initLogger()
-    {
-        /** @var $logger Mage_Core_Model_Logger */
-        $logger = $this->_objectManager->create('Mage_Core_Model_Logger');
-        $logger->addStreamLog(Mage_Core_Model_Logger::LOGGER_SYSTEM)
-            ->addStreamLog(Mage_Core_Model_Logger::LOGGER_EXCEPTION);
-        return $logger;
-    }
-
-    /**
-     * Check whether modules updates processing should be skipped
-     *
-     * @return bool
-     */
-    protected function _shouldSkipProcessModulesUpdates()
-    {
-        if (!Mage::isInstalled()) {
-            return false;
-        }
-
-        $ignoreDevelopmentMode = (bool)(string)$this->_config->getNode(self::XML_PATH_IGNORE_DEV_MODE);
-        if (Mage::getIsDeveloperMode() && !$ignoreDevelopmentMode) {
-            return false;
-        }
-
-        return (bool)(string)$this->_config->getNode(self::XML_PATH_SKIP_PROCESS_MODULES_UPDATES);
-    }
-
     /**
      * Init request object
      *
@@ -583,49 +210,6 @@ class Mage_Core_Model_App
         return $this;
     }
 
-    /**
-     * Initialize currently ran store
-     *
-     * @param string $scopeCode code of default scope (website/store_group/store code)
-     * @param string $scopeType type of default scope (website/group/store)
-     * @return Mage_Core_Model_App
-     * @throws Mage_Core_Model_Store_Exception
-     */
-    protected function _initCurrentStore($scopeCode, $scopeType)
-    {
-        Magento_Profiler::start('init_stores');
-        $this->_initStores();
-        Magento_Profiler::stop('init_stores');
-
-        if (empty($scopeCode) && !is_null($this->_website)) {
-            $scopeCode = $this->_website->getCode();
-            $scopeType = self::SCOPE_TYPE_WEBSITE;
-        }
-        switch ($scopeType) {
-            case self::SCOPE_TYPE_STORE:
-                $this->_currentStore = $scopeCode;
-                break;
-            case self::SCOPE_TYPE_GROUP:
-                $this->_currentStore = $this->_getStoreByGroup($scopeCode);
-                break;
-            case self::SCOPE_TYPE_WEBSITE:
-                $this->_currentStore = $this->_getStoreByWebsite($scopeCode);
-                break;
-            default:
-                $this->throwStoreException();
-        }
-
-        if (!empty($this->_currentStore)) {
-            $this->_checkCookieStore($scopeType);
-            $this->_checkGetStore($scopeType);
-        }
-        $this->_useSessionInUrl = $this->getStore()->getConfig(
-            Mage_Core_Model_Session_Abstract::XML_PATH_USE_FRONTEND_SID
-        );
-        Mage::dispatchEvent('core_app_init_current_store_after');
-        return $this;
-    }
-
     /**
      * Retrieve cookie object
      *
@@ -633,254 +217,7 @@ class Mage_Core_Model_App
      */
     public function getCookie()
     {
-        return Mage::getSingleton('Mage_Core_Model_Cookie');
-    }
-
-    /**
-     * Check get store
-     *
-     * @param string $type
-     * @return Mage_Core_Model_App
-     */
-    protected function _checkGetStore($type)
-    {
-        if (empty($_GET)) {
-            return $this;
-        }
-
-        /**
-         * @todo check XML_PATH_STORE_IN_URL
-         */
-        if (!isset($_GET['___store'])) {
-            return $this;
-        }
-
-        $store = $_GET['___store'];
-        if (!isset($this->_stores[$store])) {
-            return $this;
-        }
-
-        $storeObj = $this->_stores[$store];
-        if (!$storeObj->getId() || !$storeObj->getIsActive()) {
-            return $this;
-        }
-
-        /**
-         * prevent running a store from another website or store group,
-         * if website or store group was specified explicitly in Mage::run()
-         */
-        $curStoreObj = $this->_stores[$this->_currentStore];
-        if ($type == 'website' && $storeObj->getWebsiteId() == $curStoreObj->getWebsiteId()) {
-            $this->_currentStore = $store;
-        } elseif ($type == 'group' && $storeObj->getGroupId() == $curStoreObj->getGroupId()) {
-            $this->_currentStore = $store;
-        } elseif ($type == 'store') {
-            $this->_currentStore = $store;
-        }
-
-        if ($this->_currentStore == $store) {
-            $store = $this->getStore($store);
-            if ($store->getWebsite()->getDefaultStore()->getId() == $store->getId()) {
-                $this->getCookie()->delete(Mage_Core_Model_Store::COOKIE_NAME);
-            } else {
-                $this->getCookie()->set(Mage_Core_Model_Store::COOKIE_NAME, $this->_currentStore, true);
-            }
-        }
-        return $this;
-    }
-
-    /**
-     * Check cookie store
-     *
-     * @param string $type
-     * @return Mage_Core_Model_App
-     */
-    protected function _checkCookieStore($type)
-    {
-        if (!$this->getCookie()->get()) {
-            return $this;
-        }
-
-        $store = $this->getCookie()->get(Mage_Core_Model_Store::COOKIE_NAME);
-        if ($store && isset($this->_stores[$store])
-            && $this->_stores[$store]->getId()
-            && $this->_stores[$store]->getIsActive()
-        ) {
-            if ($type == 'website'
-                && $this->_stores[$store]->getWebsiteId() == $this->_stores[$this->_currentStore]->getWebsiteId()
-            ) {
-                $this->_currentStore = $store;
-            }
-            if ($type == 'group'
-                && $this->_stores[$store]->getGroupId() == $this->_stores[$this->_currentStore]->getGroupId()
-            ) {
-                $this->_currentStore = $store;
-            }
-            if ($type == 'store') {
-                $this->_currentStore = $store;
-            }
-        }
-        return $this;
-    }
-
-    /**
-     * Re-init stores
-     */
-    public function reinitStores()
-    {
-        return $this->_initStores();
-    }
-
-    /**
-     * Init store, group and website collections
-     */
-    protected function _initStores()
-    {
-        $this->_stores   = array();
-        $this->_groups   = array();
-        $this->_website  = null;
-        $this->_websites = array();
-
-        /** @var $websiteCollection Mage_Core_Model_Website */
-        $websiteCollection = Mage::getModel('Mage_Core_Model_Website')->getCollection()
-                ->initCache($this->getCache(), 'app', array(Mage_Core_Model_Website::CACHE_TAG))
-                ->setLoadDefault(true);
-
-        /** @var $websiteCollection Mage_Core_Model_Store_Group */
-        $groupCollection = Mage::getModel('Mage_Core_Model_Store_Group')->getCollection()
-                ->initCache($this->getCache(), 'app', array(Mage_Core_Model_Store_Group::CACHE_TAG))
-                ->setLoadDefault(true);
-
-        /** @var $websiteCollection Mage_Core_Model_Store */
-        $storeCollection = Mage::getModel('Mage_Core_Model_Store')->getCollection()
-            ->initCache($this->getCache(), 'app', array(Mage_Core_Model_Store::CACHE_TAG))
-            ->setLoadDefault(true);
-
-        $this->_hasSingleStore = false;
-        if ($this->_isSingleStoreAllowed) {
-            $this->_hasSingleStore = $storeCollection->count() < 3;
-        }
-
-        $websiteStores = array();
-        $websiteGroups = array();
-        $groupStores   = array();
-
-        foreach ($storeCollection as $store) {
-            /** @var $store Mage_Core_Model_Store */
-            $store->initConfigCache();
-            $store->setWebsite($websiteCollection->getItemById($store->getWebsiteId()));
-            $store->setGroup($groupCollection->getItemById($store->getGroupId()));
-
-            $this->_stores[$store->getId()] = $store;
-            $this->_stores[$store->getCode()] = $store;
-
-            $websiteStores[$store->getWebsiteId()][$store->getId()] = $store;
-            $groupStores[$store->getGroupId()][$store->getId()] = $store;
-
-            if (is_null($this->_store) && $store->getId()) {
-                $this->_store = $store;
-            }
-        }
-
-        foreach ($groupCollection as $group) {
-            /* @var $group Mage_Core_Model_Store_Group */
-            if (!isset($groupStores[$group->getId()])) {
-                $groupStores[$group->getId()] = array();
-            }
-            $group->setStores($groupStores[$group->getId()]);
-            $group->setWebsite($websiteCollection->getItemById($group->getWebsiteId()));
-
-            $websiteGroups[$group->getWebsiteId()][$group->getId()] = $group;
-
-            $this->_groups[$group->getId()] = $group;
-        }
-
-        foreach ($websiteCollection as $website) {
-            /* @var $website Mage_Core_Model_Website */
-            if (!isset($websiteGroups[$website->getId()])) {
-                $websiteGroups[$website->getId()] = array();
-            }
-            if (!isset($websiteStores[$website->getId()])) {
-                $websiteStores[$website->getId()] = array();
-            }
-            if ($website->getIsDefault()) {
-                $this->_website = $website;
-            }
-            $website->setGroups($websiteGroups[$website->getId()]);
-            $website->setStores($websiteStores[$website->getId()]);
-
-            $this->_websites[$website->getId()] = $website;
-            $this->_websites[$website->getCode()] = $website;
-        }
-    }
-
-    /**
-     * Check if system is run in the single store mode
-     *
-     * @return bool
-     */
-    public function isSingleStoreMode()
-    {
-        return $this->hasSingleStore() && Mage::helper('Mage_Core_Helper_Data')->isSingleStoreModeEnabled();
-    }
-
-    /**
-     * Check if store has only one store view
-     *
-     * @return bool
-     */
-    public function hasSingleStore()
-    {
-        if (!Mage::isInstalled()) {
-            return false;
-        }
-        return $this->_hasSingleStore;
-    }
-
-    /**
-     * Retrieve store code or null by store group
-     *
-     * @param int $group
-     * @return string|null
-     */
-    protected function _getStoreByGroup($group)
-    {
-        if (!isset($this->_groups[$group])) {
-            return null;
-        }
-        if (!$this->_groups[$group]->getDefaultStoreId()) {
-            return null;
-        }
-        return $this->_stores[$this->_groups[$group]->getDefaultStoreId()]->getCode();
-    }
-
-    /**
-     * Retrieve store code or null by website
-     *
-     * @param int|string $website
-     * @return string|null
-     */
-    protected function _getStoreByWebsite($website)
-    {
-        if (!isset($this->_websites[$website])) {
-            return null;
-        }
-        if (!$this->_websites[$website]->getDefaultGroupId()) {
-            return null;
-        }
-        return $this->_getStoreByGroup($this->_websites[$website]->getDefaultGroupId());
-    }
-
-    /**
-     * Set current default store
-     *
-     * @param string $store
-     * @return Mage_Core_Model_App
-     */
-    public function setCurrentStore($store)
-    {
-        $this->_currentStore = $store;
-        return $this;
+        return $this->_objectManager->get('Mage_Core_Model_Cookie');
     }
 
     /**
@@ -933,259 +270,59 @@ class Mage_Core_Model_App
      * Re-declare custom error handler
      *
      * @param   string $handler
-     * @return  Mage_Core_Model_App
-     */
-    public function setErrorHandler($handler)
-    {
-        set_error_handler($handler);
-        return $this;
-    }
-
-    /**
-     * Loading application area
-     *
-     * @param   string $code
-     * @return  Mage_Core_Model_App
-     */
-    public function loadArea($code)
-    {
-        $this->getArea($code)->load();
-        return $this;
-    }
-
-    /**
-     * Loading part of area data
-     *
-     * @param   string $area
-     * @param   string $part
-     * @return  Mage_Core_Model_App
-     */
-    public function loadAreaPart($area, $part)
-    {
-        $this->getArea($area)->load($part);
-        return $this;
-    }
-
-    /**
-     * Retrieve application area
-     *
-     * @param   string $code
-     * @return  Mage_Core_Model_App_Area
-     */
-    public function getArea($code)
-    {
-        if (!isset($this->_areas[$code])) {
-            $this->_areas[$code] = $this->_objectManager->create(
-                'Mage_Core_Model_App_Area',
-                array('areaCode' => $code)
-            );
-        }
-        return $this->_areas[$code];
-    }
-
-    /**
-     * Retrieve application store object
-     *
-     * @param null|string|bool|int|Mage_Core_Model_Store $id
-     * @return Mage_Core_Model_Store
-     * @throws Mage_Core_Model_Store_Exception
-     */
-    public function getStore($id = null)
-    {
-        if (!Mage::isInstalled() || $this->getUpdateMode()) {
-            return $this->_getDefaultStore();
-        }
-
-        if ($id === true && $this->hasSingleStore()) {
-            return $this->_store;
-        }
-
-        if (!isset($id) || '' === $id || $id === true) {
-            $id = $this->_currentStore;
-        }
-        if ($id instanceof Mage_Core_Model_Store) {
-            return $id;
-        }
-        if (!isset($id)) {
-            $this->throwStoreException();
-        }
-
-        if (empty($this->_stores[$id])) {
-            $store = Mage::getModel('Mage_Core_Model_Store');
-            /* @var $store Mage_Core_Model_Store */
-            if (is_numeric($id)) {
-                $store->load($id);
-            } elseif (is_string($id)) {
-                $store->load($id, 'code');
-            }
-
-            if (!$store->getCode()) {
-                $this->throwStoreException();
-            }
-            $this->_stores[$store->getStoreId()] = $store;
-            $this->_stores[$store->getCode()] = $store;
-        }
-        return $this->_stores[$id];
-    }
-
-    /**
-     * Retrieve application store object without Store_Exception
-     *
-     * @param string|int|Mage_Core_Model_Store $id
-     * @return Mage_Core_Model_Store
-     */
-    public function getSafeStore($id = null)
-    {
-        try {
-            return $this->getStore($id);
-        } catch (Exception $e) {
-            if ($this->_currentStore) {
-                $this->getRequest()->setActionName('noRoute');
-                return new Varien_Object();
-            } else {
-                Mage::throwException(Mage::helper('Mage_Core_Helper_Data')->__('Requested invalid store "%s"', $id));
-            }
-        }
-    }
-
-    /**
-     * Retrieve stores array
-     *
-     * @param bool $withDefault
-     * @param bool $codeKey
-     * @return array
-     */
-    public function getStores($withDefault = false, $codeKey = false)
-    {
-        $stores = array();
-        foreach ($this->_stores as $store) {
-            if (!$withDefault && $store->getId() == 0) {
-                continue;
-            }
-            if ($codeKey) {
-                $stores[$store->getCode()] = $store;
-            } else {
-                $stores[$store->getId()] = $store;
-            }
-        }
-
-        return $stores;
-    }
-
-    protected function _getDefaultStore()
-    {
-        if (empty($this->_store)) {
-            $this->_store = Mage::getModel('Mage_Core_Model_Store')
-                ->setId(self::DISTRO_STORE_ID)
-                ->setCode(self::DISTRO_STORE_CODE);
-        }
-        return $this->_store;
-    }
-
-    /**
-     * Retrieve default store for default group and website
-     *
-     * @return Mage_Core_Model_Store
-     */
-    public function getDefaultStoreView()
-    {
-        foreach ($this->getWebsites() as $_website) {
-            if ($_website->getIsDefault()) {
-                $_defaultStore = $this->getGroup($_website->getDefaultGroupId())->getDefaultStore();
-                if ($_defaultStore) {
-                    return $_defaultStore;
-                }
-            }
-        }
-        return null;
-    }
-
-    public function getDistroLocaleCode()
+     * @return  Mage_Core_Model_App
+     */
+    public function setErrorHandler($handler)
     {
-        return self::DISTRO_LOCALE_CODE;
+        set_error_handler($handler);
+        return $this;
     }
 
     /**
-     * Retrieve application website object
+     * Loading application area
      *
-     * @param null|bool|int|string|Mage_Core_Model_Website $id
-     * @return Mage_Core_Model_Website
-     * @throws Mage_Core_Exception
+     * @param   string $code
+     * @return  Mage_Core_Model_App
      */
-    public function getWebsite($id = null)
+    public function loadArea($code)
     {
-        if (is_null($id)) {
-            $id = $this->getStore()->getWebsiteId();
-        } elseif ($id instanceof Mage_Core_Model_Website) {
-            return $id;
-        } elseif ($id === true) {
-            return $this->_website;
-        }
-
-        if (empty($this->_websites[$id])) {
-            $website = Mage::getModel('Mage_Core_Model_Website');
-            if (is_numeric($id)) {
-                $website->load($id);
-                if (!$website->hasWebsiteId()) {
-                    throw Mage::exception('Mage_Core', 'Invalid website id requested.');
-                }
-            } elseif (is_string($id)) {
-                $websiteConfig = $this->_config->getNode('websites/' . $id);
-                if (!$websiteConfig) {
-                    throw Mage::exception('Mage_Core', 'Invalid website code requested: ' . $id);
-                }
-                $website->loadConfig($id);
-            }
-            $this->_websites[$website->getWebsiteId()] = $website;
-            $this->_websites[$website->getCode()] = $website;
-        }
-        return $this->_websites[$id];
+        $this->getArea($code)->load();
+        return $this;
     }
 
-    public function getWebsites($withDefault = false, $codeKey = false)
+    /**
+     * Loading part of area data
+     *
+     * @param   string $area
+     * @param   string $part
+     * @return  Mage_Core_Model_App
+     */
+    public function loadAreaPart($area, $part)
     {
-        $websites = array();
-        if (is_array($this->_websites)) {
-            foreach ($this->_websites as $website) {
-                if (!$withDefault && $website->getId() == 0) {
-                    continue;
-                }
-                if ($codeKey) {
-                    $websites[$website->getCode()] = $website;
-                } else {
-                    $websites[$website->getId()] = $website;
-                }
-            }
-        }
-
-        return $websites;
+        $this->getArea($area)->load($part);
+        return $this;
     }
 
     /**
-     * Retrieve application store group object
+     * Retrieve application area
      *
-     * @param null|Mage_Core_Model_Store_Group|string $id
-     * @return Mage_Core_Model_Store_Group
-     * @throws Mage_Core_Exception
+     * @param   string $code
+     * @return  Mage_Core_Model_App_Area
      */
-    public function getGroup($id = null)
+    public function getArea($code)
     {
-        if (is_null($id)) {
-            $id = $this->getStore()->getGroupId();
-        } elseif ($id instanceof Mage_Core_Model_Store_Group) {
-            return $id;
-        }
-        if (empty($this->_groups[$id])) {
-            $group = Mage::getModel('Mage_Core_Model_Store_Group');
-            if (is_numeric($id)) {
-                $group->load($id);
-                if (!$group->hasGroupId()) {
-                    throw Mage::exception('Mage_Core', 'Invalid store group id requested.');
-                }
-            }
-            $this->_groups[$group->getGroupId()] = $group;
+        if (!isset($this->_areas[$code])) {
+            $this->_areas[$code] = $this->_objectManager->create(
+                'Mage_Core_Model_App_Area',
+                array('areaCode' => $code)
+            );
         }
-        return $this->_groups[$id];
+        return $this->_areas[$code];
+    }
+
+    public function getDistroLocaleCode()
+    {
+        return self::DISTRO_LOCALE_CODE;
     }
 
     /**
@@ -1196,7 +333,7 @@ class Mage_Core_Model_App
     public function getLocale()
     {
         if (!$this->_locale) {
-            $this->_locale = Mage::getSingleton('Mage_Core_Model_Locale');
+            $this->_locale = $this->_objectManager->get('Mage_Core_Model_Locale');
         }
         return $this->_locale;
     }
@@ -1211,19 +348,6 @@ class Mage_Core_Model_App
         return $this->_objectManager->get('Mage_Core_Model_Layout');
     }
 
-    /**
-     * Retrieve translate object
-     *
-     * @return Mage_Core_Model_Translate
-     */
-    public function getTranslator()
-    {
-        if (!$this->_translator) {
-            $this->_translator = Mage::getSingleton('Mage_Core_Model_Translate');
-        }
-        return $this->_translator;
-    }
-
     /**
      * Retrieve helper object
      *
@@ -1242,8 +366,7 @@ class Mage_Core_Model_App
      */
     public function getBaseCurrencyCode()
     {
-        return (string) Mage::app()->getConfig()
-            ->getNode('default/' . Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE);
+        return (string) $this->_config->getNode('default/' . Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE);
     }
 
     /**
@@ -1277,9 +400,6 @@ class Mage_Core_Model_App
      */
     public function getCacheInstance()
     {
-        if (!$this->_cache) {
-            $this->_initCache();
-        }
         return $this->_cache;
     }
 
@@ -1290,9 +410,6 @@ class Mage_Core_Model_App
      */
     public function getCache()
     {
-        if (!$this->_cache) {
-            $this->_initCache();
-        }
         return $this->_cache->getFrontend();
     }
 
@@ -1343,7 +460,7 @@ class Mage_Core_Model_App
     public function cleanCache($tags = array())
     {
         $this->_cache->clean($tags);
-        Mage::dispatchEvent('application_clean_cache', array('tags' => $tags));
+        $this->_eventManager->dispatch('application_clean_cache', array('tags' => $tags));
         return $this;
     }
 
@@ -1392,7 +509,7 @@ class Mage_Core_Model_App
      */
     public function getRequest()
     {
-        if (empty($this->_request)) {
+        if (!$this->_request) {
             $this->_request = $this->_objectManager->get('Mage_Core_Controller_Request_Http');
         }
         return $this->_request;
@@ -1417,11 +534,6 @@ class Mage_Core_Model_App
      */
     public function getResponse()
     {
-        if (empty($this->_response)) {
-            $this->_response = $this->_objectManager->get('Mage_Core_Controller_Response_Http');
-            $this->_response->headersSentThrowsException = Mage::$headersSentThrowsException;
-            $this->_response->setHeader("Content-Type", "text/html; charset=UTF-8");
-        }
         return $this->_response;
     }
 
@@ -1437,254 +549,273 @@ class Mage_Core_Model_App
         return $this;
     }
 
-    public function addEventArea($area)
+    /**
+     * Set use session var instead of SID for URL
+     *
+     * @param bool $var
+     * @return Mage_Core_Model_App
+     */
+    public function setUseSessionVar($var)
     {
-        if (!isset($this->_events[$area])) {
-            $this->_events[$area] = array();
-        }
+        $this->_useSessionVar = (bool)$var;
         return $this;
     }
 
-    public function dispatchEvent($eventName, $args)
+    /**
+     * Retrieve use flag session var instead of SID for URL
+     *
+     * @return bool
+     */
+    public function getUseSessionVar()
     {
-        foreach ($this->_events as $area => $events) {
-            if (!isset($events[$eventName])) {
-                $eventConfig = $this->getConfig()->getEventConfig($area, $eventName);
-                if (!$eventConfig) {
-                    $this->_events[$area][$eventName] = false;
-                    continue;
-                }
-                $observers = array();
-                foreach ($eventConfig->observers->children() as $obsName=>$obsConfig) {
-                    $observers[$obsName] = array(
-                        'type'  => (string)$obsConfig->type,
-                        'model' => $obsConfig->class ? (string)$obsConfig->class : $obsConfig->getClassName(),
-                        'method'=> (string)$obsConfig->method,
-                    );
-                }
-                $events[$eventName]['observers'] = $observers;
-                $this->_events[$area][$eventName]['observers'] = $observers;
-            }
-            if (false === $events[$eventName]) {
-                continue;
-            } else {
-                $event = new Varien_Event($args);
-                $event->setName($eventName);
-                $observer = new Varien_Event_Observer();
-            }
-
-            foreach ($events[$eventName]['observers'] as $obsName => $obs) {
-                $observer->setData(array('event' => $event));
-                Magento_Profiler::start('OBSERVER:' . $obsName, array('group' => 'OBSERVER', 'observer' => $obsName));
-                switch ($obs['type']) {
-                    case 'disabled':
-                        break;
-                    case 'object':
-                    case 'model':
-                        $method = $obs['method'];
-                        $observer->addData($args);
-                        $object = Mage::getModel($obs['model']);
-                        $this->_callObserverMethod($object, $method, $observer);
-                        break;
-                    default:
-                        $method = $obs['method'];
-                        $observer->addData($args);
-                        $object = Mage::getSingleton($obs['model']);
-                        $this->_callObserverMethod($object, $method, $observer);
-                        break;
-                }
-                Magento_Profiler::stop('OBSERVER:' . $obsName);
-            }
-        }
-        return $this;
+        return $this->_useSessionVar;
     }
 
     /**
-     * Performs non-existent observer method calls protection
+     * Set Use session in URL flag
      *
-     * @param object $object
-     * @param string $method
-     * @param Varien_Event_Observer $observer
+     * @param bool $flag
      * @return Mage_Core_Model_App
-     * @throws Mage_Core_Exception
      */
-    protected function _callObserverMethod($object, $method, $observer)
+    public function setUseSessionInUrl($flag = true)
     {
-        if (method_exists($object, $method)) {
-            $object->$method($observer);
-        } elseif (Mage::getIsDeveloperMode()) {
-            Mage::throwException('Method "' . $method . '" is not defined in "' . get_class($object) . '"');
-        }
+        $this->_useSessionInUrl = (bool)$flag;
         return $this;
     }
 
     /**
-     * Set update process run flag
+     * Retrieve use session in URL flag
+     *
+     * @return bool
+     */
+    public function getUseSessionInUrl()
+    {
+        return $this->_useSessionInUrl;
+    }
+
+    /**
+     * Check if developer mode is enabled
+     * 
+     * @return bool
+     */
+    public function isDeveloperMode()
+    {
+        return $this->_appState->isDeveloperMode();
+    }
+
+    /**
+     * Retrieve application store object without Store_Exception
+     *
+     * @param string|int|Mage_Core_Model_Store $id
+     * @return Mage_Core_Model_Store
+     *
+     * @deprecated use Mage_Core_Model_StoreManager::getSafeStore()
+     */
+    public function getSafeStore($id = null)
+    {
+        return $this->_storeManager->getSafeStore($id);
+    }
+
+    /**
+     * Allow or disallow single store mode
      *
      * @param bool $value
+     *
+     * @deprecated use Mage_Core_Model_StoreManager::setIsSingleStoreModeAllowed()
+     */
+    public function setIsSingleStoreModeAllowed($value)
+    {
+        $this->_storeManager->setIsSingleStoreModeAllowed($value);
+    }
+
+    /**
+     * Check if store has only one store view
+     *
+     * @return bool
+     *
+     * @deprecated use Mage_Core_Model_StoreManager::hasSingleStore()
      */
-    public function setUpdateMode($value)
+    public function hasSingleStore()
     {
-        $this->_updateMode = $value;
+        return $this->_storeManager->hasSingleStore();
     }
 
     /**
-     * Get update process run flag
+     * Check if system is run in the single store mode
      *
      * @return bool
+     *
+     * @deprecated use Mage_Core_Model_StoreManager::isSingleStoreMode()
      */
-    public function getUpdateMode()
+    public function isSingleStoreMode()
     {
-        return $this->_updateMode;
+        return $this->_storeManager->isSingleStoreMode();
     }
 
     /**
      * @throws Mage_Core_Model_Store_Exception
+     *
+     * @deprecated use Mage_Core_Model_StoreManager::throwStoreException()
      */
     public function throwStoreException()
     {
-        throw new Mage_Core_Model_Store_Exception('');
+        $this->_storeManager->throwStoreException();
     }
 
     /**
-     * Set use session var instead of SID for URL
+     * Retrieve application store object
      *
-     * @param bool $var
-     * @return Mage_Core_Model_App
+     * @param null|string|bool|int|Mage_Core_Model_Store $id
+     * @return Mage_Core_Model_Store
+     * @throws Mage_Core_Model_Store_Exception
+     *
+     * @deprecated use Mage_Core_Model_StoreManager::getStore()
      */
-    public function setUseSessionVar($var)
+    public function getStore($id = null)
     {
-        $this->_useSessionVar = (bool)$var;
-        return $this;
+        return $this->_storeManager->getStore($id);
     }
 
     /**
-     * Retrieve use flag session var instead of SID for URL
+     * Retrieve stores array
      *
-     * @return bool
+     * @param bool $withDefault
+     * @param bool $codeKey
+     * @return Mage_Core_Model_Store[]
+     *
+     * @deprecated use Mage_Core_Model_StoreManager::getStores()
      */
-    public function getUseSessionVar()
+    public function getStores($withDefault = false, $codeKey = false)
     {
-        return $this->_useSessionVar;
+        return $this->_storeManager->getStores($withDefault, $codeKey);
     }
 
     /**
-     * Get either default or any store view
+     * Retrieve application website object
      *
-     * @return Mage_Core_Model_Store
+     * @param null|bool|int|string|Mage_Core_Model_Website $id
+     * @return Mage_Core_Model_Website
+     * @throws Mage_Core_Exception
+     *
+     * @deprecated use Mage_Core_Model_StoreManager::getWebsite()
      */
-    public function getAnyStoreView()
+    public function getWebsite($id = null)
     {
-        $store = $this->getDefaultStoreView();
-        if ($store) {
-            return $store;
-        }
-        foreach ($this->getStores() as $store) {
-            return $store;
-        }
+        return $this->_storeManager->getWebsite($id);
     }
 
     /**
-     * Set Use session in URL flag
+     * Get loaded websites
      *
-     * @param bool $flag
-     * @return Mage_Core_Model_App
+     * @param bool $withDefault
+     * @param bool|string $codeKey
+     * @return Mage_Core_Model_Website[]
+     *
+     * @deprecated use Mage_Core_Model_StoreManager::getWebsites()
      */
-    public function setUseSessionInUrl($flag = true)
+    public function getWebsites($withDefault = false, $codeKey = false)
     {
-        $this->_useSessionInUrl = (bool)$flag;
-        return $this;
+        return $this->_storeManager->getWebsites($withDefault, $codeKey);
     }
 
     /**
-     * Retrieve use session in URL flag
+     * Reinitialize store list
      *
-     * @return bool
+     * @deprecated use Mage_Core_Model_StoreManager::reinitStores()
      */
-    public function getUseSessionInUrl()
+    public function reinitStores()
     {
-        return $this->_useSessionInUrl;
+        $this->_storeManager->reinitStores();
     }
 
     /**
-     * Allow or disallow single store mode
+     * Set current default store
      *
-     * @param bool $value
-     * @return Mage_Core_Model_App
+     * @param string $store
+     *
+     * @deprecated use Mage_Core_Model_StoreManager::setCurrentStore()
      */
-    public function setIsSingleStoreModeAllowed($value)
+    public function setCurrentStore($store)
     {
-        $this->_isSingleStoreAllowed = (bool)$value;
-        return $this;
+        $this->_storeManager->setCurrentStore($store);
     }
 
     /**
-     * Prepare array of store groups
-     * can be filtered to contain default store group or not by $withDefault flag
-     * depending on flag $codeKey array keys can be group id or group code
+     * Get current store code
      *
-     * @param bool $withDefault
-     * @param bool $codeKey
-     * @return array
+     * @return string
+     *
+     * @deprecated use Mage_Core_Model_StoreManager::getCurrentStore()
      */
-    public function getGroups($withDefault = false, $codeKey = false)
+    public function getCurrentStore()
     {
-        $groups = array();
-        if (is_array($this->_groups)) {
-            foreach ($this->_groups as $group) {
-                if (!$withDefault && $group->getId() == 0) {
-                    continue;
-                }
-                if ($codeKey) {
-                    $groups[$group->getCode()] = $group;
-                } else {
-                    $groups[$group->getId()] = $group;
-                }
-            }
-        }
-        return $groups;
+        return $this->_storeManager->getCurrentStore();
     }
 
+
     /**
-     * Get is cache locked
+     * Retrieve default store for default group and website
      *
-     * @return bool
+     * @return Mage_Core_Model_Store
+     *
+     * @deprecated use Mage_Core_Model_StoreManager::getDefaultStoreView()
+     */
+    public function getDefaultStoreView()
+    {
+        return $this->_storeManager->getDefaultStoreView();
+    }
+
+    /**
+     * Retrieve application store group object
+     *
+     * @param null|Mage_Core_Model_Store_Group|string $id
+     * @return Mage_Core_Model_Store_Group
+     * @throws Mage_Core_Exception
+     *
+     * @deprecated use Mage_Core_Model_StoreManager::getGroup()
+     */
+    public function getGroup($id = null)
+    {
+        return $this->_storeManager->getGroup($id);
+    }
+
+    /**
+     * Prepare array of store groups
+     * can be filtered to contain default store group or not by $withDefault flag
+     * depending on flag $codeKey array keys can be group id or group code
+     *
+     * @param bool $withDefault
+     * @param bool $codeKey
+     * @return Mage_Core_Model_Store_Group[]
+     *
+     * @deprecated use Mage_Core_Model_StoreManager::getGroups()
      */
-    public function getIsCacheLocked()
+    public function getGroups($withDefault = false, $codeKey = false)
     {
-        return (bool)$this->_isCacheLocked;
+        return $this->_storeManager->getGroups($withDefault, $codeKey);
     }
 
     /**
      *  Unset website by id from app cache
      *
      * @param null|bool|int|string|Mage_Core_Model_Website $id
+     *
+     * @deprecated use Mage_Core_Model_StoreManager::clearWebsiteCache()
      */
     public function clearWebsiteCache($id = null)
     {
-        if (is_null($id)) {
-            $id = $this->getStore()->getWebsiteId();
-        } elseif ($id instanceof Mage_Core_Model_Website) {
-            $id = $id->getId();
-        } elseif ($id === true) {
-            $id = $this->_website->getId();
-        }
-
-        if (!empty($this->_websites[$id])) {
-            $website = $this->_websites[$id];
-
-            unset($this->_websites[$website->getWebsiteId()]);
-            unset($this->_websites[$website->getCode()]);
-        }
+        $this->_storeManager->clearWebsiteCache($id);
     }
 
     /**
-     * Check if developer mode is enabled.
+     * Get either default or any store view
      *
-     * @return bool
+     * @return Mage_Core_Model_Store|null
+     *
+     * @deprecated use Mage_Core_Model_StoreManager::getAnyStoreView()
      */
-    public function isDeveloperMode()
+    public function getAnyStoreView()
     {
-        return Mage::getIsDeveloperMode();
+        return $this->_storeManager->getAnyStoreView();
     }
 }
diff --git a/app/code/core/Mage/Core/Model/App/Area.php b/app/code/core/Mage/Core/Model/App/Area.php
index 71d636cbe63ea9a6a94c386cbf9837c6bc6499d8..8c5fc44420687e954941a151053f48d8b47cebbe 100644
--- a/app/code/core/Mage/Core/Model/App/Area.php
+++ b/app/code/core/Mage/Core/Model/App/Area.php
@@ -56,13 +56,52 @@ class Mage_Core_Model_App_Area
     protected $_code;
 
     /**
-     * Constructor
+     * Event Manager
      *
+     * @var Mage_Core_Model_Event_Manager
+     */
+    protected $_eventManager;
+
+    /**
+     * Translator
+     *
+     * @var Mage_Core_Model_Translate
+     */
+    protected $_translator;
+
+    /**
+     * Application config
+     *
+     * @var Mage_Core_Model_Config
+     */
+    protected $_config;
+
+    /**
+     * Object manager
+     *
+     * @var Magento_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * @param Mage_Core_Model_Event_Manager $eventManager
+     * @param Mage_Core_Model_Translate $translator
+     * @param Mage_Core_Model_Config $config
+     * @param Magento_ObjectManager $objectManager
      * @param string $areaCode
      */
-    public function __construct($areaCode)
-    {
+    public function __construct(
+        Mage_Core_Model_Event_Manager $eventManager,
+        Mage_Core_Model_Translate $translator,
+        Mage_Core_Model_Config $config,
+        Magento_ObjectManager $objectManager,
+        $areaCode
+    ) {
         $this->_code = $areaCode;
+        $this->_config = $config;
+        $this->_objectManager = $objectManager;
+        $this->_eventManager = $eventManager;
+        $this->_translator = $translator;
     }
 
     /**
@@ -179,20 +218,28 @@ class Mage_Core_Model_App_Area
         return $this;
     }
 
+    /**
+     * Load area configuration
+     */
     protected function _initConfig()
     {
+        $configurationNode = $this->_config->getNode($this->_code . '/di');
+        if ($configurationNode) {
+            $configuration = $configurationNode->asArray();
+            $this->_objectManager->setConfiguration($configuration);
+        }
 
     }
 
     protected function _initEvents()
     {
-        Mage::app()->addEventArea($this->_code);
+        $this->_eventManager->addEventArea($this->_code);
         return $this;
     }
 
     protected function _initTranslate()
     {
-        Mage::app()->getTranslator()->init($this->_code);
+        $this->_translator->init($this->_code);
         return $this;
     }
 
diff --git a/app/code/core/Mage/Core/Model/App/Handler.php b/app/code/core/Mage/Core/Model/App/Handler.php
new file mode 100644
index 0000000000000000000000000000000000000000..3006a73f4fe480155d60e9ab99e8400a55f5579d
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/App/Handler.php
@@ -0,0 +1,57 @@
+<?php
+/**
+ * Application request handler. Launches front controller, request routing and dispatching process.
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_App_Handler implements Magento_Http_HandlerInterface
+{
+    /**
+     * Application object
+     *
+     * @var Mage_Core_Model_AppInterface
+     */
+    protected $_app;
+
+    /**
+     * @param Mage_Core_Model_AppInterface $app
+     */
+    public function __construct(Mage_Core_Model_AppInterface $app)
+    {
+        $this->_app = $app;
+    }
+
+    /**
+     * Handle http request
+     *
+     * @param Zend_Controller_Request_Http $request
+     * @param Zend_Controller_Response_Http $response
+     */
+    public function handle(Zend_Controller_Request_Http $request, Zend_Controller_Response_Http $response)
+    {
+        $response->headersSentThrowsException = Mage::$headersSentThrowsException;
+        set_error_handler(Mage::DEFAULT_ERROR_HANDLER);
+        date_default_timezone_set(Mage_Core_Model_Locale::DEFAULT_TIMEZONE);
+        $this->_app->setRequest($request)->setResponse($response)->run();
+    }
+}
+
diff --git a/app/code/core/Mage/Core/Model/App/Proxy.php b/app/code/core/Mage/Core/Model/App/Proxy.php
new file mode 100644
index 0000000000000000000000000000000000000000..d71f97bacb85d5b13ad5d59485c182d4c2c54c6f
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/App/Proxy.php
@@ -0,0 +1,581 @@
+<?php
+/**
+ * Application proxy model
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_App_Proxy implements Mage_Core_Model_AppInterface
+{
+    /**
+     * @var Magento_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * @var Mage_Core_Model_App
+     */
+    protected $_app = null;
+
+    /**
+     * @param Magento_ObjectManager $objectManager
+     */
+    public function __construct(Magento_ObjectManager $objectManager)
+    {
+        $this->_objectManager = $objectManager;
+    }
+
+    /**
+     * Get application model
+     *
+     * @return Mage_Core_Model_App
+     */
+    protected function _getApp()
+    {
+        if (null === $this->_app) {
+            $this->_app = $this->_objectManager->get('Mage_Core_Model_App');
+        }
+        
+        return $this->_app;
+    }
+
+    /**
+     * Run application. Run process responsible for request processing and sending response.
+     *
+     * @return Mage_Core_Model_AppInterface
+     */
+    public function run()
+    {
+        return $this->_getApp()->run();
+    }
+
+    /**
+     * Throw an exception, if the application has not been installed yet
+     *
+     * @throws Magento_Exception
+     */
+    public function requireInstalledInstance()
+    {
+        $this->_getApp()->requireInstalledInstance();
+    }
+
+    /**
+     * Retrieve cookie object
+     *
+     * @return Mage_Core_Model_Cookie
+     */
+    public function getCookie()
+    {
+        return $this->_getApp()->getCookie();
+    }
+
+    /**
+     * Reinitialize stores
+     *
+     * @return void
+     */
+    public function reinitStores()
+    {
+        $this->_getApp()->reinitStores();
+    }
+
+    /**
+     * Check if system is run in the single store mode
+     *
+     * @return bool
+     */
+    public function isSingleStoreMode()
+    {
+        return $this->_getApp()->isSingleStoreMode();
+    }
+
+    /**
+     * Check if store has only one store view
+     *
+     * @return bool
+     */
+    public function hasSingleStore()
+    {
+        return $this->_getApp()->hasSingleStore();
+    }
+
+    /**
+     * Set current default store
+     *
+     * @param string $store
+     */
+    public function setCurrentStore($store)
+    {
+        $this->_getApp()->setCurrentStore($store);
+    }
+
+    /**
+     * Get current store code
+     *
+     * @return string
+     */
+    public function getCurrentStore()
+    {
+        return $this->_getApp()->getCurrentStore();
+    }
+
+    /**
+     * Re-declare custom error handler
+     *
+     * @param   string $handler
+     * @return  Mage_Core_Model_AppInterface
+     */
+    public function setErrorHandler($handler)
+    {
+        return $this->_getApp()->setErrorHandler($handler);
+    }
+
+    /**
+     * Loading application area
+     *
+     * @param   string $code
+     * @return  Mage_Core_Model_AppInterface
+     */
+    public function loadArea($code)
+    {
+        return $this->_getApp()->loadArea($code);
+    }
+
+    /**
+     * Loading part of area data
+     *
+     * @param   string $area
+     * @param   string $part
+     * @return  Mage_Core_Model_AppInterface
+     */
+    public function loadAreaPart($area, $part)
+    {
+        return $this->_getApp()->loadAreaPart($area, $part);
+    }
+
+    /**
+     * Retrieve application area
+     *
+     * @param   string $code
+     * @return  Mage_Core_Model_App_Area
+     */
+    public function getArea($code)
+    {
+        return $this->_getApp()->getArea($code);
+    }
+
+    /**
+     * Retrieve application store object
+     *
+     * @param null|string|bool|int|Mage_Core_Model_Store $id
+     * @return Mage_Core_Model_Store
+     * @throws Mage_Core_Model_Store_Exception
+     */
+    public function getStore($id = null)
+    {
+        return $this->_getApp()->getStore($id);
+    }
+
+    /**
+     * Retrieve application store object without Store_Exception
+     *
+     * @param string|int|Mage_Core_Model_Store $id
+     * @return Mage_Core_Model_Store
+     */
+    public function getSafeStore($id = null)
+    {
+        return $this->_getApp()->getSafeStore($id);
+    }
+
+    /**
+     * Retrieve stores array
+     *
+     * @param bool $withDefault
+     * @param bool $codeKey
+     * @return array
+     */
+    public function getStores($withDefault = false, $codeKey = false)
+    {
+        return $this->_getApp()->getStores($withDefault, $codeKey);
+    }
+
+    /**
+     * Retrieve default store for default group and website
+     *
+     * @return Mage_Core_Model_Store
+     */
+    public function getDefaultStoreView()
+    {
+        return $this->_getApp()->getDefaultStoreView();
+    }
+
+    /**
+     * Get distributive locale code
+     *
+     * @return string
+     */
+    public function getDistroLocaleCode()
+    {
+        return $this->_getApp()->getDistroLocaleCode();
+    }
+
+    /**
+     * Retrieve application website object
+     *
+     * @param null|bool|int|string|Mage_Core_Model_Website $id
+     * @return Mage_Core_Model_Website
+     * @throws Mage_Core_Exception
+     */
+    public function getWebsite($id = null)
+    {
+        return $this->_getApp()->getWebsite($id);
+    }
+
+    /**
+     * Get websites
+     *
+     * @param bool $withDefault
+     * @param bool $codeKey
+     * @return array
+     */
+    public function getWebsites($withDefault = false, $codeKey = false)
+    {
+        return $this->_getApp()->getWebsites($withDefault, $codeKey);
+    }
+
+    /**
+     * Retrieve application store group object
+     *
+     * @param null|Mage_Core_Model_Store_Group|string $id
+     * @return Mage_Core_Model_Store_Group
+     * @throws Mage_Core_Exception
+     */
+    public function getGroup($id = null)
+    {
+        return $this->_getApp()->getGroup($id);
+    }
+
+    /**
+     * Retrieve application locale object
+     *
+     * @return Mage_Core_Model_Locale
+     */
+    public function getLocale()
+    {
+        return $this->_getApp()->getLocale();
+    }
+
+    /**
+     * Retrieve layout object
+     *
+     * @return Mage_Core_Model_Layout
+     */
+    public function getLayout()
+    {
+        return $this->_getApp()->getLayout();
+    }
+
+    /**
+     * Retrieve helper object
+     *
+     * @param string $name
+     * @return Mage_Core_Helper_Abstract
+     */
+    public function getHelper($name)
+    {
+        return $this->_getApp()->getHelper($name);
+    }
+
+    /**
+     * Retrieve application base currency code
+     *
+     * @return string
+     */
+    public function getBaseCurrencyCode()
+    {
+        return $this->_getApp()->getBaseCurrencyCode();
+    }
+
+    /**
+     * Retrieve configuration object
+     *
+     * @return Mage_Core_Model_Config
+     */
+    public function getConfig()
+    {
+        return $this->_getApp()->getConfig();
+    }
+
+    /**
+     * Retrieve front controller object
+     *
+     * @return Mage_Core_Controller_Varien_Front
+     */
+    public function getFrontController()
+    {
+        return $this->_getApp()->getFrontController();
+    }
+
+    /**
+     * Get core cache model
+     *
+     * @return Mage_Core_Model_Cache
+     */
+    public function getCacheInstance()
+    {
+        return $this->_getApp()->getCacheInstance();
+    }
+
+    /**
+     * Retrieve cache object
+     *
+     * @return Zend_Cache_Core
+     */
+    public function getCache()
+    {
+        return $this->_getApp()->getCache();
+    }
+
+    /**
+     * Loading cache data
+     *
+     * @param   string $id
+     * @return  mixed
+     */
+    public function loadCache($id)
+    {
+        return $this->_getApp()->loadCache($id);
+    }
+
+    /**
+     * Saving cache data
+     *
+     * @param mixed $data
+     * @param string $id
+     * @param array $tags
+     * @param bool $lifeTime
+     * @return Mage_Core_Model_AppInterface
+     */
+    public function saveCache($data, $id, $tags = array(), $lifeTime = false)
+    {
+        return $this->_getApp()->saveCache($data, $id, $tags, $lifeTime);
+    }
+
+    /**
+     * Remove cache
+     *
+     * @param   string $id
+     * @return  Mage_Core_Model_AppInterface
+     */
+    public function removeCache($id)
+    {
+        return $this->_getApp()->removeCache($id);
+    }
+
+    /**
+     * Cleaning cache
+     *
+     * @param   array $tags
+     * @return  Mage_Core_Model_AppInterface
+     */
+    public function cleanCache($tags = array())
+    {
+        return $this->_getApp()->cleanCache($tags);
+    }
+
+    /**
+     * Check whether to use cache for specific component
+     *
+     * @param null|string $type
+     * @return boolean
+     */
+    public function useCache($type = null)
+    {
+        return $this->_getApp()->useCache($type);
+    }
+
+    /**
+     * Save cache usage settings
+     *
+     * @param array $data
+     * @return Mage_Core_Model_AppInterface
+     */
+    public function saveUseCache($data)
+    {
+        return $this->_getApp()->saveUseCache($data);
+    }
+
+    /**
+     * Deletes all session files
+     *
+     * @return Mage_Core_Model_AppInterface
+     */
+    public function cleanAllSessions()
+    {
+        return $this->_getApp()->cleanAllSessions();
+    }
+
+    /**
+     * Retrieve request object
+     *
+     * @return Mage_Core_Controller_Request_Http
+     */
+    public function getRequest()
+    {
+        return $this->_getApp()->getRequest();
+    }
+
+    /**
+     * Request setter
+     *
+     * @param Mage_Core_Controller_Request_Http $request
+     * @return Mage_Core_Model_AppInterface
+     */
+    public function setRequest(Mage_Core_Controller_Request_Http $request)
+    {
+        return $this->_getApp()->setRequest($request);
+    }
+
+    /**
+     * Retrieve response object
+     *
+     * @return Zend_Controller_Response_Http
+     */
+    public function getResponse()
+    {
+        return $this->_getApp()->getResponse();
+    }
+
+    /**
+     * Response setter
+     *
+     * @param Mage_Core_Controller_Response_Http $response
+     * @return Mage_Core_Model_AppInterface
+     */
+    public function setResponse(Mage_Core_Controller_Response_Http $response)
+    {
+        return $this->_getApp()->setResponse($response);
+    }
+
+   /**
+     * @throws Mage_Core_Model_Store_Exception
+     */
+    public function throwStoreException()
+    {
+        $this->_getApp()->throwStoreException();
+    }
+
+    /**
+     * Set use session var instead of SID for URL
+     *
+     * @param bool $var
+     * @return Mage_Core_Model_AppInterface
+     */
+    public function setUseSessionVar($var)
+    {
+        return $this->_getApp()->setUseSessionVar($var);
+    }
+
+    /**
+     * Retrieve use flag session var instead of SID for URL
+     *
+     * @return bool
+     */
+    public function getUseSessionVar()
+    {
+        return $this->_getApp()->getUseSessionVar();
+    }
+
+    /**
+     * Get either default or any store view
+     *
+     * @return Mage_Core_Model_Store
+     */
+    public function getAnyStoreView()
+    {
+        return $this->_getApp()->getAnyStoreView();
+    }
+
+    /**
+     * Set Use session in URL flag
+     *
+     * @param bool $flag
+     * @return Mage_Core_Model_AppInterface
+     */
+    public function setUseSessionInUrl($flag = true)
+    {
+        return $this->_getApp()->setUseSessionInUrl($flag);
+    }
+
+    /**
+     * Retrieve use session in URL flag
+     *
+     * @return bool
+     */
+    public function getUseSessionInUrl()
+    {
+        return $this->_getApp()->getUseSessionInUrl();
+    }
+
+    /**
+     * Allow or disallow single store mode
+     *
+     * @param bool $value
+     */
+    public function setIsSingleStoreModeAllowed($value)
+    {
+        $this->_getApp()->setIsSingleStoreModeAllowed($value);
+    }
+
+    /**
+     * Prepare array of store groups
+     * can be filtered to contain default store group or not by $withDefault flag
+     * depending on flag $codeKey array keys can be group id or group code
+     *
+     * @param bool $withDefault
+     * @param bool $codeKey
+     * @return array
+     */
+    public function getGroups($withDefault = false, $codeKey = false)
+    {
+        return $this->_getApp()->getGroups($withDefault, $codeKey);
+    }
+
+    /**
+     *  Unset website by id from app cache
+     *
+     * @param null|bool|int|string|Mage_Core_Model_Website $id
+     */
+    public function clearWebsiteCache($id = null)
+    {
+        $this->_getApp()->clearWebsiteCache($id);
+    }
+
+    /**
+     * Check if developer mode is enabled.
+     *
+     * @return bool
+     */
+    public function isDeveloperMode()
+    {
+        return $this->_getApp()->isDeveloperMode();
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/App/State.php b/app/code/core/Mage/Core/Model/App/State.php
new file mode 100644
index 0000000000000000000000000000000000000000..941238633d71e6f98b0e3aac3e912aa0c20adc24
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/App/State.php
@@ -0,0 +1,109 @@
+<?php
+/**
+ *  Application state flags
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_App_State
+{
+    /**
+     * Check if application is installed
+     *
+     * @return bool
+     */
+    public function isInstalled()
+    {
+       return Mage::isInstalled();
+    }
+
+    /**
+     * Check if developer mode is enabled.
+     *
+     * @return bool
+     */
+    public function isDeveloperMode()
+    {
+        return Mage::getIsDeveloperMode();
+    }
+
+    /**
+     * Set enabled developer mode
+     *
+     * @param bool $mode
+     * @return bool
+     */
+    public function setIsDeveloperMode($mode)
+    {
+        return Mage::setIsDeveloperMode($mode);
+    }
+
+    /**
+     * Set update mode flag
+     *
+     * @param bool $value
+     */
+    public function setUpdateMode($value)
+    {
+        Mage::setUpdateMode($value);
+    }
+
+    /**
+     * Get update mode flag
+     *
+     * @return bool
+     */
+    public function getUpdateMode()
+    {
+        return Mage::getUpdateMode();
+    }
+
+    /**
+     * Set is downloader flag
+     *
+     * @param bool $flag
+     */
+    public function setIsDownloader($flag = true)
+    {
+        Mage::setIsDownloader($flag);
+    }
+
+    /**
+     * Set is serializable flag
+     *
+     * @param bool $value
+     */
+    public function setIsSerializable($value = true)
+    {
+        Mage::setIsSerializable($value);
+    }
+
+    /**
+     * Get is serializable flag
+     *
+     * @return bool
+     */
+    public function getIsSerializable()
+    {
+        return Mage::getIsSerializable();
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/AppInterface.php b/app/code/core/Mage/Core/Model/AppInterface.php
new file mode 100644
index 0000000000000000000000000000000000000000..44dfe562d4e342836939300a3d18608857650f66
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/AppInterface.php
@@ -0,0 +1,305 @@
+<?php
+/**
+ * Application interface
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+interface Mage_Core_Model_AppInterface extends Mage_Core_Model_StoreManagerInterface
+{
+    /**
+     * Default application locale
+     */
+    const DISTRO_LOCALE_CODE = 'en_US';
+
+    /**
+     * Cache tag for all cache data exclude config cache
+     *
+     */
+    const CACHE_TAG = 'MAGE';
+
+    /**
+     * Default store Id (for install)
+     */
+    const DISTRO_STORE_ID       = 1;
+
+    /**
+     * Default store code (for install)
+     *
+     */
+    const DISTRO_STORE_CODE     = Mage_Core_Model_Store::DEFAULT_CODE;
+
+    /**
+     * Admin store Id
+     *
+     */
+    const ADMIN_STORE_ID = 0;
+
+    /**
+     * Dependency injection configuration node name
+     */
+    const CONFIGURATION_DI_NODE = 'di';
+
+    /**
+     * Run application. Run process responsible for request processing and sending response.
+     *
+     * @return Mage_Core_Model_AppInterface
+     */
+    public function run();
+
+    /**
+     * Throw an exception, if the application has not been installed yet
+     *
+     * @throws Magento_Exception
+     */
+    public function requireInstalledInstance();
+
+    /**
+     * Retrieve cookie object
+     *
+     * @return Mage_Core_Model_Cookie
+     */
+    public function getCookie();
+
+   /**
+     * Re-declare custom error handler
+     *
+     * @param   string $handler
+     * @return  Mage_Core_Model_AppInterface
+     */
+    public function setErrorHandler($handler);
+
+    /**
+     * Loading application area
+     *
+     * @param   string $code
+     * @return  Mage_Core_Model_AppInterface
+     */
+    public function loadArea($code);
+
+    /**
+     * Loading part of area data
+     *
+     * @param   string $area
+     * @param   string $part
+     * @return  Mage_Core_Model_AppInterface
+     */
+    public function loadAreaPart($area, $part);
+
+    /**
+     * Retrieve application area
+     *
+     * @param   string $code
+     * @return  Mage_Core_Model_App_Area
+     */
+    public function getArea($code);
+
+    /**
+     * Get distributive locale code
+     *
+     * @return string
+     */
+    public function getDistroLocaleCode();
+
+    /**
+     * Retrieve application locale object
+     *
+     * @return Mage_Core_Model_Locale
+     */
+    public function getLocale();
+
+    /**
+     * Retrieve layout object
+     *
+     * @return Mage_Core_Model_Layout
+     */
+    public function getLayout();
+
+    /**
+     * Retrieve helper object
+     *
+     * @param string $name
+     * @return Mage_Core_Helper_Abstract
+     */
+    public function getHelper($name);
+
+    /**
+     * Retrieve application base currency code
+     *
+     * @return string
+     */
+    public function getBaseCurrencyCode();
+
+    /**
+     * Retrieve configuration object
+     *
+     * @return Mage_Core_Model_Config
+     */
+    public function getConfig();
+
+    /**
+     * Retrieve front controller object
+     *
+     * @return Mage_Core_Controller_Varien_Front
+     */
+    public function getFrontController();
+
+    /**
+     * Get core cache model
+     *
+     * @return Mage_Core_Model_Cache
+     */
+    public function getCacheInstance();
+
+
+    /**
+     * Retrieve cache object
+     *
+     * @return Zend_Cache_Core
+     */
+    public function getCache();
+
+    /**
+     * Loading cache data
+     *
+     * @param   string $id
+     * @return  mixed
+     */
+    public function loadCache($id);
+
+    /**
+     * Saving cache data
+     *
+     * @param mixed $data
+     * @param string $id
+     * @param array $tags
+     * @param bool $lifeTime
+     * @return Mage_Core_Model_AppInterface
+     */
+    public function saveCache($data, $id, $tags = array(), $lifeTime = false);
+
+    /**
+     * Remove cache
+     *
+     * @param   string $id
+     * @return  Mage_Core_Model_AppInterface
+     */
+    public function removeCache($id);
+
+    /**
+     * Cleaning cache
+     *
+     * @param   array $tags
+     * @return  Mage_Core_Model_AppInterface
+     */
+    public function cleanCache($tags = array());
+
+    /**
+     * Check whether to use cache for specific component
+     *
+     * @param null|string $type
+     * @return boolean
+     */
+    public function useCache($type = null);
+
+    /**
+     * Save cache usage settings
+     *
+     * @param array $data
+     * @return Mage_Core_Model_AppInterface
+     */
+    public function saveUseCache($data);
+
+    /**
+     * Deletes all session files
+     *
+     * @return Mage_Core_Model_AppInterface
+     */
+    public function cleanAllSessions();
+
+    /**
+     * Retrieve request object
+     *
+     * @return Mage_Core_Controller_Request_Http
+     */
+    public function getRequest();
+
+    /**
+     * Request setter
+     *
+     * @param Mage_Core_Controller_Request_Http $request
+     * @return Mage_Core_Model_AppInterface
+     */
+    public function setRequest(Mage_Core_Controller_Request_Http $request);
+
+    /**
+     * Retrieve response object
+     *
+     * @return Zend_Controller_Response_Http
+     */
+    public function getResponse();
+
+    /**
+     * Response setter
+     *
+     * @param Mage_Core_Controller_Response_Http $response
+     * @return Mage_Core_Model_AppInterface
+     */
+    public function setResponse(Mage_Core_Controller_Response_Http $response);
+
+    /**
+     * Set use session var instead of SID for URL
+     *
+     * @param bool $var
+     * @return Mage_Core_Model_AppInterface
+     */
+    public function setUseSessionVar($var);
+
+    /**
+     * Retrieve use flag session var instead of SID for URL
+     *
+     * @return bool
+     */
+    public function getUseSessionVar();
+
+    /**
+     * Set Use session in URL flag
+     *
+     * @param bool $flag
+     * @return Mage_Core_Model_AppInterface
+     */
+    public function setUseSessionInUrl($flag = true);
+
+    /**
+     * Retrieve use session in URL flag
+     *
+     * @return bool
+     */
+    public function getUseSessionInUrl();
+
+    /**
+     * Check if developer mode is enabled.
+     *
+     * @return bool
+     */
+    public function isDeveloperMode();
+}
diff --git a/app/code/core/Mage/Core/Model/Cache.php b/app/code/core/Mage/Core/Model/Cache.php
index 217f503840b5dcdbc5a98c4a6e223b1fb4d38e7c..49925547b6a8736e4d30e9b4353dcc29265a64a1 100644
--- a/app/code/core/Mage/Core/Model/Cache.php
+++ b/app/code/core/Mage/Core/Model/Cache.php
@@ -29,7 +29,7 @@
  * support id and tags preffix support,
  */
 
-class Mage_Core_Model_Cache
+class Mage_Core_Model_Cache implements Mage_Core_Model_CacheInterface
 {
     const DEFAULT_LIFETIME  = 7200;
     const OPTIONS_CACHE_ID  = 'core_cache_options';
@@ -42,9 +42,14 @@ class Mage_Core_Model_Cache
     const APP_INIT_PARAM = 'cache';
 
     /**
-     * @var Mage_Core_Helper_Abstract
+     * @var Mage_Core_Model_Config
      */
-    protected $_helper;
+    protected $_config;
+
+    /**
+     * @var Mage_Core_Model_Factory_Helper
+     */
+    protected $_helperFactory;
 
     /**
      * @var string
@@ -108,23 +113,38 @@ class Mage_Core_Model_Cache
     protected $_allowedCacheOptions = null;
 
     /**
-     * @var Magento_ObjectManager
+     * @var bool
      */
-    protected $_objectManager;
+    protected $_globalBanUseCache = false;
 
     /**
-     * Class constructor. Initialize cache instance based on options
-     *
-     * @param Mage_Core_Model_App $app
+     * @param Mage_Core_Model_Config $config
+     * @param Mage_Core_Model_Config_Primary $cacheConfig
      * @param Mage_Core_Model_Dir $dirs
+     * @param Mage_Core_Model_Factory_Helper $helperFactory
+     * @param bool $banCache
      * @param array $options
      */
-    public function __construct(Magento_ObjectManager $objectManager, array $options = array())
-    {
-        $this->_objectManager = $objectManager;
-        $this->_helper = isset($options['helper']) ? $options['helper'] : Mage::helper('Mage_Core_Helper_Data');
+    public function __construct(
+        Mage_Core_Model_ConfigInterface $config,
+        Mage_Core_Model_Config_Primary $cacheConfig,
+        Mage_Core_Model_Dir $dirs,
+        Mage_Core_Model_Factory_Helper $helperFactory,
+        $banCache = false,
+        array $options = array()
+    ) {
+        $configOptions = $cacheConfig->getNode('global/cache');
+        if ($configOptions) {
+            $configOptions = $configOptions->asArray();
+        } else {
+            $configOptions = array();
+        }
+        $options = array_merge($configOptions, $options);
+
+        $this->_config = $config;
+        $this->_helperFactory = $helperFactory;
+        $this->_globalBanUseCache = $banCache;
 
-        $dirs = $objectManager->get('Mage_Core_Model_Dir');
         $this->_defaultBackendOptions['cache_dir'] = $dirs->getDir(Mage_Core_Model_Dir::CACHE);
         /**
          * Initialize id prefix
@@ -463,7 +483,7 @@ class Mage_Core_Model_Cache
          * Add global magento cache tag to all cached data exclude config cache
          */
         if (!in_array(Mage_Core_Model_Config::CACHE_TAG, $tags)) {
-            $tags[] = Mage_Core_Model_App::CACHE_TAG;
+            $tags[] = Mage_Core_Model_AppInterface::CACHE_TAG;
         }
         if ($this->_disallowSave) {
             return true;
@@ -508,7 +528,7 @@ class Mage_Core_Model_Cache
             }
             $res = $this->_frontend->clean($mode, $this->_tags($tags));
         } else {
-            $res = $this->_frontend->clean($mode, array(Mage_Core_Model_App::CACHE_TAG));
+            $res = $this->_frontend->clean($mode, array(Mage_Core_Model_AppInterface::CACHE_TAG));
             $res = $res && $this->_frontend->clean($mode, array(Mage_Core_Model_Config::CACHE_TAG));
         }
 
@@ -571,7 +591,7 @@ class Mage_Core_Model_Cache
             $this->_allowedCacheOptions = unserialize($options);
         }
 
-        if ($this->_objectManager->get('Mage_Core_Model_App')->getInitParam('global_ban_use_cache')) {
+        if ($this->_globalBanUseCache) {
             foreach ($this->_allowedCacheOptions as $key => $val) {
                 $this->_allowedCacheOptions[$key] = false;
             }
@@ -649,7 +669,7 @@ class Mage_Core_Model_Cache
     public function getTagsByType($type)
     {
         $path = self::XML_PATH_TYPES.'/'.$type.'/tags';
-        $tagsConfig = $this->_objectManager->get('Mage_Core_Model_Config')->getNode($path);
+        $tagsConfig = $this->_config->getNode($path);
         if ($tagsConfig) {
             $tags = (string) $tagsConfig;
             $tags = explode(',', $tags);
@@ -667,13 +687,15 @@ class Mage_Core_Model_Cache
     public function getTypes()
     {
         $types = array();
-        $config = $this->_objectManager->get('Mage_Core_Model_Config')->getNode(self::XML_PATH_TYPES);
+        $config = $this->_config->getNode(self::XML_PATH_TYPES);
         if ($config) {
+            /** @var $helper Mage_Core_Helper_Data*/
+            $helper = $this->_helperFactory->get('Mage_Core_Helper_Data');
             foreach ($config->children() as $type=>$node) {
                 $types[$type] = new Varien_Object(array(
                     'id'            => $type,
-                    'cache_type'    => $this->_helper->__((string)$node->label),
-                    'description'   => $this->_helper->__((string)$node->description),
+                    'cache_type'    => $helper->__((string)$node->label),
+                    'description'   => $helper->__((string)$node->description),
                     'tags'          => strtoupper((string) $node->tags),
                     'status'        => (int)$this->canUse($type),
                 ));
@@ -765,45 +787,4 @@ class Mage_Core_Model_Cache
         $this->_saveInvalidatedTypes($types);
         return $this;
     }
-
-    /**
-     * Try to get response body from cache storage with predefined processors
-     *
-     * @param Zend_Controller_Response_Abstract $response
-     * @return bool
-     */
-    public function processRequest(Zend_Controller_Response_Abstract $response)
-    {
-        if (empty($this->_requestProcessors)) {
-            return false;
-        }
-
-        $content = false;
-        foreach ($this->_requestProcessors as $processor) {
-            $processor = $this->_getProcessor($processor);
-            if ($processor) {
-                $content = $processor->extractContent($content);
-            }
-        }
-
-        if ($content) {
-            $response->appendBody($content);
-            return true;
-        }
-        return false;
-    }
-
-    /**
-     * Get request processor object
-     *
-     * @param string|object $processor Class or object
-     * @return object
-     */
-    protected function _getProcessor($processor)
-    {
-        if (!is_object($processor)) {
-            $processor = new $processor;
-        }
-        return $processor;
-    }
 }
diff --git a/app/code/core/Mage/Core/Model/Cache/Proxy.php b/app/code/core/Mage/Core/Model/Cache/Proxy.php
new file mode 100644
index 0000000000000000000000000000000000000000..a2cfe18b6ac546cefa62ab8381ab417ca37dc773
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Cache/Proxy.php
@@ -0,0 +1,236 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_Core
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * System cache proxy model
+  */
+class Mage_Core_Model_Cache_Proxy implements Mage_Core_Model_CacheInterface
+{
+    /**
+     * @var Magento_ObjectManager
+     */
+    protected  $_objectManager;
+
+    /**
+     * @var Mage_Core_Model_Cache
+     */
+    protected  $_cache;
+
+    /**
+     * @param Magento_ObjectManager $objectManager
+     */
+    public function __construct(Magento_ObjectManager $objectManager)
+    {
+        $this->_objectManager = $objectManager;
+    }
+
+    /**
+     * Create cache model
+     *
+     * @return Mage_Core_Model_Cache|mixed
+     */
+    protected function _getCache()
+    {
+        if (null == $this->_cache) {
+            $this->_cache = $this->_objectManager->get('Mage_Core_Model_Cache');
+        }
+        return $this->_cache;
+    }
+
+    /**
+     * Get cache frontend API object
+     *
+     * @return Zend_Cache_Core
+     */
+    public function getFrontend()
+    {
+        return $this->_getCache()->getFrontend();
+    }
+
+    /**
+     * Load data from cache by id
+     *
+     * @param   string $id
+     * @return  string
+     */
+    public function load($id)
+    {
+        return $this->_getCache()->load($id);
+    }
+
+    /**
+     * Save data
+     *
+     * @param string $data
+     * @param string $id
+     * @param array $tags
+     * @param int $lifeTime
+     * @return bool
+     */
+    public function save($data, $id, $tags = array(), $lifeTime = null)
+    {
+        return $this->_getCache()->save($data, $id, $tags, $lifeTime);
+    }
+
+    /**
+     * Remove cached data by identifier
+     *
+     * @param string $id
+     * @return bool
+     */
+    public function remove($id)
+    {
+        return $this->_getCache()->remove($id);
+    }
+
+    /**
+     * Clean cached data by specific tag
+     *
+     * @param array $tags
+     * @return bool
+     */
+    public function clean($tags = array())
+    {
+        return $this->_getCache()->clean($tags);
+    }
+
+    /**
+     * Clean cached data by specific tag
+     *
+     * @return bool
+     */
+    public function flush()
+    {
+        return $this->_getCache()->flush();
+    }
+
+    /**
+     * Get adapter for database cache backend model
+     *
+     * @return Zend_Db_Adapter_Abstract
+     */
+    public function getDbAdapter()
+    {
+        return $this->_getCache()->getDbAdapter();
+    }
+
+    /**
+     * Save cache usage options
+     *
+     * @param array $options
+     * @return Mage_Core_Model_Cache
+     */
+    public function saveOptions($options)
+    {
+        return $this->_getCache()->saveOptions($options);
+    }
+
+    /**
+     * Check if cache can be used for specific data type
+     *
+     * @param string $typeCode
+     * @return bool
+     */
+    public function canUse($typeCode)
+    {
+        return $this->_getCache()->canUse($typeCode);
+    }
+
+    /**
+     * Disable cache usage for specific data type
+     *
+     * @param string $typeCode
+     * @return Mage_Core_Model_Cache
+     */
+    public function banUse($typeCode)
+    {
+        return $this->_getCache()->banUse($typeCode);
+    }
+
+    /**
+     * Enable cache usage for specific data type
+     *
+     * @param string $typeCode
+     * @return Mage_Core_Model_Cache
+     */
+    public function allowUse($typeCode)
+    {
+        return $this->_getCache()->allowUse($typeCode);
+    }
+
+    /**
+     * Get cache tags by cache type from configuration
+     *
+     * @param string $type
+     * @return array
+     */
+    public function getTagsByType($type)
+    {
+        return $this->_getCache()->getTagsByType($type);
+    }
+
+    /**
+     * Get information about all declared cache types
+     *
+     * @return array
+     */
+    public function getTypes()
+    {
+        return $this->_getCache()->getTypes();
+    }
+
+    /**
+     * Get array of all invalidated cache types
+     *
+     * @return array
+     */
+    public function getInvalidatedTypes()
+    {
+        return $this->_getCache()->getInvalidatedTypes();
+    }
+
+    /**
+     * Mark specific cache type(s) as invalidated
+     *
+     * @param string|array $typeCode
+     * @return Mage_Core_Model_Cache
+     */
+    public function invalidateType($typeCode)
+    {
+        return $this->_getCache()->invalidateType($typeCode);
+    }
+
+    /**
+     * Clean cached data for specific cache type
+     *
+     * @param string $typeCode
+     * @return Mage_Core_Model_Cache
+     */
+    public function cleanType($typeCode)
+    {
+        return $this->_getCache()->cleanType($typeCode);
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/CacheInterface.php b/app/code/core/Mage/Core/Model/CacheInterface.php
new file mode 100644
index 0000000000000000000000000000000000000000..5b700190c8b1f1c36b857df34b15a0da2238c3f3
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/CacheInterface.php
@@ -0,0 +1,157 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_Core
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * System cache model interface
+ */
+interface Mage_Core_Model_CacheInterface
+{
+    /**
+     * Get cache frontend API object
+     *
+     * @return Zend_Cache_Core
+     */
+    public function getFrontend();
+
+    /**
+     * Load data from cache by id
+     *
+     * @param   string $id
+     * @return  string
+     */
+    public function load($id);
+
+    /**
+     * Save data
+     *
+     * @param string $data
+     * @param string $id
+     * @param array $tags
+     * @param int $lifeTime
+     * @return bool
+     */
+    public function save($data, $id, $tags = array(), $lifeTime = null);
+
+    /**
+     * Remove cached data by identifier
+     *
+     * @param string $id
+     * @return bool
+     */
+    public function remove($id);
+
+    /**
+     * Clean cached data by specific tag
+     *
+     * @param array $tags
+     * @return bool
+     */
+    public function clean($tags = array());
+
+    /**
+     * Clean cached data by specific tag
+     *
+     * @return bool
+     */
+    public function flush();
+
+    /**
+     * Get adapter for database cache backend model
+     *
+     * @return Zend_Db_Adapter_Abstract
+     */
+    public function getDbAdapter();
+
+    /**
+     * Save cache usage options
+     *
+     * @param array $options
+     * @return Mage_Core_Model_CacheInterface
+     */
+    public function saveOptions($options);
+
+    /**
+     * Check if cache can be used for specific data type
+     *
+     * @param string $typeCode
+     * @return bool
+     */
+    public function canUse($typeCode);
+
+    /**
+     * Disable cache usage for specific data type
+     *
+     * @param string $typeCode
+     * @return Mage_Core_Model_CacheInterface
+     */
+    public function banUse($typeCode);
+
+    /**
+     * Enable cache usage for specific data type
+     *
+     * @param string $typeCode
+     * @return Mage_Core_Model_CacheInterface
+     */
+    public function allowUse($typeCode);
+
+    /**
+     * Get cache tags by cache type from configuration
+     *
+     * @param string $type
+     * @return array
+     */
+    public function getTagsByType($type);
+
+    /**
+     * Get information about all declared cache types
+     *
+     * @return array
+     */
+    public function getTypes();
+
+    /**
+     * Get array of all invalidated cache types
+     *
+     * @return array
+     */
+    public function getInvalidatedTypes();
+
+    /**
+     * Mark specific cache type(s) as invalidated
+     *
+     * @param string|array $typeCode
+     * @return Mage_Core_Model_CacheInterface
+     */
+    public function invalidateType($typeCode);
+
+    /**
+     * Clean cached data for specific cache type
+     *
+     * @param string $typeCode
+     * @return Mage_Core_Model_CacheInterface
+     */
+    public function cleanType($typeCode);
+}
diff --git a/app/code/core/Mage/Core/Model/Config.php b/app/code/core/Mage/Core/Model/Config.php
index 1a721e2843b6345a4d8b638810676ac92b4d5638..674590dbabc71c9c1d9b7b87f1764920e418422f 100644
--- a/app/code/core/Mage/Core/Model/Config.php
+++ b/app/code/core/Mage/Core/Model/Config.php
@@ -1,5 +1,7 @@
 <?php
 /**
+ * Application configuration object. Used to access configuration when application is initialized and installed.
+ *
  * Magento
  *
  * NOTICE OF LICENSE
@@ -18,29 +20,21 @@
  * versions in the future. If you wish to customize Magento for your
  * needs please refer to http://www.magentocommerce.com for more information.
  *
- * @category    Mage
- * @package     Mage_Core
  * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
+
 /**
- * Core configuration class
- *
  * @SuppressWarnings(PHPMD.TooManyFields)
  * @SuppressWarnings(PHPMD.ExcessivePublicCount)
  * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
  * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  */
-class Mage_Core_Model_Config extends Mage_Core_Model_Config_Base
+class Mage_Core_Model_Config implements Mage_Core_Model_ConfigInterface
 {
     /**
-     * Dependency injection configuration node name
-     */
-    const XML_PATH_DI_CONFIG = 'global/di';
-
-    /**
-     * Configuration cache tag
+     * Config cache tag
      */
     const CACHE_TAG = 'CONFIG';
 
@@ -54,77 +48,6 @@ class Mage_Core_Model_Config extends Mage_Core_Model_Config_Base
      */
     const SCOPE_WEBSITES = 'websites';
 
-    /**
-     * Read additional file during initialization
-     */
-    const INIT_OPTION_EXTRA_FILE = 'MAGE_CONFIG_FILE';
-
-    /**
-     * Read additional data (XML-string) during initialization
-     */
-    const INIT_OPTION_EXTRA_DATA = 'MAGE_CONFIG_DATA';
-
-    /**
-     * Local configuration file
-     */
-    const LOCAL_CONFIG_FILE = 'local.xml';
-
-    /**
-     * Application installation date
-     */
-    const XML_PATH_INSTALL_DATE = 'global/install/date';
-
-    /**
-     * Configuration template for the application installation date
-     */
-    const CONFIG_TEMPLATE_INSTALL_DATE = '<config><global><install><date>%s</date></install></global></config>';
-
-    /**
-     * Flag which allow use cache logic
-     *
-     * @var bool
-     */
-    protected $_useCache = false;
-
-    /**
-     * Instructions for spitting config cache
-     * array(
-     *      $sectionName => $recursionLevel
-     * )
-     * Recursion level provide availability cache sub nodes separately
-     *
-     * @var array
-     */
-    protected $_cacheSections = array(
-        'admin'     => 0,
-        'adminhtml' => 0,
-        'crontab'   => 0,
-        'install'   => 0,
-        self::SCOPE_STORES => 1,
-        self::SCOPE_WEBSITES => 0
-    );
-
-    /**
-     * Loaded Configuration by cached sections
-     *
-     * @var array
-     */
-    protected $_cacheLoadedSections = array();
-
-    /**
-     * Storage for generated class names
-     *
-     * @var array
-     */
-    protected $_classNameCache = array();
-
-    /**
-     * Storage for generated block class names
-     *
-     * @var array
-     */
-    protected $_blockClassNameCache = array();
-
     /**
      * Storage of validated secure urls
      *
@@ -132,63 +55,6 @@ class Mage_Core_Model_Config extends Mage_Core_Model_Config_Base
      */
     protected $_secureUrlCache = array();
 
-    /**
-     * Resource model
-     * Used for operations with DB
-     *
-     * @var Mage_Core_Model_Resource_Config
-     */
-    protected $_resourceModel;
-
-    /**
-     * Configuration data model
-     *
-     * @var Mage_Core_Model_Config_Data
-     */
-    protected $_configDataModel;
-
-    /**
-     * Configuration for events by area
-     *
-     * @var array
-     */
-    protected $_eventAreas;
-
-    /**
-     * Flag cache for existing or already created directories
-     *
-     * @var array
-     */
-    protected $_dirExists = array();
-
-    /**
-     * Flach which allow using cache for config initialization
-     *
-     * @var bool
-     */
-    protected $_allowCacheForInit = true;
-
-    /**
-     * Property used during cache save process
-     *
-     * @var array
-     */
-    protected $_cachePartsForSave = array();
-
-    /**
-     * Empty configuration object for loading and merging configuration parts
-     *
-     * @var Mage_Core_Model_Config_Base
-     */
-    protected $_prototype;
-
-    /**
-     * Whether local configuration is loaded or not
-     *
-     * @var bool
-     */
-    protected $_isLocalConfigLoaded = false;
-
     /**
      * Active modules array per namespace
      *
@@ -196,14 +62,6 @@ class Mage_Core_Model_Config extends Mage_Core_Model_Config_Base
      */
     private $_moduleNamespaces = null;
 
-    /**
-     * Modules allowed to load
-     * If empty - all modules are allowed
-     *
-     * @var array
-     */
-    protected $_allowedModules = array();
-
     /**
      * Areas allowed to use
      *
@@ -211,20 +69,6 @@ class Mage_Core_Model_Config extends Mage_Core_Model_Config_Base
      */
     protected $_allowedAreas = null;
 
-    /**
-     * Paths to module's directories (etc, sql, locale etc)
-     *
-     * @var array
-     */
-    protected $_moduleDirs = array();
-
-    /**
-     * Cache for declared modules to prevent loading modules' config twice
-     *
-     * @var array
-     */
-    protected $_modulesCache = array();
-
     /**
      * Current area code
      *
@@ -240,735 +84,448 @@ class Mage_Core_Model_Config extends Mage_Core_Model_Config_Base
     protected $_objectManager;
 
     /**
-     * Application installation timestamp
+     * Configuration storage
      *
-     * @var int|null
+     * @var Mage_Core_Model_Config_StorageInterface
      */
-    protected $_installDate;
+    protected $_storage;
 
     /**
-     * Class construct
+     * Configuration data container
      *
-     * @param Magento_ObjectManager $objectManager
-     * @param mixed $sourceData
+     * @var Mage_Core_Model_ConfigInterface
      */
-    public function __construct(Magento_ObjectManager $objectManager, $sourceData = null)
-    {
-        $this->_objectManager = $objectManager;
-        $this->setCacheId('config_global');
-        $this->_prototype = $this->_objectManager->create('Mage_Core_Model_Config_Base');
-        $this->_prototype->loadString('<config/>');
-        $this->_cacheChecksum = null;
-        parent::__construct($sourceData);
-    }
+    protected $_config;
 
     /**
-     * Get config resource model
+     * Application object
      *
-     * @return Mage_Core_Model_Resource_Config
+     * @var Mage_Core_Model_AppInterface
      */
-    public function getResourceModel()
-    {
-        if (is_null($this->_resourceModel)) {
-            $this->_resourceModel = Mage::getResourceModel('Mage_Core_Model_Resource_Config');
-        }
-        return $this->_resourceModel;
-    }
+    protected $_app;
 
     /**
-     * Get configuration data model
+     * Module configuration reader
      *
-     * @return Mage_Core_Model_Config_Data
+     * @var Mage_Core_Model_Config_Modules_Reader
      */
-    public function getConfigDataModel()
-    {
-        if ($this->_configDataModel === null) {
-            $this->_configDataModel = Mage::getModel('Mage_Core_Model_Config_Data');
-        }
-        return $this->_configDataModel;
+    protected $_moduleReader;
+
+    /**
+     * @var Mage_Core_Model_Config_InvalidatorInterface
+     */
+    protected $_invalidator;
+
+    /**
+     * @param Magento_ObjectManager $objectManager
+     * @param Mage_Core_Model_Config_StorageInterface $storage
+     * @param Mage_Core_Model_AppInterface $app
+     * @param Mage_Core_Model_Config_Modules_Reader $moduleReader
+     * @param Mage_Core_Model_Config_InvalidatorInterface $invalidator
+     */
+    public function __construct(
+        Magento_ObjectManager $objectManager,
+        Mage_Core_Model_Config_StorageInterface $storage,
+        Mage_Core_Model_AppInterface $app,
+        Mage_Core_Model_Config_Modules_Reader $moduleReader,
+        Mage_Core_Model_Config_InvalidatorInterface $invalidator
+    ) {
+        Magento_Profiler::start('config_load');
+        $this->_objectManager = $objectManager;
+        $this->_app = $app;
+        $this->_storage = $storage;
+        $this->_config = $this->_storage->getConfiguration();
+        $this->_moduleReader = $moduleReader;
+        $this->_invalidator = $invalidator;
+        $this->_objectManager->setConfiguration($this->getNode('global/di')->asArray());
+        Magento_Profiler::stop('config_load');
     }
 
     /**
-     * Initialization of core configuration
+     * Load allowed areas from config
      *
      * @return Mage_Core_Model_Config
      */
-    public function init()
+    protected function _loadAreas()
     {
-        $this->setCacheChecksum(null);
-        $this->_cacheLoadedSections = array();
-        $this->loadBase();
+        $this->_allowedAreas = array();
+        $nodeAreas = $this->getNode('global/areas');
+        if (is_object($nodeAreas)) {
+            foreach ($nodeAreas->asArray() as $areaCode => $areaInfo) {
+                if (empty($areaCode)
+                    || (!isset($areaInfo['base_controller']) || empty($areaInfo['base_controller']))
+                ) {
+                    continue;
+                }
+                /**
+                 * TODO: Check of 'routers' nodes existance is excessive:
+                 * TODO: 'routers' check is moved Mage_Core_Model_Config::getRouters()
+                 */
 
-        $cacheLoad = $this->loadModulesCache();
-        if ($cacheLoad) {
-            return $this;
+                /**
+                 * TODO: Routers are not required in API.
+                 * TODO: That is why Check for empty router class moved to Mage_Core_Model_Config::getRouters()
+                 */
+                $this->_allowedAreas[$areaCode] = $areaInfo;
+            }
         }
-        $this->loadModules();
-        $this->loadDb();
-        $this->loadLocales();
-        $this->saveCache();
+
         return $this;
     }
 
     /**
-     * Load base configuration
+     * Returns nodes found by xpath expression
      *
-     * @return Mage_Core_Model_Config
+     * @param string $xpath
+     * @return array
      */
-    public function loadBase()
+    public function getXpath($xpath)
     {
-        /** @var $dirs Mage_Core_Model_Dir */
-        $dirs = $this->_objectManager->get('Mage_Core_Model_Dir');
-        $etcDir = $dirs->getDir(Mage_Core_Model_Dir::CONFIG);
-        if (!$this->getNode()) {
-            $this->loadString('<config/>');
-        }
-        // 1. app/etc/*.xml (except local config)
-        foreach (scandir($etcDir) as $filename) {
-            if ('.' == $filename || '..' == $filename || '.xml' != substr($filename, -4)
-                || self::LOCAL_CONFIG_FILE == $filename
-            ) {
-                continue;
-            }
-            $baseConfigFile = $etcDir . DIRECTORY_SEPARATOR . $filename;
-            $baseConfig = clone $this->_prototype;
-            $baseConfig->loadFile($baseConfigFile);
-            $this->extend($baseConfig);
-        }
-        // 2. local configuration
-        $this->_loadLocalConfig();
-        return $this;
+        return $this->_config->getXpath($xpath);
     }
 
     /**
-     * Load local configuration (part of the base configuration)
+     * Returns node found by the $path and scope info
+     *
+     * @param   string $path
+     * @param   string $scope
+     * @param   string|int $scopeCode
+     * @return Mage_Core_Model_Config_Element
      */
-    protected function _loadLocalConfig()
+    public function getNode($path = null, $scope = '', $scopeCode = null)
     {
-        /** @var $app Mage_Core_Model_App */
-        $app = $this->_objectManager->get('Mage_Core_Model_App');
-        /** @var $dirs Mage_Core_Model_Dir */
-        $dirs = $this->_objectManager->get('Mage_Core_Model_Dir');
-        $etcDir = $dirs->getDir(Mage_Core_Model_Dir::CONFIG);
-        $localConfigParts = array();
-
-        $localConfigFile = $etcDir . DIRECTORY_SEPARATOR . self::LOCAL_CONFIG_FILE;
-        if (file_exists($localConfigFile)) {
-            // 1. app/etc/local.xml
-            $localConfig = clone $this->_prototype;
-            $localConfig->loadFile($localConfigFile);
-            $localConfigParts[] = $localConfig;
-
-            // 2. app/etc/<dir>/<file>.xml
-            $localConfigExtraFile = $app->getInitParam(self::INIT_OPTION_EXTRA_FILE);
-            if (preg_match('/^[a-z\d_-]+\/[a-z\d_-]+\.xml$/', $localConfigExtraFile)) {
-                $localConfigExtraFile = $etcDir . DIRECTORY_SEPARATOR . $localConfigExtraFile;
-                $localConfig = clone $this->_prototype;
-                $localConfig->loadFile($localConfigExtraFile);
-                $localConfigParts[] = $localConfig;
+        if ($scope !== '') {
+            if (('store' === $scope) || ('website' === $scope)) {
+                $scope .= 's';
             }
-        }
-
-        // 3. extra local configuration string
-        $localConfigExtraData = $app->getInitParam(self::INIT_OPTION_EXTRA_DATA);
-        if ($localConfigExtraData) {
-            $localConfig = clone $this->_prototype;
-            $localConfig->loadString($localConfigExtraData);
-            $localConfigParts[] = $localConfig;
-        }
-
-        if ($localConfigParts) {
-            foreach ($localConfigParts as $oneConfigPart) {
-                $this->extend($oneConfigPart);
+            if (('default' !== $scope) && is_int($scopeCode)) {
+                if ('stores' == $scope) {
+                    $scopeCode = $this->_app->getStore($scopeCode)->getCode();
+                } elseif ('websites' == $scope) {
+                    $scopeCode = $this->_app->getWebsite($scopeCode)->getCode();
+                } else {
+                    Mage::throwException(
+                        $this->_objectManager->get('Mage_Core_Helper_Data')
+                            ->__('Unknown scope "%s".', $scope)
+                    );
+                }
             }
-            $this->_isLocalConfigLoaded = true;
-            $this->_loadInstallDate();
+            $path = $scope . ($scopeCode ? '/' . $scopeCode : '' ) . (empty($path) ? '' : '/' . $path);
+        }
+        try {
+            return $this->_config->getNode($path);
+        } catch (Mage_Core_Model_Config_Cache_Exception $e) {
+            $this->reinit();
+            return $this->_config->getNode($path);
         }
     }
 
     /**
-     * Load application installation date
+     * Create node by $path and set its value.
+     *
+     * @param string $path separated by slashes
+     * @param string $value
+     * @param bool $overwrite
      */
-    protected function _loadInstallDate()
+    public function setNode($path, $value, $overwrite = true)
     {
-        $installDateNode = $this->getNode(self::XML_PATH_INSTALL_DATE);
-        if ($installDateNode) {
-            $this->_installDate = strtotime((string)$installDateNode);
+        try {
+            $this->_config->setNode($path, $value, $overwrite);
+        } catch (Mage_Core_Model_Config_Cache_Exception $e) {
+            $this->reinit();
+            $this->_config->setNode($path, $value, $overwrite);
         }
     }
 
     /**
-     * Retrieve application installation date as a timestamp or NULL, if it has not been installed yet
-     *
-     * @return int|null
+     * Get currently used area code
+     * @return string|null
      */
-    public function getInstallDate()
+    public function getCurrentAreaCode()
     {
-        return $this->_installDate;
+        return $this->_currentAreaCode;
     }
 
     /**
-     * Load locale configuration from locale configuration files
+     * Set currently used area code
      *
+     * @param $areaCode
      * @return Mage_Core_Model_Config
      */
-    public function loadLocales()
+    public function setCurrentAreaCode($areaCode)
     {
-        /** @var $dirs Mage_Core_Model_Dir */
-        $dirs = $this->_objectManager->get('Mage_Core_Model_Dir');
-        $localeDir = $dirs->getDir(Mage_Core_Model_Dir::LOCALE);
-        $files = glob($localeDir . DS . '*' . DS . 'config.xml');
-
-        if (is_array($files) && !empty($files)) {
-            foreach ($files as $file) {
-                $merge = clone $this->_prototype;
-                $merge->loadFile($file);
-                $this->extend($merge);
-            }
-        }
+        $this->_currentAreaCode = $areaCode;
         return $this;
     }
 
     /**
-     * Load cached modules and locale configuration
+     * Get allowed areas
      *
-     * @return bool
+     * @return array
      */
-    public function loadModulesCache()
+    public function getAreas()
     {
-        if ($this->getInstallDate()) {
-            if ($this->_canUseCacheForInit()) {
-                Magento_Profiler::start('init_modules_config_cache');
-                $loaded = $this->loadCache();
-                Magento_Profiler::stop('init_modules_config_cache');
-                if ($loaded) {
-                    $this->_useCache = true;
-                    $this->_loadDiConfiguration();
-                    return true;
-                }
-            }
+        if (is_null($this->_allowedAreas) ) {
+            $this->_loadAreas();
         }
-        return false;
+        return $this->_allowedAreas;
     }
 
     /**
-     * Load modules configuration
+     * Retrieve area config by area code
      *
-     * @return Mage_Core_Model_Config
-     */
-    public function loadModules()
-    {
-        Magento_Profiler::start('config');
-        Magento_Profiler::start('load_modules');
-        $this->_loadDeclaredModules();
-
-        Magento_Profiler::start('load_modules_configuration');
-        $resourceConfig = sprintf('config.%s.xml', $this->getResourceConnectionModel('core'));
-        $this->loadModulesConfiguration(array('config.xml',$resourceConfig), $this);
-        Magento_Profiler::stop('load_modules_configuration');
-
-        // Prevent local configuration overriding
-        $this->_loadLocalConfig();
-
-        $this->applyExtends();
-        $this->_loadDiConfiguration();
-        Magento_Profiler::stop('load_modules');
-        Magento_Profiler::stop('config');
-        return $this;
-    }
-
-    /**
-     * Load di configuration for given area
+     * @param string|null $areaCode
+     * @throws InvalidArgumentException
+     * @return array
      */
-    protected function _loadDiConfiguration()
+    public function getAreaConfig($areaCode = null)
     {
-        $configurationNode = $this->getNode(self::XML_PATH_DI_CONFIG);
-        if ($configurationNode) {
-            $configuration = $configurationNode->asArray();
-            $this->_objectManager->setConfiguration($configuration);
+        $areaCode = empty($areaCode) ? $this->getCurrentAreaCode() : $areaCode;
+        $areas = $this->getAreas();
+        if (!isset($areas[$areaCode])) {
+            throw new InvalidArgumentException('Requested area (' . $areaCode . ') doesn\'t exist');
         }
+        return $areas[$areaCode];
     }
 
     /**
-     * Check if local configuration (DB connection, etc) is loaded
+     * Identify front name of the requested area. Return current area front name if area code is not specified.
      *
-     * @return bool
+     * @param string|null $areaCode
+     * @return string
+     * @throws LogicException If front name is not defined.
      */
-    public function isLocalConfigLoaded()
+    public function getAreaFrontName($areaCode = null)
     {
-        return $this->_isLocalConfigLoaded;
+        $areaCode = empty($areaCode) ? $this->getCurrentAreaCode() : $areaCode;
+        $areaConfig = $this->getAreaConfig($areaCode);
+        if (!isset($areaConfig['frontName'])) {
+            throw new LogicException(sprintf(
+                'Area "%s" must have front name defined in the application config.',
+                $areaCode
+            ));
+        }
+        return $areaConfig['frontName'];
     }
 
     /**
-     * Load config data from DB
+     * Get routers from config
      *
-     * @return Mage_Core_Model_Config
+     * @return array
      */
-    public function loadDb()
+    public function getRouters()
     {
-        Magento_Profiler::start('config');
-        if ($this->getInstallDate()) {
-            Magento_Profiler::start('load_db');
-            $dbConf = $this->getResourceModel();
-            $dbConf->loadToXml($this);
-            Magento_Profiler::stop('load_db');
+        $routers = array();
+        foreach ($this->getAreas() as $areaCode => $areaInfo) {
+            if (isset($areaInfo['routers']) && is_array($areaInfo['routers'])) {
+                foreach ($areaInfo['routers'] as $routerKey => $routerInfo ) {
+                    if (!isset($routerInfo['class']) || empty($routerInfo['class'])) {
+                        continue;
+                    }
+                    $routerInfo = array_merge($routerInfo, $areaInfo);
+                    unset($routerInfo['routers']);
+                    $routerInfo['area'] = $areaCode;
+                    $routers[$routerKey] = $routerInfo;
+                }
+            }
         }
-        Magento_Profiler::stop('config');
-        return $this;
+        return $routers;
     }
 
     /**
-     * Reinitialize configuration
+     * Get module config node
      *
-     * @return Mage_Core_Model_Config
+     * @param string $moduleName
+     * @return Varien_Simplexml_Element
      */
-    public function reinit()
+    public function getModuleConfig($moduleName = '')
     {
-        $this->_allowCacheForInit = false;
-        $this->_useCache = false;
-        return $this->init();
+        $modules = $this->getNode('modules');
+        if ('' === $moduleName) {
+            return $modules;
+        } else {
+            return $modules->$moduleName;
+        }
     }
 
     /**
-     * Check if cache can be used for config initialization
+     * Check if specified module is enabled
      *
+     * @param string $moduleName
      * @return bool
      */
-    protected function _canUseCacheForInit()
+    public function isModuleEnabled($moduleName)
     {
-        return Mage::app()->useCache('config') && $this->_allowCacheForInit
-            && !$this->_loadCache($this->_getCacheLockId());
-    }
-
-    /**
-     * Retrieve cache object
-     *
-     * @return Zend_Cache_Frontend_File
-     */
-    public function getCache()
-    {
-        return Mage::app()->getCache();
-    }
-
-    /**
-     * Get lock flag cache identifier
-     *
-     * @return string
-     */
-    protected function _getCacheLockId()
-    {
-        return $this->getCacheId() . '.lock';
-    }
-
-    /**
-     * Save configuration cache
-     *
-     * @param   array $tags cache tags
-     * @return  Mage_Core_Model_Config
-     */
-    public function saveCache($tags = array())
-    {
-        if (!Mage::app()->useCache('config')) {
-            return $this;
-        }
-        if (!in_array(self::CACHE_TAG, $tags)) {
-            $tags[] = self::CACHE_TAG;
-        }
-        $cacheLockId = $this->_getCacheLockId();
-        if ($this->_loadCache($cacheLockId)) {
-            return $this;
-        }
-
-        if (!empty($this->_cacheSections)) {
-            $xml = clone $this->_xml;
-            foreach ($this->_cacheSections as $sectionName => $level) {
-                $this->_saveSectionCache($this->getCacheId(), $sectionName, $xml, $level, $tags);
-                unset($xml->$sectionName);
-            }
-            $this->_cachePartsForSave[$this->getCacheId()] = $xml->asNiceXml('', false);
-        } else {
-            return parent::saveCache($tags);
-        }
-
-        $this->_saveCache(time(), $cacheLockId, array(), 60);
-        $this->removeCache();
-        foreach ($this->_cachePartsForSave as $cacheId => $cacheData) {
-            $this->_saveCache($cacheData, $cacheId, $tags, $this->getCacheLifetime());
-        }
-        unset($this->_cachePartsForSave);
-        $this->_removeCache($cacheLockId);
-        return $this;
-    }
-
-    /**
-     * Save cache of specified
-     *
-     * @param   string $idPrefix cache id prefix
-     * @param   string $sectionName
-     * @param   Varien_Simplexml_Element $source
-     * @param   int $recursionLevel
-     * @param   array $tags
-     * @return  Mage_Core_Model_Config
-     */
-    protected function _saveSectionCache($idPrefix, $sectionName, $source, $recursionLevel = 0, $tags = array())
-    {
-        if ($source && $source->$sectionName) {
-            $cacheId = $idPrefix . '_' . $sectionName;
-            if ($recursionLevel > 0) {
-                foreach (array_keys((array)$source->$sectionName->children()) as $subSectionName) {
-                    $this->_saveSectionCache(
-                        $cacheId, $subSectionName, $source->$sectionName, $recursionLevel - 1, $tags
-                    );
-                }
-            }
-            $this->_cachePartsForSave[$cacheId] = $source->$sectionName->asNiceXml('', false);
+        if (!$this->getNode('modules/' . $moduleName)) {
+            return false;
         }
-        return $this;
-    }
-
-    /**
-     * Load config section cached data
-     *
-     * @param   string $sectionName
-     * @return  Varien_Simplexml_Element
-     */
-    protected function _loadSectionCache($sectionName)
-    {
-        $cacheId = $this->getCacheId() . '_' . $sectionName;
-        $xmlString = $this->_loadCache($cacheId);
 
-        /**
-         * If we can't load section cache (problems with cache storage)
-         */
-        if (!$xmlString) {
-            $this->_useCache = false;
-            $this->reinit();
+        $isActive = $this->getNode('modules/' . $moduleName . '/active');
+        if (!$isActive || !in_array((string)$isActive, array('true', '1'))) {
             return false;
-        } else {
-            $xml = simplexml_load_string($xmlString, $this->_elementClass);
-            return $xml;
         }
+        return true;
     }
 
     /**
-     * Load cached data by identifier
+     * Get module directory by directory type
      *
-     * @param   string $cacheId
+     * @param   string $type
+     * @param   string $moduleName
      * @return  string
      */
-    protected function _loadCache($cacheId)
+    public function getModuleDir($type, $moduleName)
     {
-        return Mage::app()->loadCache($cacheId);
+        return $this->_moduleReader->getModuleDir($type, $moduleName);
     }
 
     /**
-     * Save cache data
+     * Set path to the corresponding module directory
      *
-     * @param   string $data
-     * @param   string $cacheId
-     * @param   array $tags
-     * @param   bool|int $lifetime
-     * @return  Mage_Core_Model_Config
+     * @param string $moduleName
+     * @param string $type directory type (etc, controllers, locale etc)
+     * @param string $path
+     * @return Mage_Core_Model_Config
      */
-    protected function _saveCache($data, $cacheId, $tags = array(), $lifetime = false)
+    public function setModuleDir($moduleName, $type, $path)
     {
-        return Mage::app()->saveCache($data, $cacheId, $tags, $lifetime);
+        $this->_moduleReader->setModuleDir($moduleName, $type, $path);
+        return $this;
     }
 
     /**
-     * Clear cache data by id
+     * Retrieve store Ids for $path with checking
      *
-     * @param   string $cacheId
-     * @return  Mage_Core_Model_Config
-     */
-    protected function _removeCache($cacheId)
-    {
-        return Mage::app()->removeCache($cacheId);
-    }
-
-    /**
-     * Remove configuration cache
+     * if empty $allowValues then retrieve all stores values
      *
-     * @return Mage_Core_Model_Config
-     */
-    public function removeCache()
-    {
-        Mage::app()->cleanCache(array(self::CACHE_TAG));
-        return parent::removeCache();
-    }
-
-    /**
-     * Configuration cache clean process
+     * return array($storeId => $pathValue)
      *
-     * @return Mage_Core_Model_Config
+     * @param   string $path
+     * @param   array  $allowValues
+     * @param   string  $useAsKey
+     * @return  array
      */
-    public function cleanCache()
+    public function getStoresConfigByPath($path, $allowValues = array(), $useAsKey = 'id')
     {
-        return $this->reinit();
-    }
+        $storeValues = array();
+        $stores = $this->getNode('stores');
+        /** @var $store Varien_Simplexml_Element */
+        foreach ($stores->children() as $code => $store) {
+            switch ($useAsKey) {
+                case 'id':
+                    $key = (int) $store->descend('system/store/id');
+                    break;
 
-    /**
-     * Getter for section configuration object
-     *
-     * @param array $path
-     * @return Mage_Core_Model_Config_Element
-     */
-    protected function _getSectionConfig($path)
-    {
-        $section = $path[0];
-        if (!isset($this->_cacheSections[$section])) {
-            return false;
-        }
-        $sectionPath = array_slice($path, 0, $this->_cacheSections[$section]+1);
-        $sectionKey = implode('_', $sectionPath);
+                case 'code':
+                    $key = $code;
+                    break;
 
-        if (!isset($this->_cacheLoadedSections[$sectionKey])) {
-            Magento_Profiler::start('init_config_section:' . $sectionKey, array('group' => 'init_config_section',
-                'section_key' => $sectionKey));
-            $this->_cacheLoadedSections[$sectionKey] = $this->_loadSectionCache($sectionKey);
-            Magento_Profiler::stop('init_config_section:' . $sectionKey);
-        }
+                case 'name':
+                    $key = (string) $store->descend('system/store/name');
+                    break;
 
-        if ($this->_cacheLoadedSections[$sectionKey] === false) {
-            return false;
-        }
-        return $this->_cacheLoadedSections[$sectionKey];
-    }
+                default:
+                    $key = false;
+                    break;
+            }
 
-    /**
-     * Get node value from cached section data
-     *
-     * @param   array $path
-     * @return  Mage_Core_Model_Config
-     */
-    public function getSectionNode($path)
-    {
-        $section    = $path[0];
-        $config     = $this->_getSectionConfig($path);
-        $path       = array_slice($path, $this->_cacheSections[$section] + 1);
-        if ($config) {
-            return $config->descend($path);
-        }
-        return false;
-    }
+            if ($key === false) {
+                continue;
+            }
 
-    /**
-     * Returns node found by the $path and scope info
-     *
-     * @param  string $path
-     * @param  string $scope
-     * @param  string|int $scopeCode
-     * @return Mage_Core_Model_Config_Element
-     */
-    public function getNode($path = null, $scope = '', $scopeCode = null)
-    {
-        $path = $this->_getPathInScope($path, $scope, $scopeCode);
+            $pathValue = (string) $store->descend($path);
 
-        /**
-         * Check path cache loading
-         */
-        if ($this->_useCache && ($path !== null)) {
-            $path    = explode('/', $path);
-            $section = $path[0];
-            if (isset($this->_cacheSections[$section])) {
-                $res = $this->getSectionNode($path);
-                if ($res !== false) {
-                    return $res;
-                }
+            if (empty($allowValues)) {
+                $storeValues[$key] = $pathValue;
+            } elseif (in_array($pathValue, $allowValues)) {
+                $storeValues[$key] = $pathValue;
             }
         }
 
-        return parent::getNode($path);
+        return $storeValues;
     }
 
     /**
-     * Get path for scope
+     * Get fieldset from configuration
      *
-     * @SuppressWarnings(PHPMD.NPathComplexity)
-     * @param null $path
-     * @param string $scope
-     * @param string|int $scopeCode
-     * @return null|string
+     * @param string $name fieldset name
+     * @param string $root fieldset area, could be 'admin'
+     * @return null|array
      */
-    protected function _getPathInScope($path = null, $scope, $scopeCode)
+    public function getFieldset($name, $root = 'global')
     {
-        if ($scope !== '') {
-            if (('store' === $scope) || ('website' === $scope)) {
-                $scope .= 's';
-            }
-            if ((Mage_Core_Model_Store::DEFAULT_CODE !== $scope) && is_int($scopeCode)) {
-                $scopeCode = $this->_getScopeCode($scope, $scopeCode);
-            }
-            $path = $scope . ($scopeCode ? '/' . $scopeCode : '') . (empty($path) ? '' : '/' . $path);
+        /** @var $config Mage_Core_Model_Config_Base */
+        $config = $this->_objectManager->get('Mage_Core_Model_Config_Fieldset');
+        $rootNode = $config->getNode($root . '/fieldsets');
+        if (!$rootNode) {
+            return null;
         }
-        return $path;
+        return $rootNode->$name ? $rootNode->$name->children() : null;
     }
 
     /**
-     * Get scope code by id
+     * Get standard path variables.
      *
-     * @param string $scope
-     * @param int $scopeId
-     * @return string
-     */
-    protected function _getScopeCode($scope, $scopeId)
-    {
-        $scopeCode = '';
-        if (self::SCOPE_STORES == $scope) {
-            $scopeCode = Mage::app()->getStore($scopeId)->getCode();
-        } elseif (self::SCOPE_WEBSITES == $scope) {
-            $scopeCode = Mage::app()->getWebsite($scopeId)->getCode();
-        } else {
-            Mage::throwException(Mage::helper('Mage_Core_Helper_Data')->__('Unknown scope "%s".', $scope));
-        }
-        return $scopeCode;
-    }
-
-    /**
-     * Create node by $path and set its value.
+     * To be used in blocks, templates, etc.
      *
-     * @param string $path separated by slashes
-     * @param string $value
-     * @param bool $overwrite
-     * @return Varien_Simplexml_Config
+     * @return array
      */
-    public function setNode($path, $value, $overwrite = true)
+    public function getPathVars()
     {
-        if ($this->_useCache && ($path !== null)) {
-            $sectionPath = explode('/', $path);
-            $config = $this->_getSectionConfig($sectionPath);
-            if ($config) {
-                $sectionPath = array_slice($sectionPath, $this->_cacheSections[$sectionPath[0]]+1);
-                $sectionPath = implode('/', $sectionPath);
-                $config->setNode($sectionPath, $value, $overwrite);
-            }
-        }
-        return parent::setNode($path, $value, $overwrite);
+        $path = array();
+        $path['baseUrl'] = Mage::getBaseUrl();
+        $path['baseSecureUrl'] = Mage::getBaseUrl('link', true);
+        return $path;
     }
 
-
     /**
-     * Retrieve declared module file list
+     * Check whether given path should be secure according to configuration security requirements for URL
+     * "Secure" should not be confused with https protocol, it is about web/secure/*_url settings usage only
      *
-     * @return array
+     * @param string $url
+     * @return bool
      */
-    protected function _getDeclaredModuleFiles()
+    public function shouldUrlBeSecure($url)
     {
-        /** @var $dirs Mage_Core_Model_Dir */
-        $dirs = $this->_objectManager->get('Mage_Core_Model_Dir');
-        $codeDir = $dirs->getDir(Mage_Core_Model_Dir::MODULES);
-        $moduleFiles = glob($codeDir . DS . '*' . DS . '*' . DS . '*' . DS . 'etc' . DS . 'config.xml');
-
-        if (!$moduleFiles) {
+        if (!Mage::getStoreConfigFlag(Mage_Core_Model_Store::XML_PATH_SECURE_IN_FRONTEND)) {
             return false;
         }
 
-        $collectModuleFiles = array(
-            'base'   => array(),
-            'mage'   => array(),
-            'custom' => array()
-        );
-
-        foreach ($moduleFiles as $v) {
-            $name = explode(DIRECTORY_SEPARATOR, $v);
-            $collection = $name[count($name) - 4];
-
-            if ($collection == 'Mage') {
-                $collectModuleFiles['mage'][] = $v;
-            } else {
-                $collectModuleFiles['custom'][] = $v;
+        if (!isset($this->_secureUrlCache[$url])) {
+            $this->_secureUrlCache[$url] = false;
+            $secureUrls = $this->getNode('frontend/secure_url');
+            foreach ($secureUrls->children() as $match) {
+                if (strpos($url, (string)$match) === 0) {
+                    $this->_secureUrlCache[$url] = true;
+                    break;
+                }
             }
         }
-
-        $etcDir = $dirs->getDir(Mage_Core_Model_Dir::CONFIG);
-        $additionalFiles = glob($etcDir . DS . 'modules' . DS . '*.xml');
-
-        foreach ($additionalFiles as $v) {
-            $collectModuleFiles['base'][] = $v;
-        }
-
-        return array_merge(
-            $collectModuleFiles['mage'],
-            $collectModuleFiles['custom'],
-            $collectModuleFiles['base']
-        );
+        return $this->_secureUrlCache[$url];
     }
 
     /**
-     * Add module(s) to allowed list
+     * Get default server variables values
      *
-     * @param  string|array $module
-     * @return Mage_Core_Model_Config
+     * @return array
      */
-    public function addAllowedModules($module)
+    public function getDistroBaseUrl()
     {
-        if (is_array($module)) {
-            foreach ($module as $moduleName) {
-                $this->addAllowedModules($moduleName);
-            }
-        } elseif (!in_array($module, $this->_allowedModules)) {
-            $this->_allowedModules[] = $module;
-        }
-
-        return $this;
-    }
+        if (isset($_SERVER['SCRIPT_NAME']) && isset($_SERVER['HTTP_HOST'])) {
+            $secure = (!empty($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] != 'off'))
+                || (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443');
+            $scheme = ($secure ? 'https' : 'http') . '://' ;
 
-    /**
-     * Load declared modules configuration
-     *
-     * @return  Mage_Core_Model_Config
-     */
-    protected function _loadDeclaredModules()
-    {
-        Magento_Profiler::start('load_modules_files');
-        $moduleFiles = $this->_getDeclaredModuleFiles();
-        if (!$moduleFiles) {
-            return $this;
-        }
-        Magento_Profiler::stop('load_modules_files');
+            $hostArr = explode(':', $_SERVER['HTTP_HOST']);
+            $host = $hostArr[0];
+            $port = isset($hostArr[1]) && (!$secure && $hostArr[1] != 80 || $secure && $hostArr[1] != 443)
+                ? ':'. $hostArr[1]
+                : '';
+            $path = Mage::getObjectManager()->get('Mage_Core_Controller_Request_Http')->getBasePath();
 
-        Magento_Profiler::start('load_modules_declaration');
-        $unsortedConfig = new Mage_Core_Model_Config_Base('<config/>');
-        $emptyConfig = new Mage_Core_Model_Config_Element('<config><modules/></config>');
-        $declaredModules = array();
-        foreach ($moduleFiles as $oneConfigFile) {
-            $path = explode(DIRECTORY_SEPARATOR, $oneConfigFile);
-            $moduleConfig = new Mage_Core_Model_Config_Base($oneConfigFile);
-            $modules = $moduleConfig->getXpath('modules/*');
-            if (!$modules) {
-                continue;
-            }
-            $cPath = count($path);
-            if ($cPath > 4) {
-                $moduleName = $path[$cPath - 4] . '_' . $path[$cPath - 3];
-                $this->_modulesCache[$moduleName] = $moduleConfig;
-            }
-            foreach ($modules as $module) {
-                $moduleName = $module->getName();
-                $isActive = (string)$module->active;
-                if (isset($declaredModules[$moduleName])) {
-                    $declaredModules[$moduleName]['active'] = $isActive;
-                    continue;
-                }
-                $newModule = clone $emptyConfig;
-                $newModule->modules->appendChild($module);
-                $declaredModules[$moduleName] = array(
-                    'active' => $isActive,
-                    'module' => $newModule,
-                );
-            }
-        }
-        foreach ($declaredModules as $moduleName => $module) {
-            if ($module['active'] == 'true') {
-                $module['module']->modules->{$moduleName}->active = 'true';
-                $unsortedConfig->extend(new Mage_Core_Model_Config_Base($module['module']));
-            }
+            return $scheme . $host . $port . rtrim($path, '/') . '/';
         }
-        $sortedConfig = new Mage_Core_Model_Config_Module($unsortedConfig, $this->_allowedModules);
-
-        $this->extend($sortedConfig);
-        Magento_Profiler::stop('load_modules_declaration');
-        return $this;
+        return 'http://localhost/';
     }
 
     /**
@@ -981,7 +538,17 @@ class Mage_Core_Model_Config extends Mage_Core_Model_Config_Base
      */
     public function determineOmittedNamespace($name, $asFullModuleName = false)
     {
-        $this->_initModulesPreNamespaces();
+        if (null === $this->_moduleNamespaces) {
+            $this->_moduleNamespaces = array();
+            /** @var $moduleConfig Varien_Simplexml_Element */
+            foreach ($this->getXpath('modules/*') as $moduleConfig) {
+                if ((string)$moduleConfig->active == 'true') {
+                    $moduleName = $moduleConfig->getName();
+                    $module = strtolower($moduleName);
+                    $this->_moduleNamespaces[substr($module, 0, strpos($module, '_'))][$module] = $moduleName;
+                }
+            }
+        }
 
         $name = explode('_', strtolower($name));
         $partsNum = count($name);
@@ -1007,330 +574,22 @@ class Mage_Core_Model_Config extends Mage_Core_Model_Config_Base
     }
 
     /**
-     * Init modules per namespaces
+     * Reinitialize configuration
      *
      * @return Mage_Core_Model_Config
      */
-    protected function _initModulesPreNamespaces()
+    public function reinit()
     {
-        if (null === $this->_moduleNamespaces) {
-            $this->_moduleNamespaces = array();
-            foreach ($this->_xml->xpath('modules/*') as $moduleNode) {
-                if ((string)$moduleNode->active == 'true') {
-                    $moduleName = $moduleNode->getName();
-                    $module = strtolower($moduleName);
-                    $this->_moduleNamespaces[substr($module, 0, strpos($module, '_'))][$module] = $moduleName;
-                }
-            }
-        }
-        return $this;
+        $this->removeCache();
+        $this->_invalidator->invalidate();
+        $this->_config = $this->_storage->getConfiguration();
     }
 
     /**
-     * Iterate all active modules "etc" folders and combine data from
-     * specified xml file name to one object
-     *
-     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
-     * @SuppressWarnings(PHPMD.NPathComplexity)
-     * @param   string $fileName
-     * @param   null|Mage_Core_Model_Config_Base $mergeToObject
-     * @param   null|Mage_Core_Model_Config_Base $mergeModel
-     * @return  Mage_Core_Model_Config_Base
-     */
-    public function loadModulesConfiguration($fileName, $mergeToObject = null, $mergeModel = null)
-    {
-        if ($mergeToObject === null) {
-            $mergeToObject = clone $this->_prototype;
-        }
-
-        $mergeModel = $mergeModel === null ? clone $this->_prototype : $mergeModel;
-
-        $modules = $this->getNode('modules')->children();
-        foreach ($modules as $modName => $module) {
-            if (!$module->is('active')) {
-                continue;
-            }
-            if (!is_array($fileName)) {
-                $fileName = array($fileName);
-            }
-            foreach ($fileName as $configFile) {
-                if ($configFile == 'config.xml' && isset($this->_modulesCache[$modName])) {
-                    $mergeToObject->extend($this->_modulesCache[$modName], true);
-                    //Prevent overriding <active> node of module if it was redefined in etc/modules
-                    $mergeToObject->extend(new Mage_Core_Model_Config_Base(
-                        "<config><modules><{$modName}><active>true</active></{$modName}></modules></config>"), true);
-                } else {
-                    $configFilePath = $this->getModuleDir('etc', $modName) . DS . $configFile;
-                    if ($mergeModel->loadFile($configFilePath)) {
-                        $mergeToObject->extend($mergeModel, true);
-                    }
-                }
-            }
-        }
-        unset($this->_modulesCache);
-        return $mergeToObject;
-    }
-
-    /**
-     * Go through all modules and find configuration files of active modules
-     *
-     * @param string $filename
-     * @return array
-     */
-    public function getModuleConfigurationFiles($filename)
-    {
-        $result = array();
-        $modules = $this->getNode('modules')->children();
-        foreach ($modules as $moduleName => $module) {
-            if ((!$module->is('active'))) {
-                continue;
-            }
-            $file = $this->getModuleDir('etc', $moduleName) . DIRECTORY_SEPARATOR . $filename;
-            if (file_exists($file)) {
-                $result[] = $file;
-            }
-        }
-        return $result;
-    }
-
-    /**
-     * Get default server variables values
-     *
-     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
-     * @return array
-     */
-    public function getDistroBaseUrl()
-    {
-        if (isset($_SERVER['SCRIPT_NAME']) && isset($_SERVER['HTTP_HOST'])) {
-            $secure = (!empty($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] != 'off'))
-                || (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443');
-            $scheme = ($secure ? 'https' : 'http') . '://' ;
-
-            $hostArr = explode(':', $_SERVER['HTTP_HOST']);
-            $host = $hostArr[0];
-            $port = isset($hostArr[1]) && (!$secure && $hostArr[1] != 80 || $secure && $hostArr[1] != 443)
-                ? ':'. $hostArr[1]
-                : '';
-            $path = Mage::app()->getRequest()->getBasePath();
-
-            return $scheme . $host . $port . rtrim($path, '/') . '/';
-        }
-        return 'http://localhost/';
-    }
-
-    /**
-     * Get module config node
-     *
-     * @param string $moduleName
-     * @return Varien_Simplexml_Element
-     */
-    public function getModuleConfig($moduleName = '')
-    {
-        $modules = $this->getNode('modules');
-        if ('' === $moduleName) {
-            return $modules;
-        } else {
-            return $modules->$moduleName;
-        }
-    }
-
-    /**
-     * Get module setup class instance.
-     *
-     * Defaults to Mage_Core_Setup
-     *
-     * @param string|Varien_Simplexml_Element $module
-     * @return object
-     */
-    public function getModuleSetup($module = '')
-    {
-        $className = 'Mage_Core_Setup';
-        if ('' !== $module) {
-            if (is_string($module)) {
-                $module = $this->getModuleConfig($module);
-            }
-            if (isset($module->setup)) {
-                $moduleClassName = $module->setup->getClassName();
-                if (!empty($moduleClassName)) {
-                    $className = $moduleClassName;
-                }
-            }
-        }
-        return new $className($module);
-    }
-
-    /**
-     * Get module directory by directory type
-     *
-     * @param   string $type
-     * @param   string $moduleName
-     * @return  string
-     */
-    public function getModuleDir($type, $moduleName)
-    {
-        if (isset($this->_moduleDirs[$moduleName][$type])) {
-            return $this->_moduleDirs[$moduleName][$type];
-        }
-
-        $codePool = (string)$this->getModuleConfig($moduleName)->codePool;
-        /** @var $dirs Mage_Core_Model_Dir */
-        $dirs = $this->_objectManager->get('Mage_Core_Model_Dir');
-        $dir = $dirs->getDir(Mage_Core_Model_Dir::MODULES) . DS . $codePool . DS . uc_words($moduleName, DS);
-
-        switch ($type) {
-            case 'etc':
-            case 'controllers':
-            case 'sql':
-            case 'data':
-            case 'locale':
-            case 'view':
-                $dir .= DS . $type;
-                break;
-        }
-
-        $dir = str_replace('/', DS, $dir);
-        return $dir;
-    }
-
-    /**
-     * Set path to the corresponding module directory
-     *
-     * @param string $moduleName
-     * @param string $type directory type (etc, controllers, locale etc)
-     * @param string $path
-     * @return Mage_Core_Model_Config
-     */
-    public function setModuleDir($moduleName, $type, $path)
-    {
-        if (!isset($this->_moduleDirs[$moduleName])) {
-            $this->_moduleDirs[$moduleName] = array();
-        }
-        $this->_moduleDirs[$moduleName][$type] = $path;
-        return $this;
-    }
-
-    /**
-     * Load event observers for an area (front, admin)
-     *
-     * @param   string $area
-     * @return  boolean
-     */
-    public function loadEventObservers($area)
-    {
-        $events = $this->getNode("$area/events");
-        if ($events) {
-            $events = $events->children();
-        } else {
-            return false;
-        }
-
-        foreach ($events as $event) {
-            $eventName = $event->getName();
-            $observers = $event->observers->children();
-            foreach ($observers as $observer) {
-                switch ((string)$observer->type) {
-                    case 'singleton':
-                        $callback = array(
-                            Mage::getSingleton((string)$observer->class),
-                            (string)$observer->method
-                        );
-                        break;
-                    case 'object':
-                    case 'model':
-                        $callback = array(
-                            Mage::getModel((string)$observer->class),
-                            (string)$observer->method
-                        );
-                        break;
-                    default:
-                        $callback = array($observer->getClassName(), (string)$observer->method);
-                        break;
-                }
-
-                $args = (array)$observer->args;
-                // @codingStandardsIgnoreStart
-                $observerClass = $observer->observer_class ? (string)$observer->observer_class : '';
-                // @codingStandardsIgnoreEnd
-                Mage::addObserver($eventName, $callback, $args, $observer->getName(), $observerClass);
-            }
-        }
-        return true;
-    }
-
-    /**
-     * Get standard path variables.
-     *
-     * To be used in blocks, templates, etc.
-     *
-     * @return array
-     */
-    public function getPathVars()
-    {
-        $path = array();
-
-        $path['baseUrl'] = Mage::getBaseUrl();
-        $path['baseSecureUrl'] = Mage::getBaseUrl('link', true);
-
-        return $path;
-    }
-
-    /**
-     * Check rewrite section and apply rewrites to $className, if any
-     *
-     * @param   string $className
-     * @return  string
-     */
-    protected function _applyClassRewrites($className)
-    {
-        if (!isset($this->_classNameCache[$className])) {
-            if (isset($this->_xml->global->rewrites->$className)) {
-                $className = (string) $this->_xml->global->rewrites->$className;
-            }
-            $this->_classNameCache[$className] = $className;
-        }
-
-        return $this->_classNameCache[$className];
-    }
-
-    /**
-     * Retrieve block class name
-     *
-     * @param   string $blockClass
-     * @return  string
-     */
-    public function getBlockClassName($blockClass)
-    {
-        return $this->getModelClassName($blockClass);
-    }
-
-    /**
-     * Retrieve helper class name
-     *
-     * @param   string $helperClass
-     * @return  string
-     */
-    public function getHelperClassName($helperClass)
-    {
-        return $this->getModelClassName($helperClass);
-    }
-
-
-    /**
-     * Retrieve module class name
-     *
-     * @param   string $modelClass
-     * @return  string
-     */
-    public function getModelClassName($modelClass)
-    {
-        return $this->_applyClassRewrites($modelClass);
-    }
-
-    /**
-     * Get model class instance.
+     * Get model class instance.
      *
      * Example:
-     * $config->getModelInstance('catalog/product')
+     * $config->getModelInstance('Mage_Catalog_Model_Resource_Product')
      *
      * Will instantiate Mage_Catalog_Model_Resource_Product
      *
@@ -1340,11 +599,10 @@ class Mage_Core_Model_Config extends Mage_Core_Model_Config_Base
      */
     public function getModelInstance($modelClass = '', $constructArguments = array())
     {
-        $className = $this->getModelClassName($modelClass);
-        if (class_exists($className)) {
-            Magento_Profiler::start('FACTORY:' . $className, array('group' => 'FACTORY', 'class_name' => $className));
-            $obj = $this->_objectManager->create($className, $constructArguments);
-            Magento_Profiler::stop('FACTORY:' . $className);
+        if (class_exists($modelClass)) {
+            Magento_Profiler::start('FACTORY:' . $modelClass);
+            $obj = $this->_objectManager->create($modelClass, $constructArguments);
+            Magento_Profiler::stop('FACTORY:' . $modelClass);
             return $obj;
         } else {
             return false;
@@ -1358,391 +616,19 @@ class Mage_Core_Model_Config extends Mage_Core_Model_Config_Base
      * @param   array $constructArguments
      * @return  object
      */
-    public function getResourceModelInstance($modelClass = '', $constructArguments = array())
+    public function getResourceModelInstance($modelClass='', $constructArguments=array())
     {
         return $this->getModelInstance($modelClass, $constructArguments);
     }
 
     /**
-     * Get resource configuration for resource name
-     *
-     * @param string $name
-     * @return Varien_Simplexml_Element
-     */
-    public function getResourceConfig($name)
-    {
-        return $this->_xml->global->resources->{$name};
-    }
-
-    /**
-     * Get connection configuration
-     *
-     * @param   string $name
-     * @return  Varien_Simplexml_Element
-     */
-    public function getResourceConnectionConfig($name)
-    {
-        $config = $this->getResourceConfig($name);
-        if ($config) {
-            $conn = $config->connection;
-            if ($conn) {
-                if (!empty($conn->use)) {
-                    return $this->getResourceConnectionConfig((string)$conn->use);
-                } else {
-                    return $conn;
-                }
-            }
-        }
-        return false;
-    }
-
-    /**
-     * Retrieve resource type configuration for resource name
-     *
-     * @param string $type
-     * @return Varien_Simplexml_Element
-     */
-    public function getResourceTypeConfig($type)
-    {
-        return $this->_xml->global->resource->connection->types->{$type};
-    }
-
-    /**
-     * Retrieve store Ids for $path with checking
-     *
-     * if empty $allowValues then retrieve all stores values
-     *
-     * return array($storeId => $pathValue)
-     *
-     * @param   string $path
-     * @param   array  $allowValues
-     * @param   string $useAsKey
-     * @return  array
-     */
-    public function getStoresConfigByPath($path, $allowValues = array(), $useAsKey = 'id')
-    {
-        $storeValues = array();
-        $stores = $this->getNode('stores');
-        foreach ($stores->children() as $code => $store) {
-            switch ($useAsKey) {
-                case 'id':
-                    $key = (int) $store->descend('system/store/id');
-                    break;
-                case 'code':
-                    $key = $code;
-                    break;
-                case 'name':
-                    $key = (string) $store->descend('system/store/name');
-                    break;
-                default:
-                    break;
-            }
-            if ($key === false) {
-                continue;
-            }
-
-            $pathValue = (string) $store->descend($path);
-
-            if (empty($allowValues)) {
-                $storeValues[$key] = $pathValue;
-            } else if (in_array($pathValue, $allowValues)) {
-                $storeValues[$key] = $pathValue;
-            }
-        }
-        return $storeValues;
-    }
-
-    /**
-     * Check whether given path should be secure according to configuration security requirements for URL
-     * "Secure" should not be confused with https protocol, it is about web/secure/*_url settings usage only
-     *
-     * @param string $url
-     * @return bool
-     */
-    public function shouldUrlBeSecure($url)
-    {
-        if (!Mage::getStoreConfigFlag(Mage_Core_Model_Store::XML_PATH_SECURE_IN_FRONTEND)) {
-            return false;
-        }
-
-        if (!isset($this->_secureUrlCache[$url])) {
-            $this->_secureUrlCache[$url] = false;
-            $secureUrls = $this->getNode('frontend/secure_url');
-            foreach ($secureUrls->children() as $match) {
-                if (strpos($url, (string)$match) === 0) {
-                    $this->_secureUrlCache[$url] = true;
-                    break;
-                }
-            }
-        }
-
-        return $this->_secureUrlCache[$url];
-    }
-
-    /**
-     * Get DB table names prefix
-     *
-     * @return string
-     */
-    public function getTablePrefix()
-    {
-        return $this->_xml->global->resources->db->table_prefix;
-    }
-
-    /**
-     * Get events configuration
-     *
-     * @param   string $area event area
-     * @param   string $eventName event name
-     * @return  Mage_Core_Model_Config_Element
-     */
-    public function getEventConfig($area, $eventName)
-    {
-        if (!isset($this->_eventAreas[$area])) {
-            $this->_eventAreas[$area] = $this->getNode($area)->events;
-        }
-        return $this->_eventAreas[$area]->{$eventName};
-    }
-
-    /**
-     * Save config value to DB
-     *
-     * @param string $path
-     * @param string $value
-     * @param string $scope
-     * @param int $scopeId
-     * @return Mage_Core_Model_Store_Config
-     */
-    public function saveConfig($path, $value, $scope = Mage_Core_Model_Store::DEFAULT_CODE, $scopeId = 0)
-    {
-        $resource = $this->getResourceModel();
-        $resource->saveConfig(rtrim($path, '/'), $value, $scope, $scopeId);
-
-        return $this;
-    }
-
-    /**
-     * Delete config value from DB
-     *
-     * @param   string $path
-     * @param   string $scope
-     * @param   int $scopeId
-     * @return  Mage_Core_Model_Config
-     */
-    public function deleteConfig($path, $scope = Mage_Core_Model_Store::DEFAULT_CODE, $scopeId = 0)
-    {
-        $resource = $this->getResourceModel();
-        $resource->deleteConfig(rtrim($path, '/'), $scope, $scopeId);
-
-        return $this;
-    }
-
-    /**
-     * Get fieldset from configuration
-     *
-     * @param string $name fieldset name
-     * @param string $root fieldset area, could be 'admin'
-     * @return null|array
-     */
-    public function getFieldset($name, $root = 'global')
-    {
-        /** @var $config Mage_Core_Model_Config_Base */
-        $config = Mage::getSingleton('Mage_Core_Model_Config_Fieldset');
-        $rootNode = $config->getNode($root . '/fieldsets');
-        if (!$rootNode) {
-            return null;
-        }
-        return $rootNode->$name ? $rootNode->$name->children() : null;
-    }
-
-    /**
-     * Retrieve resource connection model name
-     *
-     * @param string $moduleName
-     * @return string
-     */
-    public function getResourceConnectionModel($moduleName = null)
-    {
-        $config = null;
-        if (!is_null($moduleName)) {
-            $setupResource = $moduleName . '_setup';
-            $config        = $this->getResourceConnectionConfig($setupResource);
-        }
-        if (!$config) {
-            $config = $this->getResourceConnectionConfig(Mage_Core_Model_Resource::DEFAULT_SETUP_RESOURCE);
-        }
-
-        return (string)$config->model;
-    }
-
-    /**
-     * Get a resource model class name
-     *
-     * @param string $modelClass
-     * @return string|bool
-     */
-    public function getResourceModelClassName($modelClass)
-    {
-        return $this->getModelClassName($modelClass);
-    }
-
-    /**
-     *  Get allowed areas
-     *
-     * @return array
-     */
-    public function getAreas()
-    {
-        if (is_null($this->_allowedAreas) ) {
-            $this->_loadAreas();
-        }
-
-        return $this->_allowedAreas;
-    }
-
-    /**
-     * Retrieve area config by area code
-     *
-     * @param string|null $areaCode
-     * @return array
-     * @throws InvalidArgumentException
-     */
-    public function getAreaConfig($areaCode = null)
-    {
-        $areaCode = empty($areaCode) ? $this->getCurrentAreaCode() : $areaCode;
-        $areas = $this->getAreas();
-        if (!isset($areas[$areaCode])) {
-            throw new InvalidArgumentException('Requested area (' . $areaCode . ') doesn\'t exist');
-        }
-        return $areas[$areaCode];
-    }
-
-    /**
-     * Identify front name of the requested area. Return current area front name if area code is not specified.
-     *
-     * @param string|null $areaCode
-     * @return string
-     * @throws LogicException If front name is not defined.
-     */
-    public function getAreaFrontName($areaCode = null)
-    {
-        $areaCode = empty($areaCode) ? $this->getCurrentAreaCode() : $areaCode;
-        $areaConfig = $this->getAreaConfig($areaCode);
-        if (!isset($areaConfig['frontName'])) {
-            throw new LogicException(sprintf(
-                'Area "%s" must have front name defined in the application config.',
-                $areaCode
-            ));
-        }
-        return $areaConfig['frontName'];
-    }
-
-    /**
-     * Load allowed areas from config
-     *
-     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
-     * @return Mage_Core_Model_Config
-     */
-    protected function _loadAreas()
-    {
-        $this->_allowedAreas = array();
-        $nodeAreas = $this->getNode('global/areas');
-        if (is_object($nodeAreas)) {
-            foreach ($nodeAreas->asArray() as $areaCode => $areaInfo) {
-                if (empty($areaCode)
-                    || (!isset($areaInfo['base_controller']) || empty($areaInfo['base_controller']))
-                ) {
-                    continue;
-                }
-                /**
-                 * TODO: Check of 'routers' nodes existence is excessive:
-                 * TODO: 'routers' check is moved Mage_Core_Model_Config::getRouters()
-                 */
-
-                /**
-                 * TODO: Routers are not required in API.
-                 * TODO: That is why Check for empty router class moved to Mage_Core_Model_Config::getRouters()
-                 */
-                $this->_allowedAreas[$areaCode] = $areaInfo;
-            }
-        }
-
-        return $this;
-    }
-
-    /**
-     * Get routers from config
-     *
-     * @return array
-     */
-    public function getRouters()
-    {
-        $routers = array();
-        foreach ($this->getAreas() as $areaCode => $areaInfo) {
-            if (isset($areaInfo['routers']) && is_array($areaInfo['routers'])) {
-                foreach ($areaInfo['routers'] as $routerKey => $routerInfo ) {
-                    if (!isset($routerInfo['class']) || empty($routerInfo['class'])) {
-                        continue;
-                    }
-                    $routerInfo = array_merge($routerInfo, $areaInfo);
-                    unset($routerInfo['routers']);
-                    $routerInfo['area'] = $areaCode;
-                    $routers[$routerKey] = $routerInfo;
-                }
-            }
-        }
-        return $routers;
-    }
-
-    /**
-     * Is module enabled
-     *
-     * @param string $moduleName
-     * @return bool
-     */
-    public function isModuleEnabled($moduleName)
-    {
-        if (!$this->getNode('modules/' . $moduleName)) {
-            return false;
-        }
-
-        $isActive = $this->getNode('modules/' . $moduleName . '/active');
-        if (!$isActive || !in_array((string)$isActive, array('true', '1'))) {
-            return false;
-        }
-        return true;
-    }
-
-    /**
-     * Get currently used area code
-     * @return string|null
-     */
-    public function getCurrentAreaCode()
-    {
-        return $this->_currentAreaCode;
-    }
-
-    /**
-     * Set currently used area code
-     *
-     * @param $areaCode
-     * @return Mage_Core_Model_Config
-     */
-    public function setCurrentAreaCode($areaCode)
-    {
-        $this->_currentAreaCode = $areaCode;
-        return $this;
-    }
-
-    /**
-     * Cleanup circular references
-     *
-     * Destructor should be called explicitly in order to work around the PHP bug
-     * https://bugs.php.net/bug.php?id=62468
+     * Remove configuration cache
      */
-    public function __destruct()
+    public function removeCache()
     {
-        $this->_prototype = null;
-        parent::__destruct();
+        /** @var $eventManager Mage_Core_Model_Event_Manager */
+        $eventManager = $this->_objectManager->get('Mage_Core_Model_Event_Manager');
+        $eventManager->dispatch('application_clean_cache', array('tags' => array(self::CACHE_TAG)));
+        $this->_storage->removeCache();
     }
 }
diff --git a/app/code/core/Mage/Core/Model/Config/Base.php b/app/code/core/Mage/Core/Model/Config/Base.php
index 66b9565a1d41cdbf0746c7787dd88a9bc112edb3..bb69a3a1abb76899ab4353b3c7b1f64a7a67eb32 100644
--- a/app/code/core/Mage/Core/Model/Config/Base.php
+++ b/app/code/core/Mage/Core/Model/Config/Base.php
@@ -35,15 +35,41 @@
  * @author      Magento Core Team <core@magentocommerce.com>
  */
 
-class Mage_Core_Model_Config_Base extends Varien_Simplexml_Config
+class Mage_Core_Model_Config_Base extends Varien_Simplexml_Config implements Mage_Core_Model_ConfigInterface
 {
     /**
-     * Constructor
+     * List of instances
      *
+     * @var array
      */
-    public function __construct($sourceData=null)
+    public static $instances = array();
+
+    /**
+     * @param string|Varien_Simplexml_Element $sourceData $sourceData
+     */
+    public function __construct($sourceData = null)
     {
         $this->_elementClass = 'Mage_Core_Model_Config_Element';
         parent::__construct($sourceData);
+        self::$instances[] = $this;
+    }
+
+    /**
+     * Reinitialize config object
+     */
+    public function reinit()
+    {
+
+    }
+
+    /**
+     * Cleanup objects because of simplexml memory leak
+     */
+    public static function destroy()
+    {
+        foreach (self::$instances  as $instance) {
+            $instance->_xml = null;
+        }
+        self::$instances = array();
     }
 }
diff --git a/app/code/core/Mage/Core/Model/Config/BaseFactory.php b/app/code/core/Mage/Core/Model/Config/BaseFactory.php
new file mode 100644
index 0000000000000000000000000000000000000000..5eedcdb3bfda1e1bd3dfd7d13209f2e5c15bf4fb
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/BaseFactory.php
@@ -0,0 +1,51 @@
+<?php
+/**
+ * Base config model factory
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_BaseFactory
+{
+    /**
+     * @var Magento_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * @param Magento_ObjectManager $objectManager
+     */
+    public function __construct(Magento_ObjectManager $objectManager)
+    {
+        $this->_objectManager = $objectManager;
+    }
+
+    /**
+     * Create config model
+     *
+     * @param string|Varien_Simplexml_Element $sourceData
+     * @return Mage_Core_Model_Config_Base
+     */
+    public function create($sourceData = null)
+    {
+        return $this->_objectManager->create('Mage_Core_Model_Config_Base', array('sourceData' => $sourceData));
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Cache.php b/app/code/core/Mage/Core/Model/Config/Cache.php
new file mode 100644
index 0000000000000000000000000000000000000000..6bea9b871720062a2777370a3baa4df9f04beb33
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Cache.php
@@ -0,0 +1,261 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_Config_Cache
+{
+    /**
+     * Config cache id
+     *
+     * @var string
+     */
+    protected $_cacheId = 'config_global';
+
+    /**
+     * Cache lock id
+     *
+     * @var string
+     */
+    protected $_cacheLockId;
+
+    /**
+     * Container factory model
+     *
+     * @var Mage_Core_Model_Config_ContainerFactory
+     */
+    protected $_containerFactory;
+
+    /**
+     * Base config factory model
+     *
+     * @var Mage_Core_Model_Config_BaseFactory
+     */
+    protected $_baseFactory;
+
+    /**
+     * Cache object
+     *
+     * @var Mage_Core_Model_CacheInterface
+     */
+    protected $_cache;
+
+    /**
+     * Configuration sections
+     *
+     * @var Mage_Core_Model_Config_Sections
+     */
+    protected $_configSections;
+
+    /**
+     * List of configuration parts for save in cache
+     *
+     * @var array
+     */
+    protected $_cachePartsForSave;
+
+    /**
+     * Cache lifetime in seconds
+     *
+     * @var int
+     */
+    protected $_cacheLifetime;
+
+    /**
+     * Config container
+     *
+     * @var Mage_Core_Model_Config_Container
+     */
+    protected $_loadedConfig = null;
+
+    /**
+     * @param Mage_Core_Model_Cache $cache
+     * @param Mage_Core_Model_Config_Sections $configSections
+     * @param Mage_Core_Model_Config_ContainerFactory $containerFactory
+     * @param Mage_Core_Model_Config_BaseFactory $baseFactory
+     */
+    public function __construct(
+        Mage_Core_Model_Cache $cache,
+        Mage_Core_Model_Config_Sections $configSections,
+        Mage_Core_Model_Config_ContainerFactory $containerFactory,
+        Mage_Core_Model_Config_BaseFactory $baseFactory
+    ) {
+        $this->_containerFactory = $containerFactory;
+        $this->_cache = $cache;
+        $this->_configSections = $configSections;
+        $this->_cacheLockId = $this->_cacheId . '.lock';
+        $this->_baseFactory = $baseFactory;
+    }
+
+    /**
+     * Save cache of specified
+     *
+     * @param   string $idPrefix cache id prefix
+     * @param   string $sectionName
+     * @param   Varien_Simplexml_Element $source
+     * @param   int $recursionLevel
+     * @param   array $tags
+     * @SuppressWarnings(PHPMD.UnusedLocalVariable)
+     */
+    protected function _saveSectionCache($idPrefix, $sectionName, $source, $recursionLevel = 0, $tags = array())
+    {
+        if ($source && $source->$sectionName) {
+            $cacheId = $idPrefix . '_' . $sectionName;
+            if ($recursionLevel > 0) {
+                foreach ($source->$sectionName->children() as $subSectionName => $node) {
+                    $this->_saveSectionCache(
+                        $cacheId, $subSectionName, $source->$sectionName, $recursionLevel-1, $tags
+                    );
+                }
+            }
+            $this->_cachePartsForSave[$cacheId] = $source->$sectionName->asNiceXml('', false);
+        }
+    }
+
+    /**
+     * Lock caching to prevent concurrent cache writes
+     */
+    protected function _lock()
+    {
+        $this->_cache->save(time(), $this->_cacheLockId, array(), 60);
+    }
+
+    /**
+     * Unlock caching
+     */
+    protected function _unlock()
+    {
+        $this->_cache->remove($this->_cacheLockId);
+    }
+
+    /**
+     * Check whether caching is locked
+     *
+     * @return bool
+     */
+    protected function _isLocked()
+    {
+        return !!$this->_cache->load($this->_cacheLockId);
+    }
+
+    /**
+     * Set cache lifetime
+     *
+     * @param int $lifetime
+     */
+    public function setCacheLifetime($lifetime)
+    {
+        $this->_cacheLifetime = $lifetime;
+    }
+
+    /**
+     * Retrieve cache lifetime
+     *
+     * @return int
+     */
+    public function getCacheLifeTime()
+    {
+        return $this->_cacheLifetime;
+    }
+
+    /**
+     * @return Mage_Core_Model_ConfigInterface|bool
+     */
+    public function load()
+    {
+        $canUse = $this->_cache->canUse('config');
+        if (!$this->_loadedConfig) {
+            $config = ($canUse && false == $this->_isLocked())
+                ? $this->_cache->load($this->_cacheId)
+                : false;
+
+            if ($config) {
+                $this->_loadedConfig = $this->_containerFactory->create(array('sourceData' => $config));
+            }
+        }
+        return $canUse && $this->_loadedConfig ? $this->_loadedConfig: false;
+    }
+
+    /**
+     * Save config cache
+     *
+     * @param Mage_Core_Model_Config_Base $config
+     */
+    public function save(Mage_Core_Model_Config_Base $config)
+    {
+        if ($this->_cache->canUse('config') && false == $this->_isLocked()) {
+            $cacheSections = $this->_configSections->getSections();
+            $xml = clone $config->getNode();
+            if (!empty($cacheSections)) {
+                foreach ($cacheSections as $sectionName => $level) {
+                    $this->_saveSectionCache(
+                        $this->_cacheId, $sectionName, $xml, $level, array(Mage_Core_Model_Config::CACHE_TAG)
+                    );
+                    unset($xml->$sectionName);
+                }
+            }
+            $this->_cachePartsForSave[$this->_cacheId] = $xml->asNiceXml('', false);
+            $this->_lock();
+            $this->clean();
+            foreach ($this->_cachePartsForSave as $cacheId => $cacheData) {
+                $this->_cache->save(
+                    $cacheData, $cacheId, array(Mage_Core_Model_Config::CACHE_TAG), $this->_cacheLifetime
+                );
+            }
+            unset($this->_cachePartsForSave);
+            $this->_unlock();
+        }
+    }
+
+    /**
+     * Clean cached data
+     *
+     * @return bool
+     */
+    public function clean()
+    {
+        $this->_loadedConfig = null;
+        return $this->_cache->clean(array(Mage_Core_Model_Config::CACHE_TAG));
+    }
+
+    /**
+     * Load config section cached data
+     *
+     * @param   string $sectionKey
+     * @return  Mage_Core_Model_Config_Base|bool
+     * @throws  Mage_Core_Model_Config_Cache_Exception
+     */
+    public function getSection($sectionKey)
+    {
+        $cacheId = $this->_cacheId . '_' . $sectionKey;
+        $result = false;
+        if ($this->_cache->canUse('config')) {
+            $xmlString = $this->_cache->load($cacheId);
+            if ($xmlString) {
+                $result = $this->_baseFactory->create($xmlString);
+            } else {
+                throw new Mage_Core_Model_Config_Cache_Exception();
+            }
+        }
+        return $result;
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Cache/Exception.php b/app/code/core/Mage/Core/Model/Config/Cache/Exception.php
new file mode 100644
index 0000000000000000000000000000000000000000..5726245c7c1a58e86c4e924d263f11f11dedd6a0
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Cache/Exception.php
@@ -0,0 +1,29 @@
+<?php
+/**
+ * Exception that should be thrown when config cache cannot be loaded
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_Cache_Exception extends LogicException
+{
+
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Container.php b/app/code/core/Mage/Core/Model/Config/Container.php
new file mode 100644
index 0000000000000000000000000000000000000000..d40f36c9a4413b04fe6f30bfd523aae87d227715
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Container.php
@@ -0,0 +1,166 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_Config_Container implements Mage_Core_Model_ConfigInterface
+{
+    /**
+     * Configuration data
+     *
+     * @var Mage_Core_Model_Config_Base
+     */
+    protected $_data;
+
+    /**
+     * Configuration cache model
+     *
+     * @var Mage_Core_Model_Config_Cache
+     */
+    protected $_configCache;
+
+    /**
+     * Configuration sections
+     *
+     * @var Mage_Core_Model_Config_Sections
+     */
+    protected $_sections;
+
+    /**
+     * Loaded configuration sections
+     *
+     * @var Mage_Core_Model_Config_Base[]
+     */
+    protected $_loadedSections = array();
+
+    /**
+     * @param Mage_Core_Model_Config_Cache $configCache
+     * @param Mage_Core_Model_Config_Sections $sections
+     * @param Mage_Core_Model_Config_BaseFactory $factory
+     * @param string $sourceData
+     */
+    public function __construct(
+        Mage_Core_Model_Config_Cache $configCache,
+        Mage_Core_Model_Config_Sections $sections,
+        Mage_Core_Model_Config_BaseFactory $factory,
+        $sourceData = ''
+    ) {
+        $this->_data = $factory->create($sourceData);
+        $this->_sections = $sections;
+        $this->_configCache = $configCache;
+    }
+
+    /**
+     * Get section path
+     *
+     * @param string $path
+     * @param string $sectionKey
+     * @return string|null
+     */
+    protected function _getSectionPath($path, $sectionKey)
+    {
+        $sectionPath = substr($path, strlen($sectionKey) + 1);
+        return $sectionPath ?: null;
+    }
+
+    /**
+     * Get config section
+     *
+     * @param string $sectionKey
+     * @return Mage_Core_Model_Config_Base|null
+     */
+    protected function _getSection($sectionKey)
+    {
+        if (false === $sectionKey) {
+            return null;
+        }
+
+        if (false == array_key_exists($sectionKey, $this->_loadedSections)) {
+            Magento_Profiler::start('init_config_section:' . $sectionKey);
+            $this->_loadedSections[$sectionKey] = $this->_configCache->getSection($sectionKey);
+            Magento_Profiler::stop('init_config_section:' . $sectionKey);
+        }
+
+        return $this->_loadedSections[$sectionKey] ?: null;
+    }
+
+    /**
+     * Get configuration node
+     *
+     * @param string $path
+     * @return Varien_Simplexml_Element
+     * @throws Mage_Core_Model_Config_Cache_Exception
+     */
+    public function getNode($path = null)
+    {
+        if ($path !== null) {
+            $sectionKey = $this->_sections->getKey($path);
+            $section = $this->_getSection($sectionKey);
+            if ($section) {
+                $res = $section->getNode($this->_getSectionPath($path, $sectionKey));
+                if ($res !== false) {
+                    return $res;
+                }
+            }
+        }
+        return $this->_data->getNode($path);
+    }
+
+    /**
+     * Create node by $path and set its value
+     *
+     * @param string $path separated by slashes
+     * @param string $value
+     * @param boolean $overwrite
+     * @throws Mage_Core_Model_Config_Cache_Exception
+     */
+    public function setNode($path, $value, $overwrite = true)
+    {
+        if ($path !== null) {
+            $sectionKey = $this->_sections->getKey($path);
+            $section = $this->_getSection($sectionKey);
+            if ($section) {
+                $section->setNode($this->_getSectionPath($path, $sectionKey), $value, $overwrite);
+            }
+        }
+        $this->_data->setNode($path, $value, $overwrite);
+    }
+
+    /**
+     * Returns nodes found by xpath expression
+     *
+     * @param string $xpath
+     * @return array
+     */
+    public function getXpath($xpath)
+    {
+        return $this->_data->getXpath($xpath);
+    }
+
+    /**
+     * Reinitialize config object
+     */
+    public function reinit()
+    {
+
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/ContainerFactory.php b/app/code/core/Mage/Core/Model/Config/ContainerFactory.php
new file mode 100644
index 0000000000000000000000000000000000000000..4ba5ef77f368a1caf68937bca9b3d16609dc700e
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/ContainerFactory.php
@@ -0,0 +1,50 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_Config_ContainerFactory
+{
+    /**
+     * @var Magento_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * @param Magento_ObjectManager $objectManager
+     */
+    public function __construct(Magento_ObjectManager $objectManager)
+    {
+        $this->_objectManager = $objectManager;
+    }
+
+    /**
+     * Get config data container instance
+     *
+     * @param array $arguments
+     * @return Mage_Core_Model_ConfigInterface
+     */
+    public function create(array $arguments = array())
+    {
+        return $this->_objectManager->create('Mage_Core_Model_Config_Container', $arguments);
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Data.php b/app/code/core/Mage/Core/Model/Config/Data.php
index e7ec068f81511eb0847dc1abe2573dbd678177a9..5b11ec3f0a73d307cbe6a4b7cd0d42422c7e99cb 100644
--- a/app/code/core/Mage/Core/Model/Config/Data.php
+++ b/app/code/core/Mage/Core/Model/Config/Data.php
@@ -109,7 +109,7 @@ class Mage_Core_Model_Config_Data extends Mage_Core_Model_Abstract
     }
     
 
-     /**
+    /**
      * Get value by key for new user data from <section>/groups/<group>/fields/<field>
      * 
      * @return string
diff --git a/app/code/core/Mage/Core/Model/Config/Element.php b/app/code/core/Mage/Core/Model/Config/Element.php
index 60e029a8d9d29b7edfd952ccbc6d3ee75beaaedb..b2705b9584d354a57aa75437266859559e9e5023 100644
--- a/app/code/core/Mage/Core/Model/Config/Element.php
+++ b/app/code/core/Mage/Core/Model/Config/Element.php
@@ -71,7 +71,7 @@ class Mage_Core_Model_Config_Element extends Varien_Simplexml_Element
         } else {
             return false;
         }
-        return Mage::getConfig()->getModelClassName($model);
+        return $model;
     }
 
 }
diff --git a/app/code/core/Mage/Core/Model/Config/Fieldset.php b/app/code/core/Mage/Core/Model/Config/Fieldset.php
index c1f609a3da34ddb91a550cb64c5e3b8e0d09bc2e..6361a1efbc86c2df0ce746dbc290040af062620f 100644
--- a/app/code/core/Mage/Core/Model/Config/Fieldset.php
+++ b/app/code/core/Mage/Core/Model/Config/Fieldset.php
@@ -30,9 +30,10 @@ class Mage_Core_Model_Config_Fieldset extends Mage_Core_Model_Config_Base
      * Constructor.
      * Load configuration from enabled modules with appropriate caching.
      *
+     * @param Mage_Core_Model_Config_Modules_Reader $configReader
      * @param Varien_Simplexml_Element|string|null $data
      */
-    public function __construct($data = null)
+    public function __construct(Mage_Core_Model_Config_Modules_Reader $configReader, $data = null)
     {
         parent::__construct($data);
 
@@ -48,7 +49,7 @@ class Mage_Core_Model_Config_Fieldset extends Mage_Core_Model_Config_Base
             }
         }
 
-        $config = Mage::getConfig()->loadModulesConfiguration('fieldset.xml');
+        $config = $configReader->loadModulesConfiguration('fieldset.xml');
         $this->setXml($config->getNode());
 
         if ($canUseCache) {
diff --git a/app/code/core/Mage/Core/Model/Config/Invalidator.php b/app/code/core/Mage/Core/Model/Config/Invalidator.php
new file mode 100644
index 0000000000000000000000000000000000000000..727b4177bb70c690670447b69c0cf4b3df49506c
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Invalidator.php
@@ -0,0 +1,74 @@
+<?php
+/**
+ * Configuration objects invalidator. Invalidates all required configuration objects for total config reinitialisation
+ *
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_Invalidator implements Mage_Core_Model_Config_InvalidatorInterface
+{
+    /**
+     * Primary configuration
+     *
+     * @var Mage_Core_Model_ConfigInterface
+     */
+    protected $_primaryConfig;
+
+    /**
+     * Modules configuration
+     *
+     * @var Mage_Core_Model_ConfigInterface
+     */
+    protected $_modulesConfig;
+
+    /**
+     * Locales configuration
+     *
+     * @var Mage_Core_Model_ConfigInterface
+     */
+    protected $_localesConfig;
+
+    /**
+     * @param Mage_Core_Model_ConfigInterface $primaryConfig
+     * @param Mage_Core_Model_ConfigInterface $modulesConfig
+     * @param Mage_Core_Model_ConfigInterface $localesConfig
+     */
+    public function __construct(
+        Mage_Core_Model_ConfigInterface $primaryConfig,
+        Mage_Core_Model_ConfigInterface $modulesConfig,
+        Mage_Core_Model_ConfigInterface $localesConfig
+    ) {
+        $this->_primaryConfig = $primaryConfig;
+        $this->_modulesConfig = $modulesConfig;
+        $this->_localesConfig = $localesConfig;
+    }
+
+    /**
+     * Invalidate config objects
+     */
+    public function invalidate()
+    {
+        $this->_primaryConfig->reinit();
+        $this->_modulesConfig->reinit();
+        $this->_localesConfig->reinit();
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Invalidator/Proxy.php b/app/code/core/Mage/Core/Model/Config/Invalidator/Proxy.php
new file mode 100644
index 0000000000000000000000000000000000000000..5571abf1099e50ed9421ff18ed746522657fb92b
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Invalidator/Proxy.php
@@ -0,0 +1,46 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_Invalidator_Proxy implements Mage_Core_Model_Config_InvalidatorInterface
+{
+    /**
+     * @var Magento_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * @param Magento_ObjectManager $objectManager
+     */
+    public function __construct(Magento_ObjectManager $objectManager)
+    {
+        $this->_objectManager = $objectManager;
+    }
+
+    /**
+     * Invalidate config objects
+     */
+    public function invalidate()
+    {
+        $this->_objectManager->get('Mage_Core_Model_Config_Invalidator')->invalidate();
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/InvalidatorInterface.php b/app/code/core/Mage/Core/Model/Config/InvalidatorInterface.php
new file mode 100644
index 0000000000000000000000000000000000000000..f9997d03bf135208b9e6625d4db81c2229f8027d
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/InvalidatorInterface.php
@@ -0,0 +1,30 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+interface Mage_Core_Model_Config_InvalidatorInterface
+{
+    /**
+     * Invalidate config objects
+     */
+    public function invalidate();
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Loader.php b/app/code/core/Mage/Core/Model/Config/Loader.php
new file mode 100644
index 0000000000000000000000000000000000000000..5c7e834430028975d414f728592cbd48c72694f9
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Loader.php
@@ -0,0 +1,83 @@
+<?php
+/**
+ * Application config loader
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_Loader implements Mage_Core_Model_Config_LoaderInterface
+{
+    /**
+     * Modules configuration object
+     *
+     * @var Mage_Core_Model_Config_Modules
+     */
+    protected $_modulesConfig;
+
+    /**
+     * Modules configuration object
+     *
+     * @var Mage_Core_Model_Config_Locales
+     */
+    protected $_localesConfig;
+
+    /**
+     * Database configuration loader
+     *
+     * @var Mage_Core_Model_Config_Loader_Db
+     */
+    protected $_dbLoader;
+
+    /**
+     * @var Mage_Core_Model_Config_BaseFactory
+     */
+    protected $_configFactory;
+
+    /**
+     * @param Mage_Core_Model_Config_Modules $config
+     * @param Mage_Core_Model_Config_Locales $localesConfig
+     * @param Mage_Core_Model_Config_Loader_Db $dbLoader
+     * @param Mage_Core_Model_Config_BaseFactory $factory
+     */
+    public function __construct(
+        Mage_Core_Model_Config_Modules $config,
+        Mage_Core_Model_Config_Locales $localesConfig,
+        Mage_Core_Model_Config_Loader_Db $dbLoader,
+        Mage_Core_Model_Config_BaseFactory $factory
+    ) {
+        $this->_modulesConfig = $config;
+        $this->_localesConfig = $localesConfig;
+        $this->_dbLoader = $dbLoader;
+        $this->_configFactory = $factory;
+    }
+
+    /**
+     * Populate configuration object
+     *
+     * @param Mage_Core_Model_Config_Base $config
+     */
+    public function load(Mage_Core_Model_Config_Base $config)
+    {
+        $config->extend($this->_configFactory->create($this->_modulesConfig->getNode()));
+        $this->_dbLoader->load($config);
+        $config->extend($this->_configFactory->create($this->_localesConfig->getNode()));
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Loader/Db.php b/app/code/core/Mage/Core/Model/Config/Loader/Db.php
new file mode 100644
index 0000000000000000000000000000000000000000..d964d204f6998d797ca7e3f43501f8619478d476
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Loader/Db.php
@@ -0,0 +1,94 @@
+<?php
+/**
+ * DB-stored application configuration loader
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_Loader_Db implements Mage_Core_Model_Config_LoaderInterface
+{
+    /**
+     * Modules configuration
+     *
+     * @var Mage_Core_Model_Config_Modules
+     */
+    protected $_config;
+
+    /**
+     * DB scheme model
+     *
+     * @var Mage_Core_Model_Db_UpdaterInterface
+     */
+    protected $_dbUpdater;
+
+    /**
+     * Resource model of config data
+     *
+     * @var Mage_Core_Model_Resource_Config
+     */
+    protected $_resource;
+
+    /**
+     * @var Mage_Core_Model_Config_BaseFactory
+     */
+    protected $_configFactory;
+
+    /**
+     * @param Mage_Core_Model_Config_Modules $modulesConfig
+     * @param Mage_Core_Model_Resource_Config $resource
+     * @param Mage_Core_Model_Db_UpdaterInterface $schemeUpdater
+     * @param Mage_Core_Model_Config_BaseFactory $factory
+     */
+    public function __construct(
+        Mage_Core_Model_Config_Modules $modulesConfig,
+        Mage_Core_Model_Resource_Config $resource,
+        Mage_Core_Model_Db_UpdaterInterface $schemeUpdater,
+        Mage_Core_Model_Config_BaseFactory $factory
+    ) {
+        $this->_config = $modulesConfig;
+        $this->_resource = $resource;
+        $this->_dbUpdater = $schemeUpdater;
+        $this->_configFactory = $factory;
+    }
+
+    /**
+     * Populate configuration object
+     *
+     * @param Mage_Core_Model_Config_Base $config
+     */
+    public function load(Mage_Core_Model_Config_Base $config)
+    {
+        if (false == $this->_resource->getReadConnection()) {
+            return;
+        }
+
+        //update database scheme
+         $this->_dbUpdater->updateScheme();
+
+        //apply modules configuration
+        $config->extend($this->_configFactory->create($this->_config->getNode()));
+
+        //load db configuration
+        Magento_Profiler::start('load_db');
+        $this->_resource->loadToXml($config);
+        Magento_Profiler::stop('load_db');
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Loader/Local.php b/app/code/core/Mage/Core/Model/Config/Loader/Local.php
new file mode 100644
index 0000000000000000000000000000000000000000..69e64149ba24b8f29b6ad440a1b4abaffe0ef2cf
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Loader/Local.php
@@ -0,0 +1,118 @@
+<?php
+/**
+ * Local Application configuration loader (app/etc/local.xml)
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_Loader_Local implements Mage_Core_Model_Config_LoaderInterface
+{
+    /**
+     * Local configuration file
+     */
+    const LOCAL_CONFIG_FILE = 'local.xml';
+
+    /**
+     * Directory registry
+     *
+     * @var Mage_Core_Model_Dir
+     */
+    protected $_dirs;
+
+    /**
+     * Configuration prototype Factory
+     *
+     * @var Mage_Core_Model_Config_BaseFactory
+     */
+    protected $_prototypeFactory;
+
+    /**
+     * Custom config file
+     *
+     * @var string
+     */
+    protected $_customFile;
+
+    /**
+     * Custom configuration string
+     *
+     * @var string
+     */
+    protected $_customConfig;
+
+    /**
+     * @param Mage_Core_Model_Config_BaseFactory $prototypeFactory
+     * @param Mage_Core_Model_Dir $dirs
+     * @param string $customConfig
+     * @param string $customFile
+     */
+    public function __construct(
+        Mage_Core_Model_Config_BaseFactory $prototypeFactory,
+        Mage_Core_Model_Dir $dirs,
+        $customConfig = null,
+        $customFile = null
+    ) {
+        $this->_dirs = $dirs;
+        $this->_customFile = $customFile;
+        $this->_customConfig = $customConfig;
+        $this->_prototypeFactory = $prototypeFactory;
+    }
+
+    /**
+     * Populate configuration object
+     *
+     * @param Mage_Core_Model_Config_Base $config
+     */
+    public function load(Mage_Core_Model_Config_Base $config)
+    {
+        $etcDir = $this->_dirs->getDir(Mage_Core_Model_Dir::CONFIG);
+        $localConfigParts = array();
+
+        $localConfigFile = $etcDir . DIRECTORY_SEPARATOR . self::LOCAL_CONFIG_FILE;
+        if (file_exists($localConfigFile)) {
+            // 1. app/etc/local.xml
+            $localConfig = $this->_prototypeFactory->create('<config/>');
+            $localConfig->loadFile($localConfigFile);
+            $localConfigParts[] = $localConfig;
+
+            // 2. app/etc/<dir>/<file>.xml
+            if (preg_match('/^[a-z\d_-]+(\/|\\\)+[a-z\d_-]+\.xml$/', $this->_customFile)) {
+                $localConfigExtraFile = $etcDir . DIRECTORY_SEPARATOR . $this->_customFile;
+                $localConfig = $this->_prototypeFactory->create('<config/>');
+                $localConfig->loadFile($localConfigExtraFile);
+                $localConfigParts[] = $localConfig;
+            }
+        }
+
+        // 3. extra local configuration string
+        if ($this->_customConfig) {
+            $localConfig = $this->_prototypeFactory->create('<config/>');
+            $localConfig->loadString($this->_customConfig);
+            $localConfigParts[] = $localConfig;
+        }
+
+        if ($localConfigParts) {
+            foreach ($localConfigParts as $oneConfigPart) {
+                $config->extend($oneConfigPart);
+            }
+        }
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Loader/Locales.php b/app/code/core/Mage/Core/Model/Config/Loader/Locales.php
new file mode 100644
index 0000000000000000000000000000000000000000..40cdc30327f6e483e33b89c9ae305f74faa07d55
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Loader/Locales.php
@@ -0,0 +1,71 @@
+<?php
+/**
+ * Locale configuration loader
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_Loader_Locales implements Mage_Core_Model_Config_LoaderInterface
+{
+    /**
+     * Base dirs model
+     *
+     * @var Mage_Core_Model_Dir
+     */
+    protected $_dirs;
+
+    /**
+     * Element prototype factory
+     *
+     * @var Mage_Core_Model_Config_BaseFactory
+     */
+    protected $_factory;
+
+    /**
+     * @param Mage_Core_Model_Dir $dirs
+     * @param Mage_Core_Model_Config_BaseFactory $factory
+     */
+    public function __construct(Mage_Core_Model_Dir $dirs, Mage_Core_Model_Config_BaseFactory $factory)
+    {
+        $this->_dirs = $dirs;
+        $this->_factory = $factory;
+    }
+
+    /**
+     * Populate configuration object
+     * Load locale configuration from locale configuration files
+     *
+     * @param Mage_Core_Model_Config_Base $config
+     */
+    public function load(Mage_Core_Model_Config_Base $config)
+    {
+        $localeDir = $this->_dirs->getDir(Mage_Core_Model_Dir::LOCALE);
+        $files = glob($localeDir . DIRECTORY_SEPARATOR . '*' . DIRECTORY_SEPARATOR . 'config.xml');
+
+        if (is_array($files) && !empty($files)) {
+            foreach ($files as $file) {
+                $merge = $this->_factory->create();
+                $merge->loadFile($file);
+                $config->extend($merge);
+            }
+        }
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Loader/Locales/Proxy.php b/app/code/core/Mage/Core/Model/Config/Loader/Locales/Proxy.php
new file mode 100644
index 0000000000000000000000000000000000000000..4d321e9af720785dbbd09f67e3e433e2d4506cdb
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Loader/Locales/Proxy.php
@@ -0,0 +1,69 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_Config_Loader_Locales_Proxy implements Mage_Core_Model_Config_LoaderInterface
+{
+    /**
+     * @var Mage_Core_Model_Config_Loader_Locales
+     */
+    protected $_loader;
+
+    /**
+     * @var Magento_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * @param Magento_ObjectManager $objectManager
+     */
+    public function __construct(Magento_ObjectManager $objectManager)
+    {
+        $this->_objectManager = $objectManager;
+    }
+
+    /**
+     * Get loader instance
+     *
+     * @return Mage_Core_Model_Config_Loader_Locales
+     */
+    protected function _getLoader()
+    {
+        if (null === $this->_loader) {
+            $this->_loader = $this->_objectManager->get('Mage_Core_Model_Config_Loader_Locales');
+        }
+        return $this->_loader;
+    }
+
+    /**
+     * Populate configuration object
+     *
+     * @param Mage_Core_Model_Config_Base $config
+     * @param bool $useCache
+     * @return void
+     */
+    public function load(Mage_Core_Model_Config_Base $config, $useCache = true)
+    {
+        $this->_getLoader()->load($config, $useCache);
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Loader/Modules.php b/app/code/core/Mage/Core/Model/Config/Loader/Modules.php
new file mode 100644
index 0000000000000000000000000000000000000000..0e0b93b91d35a1ba92af8a2bcf1a776629cb1371
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Loader/Modules.php
@@ -0,0 +1,245 @@
+<?php
+/**
+ * Module configuration loader
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_Loader_Modules implements Mage_Core_Model_Config_LoaderInterface
+{
+    /**
+     * Primary application configuration
+     *
+     * @var Mage_Core_Model_Config_Primary
+     */
+    protected $_primaryConfig;
+
+    /**
+     * Load modules configuration
+     *
+     * @var Mage_Core_Model_Dir
+     */
+    protected $_dirs;
+
+    /**
+     * Prototype config factory
+     *
+     * @var Mage_Core_Model_Config_BaseFactory
+     */
+    protected $_prototypeFactory;
+
+    /**
+     * Loaded modules
+     *
+     * @var array
+     */
+    protected $_modulesCache = array();
+
+    /**
+     * List of modules that should be loaded
+     *
+     * @var array
+     */
+    protected $_allowedModules = array();
+
+    /**
+     * @var Mage_Core_Model_Config_Resource
+     */
+    protected $_resourceConfig;
+
+    /**
+     * @var Mage_Core_Model_Config_Loader_Modules_File
+     */
+    protected $_fileReader;
+
+    /**
+     * Application object manager
+     *
+     * @var Magento_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * @param Mage_Core_Model_Config_Primary $primaryConfig
+     * @param Mage_Core_Model_Dir $dirs
+     * @param Mage_Core_Model_Config_BaseFactory $prototypeFactory
+     * @param Mage_Core_Model_Config_Resource $resourceConfig
+     * @param Mage_Core_Model_Config_Loader_Modules_File $fileReader
+     * @param Magento_ObjectManager
+     * @param array $allowedModules
+     */
+    public function __construct(
+        Mage_Core_Model_Config_Primary $primaryConfig,
+        Mage_Core_Model_Dir $dirs,
+        Mage_Core_Model_Config_BaseFactory $prototypeFactory,
+        Mage_Core_Model_Config_Resource $resourceConfig,
+        Mage_Core_Model_Config_Loader_Modules_File $fileReader,
+        Magento_ObjectManager $objectManager,
+        array $allowedModules = array()
+    ) {
+        $this->_dirs = $dirs;
+        $this->_primaryConfig = $primaryConfig;
+        $this->_allowedModules = $allowedModules;
+        $this->_prototypeFactory = $prototypeFactory;
+        $this->_resourceConfig = $resourceConfig;
+        $this->_fileReader = $fileReader;
+        $this->_objectManager = $objectManager;
+    }
+
+    /**
+     * Populate configuration object
+     *
+     * @param Mage_Core_Model_Config_Base $config
+     */
+    public function load(Mage_Core_Model_Config_Base $config)
+    {
+        if (!$config->getNode()) {
+            $config->loadString('<config><modules></modules></config>');
+        }
+
+        Magento_Profiler::start('config');
+        Magento_Profiler::start('load_modules');
+
+        $config->extend($this->_primaryConfig);
+
+        $this->_loadDeclaredModules($config);
+
+        Magento_Profiler::start('load_modules_configuration');
+        $resourceConfig = sprintf('config.%s.xml', $this->_resourceConfig->getResourceConnectionModel('core'));
+        $this->_fileReader->loadConfigurationFromFile(
+            $config, array('config.xml', $resourceConfig), $config, null, $this->_modulesCache
+        );
+        Magento_Profiler::stop('load_modules_configuration');
+
+        // Prevent local configuration overriding
+        $config->extend($this->_primaryConfig);
+
+        $config->applyExtends();
+
+        Magento_Profiler::stop('load_modules');
+        Magento_Profiler::stop('config');
+        $this->_resourceConfig->setConfig($config);
+        $this->_objectManager->setConfiguration($config->getNode('global/di')->asArray());
+        $this->_modulesCache = array();
+    }
+
+    /**
+     * Load declared modules configuration
+     *
+     * @param Mage_Core_Model_Config_Base $mergeToConfig
+     */
+    protected function _loadDeclaredModules(Mage_Core_Model_Config_Base $mergeToConfig)
+    {
+        Magento_Profiler::start('load_modules_files');
+        $moduleFiles = $this->_getDeclaredModuleFiles();
+        if (!$moduleFiles) {
+            return;
+        }
+        Magento_Profiler::stop('load_modules_files');
+
+        Magento_Profiler::start('load_modules_declaration');
+        $unsortedConfig = new Mage_Core_Model_Config_Base('<config/>');
+        $emptyConfig = new Mage_Core_Model_Config_Element('<config><modules/></config>');
+        $declaredModules = array();
+        foreach ($moduleFiles as $oneConfigFile) {
+            $path = explode(DIRECTORY_SEPARATOR, $oneConfigFile);
+            $moduleConfig = new Mage_Core_Model_Config_Base($oneConfigFile);
+            $modules = $moduleConfig->getXpath('modules/*');
+            if (!$modules) {
+                continue;
+            }
+            $cPath = count($path);
+            if ($cPath > 4) {
+                $moduleName = $path[$cPath - 4] . '_' . $path[$cPath - 3];
+                $this->_modulesCache[$moduleName] = $moduleConfig;
+            }
+            foreach ($modules as $module) {
+                $moduleName = $module->getName();
+                $isActive = (string)$module->active;
+                if (isset($declaredModules[$moduleName])) {
+                    $declaredModules[$moduleName]['active'] = $isActive;
+                    continue;
+                }
+                $newModule = clone $emptyConfig;
+                $newModule->modules->appendChild($module);
+                $declaredModules[$moduleName] = array(
+                    'active' => $isActive,
+                    'module' => $newModule,
+                );
+            }
+        }
+        foreach ($declaredModules as $moduleName => $module) {
+            if ($module['active'] == 'true') {
+                $module['module']->modules->{$moduleName}->active = 'true';
+                $unsortedConfig->extend(new Mage_Core_Model_Config_Base($module['module']));
+            }
+        }
+        $sortedConfig = new Mage_Core_Model_Config_Modules_Sorted($unsortedConfig, $this->_allowedModules);
+
+        $mergeToConfig->extend($sortedConfig);
+        Magento_Profiler::stop('load_modules_declaration');
+    }
+
+    /**
+     * Retrieve Declared Module file list
+     *
+     * @return array
+     */
+    protected function _getDeclaredModuleFiles()
+    {
+        $codeDir = $this->_dirs->getDir(Mage_Core_Model_Dir::MODULES);
+        $moduleFiles = glob($codeDir . DS . '*' . DS . '*' . DS . '*' . DS . 'etc' . DS . 'config.xml');
+
+        if (!$moduleFiles) {
+            return false;
+        }
+
+        $collectModuleFiles = array(
+            'base'   => array(),
+            'mage'   => array(),
+            'custom' => array()
+        );
+
+        foreach ($moduleFiles as $v) {
+            $name = explode(DIRECTORY_SEPARATOR, $v);
+            $collection = $name[count($name) - 4];
+
+            if ($collection == 'Mage') {
+                $collectModuleFiles['mage'][] = $v;
+            } else {
+                $collectModuleFiles['custom'][] = $v;
+            }
+        }
+
+        $etcDir = $this->_dirs->getDir(Mage_Core_Model_Dir::CONFIG);
+        $additionalFiles = glob($etcDir . DS . 'modules' . DS . '*.xml');
+
+        foreach ($additionalFiles as $v) {
+            $collectModuleFiles['base'][] = $v;
+        }
+
+        return array_merge(
+            $collectModuleFiles['mage'],
+            $collectModuleFiles['custom'],
+            $collectModuleFiles['base']
+        );
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Loader/Modules/File.php b/app/code/core/Mage/Core/Model/Config/Loader/Modules/File.php
new file mode 100644
index 0000000000000000000000000000000000000000..c1d18bfd2d9109805def0dcad8751f9091ddd750
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Loader/Modules/File.php
@@ -0,0 +1,209 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_Loader_Modules_File
+{
+    /**
+     * Modules configuration
+     *
+     * @var Mage_Core_Model_Config_Modules
+     */
+    protected $_modulesConfig;
+
+    /**
+     * Base config factory
+     *
+     * @var Mage_Core_Model_Config_BaseFactory
+     */
+    protected $_prototypeFactory;
+
+    /**
+     * Module configuration directories
+     *
+     * @var array
+     */
+    protected $_moduleDirs = array();
+
+    /**
+     * Directory registry
+     *
+     * @var Mage_Core_Model_Dir
+     */
+    protected $_dirs;
+
+    /**
+     * @param Mage_Core_Model_Dir $dirs
+     * @param Mage_Core_Model_Config_BaseFactory $prototypeFactory
+     */
+    public function __construct(
+        Mage_Core_Model_Dir $dirs,
+        Mage_Core_Model_Config_BaseFactory $prototypeFactory
+    ) {
+        $this->_dirs = $dirs;
+        $this->_prototypeFactory = $prototypeFactory;
+    }
+
+    /**
+     * Iterate all active modules "etc" folders and combine data from
+     * specidied xml file name to one object
+     *
+     * @param Mage_Core_Model_ConfigInterface $modulesConfig
+     * @param string $fileName
+     * @param Mage_Core_Model_Config_Base|null $mergeToObject
+     * @param Mage_Core_Model_Config_Base|null $mergeModel
+     * @param array $configCache
+     * @return Mage_Core_Model_Config_Base|null
+     */
+    public function loadConfigurationFromFile(
+        Mage_Core_Model_ConfigInterface $modulesConfig,
+        $fileName,
+        $mergeToObject = null,
+        $mergeModel = null,
+        $configCache = array()
+    ) {
+        if ($mergeToObject === null) {
+            $mergeToObject = $this->_prototypeFactory->create('<config/>');
+        }
+        if ($mergeModel === null) {
+            $mergeModel = $this->_prototypeFactory->create('<config/>');
+        }
+        $modules = $modulesConfig->getNode('modules')->children();
+        /** @var $module Varien_Simplexml_Element */
+        foreach ($modules as $modName => $module) {
+            if ($module->is('active')) {
+                if (!is_array($fileName)) {
+                    $fileName = array($fileName);
+                }
+                foreach ($fileName as $configFile) {
+                    $this->_loadFileConfig(
+                        $configFile, $configCache, $modName, $mergeToObject, $modulesConfig, $mergeModel
+                    );
+                }
+            }
+        }
+        return $mergeToObject;
+    }
+
+    /**
+     * Load configuration from single file
+     *
+     * @param string $configFile
+     * @param array $configCache
+     * @param string $modName
+     * @param Mage_Core_Model_Config_Base $mergeToObject
+     * @param Mage_Core_Model_ConfigInterface $modulesConfig
+     * @param Mage_Core_Model_Config_Base $mergeModel
+     */
+    public function _loadFileConfig(
+        $configFile, $configCache, $modName, $mergeToObject, Mage_Core_Model_ConfigInterface $modulesConfig, $mergeModel
+    ) {
+        if ($configFile == 'config.xml' && isset($configCache[$modName])) {
+            $mergeToObject->extend($configCache[$modName], true);
+            //Prevent overriding <active> node of module if it was redefined in etc/modules
+            $mergeToObject->extend(
+                $this->_prototypeFactory->create(
+                    "<config><modules><{$modName}><active>true</active></{$modName}></modules></config>"
+                ),
+                true
+            );
+        } else {
+            $configFilePath = $this->getModuleDir($modulesConfig, 'etc', $modName) . DS . $configFile;
+            if ($mergeModel->loadFile($configFilePath)) {
+                $mergeToObject->extend($mergeModel, true);
+            }
+        }
+    }
+
+    /**
+     * Go through all modules and find configuration files of active modules
+     *
+     * @param Mage_Core_Model_ConfigInterface $modulesConfig
+     * @param $filename
+     * @return array
+     */
+    public function getConfigurationFiles(Mage_Core_Model_ConfigInterface $modulesConfig, $filename)
+    {
+        $result = array();
+        $modules = $modulesConfig->getNode('modules')->children();
+        foreach ($modules as $moduleName => $module) {
+            if ((!$module->is('active'))) {
+                continue;
+            }
+            $file = $this->getModuleDir($modulesConfig, 'etc', $moduleName) . DIRECTORY_SEPARATOR . $filename;
+            if (file_exists($file)) {
+                $result[] = $file;
+            }
+        }
+        return $result;
+    }
+
+    /**
+     * Get module directory by directory type
+     *
+     * @param Mage_Core_Model_ConfigInterface $modulesConfig
+     * @param string $type
+     * @param string $moduleName
+     * @return string
+     */
+    public function getModuleDir(Mage_Core_Model_ConfigInterface $modulesConfig, $type, $moduleName)
+    {
+        if (isset($this->_moduleDirs[$moduleName][$type])) {
+            return $this->_moduleDirs[$moduleName][$type];
+        }
+
+        $codePool = (string)$modulesConfig->getNode('modules/' . $moduleName . '/codePool');
+
+        $dir = $this->_dirs->getDir(Mage_Core_Model_Dir::MODULES) . DIRECTORY_SEPARATOR
+            . $codePool . DIRECTORY_SEPARATOR
+            . uc_words($moduleName, DIRECTORY_SEPARATOR);
+
+        switch ($type) {
+            case 'etc':
+            case 'controllers':
+            case 'sql':
+            case 'data':
+            case 'locale':
+            case 'view':
+                $dir .= DS . $type;
+                break;
+        }
+
+        $dir = str_replace('/', DS, $dir);
+        return $dir;
+    }
+
+    /**
+     * Set path to the corresponding module directory
+     *
+     * @param string $moduleName
+     * @param string $type directory type (etc, controllers, locale etc)
+     * @param string $path
+     */
+    public function setModuleDir($moduleName, $type, $path)
+    {
+        if (!isset($this->_moduleDirs[$moduleName])) {
+            $this->_moduleDirs[$moduleName] = array();
+        }
+        $this->_moduleDirs[$moduleName][$type] = $path;
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Loader/Modules/Proxy.php b/app/code/core/Mage/Core/Model/Config/Loader/Modules/Proxy.php
new file mode 100644
index 0000000000000000000000000000000000000000..d043650950513e10d93186f8853aba841a22dc65
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Loader/Modules/Proxy.php
@@ -0,0 +1,68 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_Config_Loader_Modules_Proxy implements Mage_Core_Model_Config_LoaderInterface
+{
+    /**
+     * @var Mage_Core_Model_Config_Loader_Modules
+     */
+    protected $_loader;
+
+    /**
+     * @var Magento_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * @param Magento_ObjectManager $objectManager
+     */
+    public function __construct(Magento_ObjectManager $objectManager)
+    {
+        $this->_objectManager = $objectManager;
+    }
+
+    /**
+     * Get loader instance
+     *
+     * @return Mage_Core_Model_Config_Loader_Modules
+     */
+    protected function _getSubject()
+    {
+        if (null === $this->_loader) {
+            $this->_loader = $this->_objectManager->get('Mage_Core_Model_Config_Loader_Modules');
+        }
+        return $this->_loader;
+    }
+
+    /**
+     * Populate configuration object
+     *
+     * @param Mage_Core_Model_Config_Base $config
+     * @return void
+     */
+    public function load(Mage_Core_Model_Config_Base $config)
+    {
+        $this->_getSubject()->load($config);
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Loader/Primary.php b/app/code/core/Mage/Core/Model/Config/Loader/Primary.php
new file mode 100644
index 0000000000000000000000000000000000000000..7decbe51b37ae3a9644a2f19a0769f368a38632e
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Loader/Primary.php
@@ -0,0 +1,88 @@
+<?php
+/**
+ * Primary configuration loader
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_Loader_Primary implements Mage_Core_Model_Config_LoaderInterface
+{
+    /**
+     * Directory registry
+     *
+     * @var Mage_Core_Model_Dir
+     */
+    protected $_dirs;
+
+    /**
+     * Local config loader
+     *
+     * @var Mage_Core_Model_Config_Loader_Local
+     */
+    protected $_localLoader;
+
+    /**
+     * @var Mage_Core_Model_Config_BaseFactory
+     */
+    protected $_prototypeFactory;
+
+    /**
+     * @param Mage_Core_Model_Config_BaseFactory $prototypeFactory
+     * @param Mage_Core_Model_Dir $dirs
+     * @param Mage_Core_Model_Config_Loader_Local $localLoader
+     */
+    public function __construct(
+        Mage_Core_Model_Config_BaseFactory $prototypeFactory,
+        Mage_Core_Model_Dir $dirs,
+        Mage_Core_Model_Config_Loader_Local $localLoader
+    ) {
+        $this->_dirs = $dirs;
+        $this->_localLoader = $localLoader;
+        $this->_prototypeFactory = $prototypeFactory;
+    }
+
+    /**
+     * Load primary configuration
+     *
+     * @param Mage_Core_Model_Config_Base $config
+     */
+    public function load(Mage_Core_Model_Config_Base $config)
+    {
+        $etcDir = $this->_dirs->getDir(Mage_Core_Model_Dir::CONFIG);
+        if (!$config->getNode()) {
+            $config->loadString('<config/>');
+        }
+        // 1. app/etc/*.xml (except local config)
+        foreach (scandir($etcDir) as $filename) {
+            if ('.' == $filename || '..' == $filename || '.xml' != substr($filename, -4)
+                || Mage_Core_Model_Config_Loader_Local::LOCAL_CONFIG_FILE == $filename
+            ) {
+                continue;
+            }
+            $baseConfigFile = $etcDir . DIRECTORY_SEPARATOR . $filename;
+            $baseConfig = $this->_prototypeFactory->create('<config/>');
+            $baseConfig->loadFile($baseConfigFile);
+            $config->extend($baseConfig);
+        }
+        // 2. local configuration
+        $this->_localLoader->load($config);
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Loader/Proxy.php b/app/code/core/Mage/Core/Model/Config/Loader/Proxy.php
new file mode 100644
index 0000000000000000000000000000000000000000..98fe54e563e0687475e144965860cdc70d8b007a
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Loader/Proxy.php
@@ -0,0 +1,68 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_Config_Loader_Proxy implements Mage_Core_Model_Config_LoaderInterface
+{
+    /**
+     * @var Mage_Core_Model_Config_Loader
+     */
+    protected $_loader;
+
+    /**
+     * @var Magento_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * @param Magento_ObjectManager $objectManager
+     */
+    public function __construct(Magento_ObjectManager $objectManager)
+    {
+        $this->_objectManager = $objectManager;
+    }
+
+    /**
+     * Get loader instance
+     *
+     * @return Mage_Core_Model_Config_Loader
+     */
+    protected function _getLoader()
+    {
+        if (null === $this->_loader) {
+            $this->_loader = $this->_objectManager->get('Mage_Core_Model_Config_Loader');
+        }
+        return $this->_loader;
+    }
+
+    /**
+     * Populate configuration object
+     *
+     * @param Mage_Core_Model_Config_Base $config
+     * @return void
+     */
+    public function load(Mage_Core_Model_Config_Base $config)
+    {
+        $this->_getLoader()->load($config);
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/LoaderInterface.php b/app/code/core/Mage/Core/Model/Config/LoaderInterface.php
new file mode 100644
index 0000000000000000000000000000000000000000..92da0dac7f4ad2f718cbfc7f49429acd0bb1a96e
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/LoaderInterface.php
@@ -0,0 +1,34 @@
+<?php
+/**
+ * Application config loader interface
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+interface Mage_Core_Model_Config_LoaderInterface
+{
+    /**
+     * Populate configuration object
+     *
+     * @param Mage_Core_Model_Config_Base $config
+     */
+    public function load(Mage_Core_Model_Config_Base $config);
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Locales.php b/app/code/core/Mage/Core/Model/Config/Locales.php
new file mode 100644
index 0000000000000000000000000000000000000000..dc3efbe736c3a59a915216594f5176efe8297297
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Locales.php
@@ -0,0 +1,92 @@
+<?php
+/**
+ *  Locale configuration. Contains configuration from app/locale/[locale_Code]/*.xml files
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_Locales implements Mage_Core_Model_ConfigInterface
+{
+    /**
+     * Configuration data container
+     *
+     * @var Mage_Core_Model_ConfigInterface
+     */
+    protected $_data;
+
+    /**
+     * Configuration storage
+     *
+     * @var Mage_Core_Model_Config_StorageInterface
+     */
+    protected $_storage;
+
+    /**
+     * @param Mage_Core_Model_Config_StorageInterface $storage
+     */
+    public function __construct(Mage_Core_Model_Config_StorageInterface $storage)
+    {
+        $this->_storage = $storage;
+        $this->_data = $this->_storage->getConfiguration();
+    }
+
+    /**
+     * Get configuration node
+     *
+     * @param string $path
+     * @return Varien_Simplexml_Element
+     */
+    public function getNode($path = null)
+    {
+        return $this->_data->getNode($path);
+    }
+
+    /**
+     * Create node by $path and set its value
+     *
+     * @param string $path separated by slashes
+     * @param string $value
+     * @param boolean $overwrite
+     */
+    public function setNode($path, $value, $overwrite = true)
+    {
+        $this->_data->setNode($path, $value, $overwrite);
+    }
+
+    /**
+     * Returns nodes found by xpath expression
+     *
+     * @param string $xpath
+     * @return array
+     */
+    public function getXpath($xpath)
+    {
+        return $this->_data->getXpath($xpath);
+    }
+
+    /**
+     * Reinitialize locales configuration
+     */
+    public function reinit()
+    {
+        $this->_data = $this->_storage->getConfiguration();
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Modules.php b/app/code/core/Mage/Core/Model/Config/Modules.php
new file mode 100644
index 0000000000000000000000000000000000000000..32cfac35c533213459be7ee6e83b87c1b667e32c
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Modules.php
@@ -0,0 +1,110 @@
+<?php
+/**
+ * Modules configuration. Contains primary configuration and configuration from modules /etc/*.xml files
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_Modules implements Mage_Core_Model_ConfigInterface
+{
+    /**
+     * Configuration data container
+     *
+     * @var Mage_Core_Model_ConfigInterface
+     */
+    protected $_data;
+
+    /**
+     * Configuration storage
+     *
+     * @var Mage_Core_Model_Config_StorageInterface
+     */
+    protected $_storage;
+
+    /**
+     * @param Mage_Core_Model_Config_StorageInterface $storage
+     */
+    public function __construct(Mage_Core_Model_Config_StorageInterface $storage)
+    {
+        Magento_Profiler::start('config_modules_load');
+        $this->_storage = $storage;
+        $this->_data = $this->_storage->getConfiguration();
+        Magento_Profiler::stop('config_modules_load');
+    }
+
+    /**
+     * Get configuration node
+     *
+     * @param string $path
+     * @return Varien_Simplexml_Element
+     */
+    public function getNode($path = null)
+    {
+        return $this->_data->getNode($path);
+    }
+
+    /**
+     * Create node by $path and set its value
+     *
+     * @param string $path separated by slashes
+     * @param string $value
+     * @param boolean $overwrite
+     */
+    public function setNode($path, $value, $overwrite = true)
+    {
+        $this->_data->setNode($path, $value, $overwrite);
+    }
+
+    /**
+     * Returns nodes found by xpath expression
+     *
+     * @param string $xpath
+     * @return array
+     */
+    public function getXpath($xpath)
+    {
+        return $this->_data->getXpath($xpath);
+    }
+
+    /**
+     * Get module config node
+     *
+     * @param string $moduleName
+     * @return Varien_Simplexml_Element
+     */
+    public function getModuleConfig($moduleName = '')
+    {
+        $modules = $this->getNode('modules');
+        if ('' === $moduleName) {
+            return $modules;
+        } else {
+            return $modules->$moduleName;
+        }
+    }
+
+    /**
+     * Reinitialize primary configuration
+     */
+    public function reinit()
+    {
+        $this->_data = $this->_storage->getConfiguration();
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Modules/Reader.php b/app/code/core/Mage/Core/Model/Config/Modules/Reader.php
new file mode 100644
index 0000000000000000000000000000000000000000..6c4ac0039bca0834d61414195cb253855d61ed8c
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Modules/Reader.php
@@ -0,0 +1,102 @@
+<?php
+/**
+ * Module configuration file reader
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_Modules_Reader
+{
+    /**
+     * Modules configuration
+     *
+     * @var Mage_Core_Model_Config_Modules
+     */
+    protected $_config;
+
+    /**
+     * Module file reader
+     *
+     * @var Mage_Core_Model_Config_Loader_Modules_File
+     */
+    protected $_fileReader;
+
+    /**
+     * @param Mage_Core_Model_Config_Modules $modulesConfig
+     * @param Mage_Core_Model_Config_Loader_Modules_File $fileReader
+     */
+    public function __construct(
+        Mage_Core_Model_Config_Modules $modulesConfig,
+        Mage_Core_Model_Config_Loader_Modules_File $fileReader
+    ) {
+        $this->_config = $modulesConfig;
+        $this->_fileReader = $fileReader;
+    }
+
+    /**
+     * Iterate all active modules "etc" folders and combine data from
+     * specidied xml file name to one object
+     *
+     * @param   string $fileName
+     * @param   null|Mage_Core_Model_Config_Base $mergeToObject
+     * @param   null|Mage_Core_Model_Config_Base $mergeModel
+     * @return  Mage_Core_Model_Config_Base
+     */
+    public function loadModulesConfiguration($fileName, $mergeToObject = null, $mergeModel = null)
+    {
+        return $this->_fileReader->loadConfigurationFromFile($this->_config, $fileName, $mergeToObject, $mergeModel);
+    }
+
+    /**
+     * Go through all modules and find configuration files of active modules
+     *
+     * @param string $filename
+     * @return array
+     */
+    public function getModuleConfigurationFiles($filename)
+    {
+        return $this->_fileReader->getConfigurationFiles($this->_config, $filename);
+    }
+
+    /**
+     * Get module directory by directory type
+     *
+     * @param   string $type
+     * @param   string $moduleName
+     * @return  string
+     */
+    public function getModuleDir($type, $moduleName)
+    {
+        return $this->_fileReader->getModuleDir($this->_config, $type, $moduleName);
+    }
+
+    /**
+     * Set path to the corresponding module directory
+     *
+     * @param string $moduleName
+     * @param string $type directory type (etc, controllers, locale etc)
+     * @param string $path
+     */
+    public function setModuleDir($moduleName, $type, $path)
+    {
+        $this->_fileReader->setModuleDir($moduleName, $type, $path);
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Module.php b/app/code/core/Mage/Core/Model/Config/Modules/Sorted.php
similarity index 97%
rename from app/code/core/Mage/Core/Model/Config/Module.php
rename to app/code/core/Mage/Core/Model/Config/Modules/Sorted.php
index 995164c33a9d85e6e5c73a0438b90f0d9e21635d..8be0ec530a6ee6fe98ebe3c8a4b0215663c506ac 100644
--- a/app/code/core/Mage/Core/Model/Config/Module.php
+++ b/app/code/core/Mage/Core/Model/Config/Modules/Sorted.php
@@ -1,5 +1,7 @@
 <?php
 /**
+ * Sorted modules config
+ *
  * Magento
  *
  * NOTICE OF LICENSE
@@ -18,16 +20,10 @@
  * versions in the future. If you wish to customize Magento for your
  * needs please refer to http://www.magentocommerce.com for more information.
  *
- * @category    Mage
- * @package     Mage_Core
  * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
-
-/**
- * Configuration for modules availability and dependencies
- */
-class Mage_Core_Model_Config_Module extends Mage_Core_Model_Config_Base
+class Mage_Core_Model_Config_Modules_Sorted extends Mage_Core_Model_Config_Base
 {
     /**
      * Types of dependencies between modules
diff --git a/app/code/core/Mage/Core/Model/Config/ModulesInterface.php b/app/code/core/Mage/Core/Model/Config/ModulesInterface.php
new file mode 100644
index 0000000000000000000000000000000000000000..18ec9e49601502089ed5e4fe24ff8de20d40b075
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/ModulesInterface.php
@@ -0,0 +1,33 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+interface Mage_Core_Model_Config_ModulesInterface extends Mage_Core_Model_ConfigInterface
+{
+    /**
+     * Get module config node
+     *
+     * @param string $moduleName
+     * @return Varien_Simplexml_Element
+     */
+    public function getModuleConfig($moduleName = '');
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Primary.php b/app/code/core/Mage/Core/Model/Config/Primary.php
new file mode 100644
index 0000000000000000000000000000000000000000..0acb2d113257228d1ae251900fa60ca987dfab41
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Primary.php
@@ -0,0 +1,91 @@
+<?php
+/**
+ * Primary application config (app/etc/*.xml)
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_Primary extends Mage_Core_Model_Config_Base
+{
+    /**
+     * Install date xpath
+     */
+    const XML_PATH_INSTALL_DATE = 'global/install/date';
+
+    /**
+     * Configuration template for the application installation date
+     */
+    const CONFIG_TEMPLATE_INSTALL_DATE = '<config><global><install><date>%s</date></install></global></config>';
+
+    /**
+     * Application installation timestamp
+     *
+     * @var int|null
+     */
+    protected $_installDate;
+
+    /**
+     * @var Mage_Core_Model_Config_Loader_Primary
+     */
+    protected $_loader;
+
+    /**
+     * @param Mage_Core_Model_Config_Loader_Primary $loader
+     */
+    public function __construct(Mage_Core_Model_Config_Loader_Primary $loader)
+    {
+        parent::__construct('<config/>');
+        $this->_loader = $loader;
+        $this->_loader->load($this);
+        $this->_loadInstallDate();
+    }
+
+    /**
+     * Load application installation date
+     */
+    protected function _loadInstallDate()
+    {
+        $installDateNode = $this->getNode(self::XML_PATH_INSTALL_DATE);
+        if ($installDateNode) {
+            $this->_installDate = strtotime((string)$installDateNode);
+        }
+    }
+
+    /**
+     * Retrieve application installation date as a timestamp or NULL, if it has not been installed yet
+     *
+     * @return int|null
+     */
+    public function getInstallDate()
+    {
+        return $this->_installDate;
+    }
+
+    /**
+     * Reinitialize primary configuration
+     */
+    public function reinit()
+    {
+        $this->loadString('<config/>');
+        $this->_loader->load($this);
+        $this->_loadInstallDate();
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Resource.php b/app/code/core/Mage/Core/Model/Config/Resource.php
new file mode 100644
index 0000000000000000000000000000000000000000..c3e015f80b922e168209d0ed80423eee863ae871
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Resource.php
@@ -0,0 +1,125 @@
+<?php
+/**
+ * Resource configuration. Uses application configuration to retrieve resource information.
+ * Uses latest loaded configuration object to make resource connection available on early stages of bootstrapping.
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */ 
+class Mage_Core_Model_Config_Resource
+{
+    /**
+     * @var Mage_Core_Model_ConfigInterface
+     */
+    protected $_config;
+
+    /**
+     * @param Mage_Core_Model_ConfigInterface $config
+     */
+    public function __construct(Mage_Core_Model_ConfigInterface $config)
+    {
+        $this->_config = $config;
+    }
+
+    /**
+     * Set application config
+     *
+     * @param Mage_Core_Model_ConfigInterface $config
+     */
+    public function setConfig(Mage_Core_Model_ConfigInterface $config)
+    {
+        $this->_config = $config;
+    }
+
+    /**
+     * Get resource configuration for resource name
+     *
+     * @param string $name
+     * @return Varien_Simplexml_Object
+     */
+    public function getResourceConfig($name)
+    {
+        return $this->_config->getNode('global/resources/' . $name);
+    }
+
+    /**
+     * Retrieve resource connection configuration by name
+     *
+     * @param $name
+     * @return Varien_Simplexml_Element
+     */
+    public function getResourceConnectionConfig($name)
+    {
+        $config = $this->getResourceConfig($name);
+        if ($config) {
+            $conn = $config->connection;
+            if ($conn) {
+                if (!empty($conn->use)) {
+                    return $this->getResourceConnectionConfig((string)$conn->use);
+                } else {
+                    return $conn;
+                }
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Retrieve reosurce type configuration
+     *
+     * @param $type
+     * @return Varien_Simplexml_Element
+     */
+    public function getResourceTypeConfig($type)
+    {
+        return $this->_config->getNode('global/resource/connection/types/' . $type);
+    }
+
+    /**
+     * Retrieve database table prefix
+     *
+     * @return string
+     */
+    public function getTablePrefix()
+    {
+        return (string) $this->_config->getNode('global/resources/db/table_prefix');
+    }
+
+    /**
+     * Retrieve resource connection model name
+     *
+     * @param string $moduleName
+     * @return string
+     */
+    public function getResourceConnectionModel($moduleName = null)
+    {
+        $config = null;
+        if (!is_null($moduleName)) {
+            $setupResource = $moduleName . '_setup';
+            $config        = $this->getResourceConnectionConfig($setupResource);
+        }
+        if (!$config) {
+            $config = $this->getResourceConnectionConfig(Mage_Core_Model_Resource::DEFAULT_SETUP_RESOURCE);
+        }
+
+        return (string) $config->model;
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Sections.php b/app/code/core/Mage/Core/Model/Config/Sections.php
new file mode 100644
index 0000000000000000000000000000000000000000..d5768e8be306d9e0ad0db72d608541114fde4140
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Sections.php
@@ -0,0 +1,70 @@
+<?php
+/**
+ * Config sections list. Used to cache/read config sections separately.
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_Sections
+{
+    /**
+     * Instructions for spitting config cache
+     * array(
+     *      $sectionName => $recursionLevel
+     * )
+     * Recursion level provides availability to cache subnodes separatly
+     *
+     * @var array
+     */
+    protected $_sections = array(
+        'admin'     => 0,
+        'adminhtml' => 0,
+        'crontab'   => 0,
+        'install'   => 0,
+        'stores'    => 1,
+        'websites'  => 0
+    );
+
+    /**
+     * Retrieve sections
+     *
+     * @return array
+     */
+    public function getSections()
+    {
+        return $this->_sections;
+    }
+
+    /**
+     * Retrieve section cache key by path
+     *
+     * @param string $path
+     * @return bool|string
+     */
+    public function getKey($path)
+    {
+        $pathParts = explode('/', $path);
+        if (!array_key_exists($pathParts[0], $this->_sections)) {
+            return false;
+        }
+        return implode('_', array_slice($pathParts, 0, $this->_sections[$pathParts[0]] + 1));
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Storage.php b/app/code/core/Mage/Core/Model/Config/Storage.php
new file mode 100644
index 0000000000000000000000000000000000000000..a93124f2f401f5d4b3de1ca0c46f754f9da24125
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Storage.php
@@ -0,0 +1,79 @@
+<?php
+/**
+ * Application config storage
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_Storage extends Mage_Core_Model_Config_StorageAbstract
+{
+    /**
+     * Resource configuration
+     *
+     * @var Mage_Core_Model_Config_Resource
+     */
+    protected $_resourcesConfig;
+
+    /**
+     * @param Mage_Core_Model_Config_Cache $cache
+     * @param Mage_Core_Model_Config_LoaderInterface $loader
+     * @param Mage_Core_Model_Config_BaseFactory $factory
+     * @param Mage_Core_Model_Config_Resource $resourcesConfig
+     */
+    public function __construct(
+        Mage_Core_Model_Config_Cache $cache,
+        Mage_Core_Model_Config_LoaderInterface $loader,
+        Mage_Core_Model_Config_BaseFactory $factory,
+        Mage_Core_Model_Config_Resource $resourcesConfig
+    ) {
+        parent::__construct($cache, $loader, $factory);
+        $this->_resourcesConfig = $resourcesConfig;
+    }
+
+    /**
+     * Retrieve application configuration
+     *
+     * @return Mage_Core_Model_ConfigInterface
+     */
+    public function getConfiguration()
+    {
+        $config = $this->_cache->load();
+        if (false === $config) {
+            $config = $this->_configFactory->create('<config/>');
+            $this->_loader->load($config);
+            $this->_cache->save($config);
+        }
+        /*
+         * Update resource configuration when total configuration is loaded.
+         * Required until resource model is refactored.
+         */
+        $this->_resourcesConfig->setConfig($config);
+        return $config;
+    }
+
+    /**
+     * Remove configuration cache
+     */
+    public function removeCache()
+    {
+        $this->_cache->clean();
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Storage/Locales.php b/app/code/core/Mage/Core/Model/Config/Storage/Locales.php
new file mode 100644
index 0000000000000000000000000000000000000000..399541697fa4f62ca5f0f77c47a7ddd1babbf277
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Storage/Locales.php
@@ -0,0 +1,28 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_Config_Storage_Locales extends Mage_Core_Model_Config_StorageAbstract
+{
+
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Storage/Modules.php b/app/code/core/Mage/Core/Model/Config/Storage/Modules.php
new file mode 100644
index 0000000000000000000000000000000000000000..764aadbb4c4e733c8046fb86910e3cbf3cad604d
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Storage/Modules.php
@@ -0,0 +1,28 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_Config_Storage_Modules extends Mage_Core_Model_Config_StorageAbstract
+{
+
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Storage/Writer/Db.php b/app/code/core/Mage/Core/Model/Config/Storage/Writer/Db.php
new file mode 100644
index 0000000000000000000000000000000000000000..cbab2bb7dd3c49ed4982d9eb5cc05b4517b27d8e
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Storage/Writer/Db.php
@@ -0,0 +1,67 @@
+<?php
+/**
+ * Application config db storage writer
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_Storage_Writer_Db implements Mage_Core_Model_Config_Storage_WriterInterface
+{
+    /**
+     * Resource model of config data
+     *
+     * @var Mage_Core_Model_Resource_Config
+     */
+    protected $_resource;
+
+    /**
+     * @param Mage_Core_Model_Resource_Config $resource
+     */
+    public function __construct(Mage_Core_Model_Resource_Config $resource)
+    {
+        $this->_resource = $resource;
+    }
+
+    /**
+     * Delete config value from storage
+     *
+     * @param   string $path
+     * @param   string $scope
+     * @param   int $scopeId
+     */
+    public function delete($path, $scope = Mage_Core_Model_Store::DEFAULT_CODE, $scopeId = 0)
+    {
+        $this->_resource->deleteConfig(rtrim($path, '/'), $scope, $scopeId);
+    }
+
+    /**
+     * Save config value to storage
+     *
+     * @param string $path
+     * @param string $value
+     * @param string $scope
+     * @param int $scopeId
+     */
+    public function save($path, $value, $scope = Mage_Core_Model_Store::DEFAULT_CODE, $scopeId = 0)
+    {
+        $this->_resource->saveConfig(rtrim($path, '/'), $value, $scope, $scopeId);
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/Storage/WriterInterface.php b/app/code/core/Mage/Core/Model/Config/Storage/WriterInterface.php
new file mode 100644
index 0000000000000000000000000000000000000000..9a7f4b259d09f81e95eba4e6fe529bd0003c1725
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/Storage/WriterInterface.php
@@ -0,0 +1,46 @@
+<?php
+/**
+ * Application config storage writer interface
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+interface Mage_Core_Model_Config_Storage_WriterInterface
+{
+    /**
+     * Delete config value from storage
+     *
+     * @param   string $path
+     * @param   string $scope
+     * @param   int $scopeId
+     */
+    public function delete($path, $scope = Mage_Core_Model_Store::DEFAULT_CODE, $scopeId = 0);
+
+    /**
+     * Save config value to storage
+     *
+     * @param string $path
+     * @param string $value
+     * @param string $scope
+     * @param int $scopeId
+     */
+    public function save($path, $value, $scope = Mage_Core_Model_Store::DEFAULT_CODE, $scopeId = 0);
+}
diff --git a/app/code/core/Mage/Core/Model/Config/StorageAbstract.php b/app/code/core/Mage/Core/Model/Config/StorageAbstract.php
new file mode 100644
index 0000000000000000000000000000000000000000..7a5ded4fd669a4c45cdfa175367ee17873ca9b02
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/StorageAbstract.php
@@ -0,0 +1,86 @@
+<?php
+/**
+ * Application config storage
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+abstract class Mage_Core_Model_Config_StorageAbstract implements Mage_Core_Model_Config_StorageInterface
+{
+    /**
+     * Cache storage object
+     *
+     * @var Mage_Core_Model_Config_Cache
+     */
+    protected $_cache;
+
+    /**
+     * Configuration loader
+     *
+     * @var Mage_Core_Model_Config_LoaderInterface
+     */
+    protected $_loader;
+
+    /**
+     * Configuration loader
+     *
+     * @var Mage_Core_Model_Config_BaseFactory
+     */
+    protected $_configFactory;
+
+    /**
+     * @param Mage_Core_Model_Config_Cache $cache
+     * @param Mage_Core_Model_Config_LoaderInterface $loader
+     * @param Mage_Core_Model_Config_BaseFactory $factory
+     */
+    public function __construct(
+        Mage_Core_Model_Config_Cache $cache,
+        Mage_Core_Model_Config_LoaderInterface $loader,
+        Mage_Core_Model_Config_BaseFactory $factory
+    ) {
+        $this->_cache = $cache;
+        $this->_loader = $loader;
+        $this->_configFactory = $factory;
+    }
+
+    /**
+     * Get loaded configuration
+     *
+     * @return Mage_Core_Model_ConfigInterface
+     */
+    public function getConfiguration()
+    {
+        $config = $this->_cache->load();
+        if (false === $config) {
+            $config = $this->_configFactory->create('<config/>');
+            $this->_loader->load($config);
+        }
+        return $config;
+    }
+
+    /**
+     * Remove configuration cache
+     */
+    public function removeCache()
+    {
+
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Config/StorageInterface.php b/app/code/core/Mage/Core/Model/Config/StorageInterface.php
new file mode 100644
index 0000000000000000000000000000000000000000..115e9a067da14d7bb1defb9f9b39942dc3fa3c86
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Config/StorageInterface.php
@@ -0,0 +1,39 @@
+<?php
+/**
+ * Application config storage interface
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+interface Mage_Core_Model_Config_StorageInterface
+{
+    /**
+     * Get loaded configuration
+     *
+     * @return Mage_Core_Model_ConfigInterface
+     */
+    public function getConfiguration();
+
+    /**
+     * Remove configuration cache
+     */
+    public function removeCache();
+}
diff --git a/app/code/core/Mage/Core/Model/ConfigInterface.php b/app/code/core/Mage/Core/Model/ConfigInterface.php
new file mode 100644
index 0000000000000000000000000000000000000000..0e008daa3eab498348acc370067f205d100ef5b1
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/ConfigInterface.php
@@ -0,0 +1,58 @@
+<?php
+/**
+ * Configuration model interface
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+interface Mage_Core_Model_ConfigInterface
+{
+    /**
+     * Get configuration node
+     *
+     * @param string $path
+     * @return Varien_Simplexml_Element
+     */
+    public function getNode($path = null);
+
+    /**
+     * Create node by $path and set its value
+     *
+     * @param string $path separated by slashes
+     * @param string $value
+     * @param boolean $overwrite
+     */
+    public function setNode($path, $value, $overwrite = true);
+
+    /**
+     * Returns nodes found by xpath expression
+     *
+     * @param string $xpath
+     * @return array
+     */
+    public function getXpath($xpath);
+
+    /**
+     * Reinitialize config object
+     */
+    public function reinit();
+}
diff --git a/app/code/core/Mage/Core/Model/Cookie.php b/app/code/core/Mage/Core/Model/Cookie.php
index 1de4732752dda800845fd806cc7450681a375098..c4e801d99d5a43fd3210918fbcfaf9f8bb30d620 100644
--- a/app/code/core/Mage/Core/Model/Cookie.php
+++ b/app/code/core/Mage/Core/Model/Cookie.php
@@ -80,7 +80,7 @@ class Mage_Core_Model_Cookie
      */
     protected function _getRequest()
     {
-        return Mage::app()->getRequest();
+        return Mage::getObjectManager()->get('Mage_Core_Controller_Request_Http');
     }
 
     /**
@@ -90,7 +90,7 @@ class Mage_Core_Model_Cookie
      */
     protected function _getResponse()
     {
-        return Mage::app()->getResponse();
+        return Mage::getObjectManager()->get('Mage_Core_Controller_Response_Http');
     }
 
     /**
diff --git a/app/code/core/Mage/Core/Model/Db/Updater.php b/app/code/core/Mage/Core/Model/Db/Updater.php
new file mode 100644
index 0000000000000000000000000000000000000000..a1094f38332392b129552ff9fb2c658a34173bf2
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Db/Updater.php
@@ -0,0 +1,158 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_Db_Updater implements Mage_Core_Model_Db_UpdaterInterface
+{
+    /**
+     * Modules configuration
+     *
+     * @var Mage_Core_Model_Config_Modules
+     */
+    protected $_config;
+
+    /**
+     * Default setup class name
+     *
+     * @var string
+     */
+    protected $_defaultClass = 'Mage_Core_Model_Resource_Setup';
+
+    /**
+     * Setup model factory
+     *
+     * @var Mage_Core_Model_Resource_SetupFactory
+     */
+    protected $_factory;
+
+    /**
+     * Flag which allow run data install or upgrade
+     *
+     * @var bool
+     */
+    protected static $_schemaUpdatesChecked;
+
+    /**
+     * Application state model
+     *
+     * @var Mage_Core_Model_App_State
+     */
+    protected $_appState;
+
+    /**
+     * @param Mage_Core_Model_Config_Modules $modulesConfig
+     * @param Mage_Core_Model_Resource_SetupFactory $factory
+     * @param Mage_Core_Model_App_State $appState
+     */
+    public function __construct(
+        Mage_Core_Model_Config_Modules $modulesConfig,
+        Mage_Core_Model_Resource_SetupFactory $factory,
+        Mage_Core_Model_App_State $appState
+    ) {
+        $this->_config = $modulesConfig;
+        $this->_factory = $factory;
+        $this->_appState = $appState;
+    }
+
+    /**
+     * Check whether modules updates processing should be skipped
+     *
+     * @return bool
+     */
+    protected function _shouldSkipProcessModulesUpdates()
+    {
+        if (!$this->_appState->isInstalled()) {
+            return false;
+        }
+
+        $ignoreDevelopmentMode = (bool)(string)$this->_config->getNode(self::XML_PATH_IGNORE_DEV_MODE);
+        if ($this->_appState->isDeveloperMode() && false == $ignoreDevelopmentMode) {
+            return false;
+        }
+
+        return (bool)(string)$this->_config->getNode(self::XML_PATH_SKIP_PROCESS_MODULES_UPDATES);
+    }
+
+    /**
+     * Apply database scheme updates whenever needed
+     */
+    public function updateScheme()
+    {
+        if (true == $this->_shouldSkipProcessModulesUpdates()) {
+            return;
+        }
+
+        Magento_Profiler::start('apply_db_schema_updates');
+        $this->_appState->setUpdateMode(true);
+
+        $resources = $this->_config->getNode('global/resources')->children();
+        $afterApplyUpdates = array();
+        foreach ($resources as $resName => $resource) {
+            if (!$resource->setup) {
+                continue;
+            }
+            $className = $this->_defaultClass;
+            if (isset($resource->setup->class)) {
+                $className = $resource->setup->getClassName();
+            }
+
+            $setupClass = $this->_factory->create($className, array('resourceName' => $resName));
+            $setupClass->applyUpdates();
+
+            if ($setupClass->getCallAfterApplyAllUpdates()) {
+                $afterApplyUpdates[] = $setupClass;
+            }
+        }
+
+        /** @var $setupClass Mage_Core_Model_Resource_SetupInterface*/
+        foreach ($afterApplyUpdates as $setupClass) {
+            $setupClass->afterApplyAllUpdates();
+        }
+
+        $this->_appState->setUpdateMode(false);
+        self::$_schemaUpdatesChecked = true;
+        Magento_Profiler::stop('apply_db_schema_updates');
+    }
+
+    /**
+     * Apply database data updates whenever needed
+     */
+    public function updateData()
+    {
+        if (!self::$_schemaUpdatesChecked) {
+            return;
+        }
+        $resources = $this->_config->getNode('global/resources')->children();
+        foreach ($resources as $resName => $resource) {
+            if (!$resource->setup) {
+                continue;
+            }
+            $className = $this->_defaultClass;
+            if (isset($resource->setup->class)) {
+                $className = $resource->setup->getClassName();
+            }
+            $setupClass = $this->_factory->create($className, array('resourceName' => $resName));
+            $setupClass->applyDataUpdates();
+        }
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Db/UpdaterInterface.php b/app/code/core/Mage/Core/Model/Db/UpdaterInterface.php
new file mode 100644
index 0000000000000000000000000000000000000000..88074b786d813c9ecac3424f4e333d56bb69d265
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Db/UpdaterInterface.php
@@ -0,0 +1,47 @@
+<?php
+/**
+ * DB updater interface
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+interface Mage_Core_Model_Db_UpdaterInterface
+{
+    /**
+     * if this node set to true, we will ignore Developer Mode for applying updates
+     */
+    const XML_PATH_IGNORE_DEV_MODE = 'global/skip_process_modules_updates_ignore_dev_mode';
+
+    /**
+     * if this node set to true, we will ignore applying scheme updates
+     */
+    const XML_PATH_SKIP_PROCESS_MODULES_UPDATES = 'global/skip_process_modules_updates';
+
+    /**
+     * Apply database scheme updates whenever needed
+     */
+    public function updateScheme();
+
+    /**
+     * Apply database data updates whenever needed
+     */
+    public function updateData();
+}
diff --git a/app/code/core/Mage/Core/Model/Design/Package.php b/app/code/core/Mage/Core/Model/Design/Package.php
index 1a7dff400723abe6ea7ad1329b3172d54adb44d5..c9a37e27eaee8dc09110370963d12fc550bf3043 100644
--- a/app/code/core/Mage/Core/Model/Design/Package.php
+++ b/app/code/core/Mage/Core/Model/Design/Package.php
@@ -25,80 +25,8 @@
  */
 
 
-class Mage_Core_Model_Design_Package
+class Mage_Core_Model_Design_Package implements Mage_Core_Model_Design_PackageInterface
 {
-    /**
-     * Default design area
-     */
-    const DEFAULT_AREA = 'frontend';
-
-    /**
-     * Scope separator
-     */
-    const SCOPE_SEPARATOR = '::';
-
-    /**
-     * Public directory which contains theme files
-     */
-    const PUBLIC_BASE_THEME_DIR = 'static';
-
-    /**#@+
-     * Public directories prefix group
-     */
-    const PUBLIC_MERGE_DIR  = '_merged';
-    const PUBLIC_MODULE_DIR = '_module';
-    const PUBLIC_VIEW_DIR   = '_view';
-    const PUBLIC_THEME_DIR  = '_theme';
-    /**#@-*/
-
-    /**#@+
-     * Extensions group for static files
-     */
-    const CONTENT_TYPE_CSS = 'css';
-    const CONTENT_TYPE_JS  = 'js';
-    /**#@-*/
-
-    /**#@+
-     * Protected extensions group for publication mechanism
-     */
-    const CONTENT_TYPE_PHP   = 'php';
-    const CONTENT_TYPE_PHTML = 'phtml';
-    const CONTENT_TYPE_XML   = 'xml';
-    /**#@-*/
-
-    /**
-     * Published file cache storage tag
-     */
-    const PUBLIC_CACHE_TAG = 'design_public';
-
-    /**#@+
-     * Common node path to theme design configuration
-     */
-    const XML_PATH_THEME    = 'design/theme/full_name';
-    const XML_PATH_THEME_ID = 'design/theme/theme_id';
-    /**#@-*/
-
-    /**
-     * Path to configuration node that indicates how to materialize view files: with or without "duplication"
-     */
-    const XML_PATH_ALLOW_DUPLICATION = 'global/design/theme/allow_view_files_duplication';
-
-    /**
-     * Path to config node that allows automatically updating map files in runtime
-     */
-    const XML_PATH_ALLOW_MAP_UPDATE = 'global/dev/design_fallback/allow_map_update';
-
-    /**
-     * Sub-directory where to store maps of view files fallback (if used)
-     */
-    const FALLBACK_MAP_DIR = 'maps/fallback';
-
-    /**
-     * PCRE that matches non-absolute URLs in CSS content
-     */
-    const REGEX_CSS_RELATIVE_URLS
-        = '#url\s*\(\s*(?(?=\'|").)(?!http\://|https\://|/|data\:)(.+?)(?:[\#\?].*?|[\'"])?\s*\)#';
-
     private static $_regexMatchCache      = array();
     private static $_customThemeTypeCache = array();
 
@@ -159,19 +87,28 @@ class Mage_Core_Model_Design_Package
      */
     protected $_themes = array();
 
+    /**
+     * Module configuration reader
+     *
+     * @var Mage_Core_Model_Config_Modules_Reader
+     */
+    protected $_moduleReader;
+
     /**
      * @var Magento_Filesystem
      */
     protected $_filesystem;
 
     /**
+     * @param Mage_Core_Model_Config_Modules_Reader $moduleReader
      * @param Magento_Filesystem $filesystem
      */
-    public function __construct(Magento_Filesystem $filesystem)
+    public function __construct(Mage_Core_Model_Config_Modules_Reader $moduleReader, Magento_Filesystem $filesystem)
     {
+        $this->_moduleReader = $moduleReader;
         $this->_filesystem = $filesystem;
     }
-
+   
     /**
      * Set package area
      *
@@ -1149,7 +1086,7 @@ class Mage_Core_Model_Design_Package
             return $this->_viewConfigs[$key];
         }
 
-        $configFiles = Mage::getConfig()->getModuleConfigurationFiles('view.xml');
+        $configFiles = $this->_moduleReader->getModuleConfigurationFiles('view.xml');
         $themeConfigFile = $this->getFilename('view.xml', array());
         if ($themeConfigFile && $this->_filesystem->has($themeConfigFile)) {
             $configFiles[] = $themeConfigFile;
diff --git a/app/code/core/Mage/Core/Model/Design/Package/Proxy.php b/app/code/core/Mage/Core/Model/Design/Package/Proxy.php
new file mode 100644
index 0000000000000000000000000000000000000000..b32e8b8cc7e3e16cf845e2d5b6cbca21822bb44a
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Design/Package/Proxy.php
@@ -0,0 +1,225 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_Core
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_Design_Package_Proxy implements Mage_Core_Model_Design_PackageInterface
+{
+    /**
+     * @var Magento_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * @var Mage_Core_Model_Design_Package
+     */
+    protected $_model;
+
+    /**
+     * @param Magento_ObjectManager $objectManager
+     */
+    public function __construct(Magento_ObjectManager $objectManager)
+    {
+        $this->_objectManager = $objectManager;
+    }
+
+    /**
+     * @return Mage_Core_Model_Design_Package
+     */
+    protected function _getInstance()
+    {
+        if (null === $this->_model) {
+            $this->_model = $this->_objectManager->get('Mage_Core_Model_Design_Package');
+        }
+        return $this->_model;
+    }
+
+    /**
+     * Set package area
+     *
+     * @param string $area
+     * @return Mage_Core_Model_Design_PackageInterface
+     */
+    public function setArea($area)
+    {
+        return $this->_getInstance()->setArea($area);
+    }
+
+    /**
+     * Retrieve package area
+     *
+     * @return string
+     */
+    public function getArea()
+    {
+        return $this->_getInstance()->getArea();
+    }
+
+
+    /**
+     * Set theme path
+     *
+     * @param Mage_Core_Model_Theme|int|string $theme
+     * @param string $area
+     * @return Mage_Core_Model_Design_PackageInterface
+     */
+    public function setDesignTheme($theme, $area = null)
+    {
+        return $this->_getInstance()->setDesignTheme($theme, $area);
+    }
+
+
+    /**
+     * Get default theme which declared in configuration
+     *
+     * @param string $area
+     * @param array $params
+     * @return string|int
+     */
+    public function getConfigurationDesignTheme($area = null, array $params = array())
+    {
+        return $this->_getInstance()->getConfigurationDesignTheme($area, $params);
+    }
+
+    /**
+     * Set default design theme
+     *
+     * @return Mage_Core_Model_Design_PackageInterface
+     */
+    public function setDefaultDesignTheme()
+    {
+        return $this->_getInstance()->setDefaultDesignTheme();
+    }
+
+    /**
+     * Design theme model getter
+     *
+     * @return Mage_Core_Model_Theme
+     */
+    public function getDesignTheme()
+    {
+        return $this->_getInstance()->getDesignTheme();
+    }
+
+    /**
+     * Get existing file name with fallback to default
+     *
+     * @param string $file
+     * @param array $params
+     * @return string
+     */
+    public function getFilename($file, array $params = array())
+    {
+        return $this->_getInstance()->getFilename($file, $params);
+    }
+
+    /**
+     * Get a locale file
+     *
+     * @param string $file
+     * @param array $params
+     * @return string
+     */
+    public function getLocaleFileName($file, array $params = array())
+    {
+        return $this->_getInstance()->getLocaleFileName($file, $params);
+    }
+
+    /**
+     * Find a view file using fallback mechanism
+     *
+     * @param string $file
+     * @param array $params
+     * @return string
+     */
+    public function getViewFile($file, array $params = array())
+    {
+        return $this->_getInstance()->getViewFile($file, $params);
+    }
+
+    /**
+     * Remove all merged js/css files
+     *
+     * @return bool
+     */
+    public function cleanMergedJsCss()
+    {
+        return $this->_getInstance()->cleanMergedJsCss();
+    }
+
+    /**
+     * Get url to file base on theme file identifier.
+     * Publishes file there, if needed.
+     *
+     * @param string $file
+     * @param array $params
+     * @return string
+     */
+    public function getViewFileUrl($file, array $params = array())
+    {
+        return $this->_getInstance()->getViewFileUrl($file, $params);
+    }
+
+    /**
+     * Get URLs to CSS files optimized based on configuration settings
+     *
+     * @param array $files
+     * @return array
+     */
+    public function getOptimalCssUrls($files)
+    {
+        return $this->_getInstance()->getOptimalCssUrls($files);
+    }
+
+    /**
+     * Get URLs to JS files optimized based on configuration settings
+     *
+     * @param array $files
+     * @return array
+     */
+    public function getOptimalJsUrls($files)
+    {
+        return $this->_getInstance()->getOptimalJsUrls($files);
+    }
+
+    /**
+     * Return directory for theme files publication
+     *
+     * @return string
+     */
+    public function getPublicDir()
+    {
+        return $this->_getInstance()->getPublicDir();
+    }
+
+    /**
+     * Render view config object for current package and theme
+     *
+     * @return Magento_Config_View
+     */
+    public function getViewConfig()
+    {
+        return $this->_getInstance()->getViewConfig();
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Design/PackageInterface.php b/app/code/core/Mage/Core/Model/Design/PackageInterface.php
new file mode 100644
index 0000000000000000000000000000000000000000..96a9eefdede45508454238542d35e1fc1ba4a876
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Design/PackageInterface.php
@@ -0,0 +1,228 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_Core
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+interface Mage_Core_Model_Design_PackageInterface
+{
+    /**
+     * Default design area
+     */
+    const DEFAULT_AREA = 'frontend';
+
+    /**
+     * Scope separator
+     */
+    const SCOPE_SEPARATOR = '::';
+
+    /**#@+
+     * Public directories prefix group
+     */
+    const PUBLIC_MERGE_DIR  = '_merged';
+    const PUBLIC_MODULE_DIR = '_module';
+    const PUBLIC_VIEW_DIR   = '_view';
+    const PUBLIC_THEME_DIR  = '_theme';
+    /**#@-*/
+
+    /**
+     * Public directory which contain theme files
+     */
+    const PUBLIC_BASE_THEME_DIR = 'static';
+
+    /**#@+
+     * Extensions group for static files
+     */
+    const CONTENT_TYPE_CSS = 'css';
+    const CONTENT_TYPE_JS  = 'js';
+    /**#@-*/
+
+    /**#@+
+     * Protected extensions group for publication mechanism
+     */
+    const CONTENT_TYPE_PHP   = 'php';
+    const CONTENT_TYPE_PHTML = 'phtml';
+    const CONTENT_TYPE_XML   = 'xml';
+    /**#@-*/
+
+    /**
+     * The name of the default theme in the context of a package
+     */
+    const DEFAULT_THEME_NAME = 'default';
+
+    /**
+     * Published file cache storage tag
+     */
+    const PUBLIC_CACHE_TAG = 'design_public';
+
+    /**#@+
+     * Common node path to theme design configuration
+     */
+    const XML_PATH_THEME    = 'design/theme/full_name';
+    const XML_PATH_THEME_ID = 'design/theme/theme_id';
+    /**#@-*/
+
+    /**
+     * Path to configuration node that indicates how to materialize view files: with or without "duplication"
+     */
+    const XML_PATH_ALLOW_DUPLICATION = 'global/design/theme/allow_view_files_duplication';
+
+    /**
+     * Path to config node that allows automatically updating map files in runtime
+     */
+    const XML_PATH_ALLOW_MAP_UPDATE = 'global/dev/design_fallback/allow_map_update';
+
+    /**
+     * Sub-directory where to store maps of view files fallback (if used)
+     */
+    const FALLBACK_MAP_DIR = 'maps/fallback';
+
+    /**
+     * PCRE that matches non-absolute URLs in CSS content
+     */
+    const REGEX_CSS_RELATIVE_URLS
+        = '#url\s*\(\s*(?(?=\'|").)(?!http\://|https\://|/|data\:)(.+?)(?:[\#\?].*?|[\'"])?\s*\)#';
+
+    /**
+     * Set package area
+     *
+     * @param string $area
+     * @return Mage_Core_Model_Design_PackageInterface
+     */
+    public function setArea($area);
+
+    /**
+     * Retrieve package area
+     *
+     * @return string
+     */
+    public function getArea();
+
+
+    /**
+     * Set theme path
+     *
+     * @param Mage_Core_Model_Theme|int|string $theme
+     * @param string $area
+     * @return Mage_Core_Model_Design_PackageInterface
+     */
+    public function setDesignTheme($theme, $area = null);
+
+
+    /**
+     * Get default theme which declared in configuration
+     *
+     * @param string $area
+     * @param array $params
+     * @return string|int
+     */
+    public function getConfigurationDesignTheme($area = null, array $params = array());
+
+    /**
+     * Set default design theme
+     *
+     * @return Mage_Core_Model_Design_PackageInterface
+     */
+    public function setDefaultDesignTheme();
+
+    /**
+     * Design theme model getter
+     *
+     * @return Mage_Core_Model_Theme
+     */
+    public function getDesignTheme();
+
+    /**
+     * Get existing file name with fallback to default
+     *
+     * @param string $file
+     * @param array $params
+     * @return string
+     */
+    public function getFilename($file, array $params = array());
+
+    /**
+     * Get a locale file
+     *
+     * @param string $file
+     * @param array $params
+     * @return string
+     */
+    public function getLocaleFileName($file, array $params = array());
+
+    /**
+     * Find a view file using fallback mechanism
+     *
+     * @param string $file
+     * @param array $params
+     * @return string
+     */
+    public function getViewFile($file, array $params = array());
+
+    /**
+     * Remove all merged js/css files
+     *
+     * @return bool
+     */
+    public function cleanMergedJsCss();
+
+    /**
+     * Get url to file base on theme file identifier.
+     * Publishes file there, if needed.
+     *
+     * @param string $file
+     * @param array $params
+     * @return string
+     */
+    public function getViewFileUrl($file, array $params = array());
+
+    /**
+     * Get URLs to CSS files optimized based on configuration settings
+     *
+     * @param array $files
+     * @return array
+     */
+    public function getOptimalCssUrls($files);
+
+    /**
+     * Get URLs to JS files optimized based on configuration settings
+     *
+     * @param array $files
+     * @return array
+     */
+    public function getOptimalJsUrls($files);
+
+    /**
+     * Return directory for theme files publication
+     *
+     * @return string
+     */
+    public function getPublicDir();
+
+    /**
+     * Render view config object for current package and theme
+     *
+     * @return Magento_Config_View
+     */
+    public function getViewConfig();
+}
diff --git a/app/code/core/Mage/Core/Model/Dir.php b/app/code/core/Mage/Core/Model/Dir.php
index acd4012573b98d5cc28eb886c7b2b3e4244281aa..ef670b8b6015b4d4941aacdf4b39a4b7728f6f14 100644
--- a/app/code/core/Mage/Core/Model/Dir.php
+++ b/app/code/core/Mage/Core/Model/Dir.php
@@ -176,10 +176,11 @@ class Mage_Core_Model_Dir
      * Initialize URIs and paths
      *
      * @param string $baseDir
+     * @param Varien_Io_File $fileSystem
      * @param array $uris custom URIs
      * @param array $dirs custom directories (full system paths)
      */
-    public function __construct($baseDir, array $uris = array(), array $dirs = array())
+    public function __construct($baseDir, Varien_Io_File $fileSystem, array $uris = array(), array $dirs = array())
     {
         // uris
         foreach (array_keys($this->_uris) as $code) {
@@ -202,6 +203,23 @@ class Mage_Core_Model_Dir
         foreach ($this->_getDefaultReplacements($dirs) as $code => $replacement) {
             $this->_setDir($code, $replacement);
         }
+
+        $this->_createFolders($fileSystem);
+    }
+
+    /**
+     * Create application folders if they don't exist
+     *
+     * @param Varien_Io_File $fileSystem
+     */
+    protected function _createFolders(Varien_Io_File $fileSystem)
+    {
+        foreach (self::getWritableDirCodes() as $code) {
+            $path = $this->getDir($code);
+            if ($path) {
+                $fileSystem->checkAndCreateFolder($path);
+            }
+        }
     }
 
     /**
diff --git a/app/code/core/Mage/Core/Model/EntryPoint/Cron.php b/app/code/core/Mage/Core/Model/EntryPoint/Cron.php
new file mode 100644
index 0000000000000000000000000000000000000000..3b612e4ef7755b0229447f471d64cff8ec67ecae
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/EntryPoint/Cron.php
@@ -0,0 +1,42 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_EntryPoint_Cron extends Mage_Core_Model_EntryPointAbstract
+{
+    /**
+     * Process request to application
+     */
+    protected function _processRequest()
+    {
+        /** @var $app Mage_Core_Model_App */
+        $app = $this->_objectManager->get('Mage_Core_Model_App');
+        $app->setUseSessionInUrl(false);
+        $app->requireInstalledInstance();
+
+        /** @var $eventManager Mage_Core_Model_Event_Manager */
+        $eventManager = $this->_objectManager->get('Mage_Core_Model_Event_Manager');
+        $eventManager->addEventArea('crontab');
+        $eventManager->dispatch('default');
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/EntryPoint/Http.php b/app/code/core/Mage/Core/Model/EntryPoint/Http.php
new file mode 100644
index 0000000000000000000000000000000000000000..7424a5777204587597f861901c0a2867ffcabff0
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/EntryPoint/Http.php
@@ -0,0 +1,42 @@
+<?php
+/**
+ * Http entry point
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_EntryPoint_Http extends Mage_Core_Model_EntryPointAbstract
+{
+    /**
+     * Run http application
+     */
+    protected function _processRequest()
+    {
+        try {
+            $request = $this->_objectManager->get('Mage_Core_Controller_Request_Http');
+            $response = $this->_objectManager->get('Mage_Core_Controller_Response_Http');
+            $handler = $this->_objectManager->get('Magento_Http_Handler_Composite');
+            $handler->handle($request, $response);
+        } catch (Exception $e) {
+            Mage::printException($e);
+        }
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/EntryPoint/Media.php b/app/code/core/Mage/Core/Model/EntryPoint/Media.php
new file mode 100644
index 0000000000000000000000000000000000000000..4b1801188832f4fbe3d428a93d1699dd583a46df
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/EntryPoint/Media.php
@@ -0,0 +1,51 @@
+<?php
+/**
+ * Media downloader entry point
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_EntryPoint_Media extends Mage_Core_Model_EntryPointAbstract
+{
+    /**
+     * @param string $baseDir
+     * @param array $mediaDirectory
+     * @param array $params
+     * @param string $objectManagerClass
+     */
+    public function __construct(
+        $baseDir, $mediaDirectory, array $params = array(), $objectManagerClass = 'Mage_Core_Model_ObjectManager_Http'
+    ) {
+        if (empty($mediaDirectory)) {
+            $params[Mage::PARAM_ALLOWED_MODULES] = array('Mage_Core');
+            $params[Mage::PARAM_CACHE_OPTIONS]['disable_save'] = true;
+        }
+        parent::__construct($baseDir, $params, $objectManagerClass);
+    }
+
+    /**
+     * Process request to application
+     */
+    protected function _processRequest()
+    {
+        // TODO: Move configuration file generation and media files materialization here from get.php
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/EntryPointAbstract.php b/app/code/core/Mage/Core/Model/EntryPointAbstract.php
new file mode 100644
index 0000000000000000000000000000000000000000..8cf1a693d5a7eb2ff4e0b179889b34a7e0823b18
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/EntryPointAbstract.php
@@ -0,0 +1,67 @@
+<?php
+/**
+ * Abstract application entry point
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+abstract class Mage_Core_Model_EntryPointAbstract
+{
+    /**
+     * Application object manager
+     *
+     * @var Mage_Core_Model_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * @param string $baseDir
+     * @param array $params
+     * @param Magento_ObjectManager $objectManager
+     */
+    public function __construct(
+        $baseDir, array $params = array(), Magento_ObjectManager $objectManager = null
+    ) {
+        Magento_Profiler::start('mage');
+        if (!array_key_exists(Mage::PARAM_BASEDIR, $params)) {
+            $params[Mage::PARAM_BASEDIR] = $baseDir;
+        }
+        $this->_objectManager = $objectManager ?: new Mage_Core_Model_ObjectManager(
+            new Mage_Core_Model_ObjectManager_Config($params),
+            $baseDir
+        );
+    }
+
+    /**
+     * Entry point specific processing
+     */
+    abstract protected function _processRequest();
+
+    /**
+     * Process request to application
+     */
+    final public function processRequest()
+    {
+        $this->_processRequest();
+        Magento_Profiler::stop('mage');
+    }
+}
+
diff --git a/app/code/core/Mage/Core/Model/Event/Config.php b/app/code/core/Mage/Core/Model/Event/Config.php
new file mode 100644
index 0000000000000000000000000000000000000000..de1773ffef48a98a074a764f39e56dfbdc288d8a
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Event/Config.php
@@ -0,0 +1,96 @@
+<?php
+/**
+ * Event configuration model
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_Event_Config
+{
+    /**
+     * Modules configuration model
+     *
+     * @var Mage_Core_Model_Config_Modules
+     */
+    protected $_config;
+
+    /**
+     * Configuration for events by area
+     *
+     * @var array
+     */
+    protected $_eventAreas = array();
+
+    /**
+     * @param Mage_Core_Model_Config_Modules $config
+     */
+    public function __construct(Mage_Core_Model_Config_Modules $config)
+    {
+        $this->_config = $config;
+    }
+
+    /**
+     * Get area events configuration
+     *
+     * @param   string $area event area
+     * @return  Mage_Core_Model_Config_Element
+     */
+    protected function _getAreaEvent($area)
+    {
+        if (!isset($this->_eventAreas[$area])) {
+            $this->_eventAreas[$area] = $this->_config->getNode($area)->events;
+        }
+        return $this->_eventAreas[$area];
+    }
+
+    /**
+     * Populate event manager with area event observers
+     *
+     * @param Mage_Core_Model_Event_Manager $eventManager
+     * @param $area
+     */
+    public function populate(Mage_Core_Model_Event_Manager $eventManager, $area)
+    {
+        $areaConfig = $this->_getAreaEvent($area);
+        if (!$areaConfig) {
+            return;
+        }
+
+        foreach($areaConfig->children() as $eventName => $eventConfig) {
+            $observers = array();
+            $eventObservers = $eventConfig->observers->children();
+            if (!$eventObservers) {
+                $eventManager->addObservers($area, $eventName, $observers);
+                continue;
+            }
+
+            foreach ($eventObservers as $obsName => $obsConfig) {
+                $observers[$obsName] = array(
+                    'type'  => (string)$obsConfig->type,
+                    'model' => $obsConfig->class ? (string) $obsConfig->class : $obsConfig->getClassName(),
+                    'method'=> (string)$obsConfig->method,
+                );
+            }
+            $eventManager->addObservers($area, $eventName, $observers);
+        }
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Event/Manager.php b/app/code/core/Mage/Core/Model/Event/Manager.php
index d119693d163dfc7a030cb2f311ec4445683b5416..4571447ee04abf8f52453584e2b1c57afcd48c71 100644
--- a/app/code/core/Mage/Core/Model/Event/Manager.php
+++ b/app/code/core/Mage/Core/Model/Event/Manager.php
@@ -30,14 +30,140 @@
 class Mage_Core_Model_Event_Manager
 {
     /**
-     * Dispatch global event with provided params
+     * Events cache
      *
-     * @param string $eventName
-     * @param array $params
+     * @var array
+     */
+    protected $_events = array();
+
+    /**
+     * Observer model factory
+     *
+     * @var Mage_Core_Model_ObserverFactory
+     */
+    protected $_observerFactory;
+
+    /**
+     * Observer model factory
+     *
+     * @var Mage_Core_Model_Event_Config
+     */
+    protected $_eventConfig;
+
+    /**
+     * @param Mage_Core_Model_ObserverFactory $observerFactory
+     * @param Mage_Core_Model_Event_Config $eventConfig
+     */
+    public function __construct(
+        Mage_Core_Model_ObserverFactory $observerFactory,
+        Mage_Core_Model_Event_Config $eventConfig
+    ) {
+        $this->_observerFactory = $observerFactory;
+        $this->_eventConfig = $eventConfig;
+        $this->addEventArea(Mage_Core_Model_App_Area::AREA_GLOBAL);
+    }
+
+    /**
+     * Performs non-existent observer method calls protection
+     *
+     * @param object $object
+     * @param string $method
+     * @param Varien_Event_Observer $observer
      * @return Mage_Core_Model_App
+     * @throws Mage_Core_Exception
+     */
+    protected function _callObserverMethod($object, $method, $observer)
+    {
+        if (method_exists($object, $method)) {
+            $object->$method($observer);
+        } elseif (Mage::getIsDeveloperMode()) {
+            Mage::throwException('Method "' . $method . '" is not defined in "' . get_class($object) . '"');
+        }
+        return $this;
+    }
+
+    /**
+     * Dispatch event
+     *
+     * Calls all observer callbacks registered for this event
+     * and multiple observers matching event name pattern
+     *
+     * @param string $eventName
+     * @param array $data
      */
-    public function dispatch($eventName, array $params = array())
+    public function dispatch($eventName, array $data = array())
     {
-        return Mage::dispatchEvent($eventName, $params);
+        Magento_Profiler::start('EVENT:' . $eventName, array('group' => 'EVENT', 'name' => $eventName));
+        foreach ($this->_events as $area => $events) {
+            if (false == isset($events[$eventName])) {
+                continue;
+            }
+
+            $event = new Varien_Event($data);
+            $event->setName($eventName);
+            $observer = new Varien_Event_Observer();
+
+            foreach ($this->_events[$area][$eventName] as $obsName => $obsConfiguration) {
+                $observer->setData(array('event' => $event));
+                Magento_Profiler::start('OBSERVER:' . $obsName);
+                switch ($obsConfiguration['type']) {
+                    case 'disabled':
+                        break;
+                    case 'object':
+                    case 'model':
+                        $method = $obsConfiguration['method'];
+                        $observer->addData($data);
+                        $object = $this->_observerFactory->create($obsConfiguration['model']);
+                        $this->_callObserverMethod($object, $method, $observer);
+                        break;
+                    default:
+                        $method = $obsConfiguration['method'];
+                        $observer->addData($data);
+                        $object = $this->_observerFactory->get($obsConfiguration['model']);
+                        $this->_callObserverMethod($object, $method, $observer);
+                        break;
+                }
+                Magento_Profiler::stop('OBSERVER:' . $obsName);
+            }
+        }
+
+        Magento_Profiler::stop('EVENT:' . $eventName);
+    }
+
+    /**
+     * Add event area
+     *
+     * @param string $area
+     * @return Mage_Core_Model_Event_Manager
+     */
+    public function addEventArea($area)
+    {
+        if (!isset($this->_events[$area])) {
+            Magento_Profiler::start('config_event_' . $area);
+            $this->_events[$area] = array();
+            $this->_eventConfig->populate($this, $area);
+            Magento_Profiler::stop('config_event_' . $area);
+        }
+        return $this;
+    }
+
+    /**
+     * Add event observer
+     *
+     * @param string $area
+     * @param string $eventName
+     * @param array $observers example array('observerName' => array('type' => ..., 'model' => ..., 'method' => ... ),)
+     */
+    public function addObservers($area, $eventName, array $observers)
+    {
+        if (!isset($this->_events[$area])) {
+             $this->addEventArea($area);
+        }
+
+        $existingObservers = array();
+        if (isset($this->_events[$area][$eventName])) {
+            $existingObservers = $this->_events[$area][$eventName];
+        }
+        $this->_events[$area][$eventName] = array_merge($existingObservers, $observers);
     }
 }
diff --git a/app/code/core/Mage/Core/Model/File/Storage.php b/app/code/core/Mage/Core/Model/File/Storage.php
index 9284a5c66a20e6a7f87eefc597b63af3be55857c..28d369c5aed817271219234ebd3669dfaf64dd75 100644
--- a/app/code/core/Mage/Core/Model/File/Storage.php
+++ b/app/code/core/Mage/Core/Model/File/Storage.php
@@ -222,8 +222,8 @@ class Mage_Core_Model_File_Storage extends Mage_Core_Model_Abstract
         $config = array();
         $config['media_directory'] = Mage::getBaseDir('media');
 
-        $allowedResources = (array) Mage::app()->getConfig()->getNode(self::XML_PATH_MEDIA_RESOURCE_WHITELIST);
-        foreach ($allowedResources as $key => $allowedResource) {
+        $allowedResources = (array) Mage::getConfig()->getNode(self::XML_PATH_MEDIA_RESOURCE_WHITELIST);
+        foreach ($allowedResources as $allowedResource) {
             $config['allowed_resources'][] = $allowedResource;
         }
 
diff --git a/app/code/core/Mage/Core/Model/Layout.php b/app/code/core/Mage/Core/Model/Layout.php
index 3d0e8fa04d3e5b9e206b375f21bfc3c3bdf512ef..d13182b982edfbb6b2c908dc652bd0fed3a9c111 100644
--- a/app/code/core/Mage/Core/Model/Layout.php
+++ b/app/code/core/Mage/Core/Model/Layout.php
@@ -198,7 +198,7 @@ class Mage_Core_Model_Layout extends Varien_Simplexml_Config
         $this->_structure = $structure;
         $this->_argumentProcessor = $argumentProcessor;
         $this->_translator = $translator;
-        $this->_elementClass = Mage::getConfig()->getModelClassName('Mage_Core_Model_Layout_Element');
+        $this->_elementClass = 'Mage_Core_Model_Layout_Element';
         $this->setXml(simplexml_load_string('<layout/>', $this->_elementClass));
         $this->_renderingOutput = new Varien_Object;
         $this->_scheduledStructure = $scheduledStructure;
@@ -1339,7 +1339,6 @@ class Mage_Core_Model_Layout extends Varien_Simplexml_Config
     protected function _getBlockInstance($block, array $attributes = array())
     {
         if ($block && is_string($block)) {
-            $block = Mage::getConfig()->getBlockClassName($block);
             if (class_exists($block)) {
                 $block = $this->_blockFactory->createBlock($block, $attributes);
             }
@@ -1465,8 +1464,7 @@ class Mage_Core_Model_Layout extends Varien_Simplexml_Config
     public function getBlockSingleton($type)
     {
         if (!isset($this->_helpers[$type])) {
-            $className = Mage::getConfig()->getBlockClassName($type);
-            if (!$className) {
+            if (!$type) {
                 Mage::throwException(Mage::helper('Mage_Core_Helper_Data')->__('Invalid block type: %s', $type));
             }
 
diff --git a/app/code/core/Mage/Core/Model/Layout/Element.php b/app/code/core/Mage/Core/Model/Layout/Element.php
index cae704c514e56961bd985674ffc6406f51eaec53..615816ccd3ad6caa18b1d53a2d367b3e7db8973b 100644
--- a/app/code/core/Mage/Core/Model/Layout/Element.php
+++ b/app/code/core/Mage/Core/Model/Layout/Element.php
@@ -110,12 +110,10 @@ class Mage_Core_Model_Layout_Element extends Varien_Simplexml_Element
     public function prepareBlock($args)
     {
         $type = (string)$this['type'];
-        $name = (string)$this['name'];
 
         $className = (string)$this['class'];
         if (!$className) {
-            $className = Mage::getConfig()->getBlockClassName($type);
-            $this->addAttribute('class', $className);
+            $this->addAttribute('class', $type);
         }
 
         $parent = $this->getParent();
diff --git a/app/code/core/Mage/Core/Model/Layout/Merge.php b/app/code/core/Mage/Core/Model/Layout/Merge.php
index e168830d79f0702fc34e88b22cac3a8ebbd51f6c..3bd70c94b2ce9f0ed8df20dc19dccfc32c2ff61a 100644
--- a/app/code/core/Mage/Core/Model/Layout/Merge.php
+++ b/app/code/core/Mage/Core/Model/Layout/Merge.php
@@ -118,7 +118,7 @@ class Mage_Core_Model_Layout_Merge
         }
 
         $this->_storeId = Mage::app()->getStore(empty($arguments['store']) ? null : $arguments['store'])->getId();
-        $this->_elementClass = Mage::getConfig()->getModelClassName('Mage_Core_Model_Layout_Element');
+        $this->_elementClass = 'Mage_Core_Model_Layout_Element';
 
         foreach (Mage::getConfig()->getPathVars() as $key => $value) {
             $this->_subst['from'][] = '{{' . $key . '}}';
diff --git a/app/code/core/Mage/Core/Model/Layout/Merge/Factory.php b/app/code/core/Mage/Core/Model/Layout/Merge/Factory.php
new file mode 100644
index 0000000000000000000000000000000000000000..ea725c32ff59a804e80a670c62ebaa815edca7cd
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Layout/Merge/Factory.php
@@ -0,0 +1,58 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_Core
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Layout merge model factory
+ */
+class Mage_Core_Model_Layout_Merge_Factory
+{
+    /**
+     * Default layout class name
+     */
+    const CLASS_NAME = 'Mage_Core_Model_Layout_Merge';
+
+    /**
+     * @var Magento_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * @param Magento_ObjectManager $objectManager
+     */
+    public function __construct(Magento_ObjectManager $objectManager)
+    {
+        $this->_objectManager = $objectManager;
+    }
+
+    /**
+     * @param array $arguments
+     * @return Mage_Core_Model_Layout_Merge
+     */
+    public function create(array $arguments = array())
+    {
+        return $this->_objectManager->create(self::CLASS_NAME, $arguments);
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Locale/Hierarchy/Loader.php b/app/code/core/Mage/Core/Model/Locale/Hierarchy/Loader.php
new file mode 100644
index 0000000000000000000000000000000000000000..836778fbbfb67f115ddd0be8aad2091ff04ac3be
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Locale/Hierarchy/Loader.php
@@ -0,0 +1,90 @@
+<?php
+/**
+ * Locale inheritance hierarchy loader
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_Locale_Hierarchy_Loader
+{
+    const XML_PATH_LOCALE_INHERITANCE = 'global/locale/inheritance';
+
+    /**
+     * @var Mage_Core_Model_Config_Locales
+     */
+    protected $_config;
+
+    /**
+     * Locales configuration model
+     *
+     * @param Mage_Core_Model_Config_Locales $config
+     */
+    public function __construct(Mage_Core_Model_Config_Locales $config)
+    {
+        $this->_config = $config;
+    }
+
+    /**
+     * Compose locale inheritance hierarchy based on given config
+     *
+     * @param array|string $localeConfig assoc array where key is a code of locale and value is a code of its parent locale
+     * @return array
+     */
+    protected function _composeLocaleHierarchy($localeConfig)
+    {
+        $localeHierarchy = array();
+        if (!is_array($localeConfig)) {
+            return $localeHierarchy;
+        }
+
+        foreach ($localeConfig as $locale => $localeParent) {
+            $localeParents = array($localeParent);
+            while (isset($localeConfig[$localeParent]) && !in_array($localeConfig[$localeParent], $localeParents)
+                && $locale != $localeConfig[$localeParent]
+            ) {
+                // inheritance chain starts with the deepest parent
+                array_unshift($localeParents, $localeConfig[$localeParent]);
+                $localeParent = $localeConfig[$localeParent];
+            }
+            // store hierarchy for current locale
+            $localeHierarchy[$locale] = $localeParents;
+        }
+        return $localeHierarchy;
+    }
+
+    /**
+     * Load locales inheritance hierarchy
+     *
+     * @return array
+     */
+    public function load()
+    {
+        $localeHierarchy = array();
+        $inheritanceNode = $this->_config->getNode(self::XML_PATH_LOCALE_INHERITANCE);
+        if ($inheritanceNode instanceof Varien_Simplexml_Element) {
+            $localeHierarchy = $this->_composeLocaleHierarchy(
+                $inheritanceNode->asCanonicalArray()
+            );
+        }
+        return $localeHierarchy;
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Logger.php b/app/code/core/Mage/Core/Model/Logger.php
index b3f1509a39672c7ec3c4ddb1bb27c38b3bd3fc8d..74bc77178c1004c79692fe1625ac0836ef390e19 100644
--- a/app/code/core/Mage/Core/Model/Logger.php
+++ b/app/code/core/Mage/Core/Model/Logger.php
@@ -46,9 +46,21 @@ class Mage_Core_Model_Logger
      */
     protected $_dirs = null;
 
-    public function __construct(Mage_Core_Model_Dir $dirs)
+    /**
+     * @var Varien_Io_File
+     */
+    protected $_fileSystem;
+
+    /**
+     * @param Mage_Core_Model_Dir $dirs
+     * @param Varien_Io_File $fileSystem
+     */
+    public function __construct(Mage_Core_Model_Dir $dirs, Varien_Io_File $fileSystem, $defaultFile = '')
     {
         $this->_dirs = $dirs;
+        $this->_fileSystem = $fileSystem;
+        $this->addStreamLog(Mage_Core_Model_Logger::LOGGER_SYSTEM, $defaultFile)
+            ->addStreamLog(Mage_Core_Model_Logger::LOGGER_EXCEPTION, $defaultFile);
     }
 
     /**
@@ -67,6 +79,7 @@ class Mage_Core_Model_Logger
         $file = $fileOrWrapper ?: "{$loggerKey}.log";
         if (!preg_match('#^[a-z][a-z0-9+.-]*\://#i', $file)) {
             $logDir = $this->_dirs->getDir(Mage_Core_Model_Dir::LOG);
+            $this->_fileSystem->checkAndCreateFolder($logDir);
             $file = $logDir . DIRECTORY_SEPARATOR . $file;
         }
         if (!$writerClass || !is_subclass_of($writerClass, 'Zend_Log_Writer_Stream')) {
@@ -85,9 +98,9 @@ class Mage_Core_Model_Logger
      * Reset all loggers and initialize them according to store configuration
      *
      * @param Mage_Core_Model_Store $store
-     * @param Mage_Core_Model_Config $config
+     * @param Mage_Core_Model_ConfigInterface $config
      */
-    public function initForStore(Mage_Core_Model_Store $store, Mage_Core_Model_Config $config)
+    public function initForStore(Mage_Core_Model_Store $store, Mage_Core_Model_ConfigInterface $config)
     {
         $this->_loggers = array();
         if ($store->getConfig('dev/log/active')) {
diff --git a/app/code/core/Mage/Core/Model/ObjectManager.php b/app/code/core/Mage/Core/Model/ObjectManager.php
new file mode 100644
index 0000000000000000000000000000000000000000..c600b5d110d844008dc9312e1361ae708ef79902
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/ObjectManager.php
@@ -0,0 +1,50 @@
+<?php
+/**
+ * Magento application object manager. Configures and application application
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_ObjectManager extends Magento_ObjectManager_Zend
+{
+    /**
+     * @param Magento_ObjectManager_Configuration $configuration
+     * @param string $baseDir
+     * @param Magento_Di $diInstance
+     * @param Magento_Di_InstanceManager $instanceManager
+     */
+    public function __construct(
+        Magento_ObjectManager_Configuration $configuration,
+        $baseDir,
+        Magento_Di $diInstance = null,
+        Magento_Di_InstanceManager $instanceManager = null
+    ) {
+        Magento_Profiler::start('di');
+        Magento_Profiler::start('definitions');
+        parent::__construct($baseDir . '/var/di/definitions.php', $diInstance, $instanceManager);
+        Magento_Profiler::stop('definitions');
+        Mage::setObjectManager($this);
+        Magento_Profiler::start('configuration');
+        $configuration->configure($this);
+        Magento_Profiler::stop('configuration');
+        Magento_Profiler::stop('di');
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/ObjectManager/Config.php b/app/code/core/Mage/Core/Model/ObjectManager/Config.php
new file mode 100644
index 0000000000000000000000000000000000000000..344b6d457049f9e1ee50387f106539c5571123da
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/ObjectManager/Config.php
@@ -0,0 +1,152 @@
+<?php
+/**
+ * Object Manager config
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_ObjectManager_Config extends Mage_Core_Model_ObjectManager_ConfigAbstract
+{
+    /**
+     * Initial configuration required to load main configuration
+     *
+     * @var array
+     */
+    protected $_initialConfig = array(
+        'preference' => array(
+            'Mage_Core_Model_Db_UpdaterInterface' => 'Mage_Core_Model_Db_Updater',
+            'Mage_Core_Model_AppInterface' => 'Mage_Core_Model_App_Proxy',
+            'Mage_Core_Model_Config_InvalidatorInterface' => 'Mage_Core_Model_Config_Invalidator_Proxy',
+        ),
+        'Mage_Core_Model_Cache' => array(
+            'parameters' => array('config' => 'Mage_Core_Model_Config_Proxy')
+        ),
+        'Mage_Core_Model_Config' => array(
+            'parameters' => array('storage' => 'Mage_Core_Model_Config_Storage')
+        ),
+        'Mage_Core_Model_Config_Container' => array(
+            'parameters' => array('configCache' => 'Mage_Core_Model_Config_Cache_Proxy')
+        ),
+        'Mage_Core_Model_Config_Resource' => array(
+            'parameters' => array('config' => 'Mage_Core_Model_Config_Primary')
+        ),
+        'Mage_Core_Model_Config_Locales' => array(
+            'parameters' => array('storage' => 'Mage_Core_Model_Config_Storage_Locales')
+        ),
+        'Mage_Core_Model_Config_Modules' => array(
+            'parameters' => array('storage' => 'Mage_Core_Model_Config_Storage_Modules')
+        ),
+        'Mage_Core_Model_Config_Storage' => array(
+            'parameters' => array('loader' => 'Mage_Core_Model_Config_Loader_Proxy')
+        ),
+        'Mage_Core_Model_Config_Storage_Modules' => array(
+            'parameters' => array('loader' => 'Mage_Core_Model_Config_Loader_Modules_Proxy')
+        ),
+        'Mage_Core_Model_Config_Storage_Locales' => array(
+            'parameters' => array('loader' => 'Mage_Core_Model_Config_Loader_Locales_Proxy')
+        ),
+        'Mage_Core_Model_Event_Config' => array(
+            'parameters' => array('config' => 'Mage_Core_Model_Config_Modules_Proxy')
+        ),
+        'Mage_Install_Model_Installer' => array(
+            'parameters' => array('config' => 'Mage_Core_Model_Config_Proxy')
+        ),
+        'Mage_Core_Model_Config_Invalidator' => array(
+            'parameters' => array(
+                'primaryConfig' => 'Mage_Core_Model_Config_Primary',
+                'modulesConfig' => 'Mage_Core_Model_Config_Modules',
+                'localesConfig' => 'Mage_Core_Model_Config_Locales',
+            )
+        ),
+        'Magento_Filesystem' => array(
+            'parameters' => array(
+                'adapter' => 'Magento_Filesystem_Adapter_Local'
+            ),
+            'shared' => 0
+        )
+    );
+
+    /**
+     * Configure object manager
+     *
+     * @param Magento_ObjectManager $objectManager
+     */
+    public function configure(Magento_ObjectManager $objectManager)
+    {
+        Magento_Profiler::start('initial');
+        $objectManager->setConfiguration(array_replace_recursive(
+            $this->_initialConfig,
+            array(
+                'Mage_Core_Model_Dir' => array(
+                    'parameters' => array(
+                        'baseDir' => $this->_getParam(Mage::PARAM_BASEDIR),
+                        'uris' => $this->_getParam(MAGE::PARAM_APP_URIS, array()),
+                        'dirs' => $this->_getParam(Mage::PARAM_APP_DIRS, array())
+                    )
+                ),
+                'Mage_Core_Model_Config_Loader_Local' => array(
+                    'parameters' => array(
+                        'customFile' => $this->_getParam(Mage::PARAM_CUSTOM_LOCAL_FILE),
+                        'customConfig' => $this->_getParam(Mage::PARAM_CUSTOM_LOCAL_CONFIG)
+                    )
+                ),
+                'Mage_Core_Model_Config_Loader_Modules' => array(
+                    'parameters' => array('allowedModules' => $this->_getParam(Mage::PARAM_ALLOWED_MODULES, array()))
+                ),
+                'Mage_Core_Model_Cache' => array(
+                    'parameters' => array(
+                        'options' => $this->_getParam(Mage::PARAM_CACHE_OPTIONS, array()),
+                        'banCache' => $this->_getParam(Mage::PARAM_BAN_CACHE, false),
+                    )
+                ),
+                'Mage_Core_Model_StoreManager' => array(
+                    'parameters' => array(
+                        'scopeCode' => $this->_getParam(Mage::PARAM_RUN_CODE, ''),
+                        'scopeType' => $this->_getParam(Mage::PARAM_RUN_TYPE, 'store'),
+                    )
+                )
+            )
+        ));
+
+        Magento_Profiler::start('primary_load');
+        /** @var $config Mage_Core_Model_Config_Primary*/
+        $config = $objectManager->get('Mage_Core_Model_Config_Primary');
+        Magento_Profiler::stop('primary_load');
+        $configurators = $config->getNode('global/configurators');
+        if ($configurators) {
+            $configurators = $configurators->asArray();
+            if (count($configurators)) {
+                foreach ($configurators as $configuratorClass) {
+                    /** @var $configurator  Magento_ObjectManager_Configuration*/
+                    $configurator = $objectManager->create($configuratorClass, array('params' => $this->_params));
+                    $configurator->configure($objectManager);
+                }
+            }
+        }
+        Magento_Profiler::stop('initial');
+        Magento_Profiler::start('global_primary');
+        $diConfig = $config->getNode('global/di');
+        if ($diConfig) {
+            $objectManager->setConfiguration($diConfig->asArray());
+        }
+        Magento_Profiler::stop('global_primary');
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/ObjectManager/ConfigAbstract.php b/app/code/core/Mage/Core/Model/ObjectManager/ConfigAbstract.php
new file mode 100644
index 0000000000000000000000000000000000000000..78e6122ec3c57f135068fedc0326ca2068c2b858
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/ObjectManager/ConfigAbstract.php
@@ -0,0 +1,54 @@
+<?php
+/**
+ * Abstract object manager initializer
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+abstract class Mage_Core_Model_ObjectManager_ConfigAbstract implements Magento_ObjectManager_Configuration
+{
+    /**
+     * Runtime configuration params
+     *
+     * @var array
+     */
+    protected $_params = array();
+
+    /**
+     * @param array $params
+     */
+    public function __construct($params)
+    {
+        $this->_params = $params;
+    }
+
+    /**
+     * Get init param
+     *
+     * @param string $name
+     * @param mixed $defaultValue
+     * @return mixed
+     */
+    protected function _getParam($name, $defaultValue = null)
+    {
+        return isset($this->_params[$name]) ? $this->_params[$name] : $defaultValue;
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/ObserverFactory.php b/app/code/core/Mage/Core/Model/ObserverFactory.php
new file mode 100644
index 0000000000000000000000000000000000000000..8f0834935be42a002ed4d8ca35ce791962fc8712
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/ObserverFactory.php
@@ -0,0 +1,65 @@
+<?php
+/**
+ * Observer model factory
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_ObserverFactory
+{
+    /**
+     * @var Magento_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * @param Magento_ObjectManager $objectManager
+     */
+    public function __construct(Magento_ObjectManager $objectManager)
+    {
+        $this->_objectManager = $objectManager;
+    }
+
+    /**
+     * Get observer model instance
+     *
+     * @param string $className
+     * @param array $arguments
+     * @return Mage_Core_Model_Abstract|bool
+     */
+    public function get($className, array $arguments = array())
+    {
+        return $this->_objectManager->get($className, $arguments);
+    }
+
+    /**
+     * Create observer model instance
+     *
+     * @param string $className
+     * @param array $arguments
+     * @return Mage_Core_Model_Abstract|bool
+     */
+    public function create($className, array $arguments = array())
+    {
+        return $this->_objectManager->create($className, $arguments);
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Resource.php b/app/code/core/Mage/Core/Model/Resource.php
index af3bcc3d7c3453a52d37a8f47f823974d32d5e34..ba4e273803fcceef53d2a9db28609b0864b474a0 100644
--- a/app/code/core/Mage/Core/Model/Resource.php
+++ b/app/code/core/Mage/Core/Model/Resource.php
@@ -69,6 +69,50 @@ class Mage_Core_Model_Resource
      */
     protected $_mappedTableNames;
 
+    /**
+     * Resource configuration
+     *
+     * @var Mage_Core_Model_Config_Resource
+     */
+    protected $_resourceConfig;
+
+    /**
+     * Application cache
+     *
+     * @var Mage_Core_Model_Cache
+     */
+    protected $_cache;
+
+    /**
+     * @param Mage_Core_Model_Config_Resource $resourceConfig
+     * @param Mage_Core_Model_Cache $cache
+     */
+    public function __construct(Mage_Core_Model_Config_Resource $resourceConfig, Mage_Core_Model_Cache $cache)
+    {
+        $this->_resourceConfig = $resourceConfig;
+        $this->_cache = $cache;
+    }
+
+    /**
+     * Set resource configuration
+     *
+     * @param Mage_Core_Model_Config_Resource $resourceConfig
+     */
+    public function setResourceConfig(Mage_Core_Model_Config_Resource $resourceConfig)
+    {
+        $this->_resourceConfig = $resourceConfig;
+    }
+
+    /**
+     * Set cache instance
+     *
+     * @param Mage_Core_Model_CacheInterface $cache
+     */
+    public function setCache(Mage_Core_Model_CacheInterface $cache)
+    {
+        $this->_cache = $cache;
+    }
+
     /**
      * Creates a connection to resource whenever needed
      *
@@ -79,13 +123,13 @@ class Mage_Core_Model_Resource
     {
         if (isset($this->_connections[$name])) {
             $connection = $this->_connections[$name];
-            if (isset($this->_skippedConnections[$name]) && !Mage::app()->getIsCacheLocked()) {
+            if (isset($this->_skippedConnections[$name])) {
                 $connection->setCacheAdapter(Mage::app()->getCache());
                 unset($this->_skippedConnections[$name]);
             }
             return $connection;
         }
-        $connConfig = Mage::getConfig()->getResourceConnectionConfig($name);
+        $connConfig = $this->_resourceConfig->getResourceConnectionConfig($name);
 
         if (!$connConfig) {
             $this->_connections[$name] = $this->_getDefaultConnection($name);
@@ -103,11 +147,7 @@ class Mage_Core_Model_Resource
 
         $connection = $this->_newConnection((string)$connConfig->type, $connConfig);
         if ($connection) {
-            if (Mage::app()->getIsCacheLocked()) {
-                $this->_skippedConnections[$name] = true;
-            } else {
-                $connection->setCacheAdapter(Mage::app()->getCache());
-            }
+            $connection->setCacheAdapter($this->_cache->getFrontend());
         }
 
         $this->_connections[$name] = $connection;
@@ -126,7 +166,7 @@ class Mage_Core_Model_Resource
      */
     protected function _getConnectionAdapterClassName($type)
     {
-        $config = Mage::getConfig()->getResourceTypeConfig($type);
+        $config = $this->_resourceConfig->getResourceTypeConfig($type);
         if (!empty($config->adapter)) {
             return (string)$config->adapter;
         }
@@ -214,7 +254,7 @@ class Mage_Core_Model_Resource
     public function getConnectionTypeInstance($type)
     {
         if (!isset($this->_connectionTypes[$type])) {
-            $config = Mage::getConfig()->getResourceTypeConfig($type);
+            $config = $this->_resourceConfig->getResourceTypeConfig($type);
             $typeClass = $config->getClassName();
             $this->_connectionTypes[$type] = new $typeClass();
         }
@@ -236,18 +276,11 @@ class Mage_Core_Model_Resource
 
         $tableName = $modelEntity;
 
-        Mage::dispatchEvent('resource_get_tablename', array(
-            'resource'      => $this,
-            'model_entity'  => $modelEntity,
-            'table_name'    => $tableName,
-            'table_suffix'  => $tableSuffix
-        ));
-
         $mappedTableName = $this->getMappedTableName($tableName);
         if ($mappedTableName) {
             $tableName = $mappedTableName;
         } else {
-            $tablePrefix = (string)Mage::getConfig()->getTablePrefix();
+            $tablePrefix = (string)$this->_resourceConfig->getTablePrefix();
             if ($tablePrefix && strpos($tableName, $tablePrefix) !== 0) {
                 $tableName = $tablePrefix . $tableName;
             }
diff --git a/app/code/core/Mage/Core/Model/Resource/Config.php b/app/code/core/Mage/Core/Model/Resource/Config.php
index edd72944ba80ce83fe7edc3379c6362375add5a2..84c35811b951799813f8a43ffffe571e62903f39 100644
--- a/app/code/core/Mage/Core/Model/Resource/Config.php
+++ b/app/code/core/Mage/Core/Model/Resource/Config.php
@@ -46,11 +46,11 @@ class Mage_Core_Model_Resource_Config extends Mage_Core_Model_Resource_Db_Abstra
     /**
      * Load configuration values into xml config object
      *
-     * @param Mage_Core_Model_Config $xmlConfig
+     * @param Mage_Core_Model_Config_Base $xmlConfig
      * @param string $condition
      * @return Mage_Core_Model_Resource_Config
      */
-    public function loadToXml(Mage_Core_Model_Config $xmlConfig, $condition = null)
+    public function loadToXml(Mage_Core_Model_Config_Base $xmlConfig, $condition = null)
     {
         $read = $this->_getReadAdapter();
         if (!$read) {
diff --git a/app/code/core/Mage/Core/Model/Resource/Db/Collection/Abstract.php b/app/code/core/Mage/Core/Model/Resource/Db/Collection/Abstract.php
index 46c41c4b2c9d2211573cd3466c1ff1570ef02435..9d6445e4fc2138c291e0f2ff61b9f3fadd03cec9 100644
--- a/app/code/core/Mage/Core/Model/Resource/Db/Collection/Abstract.php
+++ b/app/code/core/Mage/Core/Model/Resource/Db/Collection/Abstract.php
@@ -74,7 +74,7 @@ abstract class Mage_Core_Model_Resource_Db_Collection_Abstract extends Varien_Da
     /**
      * Fields to select changed flag
      *
-     * @var booleam
+     * @var boolean
      */
     protected $_fieldsToSelectChanged  = false;
 
@@ -340,14 +340,14 @@ abstract class Mage_Core_Model_Resource_Db_Collection_Abstract extends Varien_Da
      *
      * @param string $alias
      * @param string $expression
-     * @param array $fields
+     * @param array|string $fields
      * @return Mage_Core_Model_Resource_Db_Collection_Abstract
      */
     public function addExpressionFieldToSelect($alias, $expression, $fields)
     {
         // validate alias
         if (!is_array($fields)) {
-            $fields = array($fields=>$fields);
+            $fields = array($fields => $fields);
         }
 
         $fullExpression = $expression;
@@ -422,7 +422,7 @@ abstract class Mage_Core_Model_Resource_Db_Collection_Abstract extends Varien_Da
     {
         if (is_string($model)) {
             $this->_model = $model;
-            $this->setItemObjectClass(Mage::getConfig()->getModelClassName($model));
+            $this->setItemObjectClass($model);
         }
         return $this;
     }
@@ -653,7 +653,8 @@ abstract class Mage_Core_Model_Resource_Db_Collection_Abstract extends Varien_Da
      */
     protected function _canUseCache()
     {
-        return Mage::app()->useCache('collections') && !empty($this->_cacheConf);
+        return Mage::getObjectManager()->get('Mage_Core_Model_Cache')->canUse('collections')
+            && !empty($this->_cacheConf);
     }
 
     /**
@@ -664,7 +665,7 @@ abstract class Mage_Core_Model_Resource_Db_Collection_Abstract extends Varien_Da
      */
     protected function _loadCache($select)
     {
-        $data = Mage::app()->loadCache($this->_getSelectCacheId($select));
+        $data = Mage::getObjectManager()->get('Mage_Core_Model_Cache')->load($this->_getSelectCacheId($select));
         return $data;
     }
 
@@ -677,7 +678,9 @@ abstract class Mage_Core_Model_Resource_Db_Collection_Abstract extends Varien_Da
      */
     protected function _saveCache($data, $select)
     {
-        Mage::app()->saveCache(serialize($data), $this->_getSelectCacheId($select), $this->_getCacheTags());
+        Mage::getObjectManager()->get('Mage_Core_Model_Cache')->save(
+            serialize($data), $this->_getSelectCacheId($select), $this->_getCacheTags(), false
+        );
         return $this;
     }
 
@@ -689,7 +692,7 @@ abstract class Mage_Core_Model_Resource_Db_Collection_Abstract extends Varien_Da
     protected function _getCacheTags()
     {
         $tags = parent::_getCacheTags();
-        $tags[] = Mage_Core_Model_App::CACHE_TAG;
+        $tags[] = Mage_Core_Model_AppInterface::CACHE_TAG;
         $tags[] = self::CACHE_TAG;
         return $tags;
     }
@@ -705,7 +708,4 @@ abstract class Mage_Core_Model_Resource_Db_Collection_Abstract extends Varien_Da
     {
         return Varien_Date::formatDate($date, $includeTime);
     }
-
-
-
 }
diff --git a/app/code/core/Mage/Core/Model/Resource/Setup.php b/app/code/core/Mage/Core/Model/Resource/Setup.php
index 21523516e89f7d02cd7d168cbda96ffa304052ea..ccceb25c2e720a47169704efda63d37a535ec5b1 100644
--- a/app/code/core/Mage/Core/Model/Resource/Setup.php
+++ b/app/code/core/Mage/Core/Model/Resource/Setup.php
@@ -31,20 +31,8 @@
  * @package     Mage_Core
  * @author      Magento Core Team <core@magentocommerce.com>
  */
-class Mage_Core_Model_Resource_Setup
+class Mage_Core_Model_Resource_Setup implements Mage_Core_Model_Resource_SetupInterface
 {
-    const DEFAULT_SETUP_CONNECTION  = 'core_setup';
-    const VERSION_COMPARE_EQUAL     = 0;
-    const VERSION_COMPARE_LOWER     = -1;
-    const VERSION_COMPARE_GREATER   = 1;
-
-    const TYPE_DB_INSTALL           = 'install';
-    const TYPE_DB_UPGRADE           = 'upgrade';
-    const TYPE_DB_ROLLBACK          = 'rollback';
-    const TYPE_DB_UNINSTALL         = 'uninstall';
-    const TYPE_DATA_INSTALL         = 'data-install';
-    const TYPE_DATA_UPGRADE         = 'data-upgrade';
-
     /**
      * Setup resource name
      * @var string
@@ -54,21 +42,21 @@ class Mage_Core_Model_Resource_Setup
     /**
      * Setup resource configuration object
      *
-     * @var Varien_Simplexml_Object
+     * @var Varien_Simplexml_Element
      */
     protected $_resourceConfig;
 
     /**
      * Connection configuration object
      *
-     * @var Varien_Simplexml_Object
+     * @var Varien_Simplexml_Element
      */
     protected $_connectionConfig;
 
     /**
      * Setup module configuration object
      *
-     * @var Varien_Simplexml_Object
+     * @var Varien_Simplexml_Element
      */
     protected $_moduleConfig;
 
@@ -106,44 +94,61 @@ class Mage_Core_Model_Resource_Setup
     protected $_queriesHooked = false;
 
     /**
-     * Flag which allow to detect that some schema update was applied dueting request
+     * Modules configuration
      *
-     * @var bool
+     * @var Mage_Core_Model_Resource
      */
-    protected static $_hadUpdates;
+    protected $_resourceModel;
 
     /**
-     * Flag which allow run data install or upgrade
+     * Modules configuration reader
      *
-     * @var bool
+     * @var Mage_Core_Model_Config_Modules_Reader
+     */
+    protected $_modulesReader;
+
+    /**
+     * @var Mage_Core_Model_Config_Modules
      */
-    protected static $_schemaUpdatesChecked;
+    protected $_config;
 
     /**
      * Initialize resource configurations, setup connection, etc
      *
-     * @param string $resourceName the setup resource name
-     */
-    public function __construct($resourceName)
-    {
-        $config = Mage::getConfig();
+     * @param Mage_Core_Model_Config_Resource $resourcesConfig
+     * @param Mage_Core_Model_Config_Modules $modulesConfig
+     * @param Mage_Core_Model_Resource $resource
+     * @param Mage_Core_Model_Config_Modules_Reader $modulesReader
+     * @param string $resourceName
+     */
+    public function __construct(
+        Mage_Core_Model_Config_Resource $resourcesConfig,
+        Mage_Core_Model_Config_Modules $modulesConfig,
+        Mage_Core_Model_Resource $resource,
+        Mage_Core_Model_Config_Modules_Reader $modulesReader,
+        $resourceName
+    ) {
+        $resourcesConfig->setConfig($modulesConfig);
+        $this->_config = $modulesConfig;
+        $this->_resourceModel = $resource;
         $this->_resourceName = $resourceName;
-        $this->_resourceConfig = $config->getResourceConfig($resourceName);
-        $connection = $config->getResourceConnectionConfig($resourceName);
+        $this->_modulesReader = $modulesReader;
+        $this->_resourceConfig = $resourcesConfig->getResourceConfig($resourceName);
+        $connection = $resourcesConfig->getResourceConnectionConfig($resourceName);
         if ($connection) {
             $this->_connectionConfig = $connection;
         } else {
-            $this->_connectionConfig = $config->getResourceConnectionConfig(self::DEFAULT_SETUP_CONNECTION);
+            $this->_connectionConfig = $resourcesConfig->getResourceConnectionConfig(self::DEFAULT_SETUP_CONNECTION);
         }
 
         $modName = (string)$this->_resourceConfig->setup->module;
-        $this->_moduleConfig = $config->getModuleConfig($modName);
-        $connection = Mage::getSingleton('Mage_Core_Model_Resource')->getConnection($this->_resourceName);
+        $this->_moduleConfig = $this->_config->getModuleConfig($modName);
+        $connection = $this->_resourceModel->getConnection($this->_resourceName);
         /**
          * If module setup configuration wasn't loaded
          */
         if (!$connection) {
-            $connection = Mage::getSingleton('Mage_Core_Model_Resource')->getConnection($this->_resourceName);
+            $connection = $this->_resourceModel->getConnection($this->_resourceName);
         }
         $this->_conn = $connection;
     }
@@ -181,7 +186,7 @@ class Mage_Core_Model_Resource_Setup
     {
         $cacheKey = $this->_getTableCacheName($tableName);
         if (!isset($this->_tables[$cacheKey])) {
-            $this->_tables[$cacheKey] = Mage::getSingleton('Mage_Core_Model_Resource')->getTableName($tableName);
+            $this->_tables[$cacheKey] = $this->_resourceModel->getTableName($tableName);
         }
         return $this->_tables[$cacheKey];
     }
@@ -211,66 +216,6 @@ class Mage_Core_Model_Resource_Setup
         return Mage::getResourceSingleton('Mage_Core_Model_Resource_Resource');
     }
 
-    /**
-     * Apply database updates whenever needed
-     *
-     * @return boolean
-     */
-    static public function applyAllUpdates()
-    {
-        Mage::app()->setUpdateMode(true);
-        self::$_hadUpdates = false;
-
-        $resources = Mage::getConfig()->getNode('global/resources')->children();
-        $afterApplyUpdates = array();
-        foreach ($resources as $resName => $resource) {
-            if (!$resource->setup) {
-                continue;
-            }
-            $className = __CLASS__;
-            if (isset($resource->setup->class)) {
-                $className = $resource->setup->getClassName();
-            }
-            $setupClass = Mage::getModel($className, array('resourceName' => $resName));
-
-            $setupClass->applyUpdates();
-            if ($setupClass->getCallAfterApplyAllUpdates()) {
-                $afterApplyUpdates[] = $setupClass;
-            }
-        }
-
-        foreach ($afterApplyUpdates as $setupClass) {
-            $setupClass->afterApplyAllUpdates();
-        }
-
-        Mage::app()->setUpdateMode(false);
-        self::$_schemaUpdatesChecked = true;
-        return true;
-    }
-
-    /**
-     * Apply database data updates whenever needed
-     *
-     */
-    static public function applyAllDataUpdates()
-    {
-        if (!self::$_schemaUpdatesChecked) {
-            return;
-        }
-        $resources = Mage::getConfig()->getNode('global/resources')->children();
-        foreach ($resources as $resName => $resource) {
-            if (!$resource->setup) {
-                continue;
-            }
-            $className = __CLASS__;
-            if (isset($resource->setup->class)) {
-                $className = $resource->setup->getClassName();
-            }
-            $setupClass = Mage::getModel($className, array('resourceName' => $resName));
-            $setupClass->applyDataUpdates();
-        }
-    }
-
     /**
      * Apply data updates to the system after upgrading.
      *
@@ -305,6 +250,7 @@ class Mage_Core_Model_Resource_Setup
          * Hook queries in adapter, so that in MySQL compatibility mode extensions and custom modules will avoid
          * errors due to changes in database structure
          */
+        /** @var $helper Mage_Core_Helper_Data */
         $helper = Mage::helper('Mage_Core_Helper_Data');
         if (((string)$this->_moduleConfig->codePool != 'core') && $helper->useDbCompatibleMode()) {
             $this->_hookQueries();
@@ -480,7 +426,7 @@ class Mage_Core_Model_Resource_Setup
         $resModel   = (string)$this->_connectionConfig->model;
         $modName    = (string)$this->_moduleConfig[0]->getName();
 
-        $filesDir   = Mage::getModuleDir('sql', $modName) . DS . $this->_resourceName;
+        $filesDir   = $this->_modulesReader->getModuleDir('sql', $modName) . DS . $this->_resourceName;
         if (!is_dir($filesDir) || !is_readable($filesDir)) {
             return array();
         }
@@ -587,14 +533,12 @@ class Mage_Core_Model_Resource_Setup
 
     /**
      * Run module modification files. Return version of last applied upgrade (false if no upgrades applied)
-     *
-     * @param string $actionType self::TYPE_*
+     * @param string $actionType
      * @param string $fromVersion
      * @param string $toVersion
-     * @return string|false
-     * @throws Magento_Exception
+     * @return bool|string
+     * @throws Magento_Exception     
      */
-
     protected function _modifyResourceDb($actionType, $fromVersion, $toVersion)
     {
         switch ($actionType) {
@@ -653,7 +597,6 @@ class Mage_Core_Model_Resource_Setup
             $version = $file['toVersion'];
             $this->getConnection()->allowDdlCache();
         }
-        self::$_hadUpdates = true;
         return $version;
     }
 
@@ -920,7 +863,7 @@ class Mage_Core_Model_Resource_Setup
      */
     public function getIdxName($tableName, $fields, $indexType = '')
     {
-        return Mage::getSingleton('Mage_Core_Model_Resource')->getIdxName($tableName, $fields, $indexType);
+        return $this->_resourceModel->getIdxName($tableName, $fields, $indexType);
     }
 
     /**
@@ -934,7 +877,7 @@ class Mage_Core_Model_Resource_Setup
      */
     public function getFkName($priTableName, $priColumnName, $refTableName, $refColumnName)
     {
-        return Mage::getSingleton('Mage_Core_Model_Resource')
+        return $this->_resourceModel
             ->getFkName($priTableName, $priColumnName, $refTableName, $refColumnName);
     }
 
diff --git a/app/code/core/Mage/Core/Model/Resource/Setup/Migration.php b/app/code/core/Mage/Core/Model/Resource/Setup/Migration.php
index 5631e6ff627125b40cf7a02861fd2dab1684fe0e..f51f6a618a97123ae54cf3859cd7b5abefae3c0c 100644
--- a/app/code/core/Mage/Core/Model/Resource/Setup/Migration.php
+++ b/app/code/core/Mage/Core/Model/Resource/Setup/Migration.php
@@ -144,22 +144,32 @@ class Mage_Core_Model_Resource_Setup_Migration extends Mage_Core_Model_Resource_
     protected $_filesystem;
 
     /**
-     * Constructor
-     *
-     * @param string $resourceName
+     * @param Mage_Core_Model_Config_Resource $resourcesConfig
+     * @param Mage_Core_Model_Config_Modules $modulesConfig
+     * @param Mage_Core_Model_Resource $resource
+     * @param Mage_Core_Model_Config_Modules_Reader $modulesReader
      * @param Magento_Filesystem $filesystem
+     * @param string $resourceName
      * @param array $data
      */
-    public function __construct($resourceName, Magento_Filesystem $filesystem, array $data = array())
-    {
+    public function __construct(
+        Mage_Core_Model_Config_Resource $resourcesConfig,
+        Mage_Core_Model_Config_Modules $modulesConfig,
+        Mage_Core_Model_Resource $resource,
+        Mage_Core_Model_Config_Modules_Reader $modulesReader,
+        Magento_Filesystem $filesystem,
+        $resourceName,
+        array $data = array()
+    ) {
         $this->_filesystem = $filesystem;
         if (!isset($data['resource_config'])
             || !isset($data['connection_config'])
             || !isset($data['module_config'])
             || !isset($data['connection'])
         ) {
-            parent::__construct($resourceName);
+            parent::__construct($resourcesConfig, $modulesConfig, $resource, $modulesReader, $resourceName);
         } else {
+            $this->_resourceModel = $resource;
             $this->_resourceName = $resourceName;
 
             if (isset($data['connection'])) {
@@ -168,7 +178,6 @@ class Mage_Core_Model_Resource_Setup_Migration extends Mage_Core_Model_Resource_
 
             $this->_initConfigs($data);
         }
-
         if (isset($data['core_helper'])) {
             $this->_coreHelper = $data['core_helper'];
         } else {
diff --git a/app/code/core/Mage/Core/Model/Resource/SetupFactory.php b/app/code/core/Mage/Core/Model/Resource/SetupFactory.php
new file mode 100644
index 0000000000000000000000000000000000000000..952ea7ae32845cb69121cf4840ba71ecdb4e6ef3
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Resource/SetupFactory.php
@@ -0,0 +1,58 @@
+<?php
+/**
+ * Setup model factory
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_Resource_SetupFactory
+{
+    /**
+     * @var Magento_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * @param Magento_ObjectManager $objectManager
+     */
+    public function __construct(Magento_ObjectManager $objectManager)
+    {
+        $this->_objectManager = $objectManager;
+    }
+
+    /**
+     * Create setup model instance
+     *
+     * @param $className
+     * @param array $arguments
+     * @return Mage_Core_Model_Resource_SetupInterface
+     * @throws LogicException
+     */
+    public function create($className, array $arguments = array())
+    {
+        $object = $this->_objectManager->create($className, $arguments);
+        if (false == ($object instanceof Mage_Core_Model_Resource_SetupInterface)) {
+            throw new LogicException($className . ' doesn\'t implement Mage_Core_Model_Resource_SetupInterface');
+        }
+        return $object;
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Resource/SetupInterface.php b/app/code/core/Mage/Core/Model/Resource/SetupInterface.php
new file mode 100644
index 0000000000000000000000000000000000000000..c0d9ab2935f50a991d880e97246557646becd926
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Resource/SetupInterface.php
@@ -0,0 +1,63 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+interface Mage_Core_Model_Resource_SetupInterface
+{
+    const DEFAULT_SETUP_CONNECTION  = 'core_setup';
+    const VERSION_COMPARE_EQUAL     = 0;
+    const VERSION_COMPARE_LOWER     = -1;
+    const VERSION_COMPARE_GREATER   = 1;
+
+    const TYPE_DB_INSTALL           = 'install';
+    const TYPE_DB_UPGRADE           = 'upgrade';
+    const TYPE_DB_ROLLBACK          = 'rollback';
+    const TYPE_DB_UNINSTALL         = 'uninstall';
+    const TYPE_DATA_INSTALL         = 'data-install';
+    const TYPE_DATA_UPGRADE         = 'data-upgrade';
+
+    /**
+     * Apply module resource install, upgrade and data scripts
+     *
+     * @return Mage_Core_Model_Resource_SetupInterface
+     */
+    public function applyUpdates();
+
+    /**
+     * Check call afterApplyAllUpdates method for setup class
+     *
+     * @return boolean
+     */
+    public function getCallAfterApplyAllUpdates();
+
+    /**
+     * Run each time after applying of all updates,
+     *
+     * @return Mage_Core_Model_Resource_SetupInterface
+     */
+    public function afterApplyAllUpdates();
+
+    /**
+     *  Apply data updates to the system after upgrading
+     */
+    public function applyDataUpdates();
+}
diff --git a/app/code/core/Mage/Core/Model/Resource/Store.php b/app/code/core/Mage/Core/Model/Resource/Store.php
index 680fc17eefaf02910f8173820d0dbd6034f42ab9..f3a06a06fd094e13356c5f0a295abc5beddc06fe 100644
--- a/app/code/core/Mage/Core/Model/Resource/Store.php
+++ b/app/code/core/Mage/Core/Model/Resource/Store.php
@@ -152,7 +152,7 @@ class Mage_Core_Model_Resource_Store extends Mage_Core_Model_Resource_Db_Abstrac
             $storeId = $adapter->fetchOne($select, 'default_store_id');
 
             if ($storeId == $model->getId()) {
-                $bind = array('default_store_id' => Mage_Core_Model_App::ADMIN_STORE_ID);
+                $bind = array('default_store_id' => Mage_Core_Model_AppInterface::ADMIN_STORE_ID);
                 $where = array('group_id = ?' => $model->getOriginalGroupId());
                 $this->_getWriteAdapter()->update($this->getTable('core_store_group'), $bind, $where);
             }
diff --git a/app/code/core/Mage/Core/Model/Resource/Theme/Collection.php b/app/code/core/Mage/Core/Model/Resource/Theme/Collection.php
index b524e6c2a7d7d57ddd73fb5fc81d5ee40297fd0d..add330d19c86b573351de35474f30db376316df0 100644
--- a/app/code/core/Mage/Core/Model/Resource/Theme/Collection.php
+++ b/app/code/core/Mage/Core/Model/Resource/Theme/Collection.php
@@ -135,6 +135,7 @@ class Mage_Core_Model_Resource_Theme_Collection extends Mage_Core_Model_Resource
      */
     public function getThemeByFullPath($fullPath)
     {
+        $this->clear();
         list($area, $themePath) = explode('/', $fullPath, 2);
         $this->addFieldToFilter('area', $area);
         $this->addFieldToFilter('theme_path', $themePath);
diff --git a/app/code/core/Mage/Core/Model/Resource/Translate/String.php b/app/code/core/Mage/Core/Model/Resource/Translate/String.php
index 3a00aa01aeff9f00f4e3e12da99ed7f036e90cb7..60928dc9c790149f0d4339f62cdccd1f7ab6fe2d 100644
--- a/app/code/core/Mage/Core/Model/Resource/Translate/String.php
+++ b/app/code/core/Mage/Core/Model/Resource/Translate/String.php
@@ -77,7 +77,7 @@ class Mage_Core_Model_Resource_Translate_String extends Mage_Core_Model_Resource
     protected function _getLoadSelect($field, $value, $object)
     {
         $select = parent::_getLoadSelect($field, $value, $object);
-        $select->where('store_id = ?', Mage_Core_Model_App::ADMIN_STORE_ID);
+        $select->where('store_id = ?', Mage_Core_Model_AppInterface::ADMIN_STORE_ID);
         return $select;
     }
 
@@ -114,7 +114,7 @@ class Mage_Core_Model_Resource_Translate_String extends Mage_Core_Model_Resource
 
         $bind = array(
             'string'   => $object->getString(),
-            'store_id' => Mage_Core_Model_App::ADMIN_STORE_ID
+            'store_id' => Mage_Core_Model_AppInterface::ADMIN_STORE_ID
         );
 
         $object->setId($adapter->fetchOne($select, $bind));
@@ -186,7 +186,7 @@ class Mage_Core_Model_Resource_Translate_String extends Mage_Core_Model_Resource
         );
 
         if ($storeId === false) {
-            $where['store_id > ?'] = Mage_Core_Model_App::ADMIN_STORE_ID;
+            $where['store_id > ?'] = Mage_Core_Model_AppInterface::ADMIN_STORE_ID;
         } elseif ($storeId !== null) {
             $where['store_id = ?'] = $storeId;
         }
diff --git a/app/code/core/Mage/Core/Model/Resource/Url/Rewrite.php b/app/code/core/Mage/Core/Model/Resource/Url/Rewrite.php
index 47829c24c8c68b4888927a919f1cbd3feed5a6b1..c155996b9089fc6d2d679bb05c03c7e3b4ef260b 100644
--- a/app/code/core/Mage/Core/Model/Resource/Url/Rewrite.php
+++ b/app/code/core/Mage/Core/Model/Resource/Url/Rewrite.php
@@ -77,7 +77,7 @@ class Mage_Core_Model_Resource_Url_Rewrite extends Mage_Core_Model_Resource_Db_A
         $select = parent::_getLoadSelect($field, $value, $object);
 
         if (!is_null($object->getStoreId())) {
-            $select->where('store_id IN(?)', array(Mage_Core_Model_App::ADMIN_STORE_ID, $object->getStoreId()));
+            $select->where('store_id IN(?)', array(Mage_Core_Model_AppInterface::ADMIN_STORE_ID, $object->getStoreId()));
             $select->order('store_id ' . Varien_Db_Select::SQL_DESC);
             $select->limit(1);
         }
@@ -138,7 +138,7 @@ class Mage_Core_Model_Resource_Url_Rewrite extends Mage_Core_Model_Resource_Db_A
         $select  = $adapter->select()
             ->from($this->getMainTable())
             ->where('request_path IN (:' . implode(', :', array_flip($pathBind)) . ')')
-            ->where('store_id IN(?)', array(Mage_Core_Model_App::ADMIN_STORE_ID, (int)$object->getStoreId()));
+            ->where('store_id IN(?)', array(Mage_Core_Model_AppInterface::ADMIN_STORE_ID, (int)$object->getStoreId()));
 
         $items = $adapter->fetchAll($select, $pathBind);
 
diff --git a/app/code/core/Mage/Core/Model/Resource/Variable.php b/app/code/core/Mage/Core/Model/Resource/Variable.php
index 83d461b374e1fc40ab80c245ae69616009b44f22..e5a94c89fc64a71addcb3004a40799f970200892 100644
--- a/app/code/core/Mage/Core/Model/Resource/Variable.php
+++ b/app/code/core/Mage/Core/Model/Resource/Variable.php
@@ -134,7 +134,7 @@ class Mage_Core_Model_Resource_Variable extends Mage_Core_Model_Resource_Db_Abst
      * @param integer $storeId
      * @return Mage_Core_Model_Resource_Variable
      */
-    protected function _addValueToSelect(Zend_Db_Select $select, $storeId = Mage_Core_Model_App::ADMIN_STORE_ID)
+    protected function _addValueToSelect(Zend_Db_Select $select, $storeId = Mage_Core_Model_AppInterface::ADMIN_STORE_ID)
     {
         $adapter = $this->_getReadAdapter();
         $ifNullPlainValue = $adapter->getCheckSql('store.plain_value IS NULL', 'def.plain_value', 'store.plain_value');
@@ -157,4 +157,4 @@ class Mage_Core_Model_Resource_Variable extends Mage_Core_Model_Resource_Db_Abst
 
         return $this;
     }
-}
\ No newline at end of file
+}
diff --git a/app/code/core/Mage/Core/Model/Store.php b/app/code/core/Mage/Core/Model/Store.php
index 2299654447b73be892296e7fc8b14298d3c91618..ac0751ef09d497e00922e9a2c2e9b5c61c4b90b3 100644
--- a/app/code/core/Mage/Core/Model/Store.php
+++ b/app/code/core/Mage/Core/Model/Store.php
@@ -29,11 +29,13 @@
  *
  * @method Mage_Core_Model_Resource_Store _getResource()
  * @method Mage_Core_Model_Resource_Store getResource()
+ * @method Mage_Core_Model_Store setId(string $value)
  * @method Mage_Core_Model_Store setCode(string $value)
  * @method Mage_Core_Model_Store setWebsiteId(int $value)
  * @method Mage_Core_Model_Store setGroupId(int $value)
  * @method Mage_Core_Model_Store setName(string $value)
  * @method int getSortOrder()
+ * @method int getStoreId()
  * @method Mage_Core_Model_Store setSortOrder(int $value)
  * @method Mage_Core_Model_Store setIsActive(int $value)
  *
@@ -373,7 +375,13 @@ class Mage_Core_Model_Store extends Mage_Core_Model_Abstract
             return $this->_configCache[$path];
         }
 
-        $config = Mage::getConfig();
+        if (!Mage::isInstalled()) {
+            /** @var $config Mage_Core_Model_ConfigInterface */
+            $config = Mage::getSingleton('Mage_Core_Model_Config_Modules');
+        } else {
+            /** @var $config Mage_Core_Model_ConfigInterface */
+            $config = Mage::getSingleton('Mage_Core_Model_Config');
+        }
 
         $fullPath = 'stores/' . $this->getCode() . '/' . $path;
         $data = $config->getNode($fullPath);
@@ -401,9 +409,10 @@ class Mage_Core_Model_Store extends Mage_Core_Model_Abstract
         if ($this->_configCache === null) {
             $code = $this->getCode();
             if ($code) {
-                if (Mage::app()->useCache('config')) {
+                $cache = Mage::getObjectManager()->get('Mage_Core_Model_Cache');
+                if ($cache->canUse('config')) {
                     $cacheId = 'store_' . $code . '_config_cache';
-                    $data = Mage::app()->loadCache($cacheId);
+                    $data = $cache->load($cacheId);
                     if ($data) {
                         $data = unserialize($data);
                     } else {
@@ -411,10 +420,10 @@ class Mage_Core_Model_Store extends Mage_Core_Model_Abstract
                         foreach ($this->_configCacheBaseNodes as $node) {
                             $data[$node] = $this->getConfig($node);
                         }
-                        Mage::app()->saveCache(serialize($data), $cacheId, array(
+                        $cache->save(serialize($data), $cacheId, array(
                             self::CACHE_TAG,
                             Mage_Core_Model_Config::CACHE_TAG
-                        ));
+                        ), false);
                     }
                     $this->_configCache = $data;
                 }
@@ -701,7 +710,7 @@ class Mage_Core_Model_Store extends Mage_Core_Model_Abstract
      */
     public function isAdmin()
     {
-        return $this->getId() == Mage_Core_Model_App::ADMIN_STORE_ID;
+        return $this->getId() == Mage_Core_Model_AppInterface::ADMIN_STORE_ID;
     }
 
 
diff --git a/app/code/core/Mage/Core/Model/Store/Group.php b/app/code/core/Mage/Core/Model/Store/Group.php
index 6b5bff23f59da9474dd91fe26aba96131ad7c74c..7c32e37a169cd2f7574c30b0fc80af9fc187e59f 100644
--- a/app/code/core/Mage/Core/Model/Store/Group.php
+++ b/app/code/core/Mage/Core/Model/Store/Group.php
@@ -31,6 +31,7 @@
  * @method Mage_Core_Model_Resource_Store_Group getResource()
  * @method Mage_Core_Model_Store_Group setWebsiteId(int $value)
  * @method string getName()
+ * @method string getCode()
  * @method Mage_Core_Model_Store_Group setName(string $value)
  * @method Mage_Core_Model_Store_Group setRootCategoryId(int $value)
  * @method Mage_Core_Model_Store_Group setDefaultStoreId(int $value)
diff --git a/app/code/core/Mage/Core/Model/Store/ListInterface.php b/app/code/core/Mage/Core/Model/Store/ListInterface.php
new file mode 100644
index 0000000000000000000000000000000000000000..147aba4e6e453703511ead9725f958c594ba2797
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Store/ListInterface.php
@@ -0,0 +1,140 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license   http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+interface Mage_Core_Model_Store_ListInterface
+{
+    /**
+     * Allow or disallow single store mode
+     *
+     * @param bool $value
+     */
+    public function setIsSingleStoreModeAllowed($value);
+
+    /**
+     * Check if store has only one store view
+     *
+     * @return bool
+     */
+    public function hasSingleStore();
+
+    /**
+     * Retrieve application store object
+     *
+     * @param null|string|bool|int|Mage_Core_Model_Store $id
+     * @return Mage_Core_Model_Store
+     * @throws Mage_Core_Model_Store_Exception
+     */
+    public function getStore($id = null);
+
+    /**
+     * Retrieve stores array
+     *
+     * @param bool $withDefault
+     * @param bool $codeKey
+     * @return Mage_Core_Model_Store[]
+     */
+    public function getStores($withDefault = false, $codeKey = false);
+
+    /**
+     * Retrieve application website object
+     *
+     * @param null|bool|int|string|Mage_Core_Model_Website $id
+     * @return Mage_Core_Model_Website
+     * @throws Mage_Core_Exception
+     */
+    public function getWebsite($id = null);
+
+    /**
+     * Get loaded websites
+     *
+     * @param bool $withDefault
+     * @param bool|string $codeKey
+     * @return Mage_Core_Model_Website[]
+     */
+    public function getWebsites($withDefault = false, $codeKey = false);
+
+    /**
+     * Reinitialize store list
+     */
+    public function reinitStores();
+
+    /**
+     * Retrieve default store for default group and website
+     *
+     * @return Mage_Core_Model_Store
+     */
+    public function getDefaultStoreView();
+
+    /**
+     * Retrieve application store group object
+     *
+     * @param null|Mage_Core_Model_Store_Group|string $id
+     * @return Mage_Core_Model_Store_Group
+     * @throws Mage_Core_Exception
+     */
+    public function getGroup($id = null);
+
+    /**
+     * Prepare array of store groups
+     * can be filtered to contain default store group or not by $withDefault flag
+     * depending on flag $codeKey array keys can be group id or group code
+     *
+     * @param bool $withDefault
+     * @param bool $codeKey
+     * @return Mage_Core_Model_Store_Group[]
+     */
+    public function getGroups($withDefault = false, $codeKey = false);
+
+    /**
+     *  Unset website by id from app cache
+     *
+     * @param null|bool|int|string|Mage_Core_Model_Website $id
+     */
+    public function clearWebsiteCache($id = null);
+
+    /**
+     * Get either default or any store view
+     *
+     * @return Mage_Core_Model_Store|null
+     */
+    public function getAnyStoreView();
+
+    /**
+     * Set current default store
+     *
+     * @param string $store
+     */
+    public function setCurrentStore($store);
+
+    /**
+     * Get current store code
+     *
+     * @return string
+     */
+    public function getCurrentStore();
+
+    /**
+     * @throws Mage_Core_Model_Store_Exception
+     */
+    public function throwStoreException();
+}
\ No newline at end of file
diff --git a/app/code/core/Mage/Core/Model/Store/Storage/Db.php b/app/code/core/Mage/Core/Model/Store/Storage/Db.php
new file mode 100644
index 0000000000000000000000000000000000000000..b8124aafe6385b92240de345eb4f4d22548f9ca4
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Store/Storage/Db.php
@@ -0,0 +1,737 @@
+<?php
+/**
+ * Store loader
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license   http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Store_Storage_Db implements Mage_Core_Model_Store_StorageInterface
+{
+    /**
+     * Requested scope code
+     *
+     * @var string
+     */
+    protected $_scopeCode;
+
+    /**
+     * Requested scope type
+     *
+     * @var string
+     */
+    protected $_scopeType;
+
+    /**
+     * Flag that shows that system has only one store view
+     *
+     * @var bool
+     */
+    protected $_hasSingleStore;
+
+    /**
+     * Flag is single store mode allowed
+     *
+     * @var bool
+     */
+    protected $_isSingleStoreAllowed = true;
+
+    /**
+     * Application store object
+     *
+     * @var Mage_Core_Model_Store
+     */
+    protected $_store;
+
+    /**
+     * Stores cache
+     *
+     * @var Mage_Core_Model_Store[]
+     */
+    protected $_stores = array();
+
+    /**
+     * Application website object
+     *
+     * @var Mage_Core_Model_Website
+     */
+    protected $_website;
+
+    /**
+     * Websites cache
+     *
+     * @var Mage_Core_Model_Website[]
+     */
+    protected $_websites = array();
+
+    /**
+     * Groups cache
+     *
+     * @var Mage_Core_Model_Store_Group[]
+     */
+    protected $_groups = array();
+
+    /**
+     * Application cache model
+     *
+     * @var Mage_Core_Model_Cache
+     */
+    protected $_cache;
+
+    /**
+     * Config model
+     *
+     * @var Mage_Core_Model_Config
+     */
+    protected $_config;
+
+    /**
+     * Default store code
+     *
+     * @var string
+     */
+    protected $_currentStore = null;
+
+    /**
+     * Store factory
+     *
+     * @var Mage_Core_Model_StoreFactory
+     */
+    protected $_storeFactory;
+
+    /**
+     * Website factory
+     *
+     * @var Mage_Core_Model_Website_Factory
+     */
+    protected $_websiteFactory;
+
+    /**
+     * Group factory
+     *
+     * @var Mage_Core_Model_Store_Group_Factory
+     */
+    protected $_groupFactory;
+
+    /**
+     * Cookie model
+     *
+     * @var Mage_Core_Model_Cookie
+     */
+    protected $_cookie;
+
+    /**
+     * Application state model
+     *
+     * @var Mage_Core_Model_App_State
+     */
+    protected $_appState;
+
+    /**
+     * @param Mage_Core_Model_StoreFactory $storeFactory
+     * @param Mage_Core_Model_Website_Factory $websiteFactory
+     * @param Mage_Core_Model_Store_Group_Factory $groupFactory
+     * @param Mage_Core_Model_Cache $cache
+     * @param Mage_Core_Model_Config $config
+     * @param Mage_Core_Model_Cookie $cookie
+     * @param Mage_Core_Model_App_State $appState
+     * @param bool $isSingleStoreAllowed
+     * @param string $scopeCode
+     * @param string $scopeType
+     * @param string $currentStore
+     */
+    public function __construct(
+        Mage_Core_Model_StoreFactory $storeFactory,
+        Mage_Core_Model_Website_Factory $websiteFactory,
+        Mage_Core_Model_Store_Group_Factory $groupFactory,
+        Mage_Core_Model_Cache $cache,
+        Mage_Core_Model_Config $config,
+        Mage_Core_Model_Cookie $cookie,
+        Mage_Core_Model_App_State $appState,
+        $isSingleStoreAllowed,
+        $scopeCode,
+        $scopeType,
+        $currentStore = null
+    ) {
+        $this->_storeFactory = $storeFactory;
+        $this->_websiteFactory = $websiteFactory;
+        $this->_groupFactory = $groupFactory;
+        $this->_cache = $cache;
+        $this->_scopeCode = $scopeCode;
+        $this->_scopeType = $scopeType ?: Mage_Core_Model_StoreManagerInterface::SCOPE_TYPE_STORE;
+        $this->_config = $config;
+        $this->_isSingleStoreAllowed = $isSingleStoreAllowed;
+        $this->_appState = $appState;
+        $this->_cookie = $cookie;
+        if ($currentStore) {
+            $this->_currentStore = $currentStore;
+        }
+    }
+
+    /**
+     * Get default store
+     *
+     * @return Mage_Core_Model_Store
+     */
+    protected function _getDefaultStore()
+    {
+        if (empty($this->_store)) {
+            $this->_store = $this->_storeFactory->create()
+                ->setId(Mage_Core_Model_AppInterface::DISTRO_STORE_ID)
+                ->setCode(Mage_Core_Model_AppInterface::DISTRO_STORE_CODE);
+        }
+        return $this->_store;
+    }
+
+    /**
+     * Initialize currently ran store
+     *
+     * @throws Mage_Core_Model_Store_Exception
+     */
+    public function initCurrentStore()
+    {
+        Magento_Profiler::start('init_stores');
+        $this->_initStores();
+        Magento_Profiler::stop('init_stores');
+
+        if (empty($this->_scopeCode) && !is_null($this->_website)) {
+            $this->_scopeCode = $this->_website->getCode();
+            $this->_scopeType = Mage_Core_Model_StoreManagerInterface::SCOPE_TYPE_WEBSITE;
+        }
+        switch ($this->_scopeType) {
+            case Mage_Core_Model_StoreManagerInterface::SCOPE_TYPE_STORE:
+                $this->_currentStore = $this->_scopeCode;
+                break;
+            case Mage_Core_Model_StoreManagerInterface::SCOPE_TYPE_GROUP:
+                $this->_currentStore = $this->_getStoreByGroup($this->_scopeCode);
+                break;
+            case Mage_Core_Model_StoreManagerInterface::SCOPE_TYPE_WEBSITE:
+                $this->_currentStore = $this->_getStoreByWebsite($this->_scopeCode);
+                break;
+            default:
+                $this->throwStoreException();
+        }
+
+        if (!empty($this->_currentStore)) {
+            $this->_checkCookieStore($this->_scopeType);
+            $this->_checkGetStore($this->_scopeType);
+        }
+    }
+
+    /**
+     * Check get store
+     *
+     * @param string $type
+     */
+    protected function _checkGetStore($type)
+    {
+        if (empty($_GET)) {
+            return;
+        }
+
+        if (!isset($_GET['___store'])) {
+            return;
+        }
+
+        $store = $_GET['___store'];
+        if (!isset($this->_stores[$store])) {
+            return;
+        }
+
+        $storeObj = $this->_stores[$store];
+        if (!$storeObj->getId() || !$storeObj->getIsActive()) {
+            return;
+        }
+
+        /**
+         * prevent running a store from another website or store group,
+         * if website or store group was specified explicitly
+         */
+        $curStoreObj = $this->_stores[$this->_currentStore];
+        if ($type == 'website' && $storeObj->getWebsiteId() == $curStoreObj->getWebsiteId()) {
+            $this->_currentStore = $store;
+        } elseif ($type == 'group' && $storeObj->getGroupId() == $curStoreObj->getGroupId()) {
+            $this->_currentStore = $store;
+        } elseif ($type == 'store') {
+            $this->_currentStore = $store;
+        }
+
+        if ($this->_currentStore == $store) {
+            $store = $this->getStore($store);
+            if ($store->getWebsite()->getDefaultStore()->getId() == $store->getId()) {
+                $this->_cookie->delete(Mage_Core_Model_Store::COOKIE_NAME);
+            } else {
+                $this->_cookie->set(Mage_Core_Model_Store::COOKIE_NAME, $this->_currentStore, true);
+            }
+        }
+        return;
+    }
+
+    /**
+     * Check cookie store
+     *
+     * @param string $type
+     */
+    protected function _checkCookieStore($type)
+    {
+        if (!$this->_cookie->get()) {
+            return;
+        }
+
+        $store = $this->_cookie->get(Mage_Core_Model_Store::COOKIE_NAME);
+        if ($store && isset($this->_stores[$store])
+            && $this->_stores[$store]->getId()
+            && $this->_stores[$store]->getIsActive()
+        ) {
+            if ($type == 'website'
+                && $this->_stores[$store]->getWebsiteId() == $this->_stores[$this->_currentStore]->getWebsiteId()
+            ) {
+                $this->_currentStore = $store;
+            }
+            if ($type == 'group'
+                && $this->_stores[$store]->getGroupId() == $this->_stores[$this->_currentStore]->getGroupId()
+            ) {
+                $this->_currentStore = $store;
+            }
+            if ($type == 'store') {
+                $this->_currentStore = $store;
+            }
+        }
+    }
+
+    /**
+     * Retrieve store code or null by store group
+     *
+     * @param int $group
+     * @return string|null
+     */
+    protected function _getStoreByGroup($group)
+    {
+        if (!isset($this->_groups[$group])) {
+            return null;
+        }
+        if (!$this->_groups[$group]->getDefaultStoreId()) {
+            return null;
+        }
+        return $this->_stores[$this->_groups[$group]->getDefaultStoreId()]->getCode();
+    }
+
+    /**
+     * Retrieve store code or null by website
+     *
+     * @param int|string $website
+     * @return string|null
+     */
+    protected function _getStoreByWebsite($website)
+    {
+        if (!isset($this->_websites[$website])) {
+            return null;
+        }
+        if (!$this->_websites[$website]->getDefaultGroupId()) {
+            return null;
+        }
+        return $this->_getStoreByGroup($this->_websites[$website]->getDefaultGroupId());
+    }
+
+    /**
+     * Init store, group and website collections
+     */
+    protected function _initStores()
+    {
+        $this->_stores   = array();
+        $this->_groups   = array();
+        $this->_websites = array();
+
+        $this->_website  = null;
+
+        /** @var $websiteCollection Mage_Core_Model_Resource_Website_Collection */
+        $websiteCollection = $this->_websiteFactory->create()->getCollection();
+        $websiteCollection->initCache($this->_cache, 'app', array(Mage_Core_Model_Website::CACHE_TAG));
+        $websiteCollection->setLoadDefault(true);
+
+        /** @var $groupCollection Mage_Core_Model_Resource_Store_Group_Collection */
+        $groupCollection = $this->_groupFactory->createFromArray()->getCollection();
+        $groupCollection->initCache($this->_cache, 'app', array(Mage_Core_Model_Store_Group::CACHE_TAG));
+        $groupCollection->setLoadDefault(true);
+
+        /** @var $storeCollection Mage_Core_Model_Resource_Store_Collection */
+        $storeCollection = $this->_storeFactory->create()->getCollection();
+        $storeCollection->initCache($this->_cache, 'app', array(Mage_Core_Model_Store::CACHE_TAG));
+        $storeCollection->setLoadDefault(true);
+
+        $this->_hasSingleStore = false;
+        if ($this->_isSingleStoreAllowed) {
+            $this->_hasSingleStore = $storeCollection->count() < 3;
+        }
+
+        $websiteStores = array();
+        $websiteGroups = array();
+        $groupStores   = array();
+
+        foreach ($storeCollection as $store) {
+            /** @var $store Mage_Core_Model_Store */
+            $store->initConfigCache();
+            $store->setWebsite($websiteCollection->getItemById($store->getWebsiteId()));
+            $store->setGroup($groupCollection->getItemById($store->getGroupId()));
+
+            $this->_stores[$store->getId()] = $store;
+            $this->_stores[$store->getCode()] = $store;
+
+            $websiteStores[$store->getWebsiteId()][$store->getId()] = $store;
+            $groupStores[$store->getGroupId()][$store->getId()] = $store;
+
+            if (is_null($this->_store) && $store->getId()) {
+                $this->_store = $store;
+            }
+        }
+
+        foreach ($groupCollection as $group) {
+            /* @var $group Mage_Core_Model_Store_Group */
+            if (!isset($groupStores[$group->getId()])) {
+                $groupStores[$group->getId()] = array();
+            }
+            $group->setStores($groupStores[$group->getId()]);
+            $group->setWebsite($websiteCollection->getItemById($group->getWebsiteId()));
+
+            $websiteGroups[$group->getWebsiteId()][$group->getId()] = $group;
+
+            $this->_groups[$group->getId()] = $group;
+        }
+
+        foreach ($websiteCollection as $website) {
+            /* @var $website Mage_Core_Model_Website */
+            if (!isset($websiteGroups[$website->getId()])) {
+                $websiteGroups[$website->getId()] = array();
+            }
+            if (!isset($websiteStores[$website->getId()])) {
+                $websiteStores[$website->getId()] = array();
+            }
+            if ($website->getIsDefault()) {
+                $this->_website = $website;
+            }
+            $website->setGroups($websiteGroups[$website->getId()]);
+            $website->setStores($websiteStores[$website->getId()]);
+
+            $this->_websites[$website->getId()] = $website;
+            $this->_websites[$website->getCode()] = $website;
+        }
+    }
+
+    /**
+     * Allow or disallow single store mode
+     *
+     * @param bool $value
+     */
+    public function setIsSingleStoreModeAllowed($value)
+    {
+        $this->_isSingleStoreAllowed = (bool)$value;
+    }
+
+    /**
+     * Check if store has only one store view
+     *
+     * @return bool
+     */
+    public function hasSingleStore()
+    {
+        return $this->_hasSingleStore;
+    }
+
+    /**
+     * Retrieve application store object
+     *
+     * @param null|string|bool|int|Mage_Core_Model_Store $id
+     * @return Mage_Core_Model_Store
+     * @throws Mage_Core_Model_Store_Exception
+     */
+    public function getStore($id = null)
+    {
+        if ($this->_appState->getUpdateMode()) {
+            return $this->_getDefaultStore();
+        }
+
+        if ($id === true && $this->hasSingleStore()) {
+            return $this->_store;
+        }
+
+        if (!isset($id) || '' === $id || $id === true) {
+            $id = $this->_currentStore;
+        }
+        if ($id instanceof Mage_Core_Model_Store) {
+            return $id;
+        }
+        if (!isset($id)) {
+            $this->throwStoreException();
+        }
+
+        if (empty($this->_stores[$id])) {
+            $store = $this->_storeFactory->create();
+            if (is_numeric($id)) {
+                $store->load($id);
+            } elseif (is_string($id)) {
+                $store->load($id, 'code');
+            }
+
+            if (!$store->getCode()) {
+                $this->throwStoreException();
+            }
+            $this->_stores[$store->getStoreId()] = $store;
+            $this->_stores[$store->getCode()] = $store;
+        }
+        return $this->_stores[$id];
+    }
+
+    /**
+     * Retrieve stores array
+     *
+     * @param bool $withDefault
+     * @param bool $codeKey
+     * @return Mage_Core_Model_Store[]
+     */
+    public function getStores($withDefault = false, $codeKey = false)
+    {
+        $stores = array();
+        foreach ($this->_stores as $store) {
+            if (!$withDefault && $store->getId() == 0) {
+                continue;
+            }
+            if ($codeKey) {
+                $stores[$store->getCode()] = $store;
+            } else {
+                $stores[$store->getId()] = $store;
+            }
+        }
+
+        return $stores;
+    }
+
+    /**
+     * Retrieve application website object
+     *
+     * @param null|bool|int|string|Mage_Core_Model_Website $id
+     * @return Mage_Core_Model_Website
+     * @throws Mage_Core_Exception
+     */
+    public function getWebsite($id = null)
+    {
+        if (is_null($id)) {
+            $id = $this->getStore()->getWebsiteId();
+        } elseif ($id instanceof Mage_Core_Model_Website) {
+            return $id;
+        } elseif ($id === true) {
+            return $this->_website;
+        }
+
+        if (empty($this->_websites[$id])) {
+            $website = $this->_websiteFactory->create();
+            if (is_numeric($id)) {
+                $website->load($id);
+                if (!$website->hasWebsiteId()) {
+                    throw Mage::exception('Mage_Core', 'Invalid website id requested.');
+                }
+            } elseif (is_string($id)) {
+                $websiteConfig = $this->_config->getNode('websites/' . $id);
+                if (!$websiteConfig) {
+                    throw Mage::exception('Mage_Core', 'Invalid website code requested: ' . $id);
+                }
+                $website->loadConfig($id);
+            }
+            $this->_websites[$website->getWebsiteId()] = $website;
+            $this->_websites[$website->getCode()] = $website;
+        }
+        return $this->_websites[$id];
+    }
+
+    /**
+     * Get loaded websites
+     *
+     * @param bool $withDefault
+     * @param bool|string $codeKey
+     * @return Mage_Core_Model_Website[]
+     */
+    public function getWebsites($withDefault = false, $codeKey = false)
+    {
+        $websites = array();
+        if (is_array($this->_websites)) {
+            foreach ($this->_websites as $website) {
+                if (!$withDefault && $website->getId() == 0) {
+                    continue;
+                }
+                if ($codeKey) {
+                    $websites[$website->getCode()] = $website;
+                } else {
+                    $websites[$website->getId()] = $website;
+                }
+            }
+        }
+        return $websites;
+    }
+
+    /**
+     * Retrieve application store group object
+     *
+     * @param null|Mage_Core_Model_Store_Group|string $id
+     * @return Mage_Core_Model_Store_Group
+     * @throws Mage_Core_Exception
+     */
+    public function getGroup($id = null)
+    {
+        if (is_null($id)) {
+            $id = $this->getStore()->getGroupId();
+        } elseif ($id instanceof Mage_Core_Model_Store_Group) {
+            return $id;
+        }
+        if (empty($this->_groups[$id])) {
+            $group = $this->_groupFactory->createFromArray();
+            if (is_numeric($id)) {
+                $group->load($id);
+                if (!$group->hasGroupId()) {
+                    throw Mage::exception('Mage_Core', 'Invalid store group id requested.');
+                }
+            }
+            $this->_groups[$group->getGroupId()] = $group;
+        }
+        return $this->_groups[$id];
+    }
+
+    /**
+     * Prepare array of store groups
+     * can be filtered to contain default store group or not by $withDefault flag
+     * depending on flag $codeKey array keys can be group id or group code
+     *
+     * @param bool $withDefault
+     * @param bool $codeKey
+     * @return Mage_Core_Model_Store_Group[]
+     */
+    public function getGroups($withDefault = false, $codeKey = false)
+    {
+        $groups = array();
+        if (is_array($this->_groups)) {
+            foreach ($this->_groups as $group) {
+                /** @var $group Mage_Core_Model_Store_Group */
+                if (!$withDefault && $group->getId() == 0) {
+                    continue;
+                }
+                if ($codeKey) {
+                    $groups[$group->getCode()] = $group;
+                } else {
+                    $groups[$group->getId()] = $group;
+                }
+            }
+        }
+        return $groups;
+    }
+
+    /**
+     * Reinitialize store list
+     */
+    public function reinitStores()
+    {
+        $this->_initStores();
+    }
+
+    /**
+     * Retrieve default store for default group and website
+     *
+     * @return Mage_Core_Model_Store
+     */
+    public function getDefaultStoreView()
+    {
+        foreach ($this->getWebsites() as $_website) {
+            /** @var $_website Mage_Core_Model_Website */
+            if ($_website->getIsDefault()) {
+                $_defaultStore = $this->getGroup($_website->getDefaultGroupId())->getDefaultStore();
+                if ($_defaultStore) {
+                    return $_defaultStore;
+                }
+            }
+        }
+        return null;
+    }
+
+    /**
+     *  Unset website by id from app cache
+     *
+     * @param null|bool|int|string|Mage_Core_Model_Website $id
+     */
+    public function clearWebsiteCache($id = null)
+    {
+        if (is_null($id)) {
+            $id = $this->getStore()->getWebsiteId();
+        } elseif ($id instanceof Mage_Core_Model_Website) {
+            $id = $id->getId();
+        } elseif ($id === true) {
+            $id = $this->_website->getId();
+        }
+
+        if (!empty($this->_websites[$id])) {
+            $website = $this->_websites[$id];
+
+            unset($this->_websites[$website->getWebsiteId()]);
+            unset($this->_websites[$website->getCode()]);
+        }
+    }
+
+    /**
+     * Get either default or any store view
+     *
+     * @return Mage_Core_Model_Store|null
+     */
+    public function getAnyStoreView()
+    {
+        $store = $this->getDefaultStoreView();
+        if ($store) {
+            return $store;
+        }
+        foreach ($this->getStores() as $store) {
+            return $store;
+        }
+
+        return null;
+    }
+
+    /**
+     * Set current default store
+     *
+     * @param string $store
+     */
+    public function setCurrentStore($store)
+    {
+        $this->_currentStore = $store;
+    }
+
+    /**
+     * @throws Mage_Core_Model_Store_Exception
+     */
+    public function throwStoreException()
+    {
+        throw new Mage_Core_Model_Store_Exception('');
+    }
+
+    /**
+     * Get current store code
+     *
+     * @return string
+     */
+    public function getCurrentStore()
+    {
+        return $this->_currentStore;
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Store/Storage/Default.php b/app/code/core/Mage/Core/Model/Store/Storage/Default.php
new file mode 100644
index 0000000000000000000000000000000000000000..8d7b3c0c19c742ea55356e8a970f9dd5a1bf284a
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Store/Storage/Default.php
@@ -0,0 +1,254 @@
+<?php
+/**
+ * Store loader
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license   http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Store_Storage_Default implements Mage_Core_Model_Store_StorageInterface
+{
+    /**
+     * Application store object
+     *
+     * @var Mage_Core_Model_Store
+     */
+    protected $_store;
+
+    /**
+     * Application website object
+     *
+     * @var Mage_Core_Model_Website
+     */
+    protected $_website;
+
+    /**
+     * Application website object
+     *
+     * @var Mage_Core_Model_Store_Group
+     */
+    protected $_group;
+
+    /**
+     * @param Mage_Core_Model_StoreFactory $storeFactory
+     * @param Mage_Core_Model_Website_Factory $websiteFactory
+     * @param Mage_Core_Model_Store_Group_Factory $groupFactory
+     */
+    public function __construct(
+        Mage_Core_Model_StoreFactory $storeFactory,
+        Mage_Core_Model_Website_Factory $websiteFactory,
+        Mage_Core_Model_Store_Group_Factory $groupFactory
+    ) {
+
+        $this->_store = $storeFactory->create();
+        $this->_store->setId(Mage_Core_Model_AppInterface::DISTRO_STORE_ID);
+        $this->_store->setCode(Mage_Core_Model_AppInterface::DISTRO_STORE_CODE);
+        $this->_website = $websiteFactory->create();
+        $this->_group = $groupFactory->createFromArray();
+    }
+
+    /**
+     * Initialize current applicaition store
+     */
+    public function initCurrentStore()
+    {
+        //not applicable for default storage
+    }
+
+    /**
+     * Allow or disallow single store mode
+     *
+     * @param bool $value
+     */
+    public function setIsSingleStoreModeAllowed($value)
+    {
+        //not applicable for default storage
+    }
+
+    /**
+     * Check if store has only one store view
+     *
+     * @return bool
+     */
+    public function hasSingleStore()
+    {
+        return false;
+    }
+
+    /**
+     * Retrieve application store object
+     *
+     * @param null|string|bool|int|Mage_Core_Model_Store $id
+     * @return Mage_Core_Model_Store
+     */
+    public function getStore($id = null)
+    {
+        return $this->_store;
+    }
+
+    /**
+     * Retrieve stores array
+     *
+     * @param bool $withDefault
+     * @param bool $codeKey
+     * @return Mage_Core_Model_Store[]
+     */
+    public function getStores($withDefault = false, $codeKey = false)
+    {
+        return array();
+    }
+
+    /**
+     * Retrieve application website object
+     *
+     * @param null|bool|int|string|Mage_Core_Model_Website $id
+     * @return Mage_Core_Model_Website
+     * @throws Mage_Core_Exception
+     */
+    public function getWebsite($id = null)
+    {
+        if ($id instanceof Mage_Core_Model_Website) {
+            return $id;
+        }
+
+        return $this->_website;
+    }
+
+    /**
+     * Get loaded websites
+     *
+     * @param bool $withDefault
+     * @param bool|string $codeKey
+     * @return Mage_Core_Model_Website[]
+     */
+    public function getWebsites($withDefault = false, $codeKey = false)
+    {
+        $websites = array();
+
+        if ($withDefault) {
+            $key = $codeKey ? $this->_website->getCode() : $this->_website->getId();
+            $websites[$key] = $this->_website;
+        }
+
+        return $websites;
+    }
+
+    /**
+     * Retrieve application store group object
+     *
+     * @param null|Mage_Core_Model_Store_Group|string $id
+     * @return Mage_Core_Model_Store_Group
+     * @throws Mage_Core_Exception
+     */
+    public function getGroup($id = null)
+    {
+        if ($id instanceof Mage_Core_Model_Store_Group) {
+            return $id;
+        }
+
+        return $this->_group;
+    }
+
+    /**
+     * Prepare array of store groups
+     * can be filtered to contain default store group or not by $withDefault flag
+     * depending on flag $codeKey array keys can be group id or group code
+     *
+     * @param bool $withDefault
+     * @param bool $codeKey
+     * @return Mage_Core_Model_Store_Group[]
+     */
+    public function getGroups($withDefault = false, $codeKey = false)
+    {
+        $groups = array();
+
+        if ($withDefault) {
+            $key = $codeKey ? $this->_group->getCode() : $this->_group->getId();
+            $groups[$key] = $this->_group;
+        }
+        return $groups;
+    }
+
+    /**
+     * Reinitialize store list
+     */
+    public function reinitStores()
+    {
+        //not applicable for default storage
+    }
+
+    /**
+     * Retrieve default store for default group and website
+     *
+     * @return Mage_Core_Model_Store
+     */
+    public function getDefaultStoreView()
+    {
+       return null;
+    }
+
+    /**
+     *  Unset website by id from app cache
+     *
+     * @param null|bool|int|string|Mage_Core_Model_Website $id
+     */
+    public function clearWebsiteCache($id = null)
+    {
+        //not applicable for default storage
+    }
+
+    /**
+     * Get either default or any store view
+     *
+     * @return Mage_Core_Model_Store
+     */
+    public function getAnyStoreView()
+    {
+        return null;
+    }
+
+    /**
+     * Set current default store
+     *
+     * @param string $store
+     */
+    public function setCurrentStore($store)
+    {
+
+    }
+
+    /**
+     * @throws Mage_Core_Model_Store_Exception
+     */
+    public function throwStoreException()
+    {
+        //not applicable for default storage
+    }
+
+    /**
+     * Get current store code
+     *
+     * @return string
+     */
+    public function getCurrentStore()
+    {
+        return $this->_store->getCode();
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Store/StorageFactory.php b/app/code/core/Mage/Core/Model/Store/StorageFactory.php
new file mode 100644
index 0000000000000000000000000000000000000000..c9f07ea0bd56905d46c5846e7823d059a83ecc4f
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Store/StorageFactory.php
@@ -0,0 +1,140 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license   http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Store_StorageFactory
+{
+    /**
+     * @var Magento_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * Default storage class name
+     *
+     * @var string
+     */
+    protected $_defaultStorageClassName;
+
+    /**
+     * Installed storage class name
+     *
+     * @var string
+     */
+    protected $_installedStoreClassName;
+
+    /**
+     * @var Mage_Core_Model_Store_StorageInterface[]
+     */
+    protected $_cache = array();
+
+    /**
+     * @var Mage_Core_Model_Event_Manager
+     */
+    protected $_eventManager;
+
+    /**
+     * @var Mage_Core_Model_Logger
+     */
+    protected $_log;
+
+    /**
+     * @var Mage_Core_Model_ConfigInterface
+     */
+    protected $_config;
+
+    /**
+     * @var Mage_Core_Model_App_Proxy
+     */
+    protected $_app;
+
+    /**
+     * @var Mage_Core_Model_App_State
+     */
+    protected $_appState;
+
+    /**
+     * @param Magento_ObjectManager $objectManager
+     * @param Mage_Core_Model_Event_Manager $eventManager
+     * @param Mage_Core_Model_Logger $log
+     * @param Mage_Core_Model_ConfigInterface $config
+     * @param Mage_Core_Model_App_Proxy $app
+     * @param Mage_Core_Model_App_State $appState
+     * @param string $defaultStorageClassName
+     * @param string $installedStoreClassName
+     */
+    public function __construct(
+        Magento_ObjectManager $objectManager,
+        Mage_Core_Model_Event_Manager $eventManager,
+        Mage_Core_Model_Logger $log,
+        Mage_Core_Model_ConfigInterface $config,
+        Mage_Core_Model_App_Proxy $app,
+        Mage_Core_Model_App_State $appState,
+        $defaultStorageClassName = 'Mage_Core_Model_Store_Storage_Default',
+        $installedStoreClassName = 'Mage_Core_Model_Store_Storage_Db'
+    ) {
+        $this->_objectManager = $objectManager;
+        $this->_defaultStorageClassName = $defaultStorageClassName;
+        $this->_installedStoreClassName = $installedStoreClassName;
+        $this->_eventManager = $eventManager;
+        $this->_log = $log;
+        $this->_appState = $appState;
+        $this->_config = $config;
+        $this->_app = $app;
+    }
+
+    /**
+     * Get storage instance
+     *
+     * @param array $arguments
+     * @return Mage_Core_Model_Store_StorageInterface
+     * @throws InvalidArgumentException
+     */
+    public function get(array $arguments = array())
+    {
+        $className = $this->_appState->isInstalled() ?
+            $this->_installedStoreClassName :
+            $this->_defaultStorageClassName;
+
+        if (false == isset($this->_cache[$className])) {
+            /** @var $instance Mage_Core_Model_Store_StorageInterface */
+            $instance = $this->_objectManager->get($className, $arguments);
+
+            if (false === ($instance instanceof Mage_Core_Model_Store_StorageInterface)) {
+                throw new InvalidArgumentException($className
+                        . ' doesn\'t implement Mage_Core_Model_Store_StorageInterface'
+                );
+            }
+            $this->_cache[$className] = $instance;
+            $instance->initCurrentStore();
+            if ($className === $this->_installedStoreClassName) {
+                $useSid = $instance->getStore()->getConfig(Mage_Core_Model_Session_Abstract::XML_PATH_USE_FRONTEND_SID);
+                $this->_app->setUseSessionInUrl($useSid);
+
+                $this->_eventManager->dispatch('core_app_init_current_store_after');
+
+                $this->_log->initForStore($instance->getStore(true), $this->_config);
+            }
+        }
+        return $this->_cache[$className];
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Store/StorageInterface.php b/app/code/core/Mage/Core/Model/Store/StorageInterface.php
new file mode 100644
index 0000000000000000000000000000000000000000..9334f685530773c6f47ee0013b3efc036322b48e
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Store/StorageInterface.php
@@ -0,0 +1,30 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license   http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+interface Mage_Core_Model_Store_StorageInterface extends Mage_Core_Model_Store_ListInterface
+{
+    /**
+     * Initialize current application store
+     */
+    public function initCurrentStore();
+}
diff --git a/app/code/core/Mage/Core/Model/StoreFactory.php b/app/code/core/Mage/Core/Model/StoreFactory.php
new file mode 100644
index 0000000000000000000000000000000000000000..07a60bdda40129a364bb4b4e2aba9171b2e86847
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/StoreFactory.php
@@ -0,0 +1,52 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_Core
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_StoreFactory
+{
+    /**
+     * @var Magento_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * @param Magento_ObjectManager $objectManager
+     */
+    public function __construct(Magento_ObjectManager $objectManager)
+    {
+        $this->_objectManager = $objectManager;
+    }
+
+    /**
+     * Create store instance
+     *
+     * @param array $arguments
+     * @return Mage_Core_Model_Store
+     */
+    public function create(array $arguments = array())
+    {
+        return $this->_objectManager->create('Mage_Core_Model_Store', $arguments);
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/StoreManager.php b/app/code/core/Mage/Core/Model/StoreManager.php
new file mode 100644
index 0000000000000000000000000000000000000000..529db2958539d77859db723c4f296f6f209f7f45
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/StoreManager.php
@@ -0,0 +1,315 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license   http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_StoreManager implements Mage_Core_Model_StoreManagerInterface
+{
+    /**
+     * Store storage factory model
+     *
+     * @var Mage_Core_Model_Store_StorageFactory
+     */
+    protected $_factory;
+
+    /**
+     * Event manager
+     *
+     * @var Mage_Core_Model_Event_Manager
+     */
+    protected $_eventManager;
+
+    /**
+     * Request model
+     *
+     * @var Mage_Core_Controller_Request_Http
+     */
+    protected $_request;
+
+    /**
+     * Default store code
+     *
+     * @var string
+     */
+    protected $_currentStore = null;
+
+    /**
+     * Flag is single store mode allowed
+     *
+     * @var bool
+     */
+    protected $_isSingleStoreAllowed = true;
+
+    /**
+     * Requested scope code
+     *
+     * @var string
+     */
+    protected $_scopeCode;
+
+    /**
+     * Requested scope type
+     *
+     * @var string
+     */
+    protected $_scopeType;
+
+    /**
+     * Helper factory
+     *
+     * @var Mage_Core_Model_Factory_Helper
+     */
+    protected $_helperFactory;
+
+    /**
+     * @param Mage_Core_Model_Store_StorageFactory $factory
+     * @param Mage_Core_Controller_Request_Http $request
+     * @param Mage_Core_Model_Factory_Helper $helperFactory
+     * @param string $scopeCode
+     * @param string $scopeType
+     */
+    public function __construct(
+        Mage_Core_Model_Store_StorageFactory $factory,
+        Mage_Core_Controller_Request_Http $request,
+        Mage_Core_Model_Factory_Helper $helperFactory,
+        $scopeCode,
+        $scopeType
+    ) {
+        $this->_factory = $factory;
+        $this->_request = $request;
+        $this->_scopeCode = $scopeCode;
+        $this->_scopeType = $scopeType ?: self::SCOPE_TYPE_STORE;
+        $this->_helperFactory = $helperFactory;
+    }
+
+    /**
+     * Get storage instance
+     *
+     * @return Mage_Core_Model_Store_StorageInterface
+     */
+    protected function _getStorage()
+    {
+        $arguments = array(
+            'isSingleStoreAllowed' => $this->_isSingleStoreAllowed,
+            'currentStore' => $this->_currentStore,
+            'scopeCode' => $this->_scopeCode,
+            'scopeType' => $this->_scopeType,
+        );
+        return $this->_factory->get($arguments);
+    }
+
+    /**
+     * Retrieve application store object without Store_Exception
+     *
+     * @param string|int|Mage_Core_Model_Store $id
+     * @return Mage_Core_Model_Store
+     */
+    public function getSafeStore($id = null)
+    {
+        try {
+            return $this->getStore($id);
+        } catch (Exception $e) {
+            if ($this->_getStorage()->getCurrentStore()) {
+                $this->_request->setActionName('noRoute');
+                return new Varien_Object();
+            }
+
+            Mage::throwException(
+                $this->_helperFactory->get('Mage_Core_Helper_Data')
+                    ->__('Requested invalid store "%s"', $id)
+            );
+        }
+    }
+
+    /**
+     * Set current default store
+     *
+     * @param string $store
+     */
+    public function setCurrentStore($store)
+    {
+        $this->_currentStore = $store;
+        $this->_getStorage()->setCurrentStore($store);
+    }
+
+    /**
+     * @throws Mage_Core_Model_Store_Exception
+     */
+    public function throwStoreException()
+    {
+        $this->_getStorage()->throwStoreException();
+    }
+
+    /**
+     * Allow or disallow single store mode
+     *
+     * @param bool $value
+     */
+    public function setIsSingleStoreModeAllowed($value)
+    {
+        $this->_isSingleStoreAllowed = $value;
+        $this->_getStorage()->setIsSingleStoreModeAllowed($value);
+    }
+
+    /**
+     * Check if store has only one store view
+     *
+     * @return bool
+     */
+    public function hasSingleStore()
+    {
+        return $this->_getStorage()->hasSingleStore();
+    }
+
+    /**
+     * Check if system is run in the single store mode
+     *
+     * @return bool
+     */
+    public function isSingleStoreMode()
+    {
+        /** @var $helper Mage_Core_Helper_Data */
+        $helper =  $this->_helperFactory->get('Mage_Core_Helper_Data');
+        return $this->hasSingleStore() && $helper->isSingleStoreModeEnabled();
+    }
+
+    /**
+     * Retrieve application store object
+     *
+     * @param null|string|bool|int|Mage_Core_Model_Store $id
+     * @return Mage_Core_Model_Store
+     * @throws Mage_Core_Model_Store_Exception
+     */
+    public function getStore($id = null)
+    {
+        return $this->_getStorage()->getStore($id);
+    }
+
+    /**
+     * Retrieve stores array
+     *
+     * @param bool $withDefault
+     * @param bool $codeKey
+     * @return Mage_Core_Model_Store[]
+     */
+    public function getStores($withDefault = false, $codeKey = false)
+    {
+        return $this->_getStorage()->getStores($withDefault, $codeKey);
+    }
+
+    /**
+     * Retrieve application website object
+     *
+     * @param null|bool|int|string|Mage_Core_Model_Website $id
+     * @return Mage_Core_Model_Website
+     * @throws Mage_Core_Exception
+     */
+    public function getWebsite($id = null)
+    {
+        return $this->_getStorage()->getWebsite($id);
+    }
+
+    /**
+     * Get loaded websites
+     *
+     * @param bool $withDefault
+     * @param bool|string $codeKey
+     * @return Mage_Core_Model_Website[]
+     */
+    public function getWebsites($withDefault = false, $codeKey = false)
+    {
+        return $this->_getStorage()->getWebsites($withDefault, $codeKey);
+    }
+
+    /**
+     * Reinitialize store list
+     */
+    public function reinitStores()
+    {
+        $this->_getStorage()->reinitStores();
+    }
+
+    /**
+     * Retrieve default store for default group and website
+     *
+     * @return Mage_Core_Model_Store
+     */
+    public function getDefaultStoreView()
+    {
+        return $this->_getStorage()->getDefaultStoreView();
+    }
+
+    /**
+     * Retrieve application store group object
+     *
+     * @param null|Mage_Core_Model_Store_Group|string $id
+     * @return Mage_Core_Model_Store_Group
+     * @throws Mage_Core_Exception
+     */
+    public function getGroup($id = null)
+    {
+        return $this->_getStorage()->getGroup($id);
+    }
+
+    /**
+     * Prepare array of store groups
+     * can be filtered to contain default store group or not by $withDefault flag
+     * depending on flag $codeKey array keys can be group id or group code
+     *
+     * @param bool $withDefault
+     * @param bool $codeKey
+     * @return Mage_Core_Model_Store_Group[]
+     */
+    public function getGroups($withDefault = false, $codeKey = false)
+    {
+        return $this->_getStorage()->getGroups($withDefault, $codeKey);
+    }
+
+    /**
+     *  Unset website by id from app cache
+     *
+     * @param null|bool|int|string|Mage_Core_Model_Website $id
+     */
+    public function clearWebsiteCache($id = null)
+    {
+        $this->_getStorage()->clearWebsiteCache($id);
+    }
+
+    /**
+     * Get either default or any store view
+     *
+     * @return Mage_Core_Model_Store|null
+     */
+    public function getAnyStoreView()
+    {
+        return $this->_getStorage()->getAnyStoreView();
+    }
+
+    /**
+     * Get current store code
+     *
+     * @return string
+     */
+    public function getCurrentStore()
+    {
+        return $this->_getStorage()->getCurrentStore();
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/StoreManagerInterface.php b/app/code/core/Mage/Core/Model/StoreManagerInterface.php
new file mode 100644
index 0000000000000000000000000000000000000000..46f9bfb4420a7e68f0b2a593d73e4f82185ec263
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/StoreManagerInterface.php
@@ -0,0 +1,49 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license   http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+interface Mage_Core_Model_StoreManagerInterface extends Mage_Core_Model_Store_ListInterface
+{
+
+    /**#@+
+     * Available scope types
+     */
+    const SCOPE_TYPE_STORE   = 'store';
+    const SCOPE_TYPE_GROUP   = 'group';
+    const SCOPE_TYPE_WEBSITE = 'website';
+    /**#@-*/
+
+    /**
+     * Retrieve application store object without Store_Exception
+     *
+     * @param string|int|Mage_Core_Model_Store $id
+     * @return Mage_Core_Model_Store
+     */
+    public function getSafeStore($id = null);
+
+    /**
+     * Check if system is run in the single store mode
+     *
+     * @return bool
+     */
+    public function isSingleStoreMode();
+}
diff --git a/app/code/core/Mage/Core/Model/Theme.php b/app/code/core/Mage/Core/Model/Theme.php
index b8d6869719f113d49aa8eb0c9d84e458aae31360..6e1c5445d54ae454b16d3b5ac8eb88886779d002 100644
--- a/app/code/core/Mage/Core/Model/Theme.php
+++ b/app/code/core/Mage/Core/Model/Theme.php
@@ -177,7 +177,7 @@ class Mage_Core_Model_Theme extends Mage_Core_Model_Abstract
         $validator = $this->_objectManager->get('Mage_Core_Model_Theme_Validator');
         if (!$validator->validate($this)) {
             $messages = $validator->getErrorMessages();
-            Mage::throwException(implode(PHP_EOL, reset($messages)));
+            throw new Mage_Core_Exception(implode(PHP_EOL, reset($messages)));
         }
         return $this;
     }
@@ -289,6 +289,9 @@ class Mage_Core_Model_Theme extends Mage_Core_Model_Abstract
      */
     protected function _applyCustomizationFiles()
     {
+        if (!$this->isCustomized()) {
+            return $this;
+        }
         /** @var $link Mage_Core_Model_Theme_Customization_Link */
         $link = $this->_objectManager->create('Mage_Core_Model_Theme_Customization_Link');
         $link->setThemeId($this->getId())->changeCustomFilesUpdate();
@@ -327,11 +330,7 @@ class Mage_Core_Model_Theme extends Mage_Core_Model_Abstract
             $this->_applyCustomizationFiles();
         }
 
-        /** @var $service Mage_Core_Model_Theme_Service */
-        $service = $this->_objectManager->get('Mage_Core_Model_Theme_Service');
-        if ($service->isThemeAssignedToStore($this)) {
-            $this->_eventDispatcher->dispatch('assigned_theme_save_after');
-        }
+        $this->_checkAssignedThemeChanged();
         return parent::_afterSave();
     }
 
@@ -349,18 +348,33 @@ class Mage_Core_Model_Theme extends Mage_Core_Model_Abstract
     /**
      * Processing theme before deleting data
      *
-     * @throws Mage_Core_Exception
      * @return Mage_Core_Model_Theme
+     * @throws Mage_Core_Exception
      */
     protected function _beforeDelete()
     {
         if (!$this->isDeletable()) {
-            Mage::throwException($this->_helper->__('Theme isn\'t deletable.'));
+            throw new Mage_Core_Exception($this->_helper->__('Theme isn\'t deletable.'));
         }
         $this->getThemeImage()->removePreviewImage();
         return parent::_beforeDelete();
     }
 
+    /**
+     * Check is theme assigned to store and dispatch event if that was changed
+     *
+     * @return Mage_Core_Model_Theme
+     */
+    protected function _checkAssignedThemeChanged()
+    {
+        /** @var $service Mage_Core_Model_Theme_Service */
+        $service = $this->_objectManager->get('Mage_Core_Model_Theme_Service');
+        if ($service->isThemeAssignedToStore($this)) {
+            $this->_eventDispatcher->dispatch('assigned_theme_changed', array('theme' => $this));
+        }
+        return $this;
+    }
+
     /**
      * Update all relations after deleting theme
      *
diff --git a/app/code/core/Mage/Core/Model/Theme/Customization/Files/Js.php b/app/code/core/Mage/Core/Model/Theme/Customization/Files/Js.php
index a2fc125b08d521ed2e896c6c12df3a544c3d8d1a..08fc02d5ab9ed722ded18e0ae594217293bcf56d 100644
--- a/app/code/core/Mage/Core/Model/Theme/Customization/Files/Js.php
+++ b/app/code/core/Mage/Core/Model/Theme/Customization/Files/Js.php
@@ -238,7 +238,7 @@ class Mage_Core_Model_Theme_Customization_Files_Js extends Mage_Core_Model_Theme
         $collection = $this->getCollectionByTheme($theme);
         /** @var $file Mage_Core_Model_Theme_Files */
         foreach ($collection as $file) {
-            $position = array_search($file->getFileName(), $orderData);
+            $position = array_search($file->getId(), $orderData);
             if ($position === false) {
                 //uploaded files will be on top
                 $file->setSortOrder(0);
diff --git a/app/code/core/Mage/Core/Model/Theme/Image.php b/app/code/core/Mage/Core/Model/Theme/Image.php
index 083dcbd1701a8d4fd2f84373c4f0349027a1b044..6e1b3a609d87ccc8692e387ea3391a3b987459d6 100644
--- a/app/code/core/Mage/Core/Model/Theme/Image.php
+++ b/app/code/core/Mage/Core/Model/Theme/Image.php
@@ -171,9 +171,9 @@ class Mage_Core_Model_Theme_Image extends Varien_Object
      */
     protected function _getPreviewImagePublishedRootDir()
     {
-        /** @var $design Mage_Core_Model_Design_Package */
-        $design = $this->_objectManager->get('Mage_Core_Model_Design_Package');
-        $dirPath = $design->getPublicDir();
+        /** @var $dir Mage_Core_Model_Dir */
+        $dir = $this->_objectManager->get('Mage_Core_Model_Dir');
+        $dirPath = $dir->getDir(Mage_Core_Model_Dir::THEME);
         $this->_filesystem->setIsAllowCreateDirectories(true);
         $this->_filesystem->ensureDirectoryExists($dirPath);
         $this->_filesystem->setWorkingDirectory($dirPath);
diff --git a/app/code/core/Mage/Core/Model/Theme/Service.php b/app/code/core/Mage/Core/Model/Theme/Service.php
index 08f0e57bd4c98d98ce2d19facd90d419f1545662..c2d9a7778b051c7274edc016bf8babe816c4ccec 100644
--- a/app/code/core/Mage/Core/Model/Theme/Service.php
+++ b/app/code/core/Mage/Core/Model/Theme/Service.php
@@ -78,19 +78,27 @@ class Mage_Core_Model_Theme_Service
     protected $_layoutUpdate;
 
     /**
+     * Application event manager
+     *
      * @var Mage_Core_Model_Event_Manager
      */
     protected $_eventManager;
 
     /**
-     * Initialize service model
+     * Configuration writer
      *
+     * @var Mage_Core_Model_Config_Storage_WriterInterface
+     */
+    protected $_configWriter;
+
+    /**
      * @param Mage_Core_Model_Theme_Factory $themeFactory
      * @param Mage_Core_Model_Design_Package $design
      * @param Mage_Core_Model_App $app
      * @param Mage_Core_Helper_Data $helper
      * @param Mage_DesignEditor_Model_Resource_Layout_Update $layoutUpdate
      * @param Mage_Core_Model_Event_Manager $eventManager
+     * @param Mage_Core_Model_Config_Storage_WriterInterface $configWriter
      */
     public function __construct(
         Mage_Core_Model_Theme_Factory $themeFactory,
@@ -98,7 +106,8 @@ class Mage_Core_Model_Theme_Service
         Mage_Core_Model_App $app,
         Mage_Core_Helper_Data $helper,
         Mage_DesignEditor_Model_Resource_Layout_Update $layoutUpdate,
-        Mage_Core_Model_Event_Manager $eventManager
+        Mage_Core_Model_Event_Manager $eventManager,
+        Mage_Core_Model_Config_Storage_WriterInterface $configWriter
     ) {
         $this->_themeFactory = $themeFactory;
         $this->_design       = $design;
@@ -106,6 +115,7 @@ class Mage_Core_Model_Theme_Service
         $this->_helper       = $helper;
         $this->_layoutUpdate = $layoutUpdate;
         $this->_eventManager = $eventManager;
+        $this->_configWriter = $configWriter;
     }
 
     /**
@@ -136,13 +146,13 @@ class Mage_Core_Model_Theme_Service
         /** @var $config Mage_Core_Model_Config_Data */
         foreach ($this->_getAssignedScopesCollection($scope, $configPath) as $config) {
             if ($config->getValue() == $themeId && !in_array($config->getScopeId(), $stores)) {
-                $this->_app->getConfig()->deleteConfig($configPath, $scope, $config->getScopeId());
+                $this->_configWriter->delete($configPath, $scope, $config->getScopeId());
             }
         }
 
         if (count($stores) > 0) {
             foreach ($stores as $storeId) {
-                $this->_app->getConfig()->saveConfig($configPath, $themeCustomization->getId(), $scope, $storeId);
+                $this->_configWriter->save($configPath, $themeCustomization->getId(), $scope, $storeId);
             }
 
             $this->_app->cleanCache(Mage_Core_Model_Config::CACHE_TAG);
@@ -197,7 +207,7 @@ class Mage_Core_Model_Theme_Service
      */
     protected function _getAssignedScopesCollection($scope, $configPath)
     {
-        return $this->_app->getConfig()->getConfigDataModel()->getCollection()
+        return Mage::getSingleton('Mage_Core_Model_Config_Data')->getCollection()
             ->addFieldToFilter('scope', $scope)
             ->addFieldToFilter('path', $configPath);
     }
@@ -211,7 +221,7 @@ class Mage_Core_Model_Theme_Service
     protected function _makeTemporaryLayoutUpdatesPermanent($themeId, array $storeIds)
     {
         // currently all layout updates are related to theme only
-        $storeIds = array_merge($storeIds, array(Mage_Core_Model_App::ADMIN_STORE_ID));
+        $storeIds = array_merge($storeIds, array(Mage_Core_Model_AppInterface::ADMIN_STORE_ID));
 
         $this->_layoutUpdate->makeTemporaryLayoutUpdatesPermanent($themeId, $storeIds);
     }
diff --git a/app/code/core/Mage/Core/Model/Translate.php b/app/code/core/Mage/Core/Model/Translate.php
index a3b1083c0211e0d2954b5d62f642319db22f734d..4ad94f5f4474d4424cf086494106f748cb876b80 100644
--- a/app/code/core/Mage/Core/Model/Translate.php
+++ b/app/code/core/Mage/Core/Model/Translate.php
@@ -64,11 +64,6 @@ class Mage_Core_Model_Translate
      */
     const CONFIG_KEY_DESIGN_THEME   = 'theme';
 
-    /**
-     * Xml path locale inheritance
-     */
-    const XML_PATH_LOCALE_INHERITANCE = 'global/locale/inheritance';
-
     /**
      * Default translation string
      */
@@ -151,22 +146,14 @@ class Mage_Core_Model_Translate
      * Initialize translate model
      *
      * @param Mage_Core_Model_Design_Package $designPackage
-     * @param array $data
+     * @param Mage_Core_Model_Locale_Hierarchy_Loader $loader
      */
-    public function __construct(Mage_Core_Model_Design_Package $designPackage, array $data = array())
-    {
+    public function __construct(
+        Mage_Core_Model_Design_Package $designPackage,
+        Mage_Core_Model_Locale_Hierarchy_Loader $loader
+    ) {
         $this->_designPackage = $designPackage;
-        if (isset($data['locale_hierarchy']) && is_array($data['locale_hierarchy'])) {
-            $this->_localeHierarchy = $data['locale_hierarchy'];
-        } else {
-            // Try to load locale inheritance from Magento configuration
-            $inheritanceNode = Mage::getConfig()->getNode(self::XML_PATH_LOCALE_INHERITANCE);
-            if ($inheritanceNode instanceof Varien_Simplexml_Element) {
-                $this->_localeHierarchy = Mage::helper('Mage_Core_Helper_Translate')->composeLocaleHierarchy(
-                    $inheritanceNode->asCanonicalArray()
-                );
-            }
-        }
+        $this->_localeHierarchy = $loader->load();
     }
 
     /**
diff --git a/app/code/core/Mage/Core/Model/Url.php b/app/code/core/Mage/Core/Model/Url.php
index 4872b6baaabadb7f4ba93d9890ac542c8c1d03a8..bab614d0f4e7d8f056dbda8502c237615aae5beb 100644
--- a/app/code/core/Mage/Core/Model/Url.php
+++ b/app/code/core/Mage/Core/Model/Url.php
@@ -379,7 +379,7 @@ class Mage_Core_Model_Url extends Varien_Object
          * Add availability support urls without store code
          */
         if ($this->getType() == Mage_Core_Model_Store::URL_TYPE_LINK
-            && Mage::app()->getRequest()->isDirectAccessFrontendName($this->getRouteFrontName())) {
+            && $this->getRequest()->isDirectAccessFrontendName($this->getRouteFrontName())) {
             $this->setType(Mage_Core_Model_Store::URL_TYPE_DIRECT_LINK);
         }
 
diff --git a/app/code/core/Mage/Core/Model/Validator/Factory.php b/app/code/core/Mage/Core/Model/Validator/Factory.php
index 051de560fe9b42e454ff1feb2c46679b0f1b8f7f..7063a3116d1fd8ebd359959f8b859f44f23ab379 100644
--- a/app/code/core/Mage/Core/Model/Validator/Factory.php
+++ b/app/code/core/Mage/Core/Model/Validator/Factory.php
@@ -30,11 +30,6 @@ class Mage_Core_Model_Validator_Factory
      */
     protected $_objectManager;
 
-    /**
-     * @var Mage_Core_Model_Config
-     */
-    protected $_config;
-
     /**
      * @var Mage_Core_Model_Translate
      */
@@ -51,19 +46,18 @@ class Mage_Core_Model_Validator_Factory
      * Initialize dependencies
      *
      * @param Magento_ObjectManager $objectManager
-     * @param Mage_Core_Model_Config $config
+     * @param Mage_Core_Model_Config_Modules_Reader $moduleReader
      * @param Mage_Core_Model_Translate $translator
      */
     public function __construct(
         Magento_ObjectManager $objectManager,
-        Mage_Core_Model_Config $config,
+        Mage_Core_Model_Config_Modules_Reader $moduleReader,
         Mage_Core_Model_Translate $translator
     ) {
         $this->_objectManager = $objectManager;
-        $this->_config = $config;
         $this->_translator = $translator;
 
-        $this->_configFiles = $this->_config->getModuleConfigurationFiles('validation.xml');
+        $this->_configFiles = $moduleReader->getModuleConfigurationFiles('validation.xml');
         $this->_initializeDefaultTranslator();
     }
 
diff --git a/app/code/core/Mage/Core/Model/Website.php b/app/code/core/Mage/Core/Model/Website.php
index 8c2b6f4a238a42885a491efa287f79a0c3d8b16a..8ffae597206c90cded350394bf4a63c2c8000f38 100644
--- a/app/code/core/Mage/Core/Model/Website.php
+++ b/app/code/core/Mage/Core/Model/Website.php
@@ -33,8 +33,10 @@
  * @method string getName()
  * @method string getGroupTitle()
  * @method string getStoreTitle()
- * @method string getStoreId()
- * @method string getGroupId()
+ * @method int getStoreId()
+ * @method int getGroupId()
+ * @method int getWebsiteId()
+ * @method bool hasWebsiteId()
  * @method Mage_Core_Model_Website setName(string $value)
  * @method int getSortOrder()
  * @method Mage_Core_Model_Website setSortOrder(int $value)
diff --git a/app/code/core/Mage/Core/etc/config.xml b/app/code/core/Mage/Core/etc/config.xml
index c83669fcdbac8822bad6476af0b8f150457f83b4..d4b677579d972305c5f0365709f3568fad5f7e21 100644
--- a/app/code/core/Mage/Core/etc/config.xml
+++ b/app/code/core/Mage/Core/etc/config.xml
@@ -109,15 +109,17 @@
             </theme_registration_from_filesystem>
         </events>
         <di>
+            <preferences>
+                <Mage_Core_Model_Session_Abstract>Mage_Core_Model_Session</Mage_Core_Model_Session_Abstract>
+            </preferences>
             <Magento_Data_Structure>
                 <shared>0</shared>
             </Magento_Data_Structure>
-            <Magento_Filesystem>
+            <Mage_Core_Model_Store_StorageFactory>
                 <parameters>
-                    <adapter>Magento_Filesystem_Adapter_Local</adapter>
+                    <config>Mage_Core_Model_Config_Proxy</config>
                 </parameters>
-                <shared>0</shared>
-            </Magento_Filesystem>
+            </Mage_Core_Model_Store_StorageFactory>
             <Mage_Core_Model_Theme_Image>
                 <shared>0</shared>
             </Mage_Core_Model_Theme_Image>
diff --git a/app/code/core/Mage/Customer/Block/Widget/Dob.php b/app/code/core/Mage/Customer/Block/Widget/Dob.php
index b5d2f504ecec3c7f5805886b8f3016cf849adb35..f9fb6a3d8ef57ff97caf98e634927e65a7860955 100644
--- a/app/code/core/Mage/Customer/Block/Widget/Dob.php
+++ b/app/code/core/Mage/Customer/Block/Widget/Dob.php
@@ -33,6 +33,12 @@ class Mage_Customer_Block_Widget_Dob extends Mage_Customer_Block_Widget_Abstract
      */
     protected $_dateInputs = array();
 
+    /**
+     * Constants for borders of date-type customer attributes
+     */
+    const MIN_DATE_RANGE_KEY = 'date_range_min';
+    const MAX_DATE_RANGE_KEY = 'date_range_max';
+
     public function _construct()
     {
         parent::_construct();
@@ -118,4 +124,26 @@ class Mage_Customer_Block_Widget_Dob extends Mage_Customer_Block_Widget_Abstract
         return sprintf($dateFormat,
             $this->_dateInputs['m'], $this->_dateInputs['d'], $this->_dateInputs['y']);
     }
+
+    /**
+     * Return minimal date range value
+     *
+     * @return string
+     */
+    public function getMinDateRange()
+    {
+        $rules = $this->_getAttribute('dob')->getValidateRules();
+        return isset($rules[self::MIN_DATE_RANGE_KEY]) ? date("Y/m/d", $rules[self::MIN_DATE_RANGE_KEY]) : null;
+    }
+
+    /**
+     * Return maximal date range value
+     *
+     * @return string
+     */
+    public function getMaxDateRange()
+    {
+        $rules = $this->_getAttribute('dob')->getValidateRules();
+        return isset($rules[self::MAX_DATE_RANGE_KEY]) ? date("Y/m/d", $rules[self::MAX_DATE_RANGE_KEY]) : null;
+    }
 }
diff --git a/app/code/core/Mage/Customer/Helper/Address.php b/app/code/core/Mage/Customer/Helper/Address.php
index 90755a9a27db9a2b8f6d003ddad3148cc1afcffa..336395cb6392abda66d126067a32733a9718aef0 100644
--- a/app/code/core/Mage/Customer/Helper/Address.php
+++ b/app/code/core/Mage/Customer/Helper/Address.php
@@ -70,11 +70,12 @@ class Mage_Customer_Helper_Address extends Mage_Core_Helper_Abstract
     protected $_blockFactory;
 
     /**
-     * Class constructor
+     * @param Mage_Core_Model_Translate $translator
      * @param Mage_Core_Model_BlockFactory $blockFactory
      */
-    public function __construct(Mage_Core_Model_BlockFactory $blockFactory)
+    public function __construct(Mage_Core_Model_Translate $translator, Mage_Core_Model_BlockFactory $blockFactory)
     {
+        parent::__construct($translator);
         $this->_blockFactory = $blockFactory;
     }
 
@@ -103,8 +104,8 @@ class Mage_Customer_Helper_Address extends Mage_Core_Helper_Abstract
 
     public function getRenderer($renderer)
     {
-        if (is_string($renderer) && $className = Mage::getConfig()->getBlockClassName($renderer)) {
-            return $this->_blockFactory->createBlock($className, array());
+        if (is_string($renderer) && $renderer) {
+            return $this->_blockFactory->createBlock($renderer, array());
         } else {
             return $renderer;
         }
@@ -119,10 +120,14 @@ class Mage_Customer_Helper_Address extends Mage_Core_Helper_Abstract
      */
     public function getConfig($key, $store = null)
     {
-        $websiteId = Mage::app()->getStore($store)->getWebsiteId();
+        /** @var $storeManager Mage_Core_Model_StoreManager */
+        $storeManager = Mage::getObjectManager()->get('Mage_Core_Model_StoreManager');
+        /** @var $store Mage_Core_Model_Store */
+        $store = $storeManager->getStore($store);
 
+        $websiteId = $store->getWebsiteId();
         if (!isset($this->_config[$websiteId])) {
-            $this->_config[$websiteId] = Mage::getStoreConfig('customer/address', $store);
+            $this->_config[$websiteId] = $store->getConfig('customer/address', $store);
         }
         return isset($this->_config[$websiteId][$key]) ? (string)$this->_config[$websiteId][$key] : null;
     }
diff --git a/app/code/core/Mage/Customer/view/frontend/address.js b/app/code/core/Mage/Customer/view/frontend/address.js
new file mode 100644
index 0000000000000000000000000000000000000000..fd97d945390bb395bd3c09ca0a36b8a48f1e3109
--- /dev/null
+++ b/app/code/core/Mage/Customer/view/frontend/address.js
@@ -0,0 +1,68 @@
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    mage customer view
+ * @package     mage
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+/*jshint browser:true, jquery:true*/
+/*global confirm:true*/
+(function($, window) {
+    "use strict";
+    $.widget('mage.address', {
+        /**
+         * Options common to all instances of this widget.
+         * @type {Object}
+         */
+        options: {
+            deleteConfirmMessage: $.mage.__('Are you sure you want to delete this address?')
+        },
+
+        /**
+         * Bind event handlers for adding and deleting addresses.
+         * @private
+         */
+        _create: function() {
+            $(this.options.addAddress).on('click', $.proxy(this._addAddress, this));
+            $(this.options.deleteAddress).on('click', $.proxy(this._deleteAddress, this));
+        },
+
+        /**
+         * Add a new address.
+         * @private
+         */
+        _addAddress: function() {
+            window.location = this.options.addAddressLocation;
+        },
+
+        /**
+         * Delete the address whose id is specified in a data attribute after confirmation from the user.
+         * @private
+         * @param {Event}
+         * @return {Boolean}
+         */
+        _deleteAddress: function(e) {
+            if (confirm(this.options.deleteConfirmMessage)) {
+                window.location = this.options.deleteUrlPrefix + $(e.target).data('address');
+            }
+            return false;
+        }
+    });
+})(jQuery, window);
diff --git a/app/code/core/Mage/Customer/view/frontend/address.phtml b/app/code/core/Mage/Customer/view/frontend/address.phtml
index edb97dd2a41501673674e894cbf892f6155a0a46..8ccee739316e4d24eb2641da005c584a4bc9094a 100644
--- a/app/code/core/Mage/Customer/view/frontend/address.phtml
+++ b/app/code/core/Mage/Customer/view/frontend/address.phtml
@@ -18,8 +18,8 @@
  * versions in the future. If you wish to customize Magento for your
  * needs please refer to http://www.magentocommerce.com for more information.
  *
- * @category    design
- * @package     base_default
+ * @category    customer address
+ * @package     mage
  * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
@@ -64,7 +64,7 @@
                         <?php echo $_address->format('html') ?>
                     </address>
                     <p>
-                        <strong><a href="<?php echo $this->getUrl('customer/address/form', array('address'=>$_address->getAddressId())) ?>" class="red-link"><?php echo $this->__('Edit Address') ?></a></strong><span class="separator">&nbsp;|&nbsp;</span><strong><a href="#" onclick="return deleteAddress('<?php echo $_address->getAddressId() ?>');" class="red-link"><?php echo $this->__('Delete Address') ?></a></strong>
+                        <strong><a href="<?php echo $this->getUrl('customer/address/form', array('address'=>$_address->getAddressId())) ?>" class="red-link"><?php echo $this->__('Edit Address') ?></a></strong><span class="separator">&nbsp;|&nbsp;</span><strong><a href="#" role="delete-address" data-address="<?php echo $_address->getAddressId() ?>" class="red-link"><?php echo $this->__('Delete Address') ?></a></strong>
                     </p>
                     </td>
                 </tr>
@@ -82,13 +82,15 @@
 </table>
 <div class="buttons-set">
     <p class="back-link"><a href="<?php echo $this->getUrl('customer/account/') ?>"><small>&laquo; </small><?php echo $this->__('Back') ?></a></p>
-    <button type="button" onclick="window.location='<?php echo $this->getUrl('customer/address/form') ?>';" class="button"><span><span><?php echo $this->__('New Address') ?></span></span></button>
+    <button type="button" class="button" role="add-address"><span><span><?php echo $this->__('New Address') ?></span></span></button>
 </div>
 <script type="text/javascript">
-    function deleteAddress(addressId) {
-        if(confirm('<?php echo $this->__('Are you sure you want to delete this address?') ?>')) {
-            window.location='<?php echo $this->getUrl("customer/address/delete") ?>address/'+addressId;
-        }
-        return false;
-    }
+    head.js("<?php echo $this->getViewFileUrl('Mage_Customer::address.js') ?>", function() {
+        jQuery('div.page-title').address({
+            deleteAddress: "p a[role='delete-address']",
+            deleteUrlPrefix: "<?php echo $this->getUrl('customer/address/delete') ?>address/",
+            addAddress: "div.buttons-set button[role='add-address']",
+            addAddressLocation: "<?php echo $this->getUrl('customer/address/form') ?>"
+        });
+    });
 </script>
diff --git a/app/code/core/Mage/Customer/view/frontend/address/book.phtml b/app/code/core/Mage/Customer/view/frontend/address/book.phtml
index b9abc3d65074626fcdf1d0f202301f3a2b51e562..69ce26348fcebb605250e0d20c04915f4c4f346d 100644
--- a/app/code/core/Mage/Customer/view/frontend/address/book.phtml
+++ b/app/code/core/Mage/Customer/view/frontend/address/book.phtml
@@ -18,8 +18,8 @@
  * versions in the future. If you wish to customize Magento for your
  * needs please refer to http://www.magentocommerce.com for more information.
  *
- * @category    design
- * @package     base_default
+ * @category    customer address book
+ * @package     mage
  * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
@@ -32,7 +32,7 @@
 ?>
 <div class="page-title title-buttons">
     <h1><?php echo $this->__('Address Book') ?></h1>
-    <button type="button" title="<?php echo $this->__('Add New Address') ?>" class="button" onclick="window.location='<?php echo $this->getAddAddressUrl() ?>';"><span><span><?php echo $this->__('Add New Address') ?></span></span></button>
+    <button type="button" role="add-address" title="<?php echo $this->__('Add New Address') ?>" class="button"><span><span><?php echo $this->__('Add New Address') ?></span></span></button>
 </div>
 <?php echo $this->getMessagesBlock()->getGroupedHtml() ?>
 <div class="col2-set addresses-list">
@@ -79,7 +79,7 @@
                 <address>
                     <?php echo $this->getAddressHtml($_address) ?>
                 </address>
-                <p><a href="<?php echo $this->getUrl('customer/address/edit', array('id'=>$_address->getId())) ?>"><?php echo $this->__('Edit Address') ?></a> <span class="separator">|</span> <a href="#" class="link-remove" onclick="return deleteAddress('<?php echo $_address->getId() ?>');"><?php echo $this->__('Delete Address') ?></a></p>
+                <p><a href="<?php echo $this->getUrl('customer/address/edit', array('id'=>$_address->getId())) ?>"><?php echo $this->__('Edit Address') ?></a> <span class="separator">|</span> <a href="#" class="link-remove" role="delete-address" data-address="<?php echo $_address->getId() ?>"><?php echo $this->__('Delete Address') ?></a></p>
             </li>
             <?php endforeach; ?>
         <?php else: ?>
@@ -94,12 +94,12 @@
     <p class="back-link"><a href="<?php echo $this->escapeUrl($this->getBackUrl()) ?>"><small>&laquo; </small><?php echo $this->__('Back') ?></a></p>
 </div>
 <script type="text/javascript">
-//<![CDATA[
-    function deleteAddress(addressId) {
-        if(confirm('<?php echo $this->__('Are you sure you want to delete this address?') ?>')) {
-            window.location='<?php echo $this->getDeleteUrl() ?>id/'+addressId;
-        }
-        return false;
-    }
-//]]>
+    head.js("<?php echo $this->getViewFileUrl('Mage_Customer::address.js');?>", function() {
+        jQuery('div.page-title').address({
+            deleteAddress: "li.item a[role='delete-address']",
+            deleteUrlPrefix: '<?php echo $this->getDeleteUrl() ?>id/',
+            addAddress: "div.title-buttons button[role='add-address']",
+            addAddressLocation: '<?php echo $this->getAddAddressUrl() ?>'
+        });
+    });
 </script>
diff --git a/app/code/core/Mage/Customer/view/frontend/logout.phtml b/app/code/core/Mage/Customer/view/frontend/logout.phtml
index e3728d657b1552de5e207ac063b5e55657e24c8d..1db6c20634f4ecdced45ab7670e93bea8c4119a2 100644
--- a/app/code/core/Mage/Customer/view/frontend/logout.phtml
+++ b/app/code/core/Mage/Customer/view/frontend/logout.phtml
@@ -29,7 +29,7 @@
 </div>
 <p><?php echo Mage::helper('Mage_Customer_Helper_Data')->__('You have logged out and will be redirected to our homepage in 5 seconds.') ?></p>
 <script type="text/javascript">
-//<![CDATA[
-    setTimeout(function(){ location.href = '<?php echo $this->getUrl() ?>'},5000);
-//]]>
+    (function($){
+        $($.mage.redirect("<?php echo $this->getUrl() ?>","assign",5000));
+    })(jQuery);
 </script>
diff --git a/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Form/Element/File.php b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Form/Element/File.php
new file mode 100644
index 0000000000000000000000000000000000000000..49a216bbe2a815f609e876bef7587cdc8bd651af
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Form/Element/File.php
@@ -0,0 +1,50 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_Theme
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Form element renderer to display file element for VDE
+ */
+class Mage_DesignEditor_Block_Adminhtml_Editor_Form_Element_File extends Varien_Data_Form_Element_File
+{
+    /**
+     * Additional html attributes
+     *
+     * @var array
+     */
+    protected $_htmlAttributes = array('accept', 'multiple');
+
+    /**
+     * Html attributes
+     *
+     * @return array
+     */
+    public function getHtmlAttributes()
+    {
+        $attributes = parent::getHtmlAttributes();
+        return array_merge($attributes, $this->_htmlAttributes);
+    }
+}
+
diff --git a/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools.php b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools.php
new file mode 100644
index 0000000000000000000000000000000000000000..abf6c77f1e0c8aad1268b30e3653333d3c8706f5
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools.php
@@ -0,0 +1,46 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Block that renders VDE tools panel
+ */
+class Mage_DesignEditor_Block_Adminhtml_Editor_Tools extends Mage_Core_Block_Template
+{
+    /**
+     * Get tabs
+     *
+     * @return array
+     */
+    public function getTabs()
+    {
+        return array(
+            $this->getChildHtml('design_editor_tools_design'),
+            $this->getChildHtml('design_editor_tools_block'),
+            $this->getChildHtml('design_editor_tools_settings'),
+            $this->getChildHtml('design_editor_tools_code'),
+        );
+    }
+}
diff --git a/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Block.php b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Block.php
new file mode 100644
index 0000000000000000000000000000000000000000..4ddbb779bd51c8a23463aa1fe1f0f657fc26861b
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Block.php
@@ -0,0 +1,32 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Block that renders Block tab
+ */
+class Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Block extends Mage_Core_Block_Template
+{
+}
diff --git a/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code.php b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code.php
new file mode 100644
index 0000000000000000000000000000000000000000..9e4c715a67b4806568699ecb6eb53f00ec2f46fc
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code.php
@@ -0,0 +1,45 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Block that renders Code tab (or Scripts tab)
+ */
+class Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code extends Mage_Core_Block_Template
+{
+    /**
+     * Get tabs html
+     *
+     * @return array
+     */
+    public function getTabs()
+    {
+        return array(
+            $this->getChildHtml('design_editor_tools_code_css'),
+            $this->getChildHtml('design_editor_tools_code_js'),
+            $this->getChildHtml('design_editor_tools_code_custom')
+        );
+    }
+}
diff --git a/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code/Css.php b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code/Css.php
new file mode 100644
index 0000000000000000000000000000000000000000..3187b44bbea5ec52ef4b83f2a12a80108192213b
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code/Css.php
@@ -0,0 +1,50 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Block that renders CSS tab
+ */
+class Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Css extends Mage_Core_Block_Template
+{
+    /**
+     * Get file groups content
+     *
+     * @return array
+     */
+    public function getFileGroups()
+    {
+        $groups = array();
+        foreach ($this->getCssFiles() as $groupName => $files) {
+            $groups[] =  $this->getChildBlock('design_editor_tools_code_css_group')
+                ->setTitle($groupName)
+                ->setFiles($files)
+                ->setThemeId($this->getThemeId())
+                ->toHtml();
+        }
+
+        return $groups;
+    }
+}
diff --git a/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code/Css/Group.php b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code/Css/Group.php
new file mode 100644
index 0000000000000000000000000000000000000000..e5c1cb6dcbb4139cfa3672960504779474371ee7
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code/Css/Group.php
@@ -0,0 +1,66 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Block that renders group of files
+ */
+class Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Css_Group extends Mage_Backend_Block_Widget_Form
+{
+    /**
+     * Get url to download CSS file
+     *
+     * @param string $fileId
+     * @param int $themeId
+     * @return string
+     */
+    public function getDownloadUrl($fileId, $themeId)
+    {
+        return $this->getUrl('*/system_design_theme/downloadCss', array(
+            'theme_id' => $themeId,
+            'file'     => $this->_helperFactory->get('Mage_Theme_Helper_Data')->urlEncode($fileId)
+        ));
+    }
+
+    /**
+     * Check if files group needs "add" button
+     *
+     * @return bool
+     */
+    public function hasAddButton()
+    {
+        return false;
+    }
+
+    /**
+     * Check if files group needs download buttons next to each file
+     *
+     * @return bool
+     */
+    public function hasDownloadButton()
+    {
+        return true;
+    }
+}
diff --git a/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code/Custom.php b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code/Custom.php
new file mode 100644
index 0000000000000000000000000000000000000000..f26387cf08a11015c1d0cf8d9cb32094f604eb70
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code/Custom.php
@@ -0,0 +1,120 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Block that renders Custom tab
+ *
+ * @method Mage_Core_Model_Theme getTheme()
+ * @method setTheme($theme)
+ */
+class Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Custom extends Mage_Backend_Block_Widget_Form
+{
+    /**
+     * Upload file element html id
+     */
+    const FILE_ELEMENT_NAME = 'css_file_uploader';
+
+    /**
+     * Create a form element with necessary controls
+     *
+     * @return Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Tab_Css
+     */
+    protected function _prepareForm()
+    {
+        $form = new Varien_Data_Form(array(
+            'action'   => '#',
+            'method'   => 'post'
+        ));
+        $this->setForm($form);
+        $form->setUseContainer(true);
+
+        $form->addType('css_file', 'Mage_DesignEditor_Block_Adminhtml_Editor_Form_Element_File');
+
+        $form->addField($this->getFileElementName(), 'css_file', array(
+            'name'     => $this->getFileElementName(),
+            'accept'   => 'text/css',
+            'no_span'  => true
+        ));
+
+        parent::_prepareForm();
+        return $this;
+    }
+
+    /**
+     * Get url to download custom CSS file
+     *
+     * @param Mage_Core_Model_Theme $theme
+     * @return string
+     */
+    public function getDownloadCustomCssUrl($theme)
+    {
+        return $this->getUrl('*/system_design_theme/downloadCustomCss', array('theme_id' => $theme->getThemeId()));
+    }
+
+    /**
+     * Get url to save custom CSS file
+     *
+     * @param Mage_Core_Model_Theme $theme
+     * @return string
+     */
+    public function getSaveCustomCssUrl($theme)
+    {
+        return $this->getUrl('*/system_design_editor_tools/saveCssContent', array('theme_id' => $theme->getThemeId()));
+    }
+
+    /**
+     * Get theme custom css content
+     *
+     * @param Mage_Core_Model_Theme $theme
+     * @return string
+     */
+    public function getCustomCssContent($theme)
+    {
+        /** @var $cssFile Mage_Core_Model_Theme_Files */
+        $cssFile = $theme->getCustomizationData(Mage_Core_Model_Theme_Customization_Files_Css::TYPE)->getFirstItem();
+        return $cssFile->getContent();
+    }
+
+    /**
+     * Get custom CSS file name
+     *
+     * @return string
+     */
+    public function getCustomFileName()
+    {
+        return pathinfo(Mage_Core_Model_Theme_Customization_Files_Css::FILE_PATH, PATHINFO_BASENAME);
+    }
+
+    /**
+     * Get file element name
+     *
+     * @return string
+     */
+    public function getFileElementName()
+    {
+        return self::FILE_ELEMENT_NAME;
+    }
+}
diff --git a/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code/Js.php b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code/Js.php
new file mode 100644
index 0000000000000000000000000000000000000000..37d443fb3861f1c979bbf9ecaf15687064eefaed
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code/Js.php
@@ -0,0 +1,189 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Block that renders JS tab
+ *
+ * @method Mage_Core_Model_Theme getTheme()
+ * @method setTheme($theme)
+ *
+ * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
+ */
+class Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Js extends Mage_Backend_Block_Widget_Form
+{
+    /**
+     * @var Mage_Core_Model_Theme_Service
+     */
+    protected $_service;
+
+    /**
+     * @param Mage_Core_Controller_Request_Http $request
+     * @param Mage_Core_Model_Layout $layout
+     * @param Mage_Core_Model_Event_Manager $eventManager
+     * @param Mage_Backend_Model_Url $urlBuilder
+     * @param Mage_Core_Model_Translate $translator
+     * @param Mage_Core_Model_Cache $cache
+     * @param Mage_Core_Model_Design_Package $designPackage
+     * @param Mage_Core_Model_Session $session
+     * @param Mage_Core_Model_Store_Config $storeConfig
+     * @param Mage_Core_Controller_Varien_Front $frontController
+     * @param Mage_Core_Model_Factory_Helper $helperFactory
+     * @param Mage_Core_Model_Dir $dirs
+     * @param Mage_Core_Model_Logger $logger
+     * @param Magento_Filesystem $filesystem
+     * @param Mage_Core_Model_Theme_Service $service
+     * @param array $data
+     *
+     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
+     */
+    public function __construct(
+        Mage_Core_Controller_Request_Http $request,
+        Mage_Core_Model_Layout $layout,
+        Mage_Core_Model_Event_Manager $eventManager,
+        Mage_Backend_Model_Url $urlBuilder,
+        Mage_Core_Model_Translate $translator,
+        Mage_Core_Model_Cache $cache,
+        Mage_Core_Model_Design_Package $designPackage,
+        Mage_Core_Model_Session $session,
+        Mage_Core_Model_Store_Config $storeConfig,
+        Mage_Core_Controller_Varien_Front $frontController,
+        Mage_Core_Model_Factory_Helper $helperFactory,
+        Mage_Core_Model_Dir $dirs,
+        Mage_Core_Model_Logger $logger,
+        Magento_Filesystem $filesystem,
+        Mage_Core_Model_Theme_Service $service,
+        array $data = array()
+    ) {
+        parent::__construct($request, $layout, $eventManager, $urlBuilder, $translator, $cache, $designPackage,
+            $session, $storeConfig, $frontController, $helperFactory, $dirs, $logger, $filesystem, $data
+        );
+        $this->_service = $service;
+    }
+
+    /**
+     * Create a form element with necessary controls
+     *
+     * @return Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Js
+     */
+    protected function _prepareForm()
+    {
+        $form = new Varien_Data_Form(array(
+            'action' => '#',
+            'method' => 'post'
+        ));
+        $this->setForm($form);
+        $form->setUseContainer(true);
+
+        $form->addType('js_files', 'Mage_DesignEditor_Block_Adminhtml_Editor_Form_Element_File');
+
+        $jsConfig = array(
+            'name'     => 'js_files_uploader',
+            'title'    => $this->__('Select JS Files to Upload'),
+            'accept'   => 'application/x-javascript',
+            'multiple' => '',
+        );
+        if ($this->_service->isThemeAssignedToStore($this->getTheme())) {
+            $confirmMessage = $this->__('You are about to upload JavaScript files. '
+                . 'This will take effect immediately and might affect the design of your store if your theme '
+                . 'is assigned to the store front. Are you sure you want to do this?');
+            $jsConfig['onclick'] = "return confirm('{$confirmMessage}');";
+        }
+        $form->addField('js_files_uploader', 'js_files', $jsConfig);
+
+        parent::_prepareForm();
+        return $this;
+    }
+
+    /**
+     * Return confirmation message for delete action
+     *
+     * @return string
+     */
+    public function getConfirmMessageDelete()
+    {
+        if ($this->_service->isThemeAssignedToStore($this->getTheme())) {
+            $confirmMessage = $this->__('Are you sure you want to delete the selected JavaScript file? This operation'
+                . ' cannot be undone. It will affect the theme and frontend design if the theme is currently assigned'
+                . '  to the store front');
+        } else {
+            $confirmMessage = $this->__('Are you sure you want to delete the selected JavaScript file? This operation'
+                . 'cannot be undone. It will affect the theme.');
+        }
+        return $confirmMessage;
+    }
+
+    /**
+     * Get upload js url
+     *
+     * @return string
+     */
+    public function getJsUploadUrl()
+    {
+        return $this->getUrl('*/system_design_editor_tools/uploadjs', array('id' => $this->getTheme()->getId()));
+    }
+
+    /**
+     * Get reorder js url
+     *
+     * @return string
+     */
+    public function getJsReorderUrl()
+    {
+        return $this->getUrl('*/system_design_editor_tools/reorderjs', array('id' => $this->getTheme()->getId()));
+    }
+
+    /**
+     * Get delete js url
+     *
+     * @return string
+     */
+    public function getJsDeleteUrl()
+    {
+        return $this->getUrl('*/system_design_editor_tools/deleteCustomFiles', array(
+            'id' => $this->getTheme()->getId()
+        ));
+    }
+
+    /**
+     * Get custom js files
+     *
+     * @return Mage_Core_Model_Resource_Theme_Files_Collection
+     */
+    public function getJsFiles()
+    {
+        return $this->getTheme()->getCustomizationData(Mage_Core_Model_Theme_Customization_Files_Js::TYPE);
+    }
+
+    /**
+     * Get js tab title
+     *
+     * @return string
+     */
+    public function getTitle()
+    {
+        return $this->__('Custom javascript files');
+    }
+}
diff --git a/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Design.php b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Design.php
new file mode 100644
index 0000000000000000000000000000000000000000..a35fc72c110fdd756df749689b6d1784345044c4
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Design.php
@@ -0,0 +1,33 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Block that renders Design tab
+ */
+class Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Design extends Mage_Core_Block_Template
+{
+
+}
diff --git a/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Settings.php b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Settings.php
new file mode 100644
index 0000000000000000000000000000000000000000..d790e54779426efbfde2fa4aeff28821d9f78b43
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Settings.php
@@ -0,0 +1,33 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Block that renders Settings tab
+ */
+class Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Settings extends Mage_Core_Block_Template
+{
+
+}
diff --git a/app/code/core/Mage/DesignEditor/Block/Adminhtml/Theme/Selector/StoreView.php b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Theme/Selector/StoreView.php
index 4031c6d363012ac61631bf3ca147d1b12e406663..9412bfe74bdb046555a9d824d657b8bdeacb7b6d 100644
--- a/app/code/core/Mage/DesignEditor/Block/Adminhtml/Theme/Selector/StoreView.php
+++ b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Theme/Selector/StoreView.php
@@ -140,7 +140,7 @@ class Mage_DesignEditor_Block_Adminhtml_Theme_Selector_StoreView extends Mage_Ba
         $assignSaveButton = $this->getLayout()->createBlock('Mage_Backend_Block_Widget_Button');
         $assignSaveButton->setData(array(
             'label'     => $this->__('Assign'),
-            'class'     => 'action-save',
+            'class'     => 'action-save primary',
             'data_attribute' => array(
                 'mage-init' => array(
                     'button' => array(
diff --git a/app/code/core/Mage/DesignEditor/Controller/Varien/Router/Standard.php b/app/code/core/Mage/DesignEditor/Controller/Varien/Router/Standard.php
index 4adae5b9a4bc5ab9dfbb794298a86684a9fc5f89..c2a154194a994874ec8b923734828197963fa828 100644
--- a/app/code/core/Mage/DesignEditor/Controller/Varien/Router/Standard.php
+++ b/app/code/core/Mage/DesignEditor/Controller/Varien/Router/Standard.php
@@ -42,18 +42,19 @@ class Mage_DesignEditor_Controller_Varien_Router_Standard extends Mage_Core_Cont
      * @param Mage_Core_Controller_Varien_Action_Factory $controllerFactory
      * @param Magento_ObjectManager $objectManager
      * @param Magento_Filesystem $filesystem
+     * @param Mage_Core_Model_App $app
      * @param string $areaCode
-     * @param string $baseController
-     * @throws InvalidArgumentException
+     * @param $baseController
      */
     public function __construct(
         Mage_Core_Controller_Varien_Action_Factory $controllerFactory,
         Magento_ObjectManager $objectManager,
         Magento_Filesystem $filesystem,
+        Mage_Core_Model_App $app,
         $areaCode,
         $baseController
     ) {
-        parent::__construct($controllerFactory, $filesystem, $areaCode, $baseController);
+        parent::__construct($controllerFactory, $filesystem, $app, $areaCode, $baseController);
         $this->_objectManager = $objectManager;
     }
 
diff --git a/app/code/core/Mage/DesignEditor/Helper/Data.php b/app/code/core/Mage/DesignEditor/Helper/Data.php
index 75472cd587e0626ebeb8cc1d5c35526695cf4bde..6f441595bac9470afa6effcbc9b3d975b02fc4a3 100644
--- a/app/code/core/Mage/DesignEditor/Helper/Data.php
+++ b/app/code/core/Mage/DesignEditor/Helper/Data.php
@@ -47,10 +47,12 @@ class Mage_DesignEditor_Helper_Data extends Mage_Core_Helper_Abstract
     protected $_configuration;
 
     /**
+     * @param Mage_Core_Model_Translate $translator
      * @param Mage_Core_Model_Config $configuration
      */
-    public function __construct(Mage_Core_Model_Config $configuration)
+    public function __construct(Mage_Core_Model_Translate $translator, Mage_Core_Model_Config $configuration)
     {
+        parent::__construct($translator);
         $this->_configuration = $configuration;
     }
 
diff --git a/app/code/core/Mage/DesignEditor/Model/Change/Factory.php b/app/code/core/Mage/DesignEditor/Model/Change/Factory.php
index fc27523a41f3f70558d741e3743c8a95faaa75dc..1084c0c348c6f98a44caea292c9eb2b9ece57ef7 100644
--- a/app/code/core/Mage/DesignEditor/Model/Change/Factory.php
+++ b/app/code/core/Mage/DesignEditor/Model/Change/Factory.php
@@ -131,8 +131,8 @@ class Mage_DesignEditor_Model_Change_Factory
     protected static function _getAttributes(Varien_Simplexml_Element $layoutUpdate)
     {
         $attributes = array(
-            'type'        => $layoutUpdate->getAttribute('type') ?: self::DEFAULT_TYPE,
-            'action_name' => $layoutUpdate->getName()
+            'type'        => (string) $layoutUpdate->getAttribute('type') ?: self::DEFAULT_TYPE,
+            'action_name' => (string) $layoutUpdate->getName()
         );
 
         return $attributes;
diff --git a/app/code/core/Mage/DesignEditor/controllers/Adminhtml/System/Design/Editor/ToolsController.php b/app/code/core/Mage/DesignEditor/controllers/Adminhtml/System/Design/Editor/ToolsController.php
new file mode 100644
index 0000000000000000000000000000000000000000..6ac9ac6aeaa513f72d1efddff2f47b33adbf9c30
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/controllers/Adminhtml/System/Design/Editor/ToolsController.php
@@ -0,0 +1,230 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Backend controller for the design editor
+ */
+class Mage_DesignEditor_Adminhtml_System_Design_Editor_ToolsController extends Mage_Adminhtml_Controller_Action
+{
+    /**
+     *  Upload custom CSS action
+     */
+    public function uploadAction()
+    {
+        $themeId = (int)$this->getRequest()->getParam('theme');
+
+        /** @var $themeCss Mage_Core_Model_Theme_Customization_Files_Css */
+        $themeCss = $this->_objectManager->create('Mage_Core_Model_Theme_Customization_Files_Css');
+
+        /** @var $serviceModel Mage_Theme_Model_Uploader_Service */
+        $serviceModel = $this->_objectManager->get('Mage_Theme_Model_Uploader_Service');
+        try {
+            $theme = $this->_loadTheme($themeId);
+
+            $cssFileContent = $serviceModel->uploadCssFile(
+                Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Custom::FILE_ELEMENT_NAME
+            )->getFileContent();
+            $themeCss->setDataForSave($cssFileContent);
+            $themeCss->saveData($theme);
+            $response = array('error' => false, 'content' => $cssFileContent);
+            $this->_session->addSuccess($this->__('Success: Theme custom css was saved.'));
+        } catch (Mage_Core_Exception $e) {
+            $this->_session->addError($e->getMessage());
+            $response = array('error' => true, 'message' => $e->getMessage());
+        } catch (Exception $e) {
+            $errorMessage = $this->__('Cannot upload css file');
+            $this->_session->addError($errorMessage);
+            $response = array('error' => true, 'message' => $errorMessage);
+            $this->_objectManager->get('Mage_Core_Model_Logger')->logException($e);
+        }
+        $this->loadLayout();
+        $response['message_html'] = $this->getLayout()->getMessagesBlock()->toHtml();
+        $this->getResponse()->setBody($this->_objectManager->get('Mage_Core_Helper_Data')->jsonEncode($response));
+    }
+
+    /**
+     * Save custom css file
+     */
+    public function saveCssContentAction()
+    {
+        $themeId = $this->getRequest()->getParam('theme_id', false);
+        $customCssContent = $this->getRequest()->getParam('custom_css_content', null);
+        try {
+            if (!$themeId || (null === $customCssContent)) {
+                throw new InvalidArgumentException('Param "stores" is not valid');
+            }
+
+            $theme = $this->_loadTheme($themeId);
+
+            /** @var $themeCss Mage_Core_Model_Theme_Customization_Files_Css */
+            $themeCss = $this->_objectManager->create('Mage_Core_Model_Theme_Customization_Files_Css');
+            $themeCss->setDataForSave($customCssContent);
+            $theme->setCustomization($themeCss)->save();
+            $response = array('error' => false);
+            $this->_session->addSuccess($this->__('Theme custom css was saved.'));
+        } catch (Mage_Core_Exception $e) {
+            $this->_session->addError($e->getMessage());
+            $response = array('error' => true, 'message' => $e->getMessage());
+        } catch (Exception $e) {
+            $errorMessage = $this->__('Cannot save custom css');
+            $this->_session->addError($errorMessage);
+            $response = array('error' => true, 'message' => $errorMessage);
+            $this->_objectManager->get('Mage_Core_Model_Logger')->logException($e);
+        }
+        $this->loadLayout();
+        $response['message_html'] = $this->getLayout()->getMessagesBlock()->toHtml();
+        $this->getResponse()->setBody($this->_objectManager->get('Mage_Core_Helper_Data')->jsonEncode($response));
+    }
+
+    /**
+     * Ajax list of existing javascript files
+     */
+    public function jsListAction()
+    {
+        $themeId = $this->getRequest()->getParam('id');
+        try {
+            $theme = $this->_loadTheme($themeId);
+            $this->loadLayout();
+
+            /** @var $filesJs Mage_Core_Model_Theme_Customization_Files_Js */
+            $filesJs = $this->_objectManager->create('Mage_Core_Model_Theme_Customization_Files_Js');
+            $customJsFiles = $theme->setCustomization($filesJs)
+                ->getCustomizationData(Mage_Core_Model_Theme_Customization_Files_Js::TYPE);
+
+            $jsItemsBlock = $this->getLayout()->getBlock('design_editor_tools_code_js_items');
+            $jsItemsBlock->setJsFiles($customJsFiles);
+
+            $result = array('error' => false, 'content' => $jsItemsBlock->toHtml());
+            $this->getResponse()->setBody($this->_objectManager->get('Mage_Core_Helper_Data')->jsonEncode($result));
+        } catch (Exception $e) {
+            $this->_objectManager->get('Mage_Core_Model_Logger')->logException($e);
+        }
+    }
+
+    /**
+     * Upload js file
+     */
+    public function uploadJsAction()
+    {
+        /** @var $serviceModel Mage_Theme_Model_Uploader_Service */
+        $serviceModel = $this->_objectManager->get('Mage_Theme_Model_Uploader_Service');
+        $themeId = $this->getRequest()->getParam('id');
+        try {
+            $theme = $this->_loadTheme($themeId);
+            $serviceModel->uploadJsFile('js_files_uploader', $theme, false);
+            $theme->setCustomization($serviceModel->getJsFiles())->save();
+            $this->_forward('jsList');
+            return;
+        } catch (Mage_Core_Exception $e) {
+            $this->_getSession()->addError($e->getMessage());
+            $response = array('error' => true, 'message' => $e->getMessage());
+        } catch (Exception $e) {
+            $errorMessage = $this->__('Cannot upload js file');
+            $this->_getSession()->addError($errorMessage);
+            $response = array('error' => true, 'message' => $errorMessage);
+            $this->_objectManager->get('Mage_Core_Model_Logger')->logException($e);
+        }
+        $this->loadLayout();
+        $response['message_html'] = $this->getLayout()->getMessagesBlock()->toHtml();
+        $this->getResponse()->setBody($this->_objectManager->get('Mage_Core_Helper_Data')->jsonEncode($response));
+    }
+
+    /**
+     * Delete custom file action
+     */
+    public function deleteCustomFilesAction()
+    {
+        $themeId = $this->getRequest()->getParam('id');
+        $removeJsFiles = (array)$this->getRequest()->getParam('js_removed_files');
+        try {
+            $theme = $this->_loadTheme($themeId);
+
+            /** @var $themeJs Mage_Core_Model_Theme_Customization_Files_Js */
+            $themeJs = $this->_objectManager->create('Mage_Core_Model_Theme_Customization_Files_Js');
+            $theme->setCustomization($themeJs);
+
+            $themeJs->setDataForDelete($removeJsFiles);
+            $theme->save();
+
+            $this->_forward('jsList');
+        } catch (Exception $e) {
+            $this->_redirectUrl($this->_getRefererUrl());
+            $this->_objectManager->get('Mage_Core_Model_Logger')->logException($e);
+        }
+    }
+
+    /**
+     * Reorder js file
+     */
+    public function reorderJsAction()
+    {
+        $themeId = $this->getRequest()->getParam('id');
+        $reorderJsFiles = (array)$this->getRequest()->getParam('js_order', array());
+        /** @var $themeJs Mage_Core_Model_Theme_Customization_Files_Js */
+        $themeJs = $this->_objectManager->create('Mage_Core_Model_Theme_Customization_Files_Js');
+        try {
+            $theme = $this->_loadTheme($themeId);
+            $themeJs->setJsOrderData($reorderJsFiles);
+            $theme->setCustomization($themeJs);
+            $theme->save();
+
+            $result = array('success' => true);
+        } catch (Mage_Core_Exception $e) {
+            $this->_session->addError($e->getMessage());
+            $result = array('error' => true, 'message' => $e->getMessage());
+        } catch (Exception $e) {
+            $errorMessage = $this->__('Cannot upload css file');
+            $this->_session->addError($errorMessage);
+            $result = array('error' => true, 'message' => $errorMessage);
+            $this->_objectManager->get('Mage_Core_Model_Logger')->logException($e);
+        }
+        $this->loadLayout();
+        $result['message_html'] = $this->getLayout()->getMessagesBlock()->toHtml();
+        $this->getResponse()->setBody($this->_objectManager->get('Mage_Core_Helper_Data')->jsonEncode($result));
+    }
+
+    /**
+     * Load theme by theme id
+     *
+     * Method also checks if theme actually loaded and if theme is virtual or not
+     *
+     * @param int $themeId
+     * @return Mage_Core_Model_Theme
+     * @throws Mage_Core_Exception
+     */
+    protected function _loadTheme($themeId)
+    {
+        /** @var $theme Mage_Core_Model_Theme */
+        $theme = $this->_objectManager->create('Mage_Core_Model_Theme');
+        if (!$themeId || !$theme->load($themeId)->getId()) {
+            throw new Mage_Core_Exception($this->__('Theme "%s" was not found.', $themeId));
+        }
+        if (!$theme->isEditable()) {
+            throw new Mage_Core_Exception($this->__('Theme "%s" is not editable.', $themeId));
+        }
+        return $theme;
+    }
+}
diff --git a/app/code/core/Mage/DesignEditor/controllers/Adminhtml/System/Design/EditorController.php b/app/code/core/Mage/DesignEditor/controllers/Adminhtml/System/Design/EditorController.php
index 01c0dfb6cad606b04788626c9a66e93686b59d40..9d8cd519a543b44cb0c90d2a1d644db18e7c30b5 100644
--- a/app/code/core/Mage/DesignEditor/controllers/Adminhtml/System/Design/EditorController.php
+++ b/app/code/core/Mage/DesignEditor/controllers/Adminhtml/System/Design/EditorController.php
@@ -37,60 +37,6 @@ class Mage_DesignEditor_Adminhtml_System_Design_EditorController extends Mage_Ad
         $this->_doSelectionTheme('firstEntrance');
     }
 
-    /**
-     * Display available theme list. Only when no customized themes
-     */
-    public function firstEntranceAction()
-    {
-        $this->_doSelectionTheme('index');
-    }
-
-    /**
-     * Check whether is customized themes in database
-     *
-     * @return bool
-     */
-    protected function _isFirstEntrance()
-    {
-        /** @var $themeService Mage_Core_Model_Theme_Service */
-        $themeService = $this->_objectManager->get('Mage_Core_Model_Theme_Service');
-        return !$themeService->isCustomizationsExist();
-    }
-
-    /**
-     * Load layout
-     *
-     * @param string $forwardAction
-     */
-    protected function _doSelectionTheme($forwardAction)
-    {
-        if ($forwardAction == 'index' xor $this->_isFirstEntrance()) {
-            $this->_forward($forwardAction);
-            return;
-        }
-
-        try {
-            $this->_title($this->__('System'))->_title($this->__('Design'))->_title($this->__('Editor'));
-            $this->loadLayout();
-            $this->_setActiveMenu('Mage_DesignEditor::system_design_editor');
-            if (!$this->_isFirstEntrance()) {
-                /** @var $themeService Mage_Core_Model_Theme_Service */
-                $themeService = $this->_objectManager->get('Mage_Core_Model_Theme_Service');
-                $this->getLayout()->getBlock('assigned.theme.list')->setCollection(
-                    $themeService->getAssignedThemeCustomizations()
-                );
-                $this->getLayout()->getBlock('unassigned.theme.list')->setCollection(
-                    $themeService->getUnassignedThemeCustomizations()
-                );
-            }
-            $this->renderLayout();
-        } catch (Exception $e) {
-            $this->_getSession()->addError($this->__('Cannot load list of themes.'));
-            $this->_redirectUrl($this->_getRefererUrl());
-            $this->_objectManager->get('Mage_Core_Model_Logger')->logException($e);
-        }
-    }
-
     /**
      * Ajax loading available themes
      */
@@ -117,8 +63,8 @@ class Mage_DesignEditor_Adminhtml_System_Design_EditorController extends Mage_Ad
         } catch (Exception $e) {
             $this->_objectManager->get('Mage_Core_Model_Logger')->logException($e);
             $this->getResponse()->setBody($coreHelper->jsonEncode(
-                    array('error' => $this->_helper->__('Theme list can not be loaded')))
-            );
+                array('error' => $this->_helper->__('Theme list can not be loaded'))
+            ));
         }
     }
 
@@ -135,7 +81,7 @@ class Mage_DesignEditor_Adminhtml_System_Design_EditorController extends Mage_Ad
         try {
             $theme->load($themeId);
             if (!$theme->getId()) {
-                throw new InvalidArgumentException($this->__('The theme was not found.'));
+                throw new InvalidArgumentException(sprintf('Theme "%s" was not found.', $themeId));
             }
 
             if (!$theme->isVirtual()) {
@@ -161,9 +107,11 @@ class Mage_DesignEditor_Adminhtml_System_Design_EditorController extends Mage_Ad
             );
             $pageTypes = $customFrontLayout->getPageHandlesHierarchy();
 
-            $this->_title($this->__('System'))->_title($this->__('Design'))->_title($this->__('Editor'));
+            $this->_setTitle();
             $this->loadLayout();
 
+            $this->_configureToolsBlock($theme);
+
             /** @var $toolbarBlock Mage_DesignEditor_Block_Adminhtml_Editor_Toolbar_Buttons */
             $toolbarBlock = $this->getLayout()->getBlock('design_editor_toolbar_buttons');
             $toolbarBlock->setThemeId($themeId)
@@ -219,40 +167,6 @@ class Mage_DesignEditor_Adminhtml_System_Design_EditorController extends Mage_Ad
         $this->_redirect('*/*/');
     }
 
-    /**
-     * Get current handle
-     *
-     * @return string
-     */
-    protected function _getCurrentHandleUrl()
-    {
-        /** @var $vdeUrlModel Mage_DesignEditor_Model_Url_Handle */
-        $vdeUrlModel = $this->_objectManager->get('Mage_DesignEditor_Model_Url_Handle');
-        $handle = $this->_getSession()->getData(Mage_DesignEditor_Model_State::CURRENT_HANDLE_SESSION_KEY);
-        if (empty($handle)) {
-            $handle = 'default';
-        }
-
-        return $vdeUrlModel->getUrl('design/page/type', array('handle' => $handle));
-    }
-
-    /**
-     * Get current url
-     *
-     * @return string
-     */
-    protected function _getCurrentUrl()
-    {
-        /** @var $vdeUrlModel Mage_DesignEditor_Model_Url_NavigationMode */
-        $vdeUrlModel = $this->_objectManager->get('Mage_DesignEditor_Model_Url_NavigationMode');
-        $url = $this->_getSession()->getData(Mage_DesignEditor_Model_State::CURRENT_URL_SESSION_KEY);
-        if (empty($url)) {
-            $url = '';
-        }
-
-        return $vdeUrlModel->getUrl(ltrim($url, '/'));
-    }
-
     /**
      * Assign theme to list of store views
      */
@@ -292,7 +206,7 @@ class Mage_DesignEditor_Adminhtml_System_Design_EditorController extends Mage_Ad
             $themeService = $this->_objectManager->get('Mage_Core_Model_Theme_Service');
             /** @var $themeCustomization Mage_Core_Model_Theme */
             $themeCustomization = $themeService->assignThemeToStores($themeId, $stores);
-            
+
             $message = $coreHelper->__('Theme successfully assigned');
             $response = array(
                 'success' => $message,
@@ -302,8 +216,8 @@ class Mage_DesignEditor_Adminhtml_System_Design_EditorController extends Mage_Ad
         } catch (Exception $e) {
             $this->_objectManager->get('Mage_Core_Model_Logger')->logException($e);
             $this->getResponse()->setBody($coreHelper->jsonEncode(
-                    array('error' => $this->_helper->__('Theme is not assigned')))
-            );
+                array('error' => $this->_helper->__('Theme is not assigned'))
+            ));
             $response = array(
                 'error'   => true,
                 'message' => $this->_helper->__('Theme is not assigned')
@@ -327,10 +241,10 @@ class Mage_DesignEditor_Adminhtml_System_Design_EditorController extends Mage_Ad
             /** @var $theme Mage_Core_Model_Theme */
             $theme = $this->_objectManager->get('Mage_Core_Model_Theme');
             if (!($themeId && $theme->load($themeId)->getId())) {
-                throw new Mage_Core_Exception($this->__('The theme was not found.'));
+                Mage::throwException($this->__('The theme was not found.'));
             }
             if (!$theme->isVirtual()) {
-                throw new Mage_Core_Exception($this->__('This theme is not editable.'));
+                Mage::throwException($this->__('This theme is not editable.'));
             }
             $theme->setThemeTitle($themeTitle);
             $theme->save();
@@ -343,11 +257,85 @@ class Mage_DesignEditor_Adminhtml_System_Design_EditorController extends Mage_Ad
         } catch (Exception $e) {
             $this->_objectManager->get('Mage_Core_Model_Logger')->logException($e);
             $this->getResponse()->setBody($coreHelper->jsonEncode(
-                    array('error' => true, 'message' => $this->__('Theme is not saved')))
-            );
+                array('error' => true, 'message' => $this->__('Theme is not saved'))
+            ));
         }
     }
 
+    /**
+     * Get layout xml
+     */
+    public function getLayoutUpdateAction()
+    {
+        $historyData = Mage::app()->getRequest()->getPost('historyData');
+        if (!$historyData) {
+            $this->getResponse()->setBody(Mage::helper('Mage_Core_Helper_Data')->jsonEncode(
+                array(Mage_Core_Model_Message::ERROR => array($this->__('Invalid post data')))
+            ));
+            return;
+        }
+
+        try {
+            $layoutUpdate = $this->_compactHistory($historyData);
+            $this->getResponse()->setBody(Mage::helper('Mage_Core_Helper_Data')->jsonEncode(array(
+                Mage_Core_Model_Message::SUCCESS => array($layoutUpdate)
+            )));
+        } catch (Mage_Core_Exception $e) {
+            $this->getResponse()->setBody(Mage::helper('Mage_Core_Helper_Data')->jsonEncode(
+                array(Mage_Core_Model_Message::ERROR => array($e->getMessage()))
+            ));
+        }
+    }
+
+    /**
+     * Save temporary layout update
+     */
+    public function saveTemporaryLayoutUpdateAction()
+    {
+        $themeId = (int)$this->_getSession()->getData('theme_id');
+        /** @var $coreHelper Mage_Core_Helper_Data */
+        $coreHelper = $this->_objectManager->get('Mage_Core_Helper_Data');
+
+        try {
+            if (!is_numeric($themeId)) {
+                throw new InvalidArgumentException('Theme id is not valid');
+            }
+
+            if ($this->getRequest()->has('layoutUpdate')) {
+                $this->_saveLayoutUpdate(
+                    $this->getRequest()->getParam('layoutUpdate'),
+                    $this->getRequest()->getParam('handle'),
+                    $themeId,
+                    true
+                );
+            }
+            $this->getResponse()->setBody($coreHelper->jsonEncode(
+                array('success' => $this->__('Temporary layout update saved'))
+            ));
+        } catch (Exception $e) {
+            $this->_objectManager->get('Mage_Core_Model_Logger')->logException($e);
+            $this->getResponse()->setBody($coreHelper->jsonEncode(
+                array('error' => $this->__('Temporary layout update not saved'))
+            ));
+        }
+    }
+
+    /**
+     * Display available theme list. Only when no customized themes
+     */
+    public function firstEntranceAction()
+    {
+        $this->_doSelectionTheme('index');
+    }
+
+    /**
+     * Set page title
+     */
+    protected function _setTitle()
+    {
+        $this->_title($this->__('System'))->_title($this->__('Design'))->_title($this->__('Editor'));
+    }
+
     /**
      * Whether the current user has enough permissions to execute an action
      *
@@ -398,7 +386,7 @@ class Mage_DesignEditor_Adminhtml_System_Design_EditorController extends Mage_Ad
         /** @var $layoutCollection Mage_DesignEditor_Model_Resource_Layout_Update_Collection */
         $layoutCollection = $this->_objectManager
             ->create('Mage_DesignEditor_Model_Resource_Layout_Update_Collection');
-        $layoutCollection->addStoreFilter(Mage_Core_Model_App::ADMIN_STORE_ID)
+        $layoutCollection->addStoreFilter(Mage_Core_Model_AppInterface::ADMIN_STORE_ID)
             ->addThemeFilter($themeId)
             ->addFieldToFilter('handle', $handle)
             ->addFieldToFilter('is_vde', true)
@@ -414,7 +402,7 @@ class Mage_DesignEditor_Adminhtml_System_Design_EditorController extends Mage_Ad
 
         if ($xml || $layoutUpdate) {
             $layoutUpdateData = array(
-                'store_id'     => Mage_Core_Model_App::ADMIN_STORE_ID,
+                'store_id'     => Mage_Core_Model_AppInterface::ADMIN_STORE_ID,
                 'theme_id'     => $themeId,
                 'handle'       => $handle,
                 'xml'          => $this->_compactHistory($layoutUpdate, $xml),
@@ -447,74 +435,133 @@ class Mage_DesignEditor_Adminhtml_System_Design_EditorController extends Mage_Ad
     }
 
     /**
-     * Get layout xml
+     * Get theme customization
+     *
+     * @param Mage_Core_Model_Theme $theme
+     * @return Mage_Core_Model_Theme
      */
-    public function getLayoutUpdateAction()
+    protected function _getThemeCustomization($theme)
     {
-        $historyData = Mage::app()->getRequest()->getPost('historyData');
-        if (!$historyData) {
-            $this->getResponse()->setBody(Mage::helper('Mage_Core_Helper_Data')->jsonEncode(
-                array(Mage_Core_Model_Message::ERROR => array($this->__('Invalid post data')))
-            ));
-            return;
+        /** @var $service Mage_Core_Model_Theme_Service */
+        $service = $this->_objectManager->get('Mage_Core_Model_Theme_Service');
+        return $service->createThemeCustomization($theme);
+    }
+
+    /**
+     * Pass CSS files data to the block who need it for rendering
+     *
+     * @param Mage_Core_Model_Theme $theme
+     * @return Mage_DesignEditor_Adminhtml_System_Design_EditorController
+     */
+    protected function _configureToolsBlock($theme)
+    {
+        /** @var $customTabBlock Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Custom */
+        $customTabBlock = $this->getLayout()->getBlock('design_editor_tools_code_custom');
+        if ($customTabBlock) {
+            $theme->setCustomization($this->_objectManager->create('Mage_Core_Model_Theme_Customization_Files_Css'));
+            $customTabBlock->setTheme($theme);
         }
 
-        try {
-            $layoutUpdate = $this->_compactHistory($historyData);
-            $this->getResponse()->setBody(Mage::helper('Mage_Core_Helper_Data')->jsonEncode(array(
-                Mage_Core_Model_Message::SUCCESS => array($layoutUpdate)
-            )));
-        } catch (Mage_Core_Exception $e) {
-            $this->getResponse()->setBody(Mage::helper('Mage_Core_Helper_Data')->jsonEncode(
-                array(Mage_Core_Model_Message::ERROR => array($e->getMessage()))
-            ));
+        /** @var $cssTabBlock Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Css */
+        $cssTabBlock = $this->getLayout()->getBlock('design_editor_tools_code_css');
+        if ($cssTabBlock) {
+            /** @var $helper Mage_Core_Helper_Theme */
+            $helper = $this->_objectManager->get('Mage_Core_Helper_Theme');
+            $cssFiles = $helper->getGroupedCssFiles($theme);
+            $cssTabBlock->setCssFiles($cssFiles)
+                ->setThemeId($theme->getId());
+        }
+
+        /** @var $jsTabBlock Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Js */
+        $jsTabBlock = $this->getLayout()->getBlock('design_editor_tools_code_js');
+        if ($jsTabBlock) {
+            /** @var $jsFileModel Mage_Core_Model_Theme_Customization_Files_Js */
+            $jsFileModel = $this->_objectManager->create('Mage_Core_Model_Theme_Customization_Files_Js');
+            $theme->setCustomization($jsFileModel);
+
+            $jsTabBlock->setTheme($theme);
         }
+
+        return $this;
     }
 
     /**
-     * Save temporary layout update
-     * @throws InvalidArgumentException
+     * Check whether is customized themes in database
+     *
+     * @return bool
      */
-    public function saveTemporaryLayoutUpdateAction()
+    protected function _isFirstEntrance()
     {
-        $themeId = (int)$this->_getSession()->getData('theme_id');
-        /** @var $coreHelper Mage_Core_Helper_Data */
-        $coreHelper = $this->_objectManager->get('Mage_Core_Helper_Data');
+        /** @var $themeService Mage_Core_Model_Theme_Service */
+        $themeService = $this->_objectManager->get('Mage_Core_Model_Theme_Service');
+        return !$themeService->isCustomizationsExist();
+    }
 
-        try {
-            if (!is_numeric($themeId)) {
-                throw new InvalidArgumentException('Theme id is not valid');
-            }
+    /**
+     * Load layout
+     *
+     * @param string $forwardAction
+     */
+    protected function _doSelectionTheme($forwardAction)
+    {
+        if ($forwardAction == 'index' xor $this->_isFirstEntrance()) {
+            $this->_forward($forwardAction);
+            return;
+        }
 
-            if ($this->getRequest()->has('layoutUpdate')) {
-                $this->_saveLayoutUpdate(
-                    $this->getRequest()->getParam('layoutUpdate'),
-                    $this->getRequest()->getParam('handle'),
-                    $themeId,
-                    true
+        try {
+            $this->_setTitle();
+            $this->loadLayout();
+            $this->_setActiveMenu('Mage_DesignEditor::system_design_editor');
+            if (!$this->_isFirstEntrance()) {
+                /** @var $themeService Mage_Core_Model_Theme_Service */
+                $themeService = $this->_objectManager->get('Mage_Core_Model_Theme_Service');
+                $this->getLayout()->getBlock('assigned.theme.list')->setCollection(
+                    $themeService->getAssignedThemeCustomizations()
+                );
+                $this->getLayout()->getBlock('unassigned.theme.list')->setCollection(
+                    $themeService->getUnassignedThemeCustomizations()
                 );
             }
-            $this->getResponse()->setBody($coreHelper->jsonEncode(
-                array('success' => $this->__('Temporary layout update saved'))
-            ));
+            $this->renderLayout();
         } catch (Exception $e) {
+            $this->_getSession()->addError($this->__('Cannot load list of themes.'));
+            $this->_redirectUrl($this->_getRefererUrl());
             $this->_objectManager->get('Mage_Core_Model_Logger')->logException($e);
-            $this->getResponse()->setBody($coreHelper->jsonEncode(
-                array('error' => $this->__('Temporary layout update not saved'))
-            ));
         }
     }
 
     /**
-     * Get theme customization
+     * Get current handle
      *
-     * @param Mage_Core_Model_Theme $theme
-     * @return Mage_Core_Model_Theme
+     * @return string
      */
-    protected function _getThemeCustomization($theme)
+    protected function _getCurrentHandleUrl()
     {
-        /** @var $service Mage_Core_Model_Theme_Service */
-        $service = $this->_objectManager->get('Mage_Core_Model_Theme_Service');
-        return $service->createThemeCustomization($theme);
+        /** @var $vdeUrlModel Mage_DesignEditor_Model_Url_Handle */
+        $vdeUrlModel = $this->_objectManager->get('Mage_DesignEditor_Model_Url_Handle');
+        $handle = $this->_getSession()->getData(Mage_DesignEditor_Model_State::CURRENT_HANDLE_SESSION_KEY);
+        if (empty($handle)) {
+            $handle = 'default';
+        }
+
+        return $vdeUrlModel->getUrl('design/page/type', array('handle' => $handle));
+    }
+
+    /**
+     * Get current url
+     *
+     * @return string
+     */
+    protected function _getCurrentUrl()
+    {
+        /** @var $vdeUrlModel Mage_DesignEditor_Model_Url_NavigationMode */
+        $vdeUrlModel = $this->_objectManager->get('Mage_DesignEditor_Model_Url_NavigationMode');
+        $url = $this->_getSession()->getData(Mage_DesignEditor_Model_State::CURRENT_URL_SESSION_KEY);
+        if (empty($url)) {
+            $url = '';
+        }
+
+        return $vdeUrlModel->getUrl(ltrim($url, '/'));
     }
 }
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/css/styles.css b/app/code/core/Mage/DesignEditor/view/adminhtml/css/styles.css
index d5aa9405d1444b8176ca673d08d77edf6a75293c..d5f06e2ba6c467f331d1aefd410e7a039f34b3cb 100644
--- a/app/code/core/Mage/DesignEditor/view/adminhtml/css/styles.css
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/css/styles.css
@@ -23,49 +23,6 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 
-/*
-Fonts
--------------------------------------- */
-@font-face {
-    font-family: 'CallunaSans';
-    src: url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansLight-webfont.woff');
-    src: url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansLight-webfont.eot?#iefix') format('embedded-opentype'), url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansLight-webfont.svg#webfont85gDAx2H') format('svg'), url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansLight-webfont.woff') format('woff'), url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansLight-webfont.ttf') format('truetype');
-    font-style: normal;
-    font-weight: 200;
-}
-
-@font-face {
-    font-family: 'CallunaSans';
-    src: url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansRegular-webfont.woff');
-    src: url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansRegular-webfont.eot?#iefix') format('embedded-opentype'), url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansRegular-webfont.svg#webfont85gDAx2D') format('svg'), url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansRegular-webfont.woff') format('woff'), url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansRegular-webfont.ttf') format('truetype');
-    font-style: normal;
-    font-weight: 400;
-}
-
-@font-face {
-    font-family: 'CallunaSans';
-    src: url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansSemiBold-webfont.woff');
-    src: url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansSemiBold-webfont.eot?#iefix') format('embedded-opentype'), url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansSemiBold-webfont.svg#webfont85gDAx2A') format('svg'), url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansSemiBold-webfont.woff') format('woff'), url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansSemiBold-webfont.ttf') format('truetype');
-    font-style: normal;
-    font-weight: 500;
-}
-
-@font-face {
-    font-family: 'CallunaSans';
-    src: url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansBold-webfont.woff');
-    src: url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansBold-webfont.eot?#iefix') format('embedded-opentype'), url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansBold-webfont.svg#webfont85gDAx2C') format('svg'), url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansBold-webfont.woff') format('woff'), url('Mage_DesignEditor::/css/fonts/calluna/CallunaSansBold-webfont.ttf') format('truetype');
-    font-style: normal;
-    font-weight: 600;
-}
-
-@font-face {
-    font-family: 'MUI-Icons';
-    src: url('Mage_DesignEditor::/css/fonts/MUI-Icons.eot');
-    src: url('Mage_DesignEditor::/css/fonts/MUI-Icons.eot?#iefix') format('embedded-opentype'), url('Mage_DesignEditor::/css/fonts/MUI-Icons.svg#MUI-Icons') format('svg'), url('Mage_DesignEditor::/css/fonts/MUI-Icons.woff') format('woff'), url('Mage_DesignEditor::/css/fonts/MUI-Icons.ttf') format('truetype');
-    font-weight: normal;
-    font-style: normal;
-}
-
 /*
    Actions look like buttons
 -------------------------------------- */
@@ -109,69 +66,12 @@ Fonts
     user-select: none;
 }
 
-.action-theme-preview:hover,
-.action-theme-assign:hover,
-.action-save:hover,
-#vde_toolbar_buttons .action-theme-assign,
-#vde_toolbar_buttons .action-theme-assign:visited,
-.popup .action-save,
-.popup .action-save:visited {
-    border: 1px solid #b6754a;
-    color: #fff;
-    text-decoration: none;
-    text-shadow: 0 -1px 1px rgba(1, 1, 1, 0.5);
-    background: #f4863e;
-    background: -moz-linear-gradient(top, #f4863e 0%, #e97d37 100%);
-    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #f4863e), color-stop(100%, #e97d37));
-    background: -webkit-linear-gradient(top, #f4863e 0%, #e97d37 100%);
-    background: -o-linear-gradient(top, #f4863e 0%, #e97d37 100%);
-    background: -ms-linear-gradient(top, #f4863e 0%, #e97d37 100%);
-    background: linear-gradient(to bottom, #f4863e 0%, #e97d37 100%);
-}
-
-.action-theme-preview:focus,
-.action-theme-assign:focus,
-.action-save:focus {
-    outline: thin dotted #333;
-    outline: 5px auto -webkit-focus-ring-color;
-    outline-offset: -2px;
-}
-
-.action-theme-preview:active,
-.action-theme-preview.active,
-.action-theme-assign:active,
-.action-theme-assign.active,
-.action-save:active,
-.action-save.active {
-    border: 1px solid #b6754a;
-    color: #fff;
-    text-decoration: none;
-    text-shadow: 0 -1px 1px rgba(1, 1, 1, 0.5);
-    background: #f4863e;
-    background: -moz-linear-gradient(top, #f4863e 0%, #e97d37 100%);
-    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #f4863e), color-stop(100%, #e97d37));
-    background: -webkit-linear-gradient(top, #f4863e 0%, #e97d37 100%);
-    background: -o-linear-gradient(top, #f4863e 0%, #e97d37 100%);
-    background: -ms-linear-gradient(top, #f4863e 0%, #e97d37 100%);
-    background: linear-gradient(to bottom, #f4863e 0%, #e97d37 100%);
-}
-
-.action-theme-preview[disabled],
-.action-theme-assign[disabled],
-.action-save[disabled] {
-    cursor: not-allowed;
-    background-color: #e6e6e6;
-    background-image: none;
-    opacity: 0.65;
-    -webkit-box-shadow: none;
-    -moz-box-shadow: none;
-    box-shadow: none;
-}
+
 
 /*
     Actions look like links
 -------------------------------------- */
-.popup .action-close {
+#store-view-window .action-close {
     background: none;
     border: none;
     color: #6d665e;
@@ -181,9 +81,9 @@ Fonts
     border-bottom: 1px solid #b5b3af;
 }
 
-.popup .action-close:hover {
+#store-view-window .action-close:hover {
     color: #000;
-    border-bottom-color: #000;
+    border-bottom: 1px solid #000;
 }
 
 /*
@@ -250,6 +150,8 @@ Fonts
     font-size: 13px;
     min-width: 440px;
     box-shadow: 0 2px 10px 0 #333;
+    border: 0;
+    border-radius: 0;
 }
 
 .fade .popup-header {
@@ -258,9 +160,10 @@ Fonts
     background: #f3efea;
 }
 
-.fade .popup-title {
+.fade .popup .popup-title {
     font: 20px/1 'CallunaSans', Arial, sans-serif;
     font-weight: 300;
+    padding-left: 0;
 }
 
 .fade .popup .actions {
@@ -337,54 +240,6 @@ Fonts
     Themes Tabs
 -------------------------------------- */
 /* TODO: remove after unified tabs implementation */
-#theme_selector_tabs {
-
-}
-
-#theme_selector_tabs .tabs-horiz {
-    margin: 0;
-    padding: 0;
-    background: none;
-    list-style: none;
-    border-bottom: 1px solid #ccc;
-}
-
-#theme_selector_tabs .tabs-horiz > li {
-    margin: 0 -1px -1px 0;
-    float: left;
-    background: #eaeaea;
-    background: -moz-linear-gradient(top, #eaeaea 0%, #dfdfdf 100%);
-    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #eaeaea), color-stop(100%, #dfdfdf));
-    background: -webkit-linear-gradient(top, #eaeaea 0%, #dfdfdf 100%);
-    background: -o-linear-gradient(top, #eaeaea 0%, #dfdfdf 100%);
-    background: -ms-linear-gradient(top, #eaeaea 0%, #dfdfdf 100%);
-    background: linear-gradient(to bottom, #eaeaea 0%, #dfdfdf 100%);
-}
-
-#theme_selector_tabs .tabs-horiz > li:hover {
-    background: #dfdfdf;
-    background: -moz-linear-gradient(top, #dfdfdf 0%, #eaeaea 100%);
-    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #dfdfdf), color-stop(100%, #eaeaea));
-    background: -webkit-linear-gradient(top, #dfdfdf 0%, #eaeaea 100%);
-    background: -o-linear-gradient(top, #dfdfdf 0%, #eaeaea 100%);
-    background: -ms-linear-gradient(top, #dfdfdf 0%, #eaeaea 100%);
-    background: linear-gradient(to bottom, #dfdfdf 0%, #eaeaea 100%);
-}
-
-#theme_selector_tabs .tabs-horiz > li a {
-    padding-right: 12px;
-    padding-left: 12px;
-    padding-top: 8px;
-    padding-bottom: 8px;
-    line-height: 18px;
-    border: 1px solid #ccc;
-    text-decoration: none;
-    color: #666;
-}
-
-#theme_selector_tabs .tabs-horiz .ui-tabs-active a {
-    border-bottom-color: #fff;
-}
 
 /*
     Themes Tabs Panel
@@ -417,8 +272,8 @@ Fonts
     padding: 40px 0 0;
 }
 
-.ie8 .theme {
-    margin-right: 3%;
+.eq-ie8 .theme {
+    margin-right: 3.33%;
 }
 
 @media screen and (min-width: 1280px) {
@@ -480,6 +335,7 @@ Fonts
 }
 
 .theme-title {
+    margin: 0;
     color: #f2ebde;
     font-family: 'CallunaSans', Arial, sans-serif;
     font-weight: 200;
@@ -503,15 +359,10 @@ Fonts
     white-space: nowrap;
 }
 
-.theme-data .action-theme-assign {
+.theme-data .actions [class^='action-'] {
     margin-left: 8px;
 }
 
-.theme-data .action-theme-assign span {
-    background: none;
-    padding-left: 4px;
-}
-
 .theme-data .action-theme-preview:hover,
 .theme-data .action-theme-preview:active,
 .theme-data .action-theme-assign:hover,
@@ -524,12 +375,18 @@ Fonts
 }
 
 .theme-data .action-edit,
-.theme-data .action-delete {
-    color: #fff;
+.theme-data .action-delete,
+.theme-data .action-edit:active,
+.theme-data .action-delete:active {
+    background: none;
+    border: none;
     text-decoration: none;
+    display: inline-block;
+    box-shadow: none;
+    color: #fff;
     font-size: 16px;
     vertical-align: middle;
-    margin: 3px 0 0 7px;
+    padding: 5px;
 }
 
 .theme-data .action-edit:before,
@@ -542,25 +399,20 @@ Fonts
     font-weight: normal;
     -webkit-font-smoothing: antialiased;
     content: "\e05b";
+    color: #fff;
 }
 
-.theme-data .action-delete:before {
-    content: "\e07f";
+.theme-data .actions .action-delete {
+    margin-left: 0;
 }
 
-.theme-data .action-edit,
-.theme-data .action-delete {
-    background: none;
-    border: none;
-    display: inline-block;
-    width: 22px;
-    height: 24px;
-    overflow: hidden;
+.theme-data .action-delete:before {
+    content: "\e07f";
 }
 
-.theme-data .action-edit span {
-    background: none;
-    padding: 0;
+.theme-data .action-edit > span,
+.theme-data .action-delete > span {
+    display: none;
 }
 
 /*
@@ -575,6 +427,8 @@ Fonts
 
 .themes-customizations .theme-data .actions {
     bottom: 20px;
+    left: 0;
+    right: 10px;
 }
 
 .themes-customizations h3 {
@@ -593,7 +447,6 @@ Fonts
     text-overflow: ellipsis;
 }
 
-
 /*
     Unassigned Themes
 -------------------------------------- */
@@ -609,7 +462,9 @@ Fonts
     top: 0;
     left: 0;
     right: 0;
+    display: none;
 }
+
 .edit-theme-title-form > input[type="text"] {
     width: 70%;
 }
@@ -631,6 +486,7 @@ Fonts
     top: 5px;
     right: 0;
     left: 52%;
+    margin: 0;
     white-space: nowrap;
     overflow: hidden;
     text-overflow: ellipsis;
@@ -643,6 +499,14 @@ Fonts
 /*
     Websites/Stores/Storeviews List in Popup
 -------------------------------------- */
+.websites,
+.stores,
+.storeviews {
+    margin: 0;
+    padding: 0;
+    list-style: none;
+}
+
 .website {
     padding: 10px 0 0;
 }
@@ -666,9 +530,706 @@ Fonts
     margin: -3px 3px 0 0;
 }
 
+/*
+    Tools Panel
+-------------------------------------- */
+.vde-tools {
+    background: #060708;
+    color: #fff;
+    position: fixed;
+    left: 0;
+    bottom: 0;
+    right: 0;
+    padding: 0 0 52px;
+    z-index: 900;
+}
+
+.vde-tools-header {
+    position: absolute;
+    left: 0;
+    right: 0;
+    top: 0;
+    height: 52px;
+    background: #32312C;
+}
+
+.vde-tools-header-inner,
+.vde-tab-data,
+.vde-tab-content-header,
+.vde-tools-handler-container,
+.vde-tools-footer-inner {
+    min-width: 1000px;
+    max-width: 1300px;
+    margin: 0 auto;
+}
+
+.vde-tools-header-inner,
+.vde-tools-footer-inner {
+    position: relative;
+}
+
+.vde-tools.opened .vde-tools-header-inner:before,
+.vde-tools.opened .vde-tools-footer-inner:before,
+.custom-code .textarea-container:before,
+.custom-code .textarea-container:after {
+    position: absolute;
+    left: 0;
+    top: 52px;
+    right: 0;
+    height: 10px;
+    background: url(Mage_DesignEditor::images/vde-panel-top-shadow.png) repeat-x;
+    content: '';
+    z-index: 1;
+}
+
+.vde-tools.opened .vde-tools-footer-inner:before,
+.custom-code .textarea-container:after {
+    top: -10px;
+    background-position: 0 -10px;
+}
+
+.vde-tools-header .action-close {
+    position: absolute;
+    top: 17px;
+    right: -7px;
+    background: none;
+    border: none;
+    font-weight: normal;
+    cursor: pointer;
+    color: #f2ebde;
+    z-index: 2;
+}
+
+.vde-tools-header .action-close:hover {
+    color: #fff;
+}
+
+.vde-tools-header .action-close span {
+    display: none;
+}
+
+.vde-tools-header .action-close:before {
+    font-family: 'MUI-Icons';
+    font-style: normal;
+    speak: none;
+    font-weight: normal;
+    -webkit-font-smoothing: antialiased;
+    content: '\e061'; /* close icon */
+    font-size: 20px;
+}
+
+.vde-tools-content {
+    position: relative;
+    height: 0;
+    overflow: hidden;
+}
+
+.vde-tools-footer {
+    position: absolute;
+    bottom: 0;
+    left: 0;
+    right: 0;
+    background: #32312C;
+    height: 52px;
+    z-index: 1001;
+}
+
+.vde-tab-content-inner.hasScroll .vde-tab-data {
+    left: 9px;
+}
+
+.vde-tools .ui-resizable-handle {
+    position: absolute;
+    font-size: 0.1px;
+    display: block;
+}
+
+.vde-tools .ui-resizable-n {
+    cursor: n-resize;
+    width: 10px;
+    height: 16px;
+    top: 17px;
+    left: 0;
+    background: url(Mage_DesignEditor::images/vde-tools-panel-draggable-handler-bg.png) no-repeat;
+}
+
+.vde-tab-controls {
+    margin: 0;
+    padding: 0;
+    list-style: none;
+}
+
+.vde-tab-controls > .item {
+    display: inline-block;
+}
+
+.vde-tools-footer .vde-tab-controls > .item > a {
+    display: inline-block;
+    width: 52px;
+    height: 52px;
+    line-height: 52px;
+    text-align: center;
+    -moz-transition: background-color .3s ease;
+    -webkit-transition: background-color .3s ease;
+    transition: background-color .3s ease;
+}
+
+.vde-tab-controls > .item > a span {
+    display: block;
+    overflow: hidden;
+    text-indent: -999em;
+    width: 30px;
+    height: 27px;
+    background: url(Mage_DesignEditor::images/vde-tools-main-tabs-icons-sprite.png) no-repeat;
+    margin: 12px auto 0;
+}
+
+.vde-tab-controls > .item-design > a span {
+    background-position: 2px 0;
+}
+
+.vde-tab-controls > .item-block > a span {
+    background-position: -28px 0;
+}
+
+.vde-tab-controls > .item-settings > a span {
+    background-position: -58px 0;
+}
+
+.vde-tab-controls > .item-code > a span {
+    background-position: -88px 0;
+}
+
+.vde-tab-controls > .item-design > a:hover span {
+    background-position: 2px -27px;
+}
+
+.vde-tab-controls > .item-block > a:hover span {
+    background-position: -28px -27px;
+}
+
+.vde-tab-controls > .item-settings > a:hover span {
+    background-position: -58px -27px;
+}
+
+.vde-tab-controls > .item-code > a:hover span {
+    background-position: -88px -27px;
+}
+
+.vde-tab-controls > .item.active > a {
+    background-color: #000;
+}
+
+.tab-panel {
+    position: relative;
+    display: none;
+}
+
+.tab-panel.active {
+    display: block;
+}
+
+.vde-tools-content-inner {
+    position: relative;
+}
+
+.vde-tools-content-inner > .vde-tab-content {
+
+}
+
+.vde-tools-handler-container {
+    position: relative;
+}
+
+.vde-tab-content-title {
+    font: 20px/52px "CallunaSans", Arial, sans-serif;
+    font-weight: 400;
+    color: #f2ebde;
+    text-shadow: 0 -1px 1px #000;
+    float: left;
+    margin: 0 28px 0 22px;
+}
+
+.vde-tab-content-inner {
+    position: relative;
+    height: 348px;
+    overflow-y: auto;
+    background: #000;
+}
+
+.vde-tab-data {
+    position: relative;
+    padding: 50px 0;
+    color: #f2ebde;
+}
+
+.vde-tab-data .title {
+    font: 24px/1.333 "CallunaSans", Arial, sans-serif;
+    font-weight: 500;
+    color: #f2ebde;
+    margin: 0;
+}
+
+.vde-tab-data .action-download,
+.vde-tab-data .action-delete,
+.vde-tab-data .action-edit {
+    display: inline-block;
+    margin-left: 10px;
+    float: right;
+    color: #9f978b;
+    background: none;
+    border: none;
+    padding: 0;
+    text-decoration: none;
+    -moz-transition: color .5s ease;
+    -webkit-transition: color .5s ease;
+    transition: color .5s ease;
+}
+
+.vde-tab-data .action-download:hover,
+.vde-tab-data .action-download:focus,
+.vde-tab-data .action-delete:hover,
+.vde-tab-data .action-delete:focus,
+.vde-tab-data .action-edit:hover,
+.vde-tab-data .action-edit:focus {
+    color: #fff;
+}
+
+.vde-tab-data .action-download:before,
+.vde-tab-data .action-delete:before,
+.vde-tab-data .action-edit:before {
+    font-family: 'MUI-Icons';
+    font-style: normal;
+    speak: none;
+    font-weight: normal;
+    -webkit-font-smoothing: antialiased;
+    content: '\e073'; /* download icon (arrow down) */
+    font-size: 16px;
+}
+
+.vde-tab-data .action-download span,
+.vde-tab-data .action-delete span,
+.vde-tab-data .action-edit span {
+    display: none;
+}
+
+.vde-tab-data .action-delete:before {
+    content: '\e07f'; /* trash icon */
+}
+
+.vde-tab-data .action-edit:before {
+    content: '\e05b'; /* edit icon */
+}
+
+.vde-tab-content-header .vde-tab-controls {
+    padding: 8px 0 4px;
+}
+
+.vde-tab-content-header .vde-tab-controls > .item {
+    float: left;
+    margin-right: 3px;
+}
+
+.vde-tab-content-header .vde-tab-controls > .item > a {
+    display: inline-block;
+    font: 13px "CallunaSans", Arial, sans-serif;
+    font-weight: 600;
+    line-height: 40px;
+    text-align: center;
+    height: 40px;
+    padding: 0 22px;
+    background: #000;
+    border-radius: 5px;
+    color: #ccc;
+    text-transform: uppercase;
+    text-decoration: none;
+}
+
+.vde-tab-content-header .vde-tab-controls > .item.active > a {
+    height: 44px;
+    border-radius: 5px 5px 0 0;
+}
+
+/*
+    Files List Block
+-------------------------------------- */
+.files-list {
+    display: block;
+    float: left;
+    margin-left: 14.127659574%;
+    -webkit-box-sizing: border-box;
+    -moz-box-sizing: border-box;
+    -ms-box-sizing: border-box;
+    box-sizing: border-box;
+    width: 23.914893614%;
+    min-height: 250px;
+}
+
+.files-wrapper .files-list:first-child,
+.files-wrapper .files-list:nth-child(3n+1) {
+    margin-left: 0;
+}
+
+.files-list-header {
+    position: relative;
+    margin: 0 0 13px;
+    padding-right: 20px;
+    white-space: nowrap;
+}
+
+.files-list-header > .title {
+    margin: 0;
+    width: 100%;
+    overflow: hidden;
+    text-overflow: ellipsis;
+}
+.custom-file > .action-add,
+.files-list-header > .action-add {
+    display: inline-block;
+    position: absolute;
+    top: 3px;
+    right: 0;
+    margin: 6px 0 0 0;
+    padding: 0;
+    width: 16px;
+    height: 16px;
+    line-height: 16px;
+    text-align: center;
+    color: #000;
+    background: #9f978b;
+    border-radius: 4px;
+    text-decoration: none;
+    -moz-transition: background .5s ease;
+    -webkit-transition: background .5s ease;
+    transition: background .5s ease;
+    overflow: hidden;
+}
+
+.custom-file > .action-add .field-row,
+.files-list-header > .action-add .field-row {
+    display: block;
+}
+
+.custom-file > .action-add input[type="file"],
+.files-list-header > .action-add input[type="file"] {
+    position: absolute;
+    left:0;
+    right:0;
+    top: 0;
+    bottom:0;
+    opacity: 0;
+    width: 16px;
+    height: 16px;
+}
+
+.custom-file > .action-add:hover,
+.custom-file > .action-add:focus,
+.files-list-header > .action-add:hover,
+.files-list-header > .action-add:focus {
+    background: #fff;
+    border-radius: 4px;
+}
+
+.custom-file > .action-add:before,
+.files-list-header > .action-add:before {
+    font-family: 'MUI-Icons';
+    font-style: normal;
+    speak: none;
+    font-weight: normal;
+    -webkit-font-smoothing: antialiased;
+    content: '\e02d'; /* plus icon */
+    font-size: 16px;
+}
+
+.eq-ie9 .custom-file > .action-add:before,
+.eq-ie9 .files-list-header > .action-add:before {
+    line-height: 18px !important;
+}
+
+.custom-file > .action-add span,
+.files-list-header > .action-add span {
+    display: none;
+}
+
+.custom-file > .action-add {
+    position: relative;
+}
+
+.custom-file > .action-download {
+    top: 2px;
+}
+
+.custom-file > .action-add:before {
+    font-size: 16px !important;
+}
+
+.files-list-content .items {
+    margin: 0;
+    padding: 0;
+    list-style: none;
+}
+
+.files-list-content .item {
+    position: relative;
+    padding: 10px 50px 8px 0;
+    border-bottom: 1px solid #31302b;
+    white-space: nowrap;
+}
+
+.files-list-content .item [class^="action-"] {
+    position: absolute;
+    top: 10px;
+    right: 0;
+}
+
+.files-list-content .item .action-edit {
+    right: 30px;
+}
+
+.files-list-content .item .filename {
+    display: block;
+    width: 100%;
+    text-overflow: ellipsis;
+    overflow: hidden;
+}
+
+.vde-tab-content-inner .filename {
+    font: bold 16px/1.333 "Helvetica", Arial, sans-serif;
+    vertical-align: middle;
+}
+
+/*
+    JS Tabs
+-------------------------------------- */
+#vde-tab-js .title {
+    display: inline;
+    margin-right: 10px;
+}
+
+#vde-tab-js .files-list-header .action-add {
+    position: relative;
+}
+
+#vde-tab-js .files-list {
+    width: 100%;
+    margin: 0;
+}
+
+#vde-tab-js .files-list .items .item {
+    display: inline-block;
+    width: 26%;
+    margin-right: 3%;
+}
+
+/*
+    VDE Messages
+-------------------------------------- */
+.vde-message {
+    margin: -40px 0 46px;
+    background: url(Mage_DesignEditor::images/vde-message-bg.gif);
+    border-bottom: 1px solid #43423D;
+    border-radius: 5px;
+    font: 14px/1.666 Helvetica, Arial, sans-serif;
+}
+
+.vde-message > .message-inner {
+    position: relative;
+    padding: 20px 45px 15px 20px;
+}
+
+.vde-message .action-close {
+    padding: 0;
+    display: inline-block;
+    position: absolute;
+    top: 17px;
+    right: 20px;
+    width: 16px;
+    height: 16px;
+    line-height: 16px;
+    background: #201f1c;
+    border-radius: 4px;
+    color: #8b857b;
+    text-align: center;
+    border: none;
+    -moz-transition: all .5s ease;
+    -webkit-transition: all .5s ease;
+    transition: all .5s ease;
+}
+
+@-moz-document url-prefix() {
+    .vde-message .action-close {
+        line-height: 14px;
+    }
+}
+
+.vde-message .action-close:hover {
+    color: #fff;
+    background: #000;
+}
+
+.vde-message .action-close:before {
+    font-family: 'MUI-Icons';
+    font-style: normal;
+    speak: none;
+    font-weight: normal;
+    -webkit-font-smoothing: antialiased;
+    content: '\e061'; /* close icon */
+    font-size: 10px;
+}
+
+.vde-message .action-close span {
+    display: none;
+}
+
+.vde-message .message-content {
+
+}
+
+/*
+    Custom Code
+-------------------------------------- */
+[class^="custom-code"] {
+    display: block;
+    float: left;
+    margin-left: 2.127659574%;
+    -webkit-box-sizing: border-box;
+    -moz-box-sizing: border-box;
+    -ms-box-sizing: border-box;
+    box-sizing: border-box;
+}
+
+.custom-code-description {
+    width: 31.914893614%;
+    margin-left: 0;
+}
+
+.custom-code-description .custom-file {
+    position: relative;
+}
+
+.custom-code-description .title,
+.custom-code-description p {
+    margin-bottom: 20px;
+}
+
+.custom-code-description p {
+    font: 14px/18px Helvetica, Arial, sans-serif;
+    color: #8d857a;
+}
+
+.custom-code-description [class^="action-"] {
+    position: relative;
+    float: right;
+    margin: 0 0 0 10px;
+}
+
+.custom-code-description [class^="action-"]:before {
+    font-size: 18px;
+}
+
+.custom-code {
+    width: 65.95744680199999%;
+}
+
+.custom-code .textarea-container {
+    position: relative;
+    border: 1px solid #31302b;
+    border-radius: 5px;
+}
+
+.custom-code .textarea-container:before,
+.custom-code .textarea-container:after {
+    left: 30px;
+    right: 20px;
+}
+
+.custom-code .textarea-container:before {
+    top: 0;
+}
+
+.custom-code .textarea-container:after {
+    top: auto;
+    bottom: 5px;
+}
+
+.custom-code textarea {
+    width: 100%;
+    background: none;
+    border: none;
+    resize: vertical;
+    font: 14px/18px Helvetica, Arial, sans-serif;
+    color: #f2ebde;
+    padding: 20px 0 20px 20px;
+}
+
+.custom-code textarea:focus {
+    outline: none;
+}
+
+@-moz-document url-prefix() {
+    .custom-code textarea {
+        padding-bottom: 3px;
+    }
+}
+
+.custom-code .action-update {
+    float: right;
+    margin: 7px 0 0 0;
+}
+
+.custom-code .action-update,
+.custom-code .action-update:visited {
+    font: 14px/18px 'CallunaSans', Arial, Helvetica, sans-serif;
+    font-weight: 500;
+    color: #322e2a;
+    background: #dbd6ce;
+    display: inline-block;
+    padding: 5px 14px;
+    text-align: center;
+    text-decoration: none;
+    vertical-align: top;
+    cursor: pointer;
+    border: transparent;
+    border-radius: 5px;
+    -webkit-touch-callout: none;
+    -webkit-user-select: none;
+    -moz-user-select: none;
+    -ms-user-select: none;
+    user-select: none;
+}
+
+.custom-code .action-update:hover,
+.custom-code .action-update:focus {
+    background: #cac2b5;
+    color: #322e2a;
+}
+
+.custom-code .action-update:active,
+.custom-code .action-update.active {
+    box-shadow: 0 1px 5px #aaa59b inset;
+}
+
+.custom-code .action-update[disabled],
+.custom-code .action-update.disabled,
+.custom-code .action-update[disabled]:hover,
+.custom-code .action-update.disabled:hover,
+.custom-code .action-update[disabled]:focus,
+.custom-code .action-update.disabled:focus,
+.custom-code .action-update[disabled]:active,
+.custom-code .action-update.disabled:active,
+.custom-code .action-update[disabled].active,
+.custom-code .action-update.disabled.active {
+    cursor: not-allowed;
+    opacity: 0.65;
+    background: #d9d6cf;
+    box-shadow: none;
+    text-shadow: none;
+}
+
 /*
     VDE
 -------------------------------------- */
+
 #vde_toolbar {
     position: fixed;
     margin-top: -54pt;
@@ -722,6 +1283,7 @@ Fonts
     line-height: 21pt;
     padding: 2pt 0;
 }
+
 .action-switch-mode {
     float: left;
     background: none;
@@ -742,7 +1304,7 @@ Fonts
     text-decoration: none;
     background-image: url(../images/button.png);
     background-size: contain;
-    background-color:#f4f3f1 !important;
+    background-color: #f4f3f1 !important;
     float: left;
     margin-right: 3px;
 }
@@ -769,6 +1331,7 @@ Fonts
     border-color: red;
     color: red;
 }
+
 .vde_toolbar_cell_title {
     font-weight: bold;
     cursor: pointer;
@@ -852,6 +1415,7 @@ Fonts
     display: block;
     text-decoration: none;
 }
+
 #vde_handles_hierarchy .vde_toolbar_cell_content {
     padding: 1em .5em 1em 0;
 }
@@ -901,6 +1465,12 @@ Fonts
 -------------------------------------- */
 .themes:before,
 .themes:after,
+.files-list-header:before,
+.files-list-header:after,
+.vde-tab-data > .tab-panel:before,
+.vde-tab-data > .tab-panel:after,
+.vde-tab-content-header:before,
+.vde-tab-content-header:after,
 .clearfix:before,
 .clearfix:after {
     content: "";
@@ -908,6 +1478,9 @@ Fonts
 }
 
 .themes:after,
+.files-list-header:after,
+.vde-tab-data > .tab-panel:after,
+.vde-tab-content-header:after,
 .clearfix:after {
     clear: both;
 }
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/editor/container.phtml b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/container.phtml
index 287d07b95146e54dfef04646ea109f8246d9cf95..62f6daeecfeaa36b98a9b3b73175eada62336b94 100644
--- a/app/code/core/Mage/DesignEditor/view/adminhtml/editor/container.phtml
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/container.phtml
@@ -29,3 +29,4 @@
 <?php echo $this->getChildHtml('design_editor_toolbar'); ?>
 <?php echo $this->getChildHtml('theme.selector.storeview'); ?>
 <iframe name="vde_container_frame" id="vde_container_frame" class="vde_container_frame" src="<?php echo $this->getFrameUrl(); ?>"></iframe>
+<?php echo $this->getChildHtml('design_editor_tools'); ?>
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools.phtml b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..c590253ef5a3307973c9c6fc2169d6321d90da58
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools.phtml
@@ -0,0 +1,88 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    design
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+
+<?php /** @var $this Mage_DesignEditor_Block_Adminhtml_Editor_Tools */ ?>
+<section class="vde-tools">
+    <header class="vde-tools-header">
+        <div class="vde-tools-header-inner">
+            <button class="action-close" title="<?php echo $this->__('Close Panel'); ?>">
+                <span><?php echo $this->__('Close Panel'); ?></span>
+            </button>
+        </div>
+    </header>
+    <div class="vde-tools-content">
+        <div class="vde-tools-content-inner">
+            <div class="vde-tools-handler-container"></div>
+            <?php echo join('', $this->getTabs()) ?>
+        </div>
+    </div>
+    <footer class="vde-tools-footer">
+        <div class="vde-tools-footer-inner">
+            <div class="vde-tools-tabs">
+                <ul class="vde-tab-controls">
+                    <li class="item item-design">
+                        <a href="#vde-tab-design" data-toggle="tab" title="<?php echo $this->__('Design'); ?>">
+                            <span><?php echo $this->__('Design'); ?></span>
+                        </a>
+                    </li>
+                    <li class="item item-block">
+                        <a href="#vde-tab-block" data-toggle="tab" title="<?php echo $this->__('Block'); ?>">
+                            <span><?php echo $this->__('Block'); ?></span>
+                        </a>
+                    </li>
+                    <li class="item item-settings">
+                        <a href="#vde-tab-settings" data-toggle="tab" title="<?php echo $this->__('Settings'); ?>">
+                            <span><?php echo $this->__('Settings'); ?></span>
+                        </a>
+                    </li>
+                    <li class="item item-code">
+                        <a href="#vde-tab-code" data-toggle="tab" title="<?php echo $this->__('Code'); ?>">
+                            <span><?php echo $this->__('Code'); ?></span>
+                        </a>
+                    </li>
+                </ul>
+            </div>
+        </div>
+    </footer>
+</section>
+
+<script type="text/javascript">
+(function($) {
+    'use strict';
+
+    $('.vde-tools').toolsPanel();
+
+    $('[class^="action-"][href="#vde-tab-custom"]').on('click.activateCustomCodeTab', function() {
+        $('.vde-tab-controls a[href="#vde-tab-custom"]').trigger('click');
+    });
+
+    $('.action-edit[href="#vde-tab-custom"]').on('click.focusOnCustomCodeTextarea', function() {
+        $('#custom_code').focus();
+    });
+
+})(window.jQuery);
+</script>
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/block.phtml b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/block.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..305b20bb9e9ec69f08a47387b6946eac6f0e9cae
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/block.phtml
@@ -0,0 +1,49 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    design
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<?php /** @var $this Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Block */ ?>
+
+<div class="vde-tab-content tab-panel" id="vde-tab-block">
+    <div class="vde-tab-content-header">
+        <h4 class="vde-tab-content-title"><?php echo $this->__('Block'); ?></h4>
+    </div>
+    <div class="vde-tab-content-inner">
+        <div class="vde-tab-data">
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            Design Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            Design Lorem isum dolor sit amet, t amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+        </div>
+    </div>
+</div>
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code.phtml b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..5ed736e0317e7542214ce825fff1154081a76944
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code.phtml
@@ -0,0 +1,47 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    design
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<?php /** @var $this Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code */ ?>
+<div class="vde-tab-content tab-panel" id="vde-tab-code">
+    <div class="vde-tab-content-header">
+        <h4 class="vde-tab-content-title"><?php echo $this->__('Scripts'); ?></h4>
+
+        <div class="vde-tools-tabs">
+            <ul class="vde-tab-controls">
+                <li class="item active"><a href="#vde-tab-css" data-toggle="tab"><?php echo $this->__('Css'); ?></a></li>
+                <li class="item"><a href="#vde-tab-js" data-toggle="tab"><?php echo $this->__('JS'); ?></a></li>
+                <li class="item"><a href="#vde-tab-custom" data-toggle="tab"><?php echo $this->__('Custom CSS'); ?></a></li>
+            </ul>
+        </div>
+    </div>
+    <div class="vde-tab-content-inner">
+        <div class="vde-tab-data">
+            <?php echo join('', $this->getTabs()) ?>
+        </div>
+    </div>
+</div>
+
+
diff --git a/app/code/core/Mage/Weee/view/frontend/tax_toggle.js b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code/css.phtml
similarity index 69%
rename from app/code/core/Mage/Weee/view/frontend/tax_toggle.js
rename to app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code/css.phtml
index 3bfb4f8b3a880b5e7b733c76676270fa87d8a8ef..e132fb22c1e75dad9685505d03acb57ae257271e 100644
--- a/app/code/core/Mage/Weee/view/frontend/tax_toggle.js
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code/css.phtml
@@ -1,3 +1,4 @@
+<?php
 /**
  * Magento
  *
@@ -17,20 +18,15 @@
  * versions in the future. If you wish to customize Magento for your
  * needs please refer to http://www.magentocommerce.com for more information.
  *
- * @category    Varien
- * @package     js
+ * @category    design
+ * @package     Mage_DesignEditor
  * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
-
-/**************************** WEEE STUFF ********************************/
-function taxToggle(details, switcher, expandedClassName)
-{
-    if ($(details).style.display == 'none') {
-        $(details).show();
-        $(switcher).addClassName(expandedClassName);
-    } else {
-        $(details).hide();
-        $(switcher).removeClassName(expandedClassName);
-    }
-}
+?>
+<?php /** @var $this Mage_DesignEditor_Block_Editor_Tools_Code_Css */ ?>
+<div class="tab-panel active" id="vde-tab-css">
+    <div class="files-wrapper">
+        <?php echo join('', $this->getFileGroups()) ?>
+    </div>
+</div>
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code/css/group.phtml b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code/css/group.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..19a8c791804015a85c252d2b7c394085ff6c510c
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code/css/group.phtml
@@ -0,0 +1,58 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    design
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<?php /** @var $this Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Css_Group */ ?>
+
+<div class="files-list">
+    <div class="files-list-header">
+        <h5 class="title" title="<?php echo $this->escapeHtml($this->getTitle()) ?>"><?php echo $this->getTitle() ?></h5>
+        <?php if ($this->hasAddButton()): ?>
+            <a href="#vde-tab-custom" class="action-add" data-toggle="tab" title="<?php echo $this->__('Add Custom'); ?>">
+                <span><?php echo $this->__('Add Custom'); ?></span>
+            </a>
+        <?php endif ?>
+    </div>
+    <div class="files-list-content">
+        <ul class="items">
+            <?php foreach ($this->getFiles() as $file): ?>
+                <li class="item">
+                    <span class="filename" title="<?php echo $file['safePath'] ?>"><?php echo $file['id'] ?></span>
+                    <?php if ($this->hasDownloadButton()): ?>
+                        <a href="<?php echo $this->getDownloadUrl($file['id'], $this->getThemeId()) ?>" class="action-download" title="<?php echo $this->__('Download file'); ?>">
+                            <span><?php echo $this->__('Download file'); ?></span>
+                        </a>
+                    <?php endif ?>
+                    <!--
+                    placeholder for "Edit button"
+                    <a href="#vde-tab-custom" class="action-edit" title="<?php echo $this->__('Edit Custom CSS'); ?>">
+                        <span><?php echo $this->__('Edit Custom CSS'); ?></span>
+                    </a>
+                    -->
+                </li>
+            <?php endforeach ?>
+        </ul>
+    </div>
+</div>
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code/custom.phtml b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code/custom.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..613e9586e0729bd8b4eb17379f7bbf3dd3a5d92e
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code/custom.phtml
@@ -0,0 +1,99 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    design
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<?php /** @var $this Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Custom */ ?>
+
+<div class="tab-panel" id="vde-tab-custom">
+    <div id="vde-tab-custom-messages-placeholder">
+        <?php echo $this->getChildHtml('messages') ?>
+    </div>
+    <div class="custom-code-description">
+        <h5 class="title"><?php echo $this->__('Custom CSS'); ?></h5>
+        <p><?php echo $this->__('Update the custom.css file to right in order to overwrite the default styles.'); ?></p>
+        <p><?php echo $this->__('Or, replace, delete or download the file:'); ?></p>
+        <div class="custom-file">
+            <span class="filename"><?php echo $this->getCustomFileName() ?></span>
+
+            <button onclick="document.location='<?php echo $this->getDownloadCustomCssUrl($this->getTheme()) ?>'" class="action-download" title="<?php echo $this->__('Download file'); ?>">
+                <span><?php echo $this->__('Download file'); ?></span>
+            </button>
+            <span class="action-add" title="<?php echo $this->__('Upload File'); ?>">
+                <span><?php echo $this->__('Upload File'); ?></span>
+                <?php echo $this->getFormHtml() ?>
+            </span>
+        </div>
+    </div>
+    <div class="custom-code">
+        <div class="textarea-container">
+            <textarea name="custom_code" id="custom_code" cols="30" rows="10"><?php echo $this->getCustomCssContent($this->getTheme()) ?></textarea>
+        </div>
+        <button class="action-update" title="<?php echo $this->__('Update'); ?>"><?php echo $this->__('Update'); ?></button>
+    </div>
+</div>
+
+
+<script type="text/javascript">
+    (function ($) {
+        $('#vde-tab-custom').customCssPanel({
+            saveCustomCssUrl: '<?php echo $this->getSaveCustomCssUrl($this->getTheme()) ?>'
+        });
+
+        $( '#' + '<?php echo $this->getFileElementName() ?>' ).fileupload({
+            dataType: 'json',
+            replaceFileInput: false,
+            url : '<?php echo $this->getUrl('*/system_design_editor_tools/upload', array('theme' => $this->getTheme()->getThemeId())) ?>',
+
+            /**
+             * Handler of "file selected" event
+             * @param e
+             * @param data
+             */
+            add: function (e, data) {
+                data.submit();
+            },
+
+            /**
+             * Handler on "upload ajax request done" event
+             * @param e
+             * @param data
+             */
+            done: function (e, data) {
+                var contentArea = $('#custom_code');
+                contentArea.val('');
+                $('#css_uploader_button').attr('disabled', 'disabled');
+                if (!data.result.error) {
+                    contentArea.val(data.result.content);
+                    $('#vde-tab-custom').customCssPanel('updateButtons');
+                    $('#vde-tab-custom').trigger('refreshIframe');
+                }
+
+                if (data.result.message_html) {
+                    $('#vde-tab-custom-messages-placeholder').append(data.result.message_html);
+                }
+            }
+        });
+    })(jQuery);
+</script>
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code/js.phtml b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code/js.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..457354d2e52455b91bdc6aec3c8df50db2130a38
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code/js.phtml
@@ -0,0 +1,183 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    design
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<?php /** @var $this Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Js */ ?>
+<div class="tab-panel" id="vde-tab-js">
+    <div id="vde-tab-js-messages-placeholder">
+        <?php echo $this->getChildHtml('messages') ?>
+    </div>
+    <div class="files-wrapper">
+        <div class="files-list">
+            <div class="files-list-header">
+                <h5 class="title" title="<?php echo $this->escapeHtml($this->getTitle()) ?>"><?php echo $this->getTitle() ?></h5>
+                <span class="action-add" title="<?php echo $this->__('Add Files'); ?>">
+                    <span><?php echo $this->__('Add Files'); ?></span>
+                    <?php echo $this->getFormHtml() ?>
+                </span>
+            </div>
+            <div id="js-file-uploader" class="uploader"></div>
+            <div class="files-list-content">
+                <ul class="items ui-sortable">
+                    <?php echo $this->getChildBlock('design.editor.tools.code.js.items')->setJsFiles($this->getJsFiles())->toHtml(); ?>
+                </ul>
+            </div>
+        </div>
+    </div>
+</div>
+
+<div class="no-display" id="js-file-uploader-template">
+    <div id="{{id}}" class="file-row">
+        <span class="file-info">{{name}} ({{size}})</span>
+        <div class="progressbar-container">
+            <div class="progressbar upload-progress" style="width: 0%;"></div>
+        </div>
+        <div class="clear"></div>
+    </div>
+</div>
+<script type="text/javascript">
+    (function ($) {
+        $('#vde-tab-js .js-file .action-delete').live('click', function() {
+            if (!confirm('<?php echo $this->getConfirmMessageDelete() ?>')) {
+                return false;
+            }
+
+            $.ajax({
+                url: '<?php echo $this->getJsDeleteUrl(); ?>',
+                data: {js_removed_files: [$(this).data('id')]},
+                dataType: 'json'
+            }).done(function(data) {
+                if (!data.error) {
+                    $('#vde-tab-js .files-list-content .items').html(data.content);
+                    $('#vde-tab-js .files-list-content .items').trigger('refreshIframe');
+                }
+                if (data.message_html) {
+                    $('#vde-tab-js-messages-placeholder').append(data.message_html);
+                }
+            });
+
+            return false;
+        });
+
+        $('#js_files_uploader').fileupload({
+            dataType: 'json',
+            replaceFileInput: false,
+            sequentialUploads: true,
+            url : '<?php echo $this->getJsUploadUrl(); ?>',
+
+            /**
+             * Add data
+             * @param e
+             * @param data
+             */
+            add: function (e, data) {
+                $.each(data.files, function (index, file) {
+                    data.fileId =  Math.random().toString(36).substr(2,9);
+                    var progressTmpl = $('#js-file-uploader-template').children(':first').clone();
+                    progressTmpl.attr('id', data.fileId);
+                    var fileInfoHtml = progressTmpl.html().replace('{{size}}', byteConvert(file.size))
+                            .replace('{{name}}', file.name);
+                    progressTmpl.html(fileInfoHtml) ;
+                    progressTmpl.appendTo('#js-file-uploader');
+                });
+                data.submit();
+            },
+
+            /**
+             * On done event
+             * @param e
+             * @param data
+             */
+            done: function (e, data) {
+                var progressSelector = '#' + data.fileId + ' .progressbar-container .progressbar';
+                $(progressSelector).css('width','100%');
+
+                var contentArea = $('#vde-tab-js .files-list-content .items');
+                $(this).val('');
+                if (!data.result.error) {
+                    $(progressSelector).removeClass('upload-progress').addClass('upload-success');
+                    contentArea.html(data.result.content);
+                } else {
+                    $(progressSelector).removeClass('upload-progress').addClass('upload-failure');
+                }
+                $('#' + data.fileId).delay(2000).fadeOut(2000);
+                if (data.result.message_html) {
+                    $('#vde-tab-js-messages-placeholder').append(data.result.message_html);
+                }
+            },
+
+            /**
+             * On progress
+             * @param e
+             * @param data
+             */
+            progress: function(e, data) {
+                var progress = parseInt(data.loaded / data.total * 100, 10);
+                var progressSelector = '#' + data.fileId + ' .progressbar-container .progressbar';
+                $(progressSelector).css('width', progress + '%');
+            },
+
+            stop: function(e, data) {
+                $('.ui-sortable').trigger('refreshIframe');
+            },
+
+            /**
+             * Fail event
+             * @param e
+             * @param data
+             */
+            fail: function(e, data) {
+                var progressSelector = '#' + data.fileId + ' .progressbar-container .progressbar';
+                $(progressSelector).removeClass('upload-progress').addClass('upload-failure');
+
+                $(this).val('');
+                alert($.mage.__('File extension not known or unsupported type.'));
+            }
+        });
+
+        $('.ui-sortable').sortable({
+            update: function( event, ui ) {
+                var jsOrder = $(this).sortable('serialize', {key: 'js_order[]'});
+                $.ajax({
+                    url: '<?php echo $this->getJsReorderUrl(); ?>',
+                    type: 'POST',
+                    dataType: 'json',
+                    data: jsOrder,
+                    showLoader: false,
+                    success: $.proxy(function(response) {
+                        $('.ui-sortable').trigger('refreshIframe');
+                        if (response.message_html) {
+                            $('#vde-tab-custom-messages-placeholder').append(response.message_html);
+                        }
+                    }, this),
+                    error: $.proxy(function() {
+                        alert($.mage.__('Error: unknown error.'));
+                    }, this)
+                });
+            }
+        });
+        $('.ui-sortable').disableSelection();
+    })(jQuery);
+</script>
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code/js/items.phtml b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code/js/items.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..8165ab3ab7a3430bd321c0b2ddf3d105e791eb17
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code/js/items.phtml
@@ -0,0 +1,43 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    design
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<?php /** @var $this Mage_Backend_Block_Template */ ?>
+
+<?php if (!$this->getJsFiles()->count()): ?>
+    <li>
+        <span class="filename"><?php echo $this->__('No files found') ?></span>
+    </li>
+<?php else: ?>
+    <?php /** @var $file Mage_Core_Model_Theme_Files */ ?>
+    <?php foreach ($this->getJsFiles() as $file): ?>
+        <li class="js-file item" id="js-file-<?php echo $file->getId() ?>">
+            <span class="filename" title="<?php echo $file->getFileName() ?>"><?php echo $file->getFileName() ?></span>
+            <a href="#" class="action-delete" title="<?php echo $this->__('Delete file'); ?>" data-id="<?php echo $file->getId() ?>">
+                <span><?php echo $this->__('Delete file'); ?></span>
+            </a>
+        </li>
+    <?php endforeach ?>
+<?php endif; ?>
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code/message.phtml b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code/message.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..2909fe84f571aab51ac5fd48a30dde523f014b4e
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/code/message.phtml
@@ -0,0 +1,45 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    design
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+
+<?php /** @var $this Mage_Core_Block_Messages */ ?>
+
+<?php foreach ($this->_getMessageTypes() as $type): ?>
+    <?php foreach ($this->getMessages($type) as $message):?>
+        <?php if ($message->getText()): ?>
+        <div class="vde-message">
+            <div class="message-inner">
+                <div class="message-content">
+                    <?php echo $this->_escapeMessageFlag ? $this->escapeHtml($message->getText()) : $message->getText() ?>
+                </div>
+                <button class="action-close" title="<?php echo $this->__('Close Message'); ?>">
+                    <span><?php echo $this->__('Close Message'); ?></span>
+                </button>
+            </div>
+        </div>
+        <?php endif; ?>
+    <?php endforeach; ?>
+<?php endforeach; ?>
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/design.phtml b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/design.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..cef2ed525613de30048734035b186f5557b6a511
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/design.phtml
@@ -0,0 +1,38 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    design
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<?php /** @var $this Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Design */ ?>
+
+<div class="vde-tab-content tab-panel active" id="vde-tab-design">
+    <div class="vde-tab-content-header">
+        <h4 class="vde-tab-content-title"><?php echo $this->__('Design'); ?></h4>
+    </div>
+    <div class="vde-tab-content-inner">
+        <div class="vde-tab-data">
+            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+        </div>
+    </div>
+</div>
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/settings.phtml b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/settings.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..9ce622dd7d886bf15ce44b8aeca5dc7c13be5f62
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/editor/tools/settings.phtml
@@ -0,0 +1,42 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    design
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<?php /** @var $this Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Settings */ ?>
+
+<div class="vde-tab-content tab-panel" id="vde-tab-settings">
+    <div class="vde-tab-content-header">
+        <h4 class="vde-tab-content-title"><?php echo $this->__('Settings'); ?></h4>
+    </div>
+    <div class="vde-tab-content-inner">
+        <div class="vde-tab-data">
+            Design Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            Design Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            Design rem ipsum dolor sit aet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            Design Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+            Design Lorem ipsum dolor sit amet, t amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
+        </div>
+    </div>
+</div>
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/images/vde-message-bg.gif b/app/code/core/Mage/DesignEditor/view/adminhtml/images/vde-message-bg.gif
new file mode 100644
index 0000000000000000000000000000000000000000..cd8b5eb91e4b136a07e01df8c548b6642c880981
Binary files /dev/null and b/app/code/core/Mage/DesignEditor/view/adminhtml/images/vde-message-bg.gif differ
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/images/vde-panel-top-shadow.png b/app/code/core/Mage/DesignEditor/view/adminhtml/images/vde-panel-top-shadow.png
new file mode 100644
index 0000000000000000000000000000000000000000..0c3736142df1f0da10c1e763b24f652aff321c17
Binary files /dev/null and b/app/code/core/Mage/DesignEditor/view/adminhtml/images/vde-panel-top-shadow.png differ
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/images/vde-tools-main-tabs-icons-sprite.png b/app/code/core/Mage/DesignEditor/view/adminhtml/images/vde-tools-main-tabs-icons-sprite.png
new file mode 100644
index 0000000000000000000000000000000000000000..be8290a8fa6289d33841f9c21400a1dd81fdc36e
Binary files /dev/null and b/app/code/core/Mage/DesignEditor/view/adminhtml/images/vde-tools-main-tabs-icons-sprite.png differ
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/images/vde-tools-panel-draggable-handler-bg.png b/app/code/core/Mage/DesignEditor/view/adminhtml/images/vde-tools-panel-draggable-handler-bg.png
new file mode 100644
index 0000000000000000000000000000000000000000..43bef6905237d747432af96e23e30f000bc04b71
Binary files /dev/null and b/app/code/core/Mage/DesignEditor/view/adminhtml/images/vde-tools-panel-draggable-handler-bg.png differ
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/js/custom-css.js b/app/code/core/Mage/DesignEditor/view/adminhtml/js/custom-css.js
new file mode 100644
index 0000000000000000000000000000000000000000..cb78fcf3bc9e72bb5131793b027b5df3bb9b5029
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/js/custom-css.js
@@ -0,0 +1,90 @@
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    design
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+/*jshint jquery:true*/
+(function($) {
+    'use strict';
+    $.widget('vde.customCssPanel', {
+        options: {
+            saveCustomCssUrl: null,
+            customCssCode: '#custom_code',
+            btnUpdateCss: '#vde-tab-custom .action-update',
+            btnUpdateDownload: '#vde-tab-custom .action-download'
+        },
+
+        updateButtons: function() {
+            this._prepareUpdateButton();
+        },
+
+        _create: function() {
+            this.btnCssUpdate = $(this.options.btnUpdateCss);
+            this.customCssCode = $(this.options.customCssCode);
+            this.btnUpdateDownload = $(this.options.btnUpdateDownload);
+            this._prepareUpdateButton();
+            this._events();
+        },
+
+        _events: function() {
+            this.btnCssUpdate.on('click', $.proxy(this._updateCustomCss, this));
+            this.customCssCode.on('input onchange', $.proxy(this._editCustomCss, this));
+        },
+
+        _editCustomCss: function()
+        {
+            if ($.trim($(this.customCssCode).val())) {
+                this.btnCssUpdate.removeAttr('disabled');
+            }
+        },
+
+        _updateCustomCss: function()
+        {
+            $.ajax({
+                type: 'POST',
+                url:  this.options.saveCustomCssUrl,
+                data: {custom_css_content: $(this.customCssCode).val()},
+                dataType: 'json',
+                success: $.proxy(function(response) {
+                    if (response.message_html) {
+                        $('#vde-tab-custom-messages-placeholder').append(response.message_html);
+                    }
+                    this.element.trigger('refreshIframe');
+                    this._prepareUpdateButton();
+                }, this),
+                error: function() {
+                    alert($.mage.__('Error: unknown error.'));
+                }
+            });
+        },
+
+        _prepareUpdateButton: function()
+        {
+            if (!$.trim($(this.customCssCode).val())) {
+                this.btnCssUpdate.attr('disabled', 'disabled');
+                $(this.btnUpdateDownload).fadeOut();
+            } else {
+                $(this.btnUpdateDownload).fadeIn();
+            }
+        }
+    });
+})(window.jQuery);
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/js/theme-selector.js b/app/code/core/Mage/DesignEditor/view/adminhtml/js/theme-selector.js
index e5ac5caed9d82e415a201d56acc879edabfab5ed..1338e666f63ca060741c39c4540072519178b812 100644
--- a/app/code/core/Mage/DesignEditor/view/adminhtml/js/theme-selector.js
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/js/theme-selector.js
@@ -26,12 +26,13 @@
 (function($) {
     $.widget('vde.themeSelector', {
         options: {
-            assignEvent:      'assign',
-            assignSaveEvent:  'assign-save',
-            previewEvent:     'preview',
-            editEvent:        'edit',
-            deleteEvent:      'delete',
-            loadEvent:        'loaded',
+            refreshIframeEvent: 'refreshIframe',
+            assignEvent:        'assign',
+            assignSaveEvent:    'assign-save',
+            previewEvent:       'preview',
+            editEvent:          'edit',
+            deleteEvent:        'delete',
+            loadEvent:          'loaded',
             storeView: {
                 windowSelector: '#store-view-window'
             },
@@ -63,6 +64,8 @@
          * @protected
          */
         _bind: function() {
+            $('body').on(this.options.refreshIframeEvent, $.proxy(this._onIframeRefresh, this));
+
             //this.element is <body>
             this.element.on(this.options.assignEvent, $.proxy(this._onAssign, this));
             this.element.on(this.options.assignSaveEvent, $.proxy(this._onAssignSave, this));
@@ -81,6 +84,14 @@
             }, this));
         },
 
+        /**
+         * Iframe refresh
+         * @protected
+         */
+        _onIframeRefresh: function() {
+            $(this.options.frameSelector)[0].contentWindow.location.reload(true);
+        },
+
         /**
          * Preview action
          * @protected
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/js/tools-panel.js b/app/code/core/Mage/DesignEditor/view/adminhtml/js/tools-panel.js
new file mode 100644
index 0000000000000000000000000000000000000000..57cfcd63d07bc6eab4637099a2ed8eef42d42640
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/js/tools-panel.js
@@ -0,0 +1,133 @@
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    design
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+/*jshint jquery:true*/
+(function($) {
+    'use strict';
+    $.widget('vde.toolsPanel', {
+        options: {
+            openedPanelClass: 'opened',
+            activeTabClass: 'active',
+            panelDefaultHeight: 500,
+            showHidePanelAnimationSpeed: 300,
+            resizableArea: '.vde-tools-content',
+            resizableAreaInner: '.vde-tab-content.active .vde-tab-content-inner',
+            panelHeader: '.vde-tab-content-header',
+            panelTab: 'a[data-toggle="tab"]',
+            resizeHandlerControl: '.ui-resizable-handle',
+            resizeHandlerControlContainer: '.vde-tools-handler-container',
+            scrollExistClass: 'hasScroll',
+            mainTabs: '.vde-tools-footer .vde-tab-controls > .item',
+            btnClose: '.vde-tools-header .action-close',
+            btnCloseMsg: '.vde-message .action-close'
+        },
+
+        _create: function() {
+            this.panel = this.element;
+
+            this.resizableArea = $(this.options.resizableArea);
+            this.resizableAreaInner = $(this.options.resizableAreaInner);
+            this.panelTab = $(this.options.panelTab);
+            this.resizeHandlerControlContainer = $(this.options.resizeHandlerControlContainer);
+            this.panelHeaderHeight = $(this.options.panelHeader).height();
+            this.btnClose = $(this.options.btnClose, this.panel);
+            this.mainTabs = $(this.options.mainTabs);
+            this.btnCloseMsg = $(this.options.btnCloseMsg, this.panel);
+
+            this._events();
+        },
+
+        _init: function() {
+            $(this.options.resizeHandlerControl).prependTo(this.resizeHandlerControlContainer);
+            this._recalcDataHeight(this._getResizableAreaHeight());
+        },
+
+        _events: function() {
+            var self = this;
+            this.resizableArea.resizable({
+                handles: 'n',
+                minHeight: 100,
+                maxHeight: 700,
+                resize: function(event, ui) {
+                    self._recalcDataHeight(ui.size.height);
+                }
+            }).bind('resize.vdeToolsResize', function () {
+                self._recalcDataHeight(self._getResizableAreaHeight());
+                $(this).css('top', 'auto');
+            });
+
+            this.panelTab.on('shown', function () {
+                if (!self.panel.hasClass(self.options.openedPanelClass)) {
+                    self._show();
+                } else {
+                    self._recalcDataHeight(self.options.panelDefaultHeight);
+                }
+                self.resizableArea.trigger('resize.vdeToolsResize');
+            });
+
+            this.btnClose.live('click.hideVDEToolsPanel', $.proxy(this._hide, this));
+
+            this.btnCloseMsg.live('click.hideVDEMessage', $.proxy(function(e) {
+                $(e.target).parents('.vde-message')[0].remove();
+            }, this));
+        },
+
+        _toggleClassIfScrollBarExist: function(elem) {
+            elem.toggleClass(this.options.scrollExistClass, elem.get(0).scrollHeight > elem.height());
+        },
+
+        _getActiveResizableAreaInner: function() {
+            return $(this.options.resizableAreaInner);
+        },
+
+        _getResizableAreaHeight: function() {
+            return this.resizableArea.height();
+        },
+
+        _recalcDataHeight: function(height) {
+            var elem = this._getActiveResizableAreaInner();
+
+            elem.height(height - this.panelHeaderHeight);
+            this._toggleClassIfScrollBarExist(elem);
+        },
+
+        _show: function() {
+            this.panel.addClass(this.options.openedPanelClass);
+            this.resizableArea.animate({
+                height: this.options.panelDefaultHeight - this.panelHeaderHeight
+            }, this.options.showHidePanelAnimationSpeed, $.proxy(function() {
+                this.resizableArea.trigger('resize.vdeToolsResize');
+            }, this));
+        },
+
+        _hide: function() {
+            this.resizableArea.animate({
+                height: 0
+            }, this.options.showHidePanelAnimationSpeed, $.proxy(function() {
+                this.panel.removeClass(this.options.openedPanelClass);
+                this.mainTabs.removeClass(this.options.activeTabClass);
+            }, this));
+        }
+    });
+})(window.jQuery);
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/layout.xml b/app/code/core/Mage/DesignEditor/view/adminhtml/layout.xml
index 0c96166cbb2ec36e06df70c8ee2a7e34967967c3..aa3c592c994507bcce94ea533d55307c5f1bed19 100644
--- a/app/code/core/Mage/DesignEditor/view/adminhtml/layout.xml
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/layout.xml
@@ -83,11 +83,16 @@
             <action method="setTemplate"><file>Mage_DesignEditor::editor.phtml</file></action>
         </reference>
         <reference name="head">
+            <action method="addJs"><file>jquery/jquery.tabs.js</file></action>
+            <action method="addJs"><file>jquery/jstree/jquery.jstree.js</file></action>
+            <action method="addJs"><file>jquery/slimScroll/slimScroll.min.js</file></action>
+            <action method="addJs"><file>Mage_DesignEditor::js/tools-panel.js</file></action>
+            <action method="addJs"><file>Mage_DesignEditor::js/custom-css.js</file></action>
             <action method="addJs"><file>Mage_DesignEditor::js/theme-selector.js</file></action>
             <action method="addJs"><file>Mage_DesignEditor::js/base.js</file></action>
             <action method="addJs"><file>Mage_DesignEditor::js/design_editor.js</file></action>
-            <action method="addJs"><file>jquery/jstree/jquery.jstree.js</file></action>
-            <action method="addJs"><file>jquery/slimScroll/slimScroll.min.js</file></action>
+            <action method="addJs"><file>Mage_Adminhtml::jquery/fileUploader/jquery.iframe-transport.js</file></action>
+            <action method="addJs"><file>Mage_Adminhtml::jquery/fileUploader/jquery.fileupload.js</file></action>
             <action method="addCss"><file>Mage_DesignEditor::css/styles.css</file></action>
         </reference>
         <reference name="content">
@@ -98,7 +103,48 @@
                     <block type="Mage_DesignEditor_Block_Adminhtml_Editor_Toolbar_Buttons" name="design_editor_toolbar_buttons" template="Mage_DesignEditor::editor/toolbar/buttons.phtml" />
                 </block>
                 <block type="Mage_DesignEditor_Block_Adminhtml_Theme_Selector_StoreView" name="theme.selector.storeview" template="Mage_DesignEditor::theme/selector/storeview.phtml" />
+                <block type="Mage_DesignEditor_Block_Adminhtml_Editor_Tools" name="design_editor_tools" template="Mage_DesignEditor::editor/tools.phtml">
+                    <block type="Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Design" name="design_editor_tools_design" template="Mage_DesignEditor::editor/tools/design.phtml" />
+                    <block type="Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Block" name="design_editor_tools_block" template="Mage_DesignEditor::editor/tools/block.phtml" />
+                    <block type="Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Settings" name="design_editor_tools_settings" template="Mage_DesignEditor::editor/tools/settings.phtml" />
+                    <block type="Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code" name="design_editor_tools_code" template="Mage_DesignEditor::editor/tools/code.phtml">
+                        <!-- Tab with CSS list -->
+                        <block type="Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Css" name="design_editor_tools_code_css" template="Mage_DesignEditor::editor/tools/code/css.phtml">
+                            <block type="Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Css_Group" name="design_editor_tools_code_css_group" template="Mage_DesignEditor::editor/tools/code/css/group.phtml" />
+                        </block>
+                        <!-- Tab with JavaScript list -->
+                        <block type="Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Js" name="design_editor_tools_code_js" template="Mage_DesignEditor::editor/tools/code/js.phtml">
+                            <block template="Mage_DesignEditor::/editor/tools/code/js/items.phtml" type="Mage_Backend_Block_Template" name="design_editor_tools_code_js_items" as="design.editor.tools.code.js.items" />
+                        </block>
+                        <!-- Tab with Custom CSS -->
+                        <block type="Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Custom" name="design_editor_tools_code_custom" template="Mage_DesignEditor::editor/tools/code/custom.phtml">
+                            <block type="Mage_Core_Block_Messages" name="messages" template="Mage_DesignEditor::editor/tools/code/message.phtml" />
+                        </block>
+                    </block>
+                </block>
             </block>
         </reference>
     </adminhtml_system_design_editor_launch>
+
+    <adminhtml_system_design_editor_tools_upload>
+        <block type="Mage_Core_Block_Messages" name="messages" template="Mage_DesignEditor::editor/tools/code/message.phtml" />
+    </adminhtml_system_design_editor_tools_upload>
+
+    <adminhtml_system_design_editor_tools_savecsscontent>
+        <block type="Mage_Core_Block_Messages" name="messages" template="Mage_DesignEditor::editor/tools/code/message.phtml" />
+    </adminhtml_system_design_editor_tools_savecsscontent>
+
+    <adminhtml_system_design_editor_tools_uploadjs>
+        <block type="Mage_Core_Block_Messages" name="messages" template="Mage_DesignEditor::editor/tools/code/message.phtml" />
+    </adminhtml_system_design_editor_tools_uploadjs>
+
+    <adminhtml_system_design_editor_tools_jslist>
+        <container name="root" label="Root" output="1">
+            <block type="Mage_Backend_Block_Template" template="Mage_DesignEditor::/editor/tools/code/js/items.phtml" name="design_editor_tools_code_js_items"/>
+        </container>
+    </adminhtml_system_design_editor_tools_jslist>
+
+    <adminhtml_system_design_editor_tools_reorderjs>
+        <block type="Mage_Core_Block_Messages" name="messages" template="Mage_DesignEditor::editor/tools/code/message.phtml" />
+    </adminhtml_system_design_editor_tools_reorderjs>
 </layout>
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/theme/customized.phtml b/app/code/core/Mage/DesignEditor/view/adminhtml/theme/customized.phtml
index cc3f752e910dc22dfceff718fba2228b44b04768..45a9594a8d94487314659bcd8e005c6c569d719e 100644
--- a/app/code/core/Mage/DesignEditor/view/adminhtml/theme/customized.phtml
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/theme/customized.phtml
@@ -31,7 +31,7 @@
 ?>
 
 <li class="theme" id="theme-id-<?php echo $this->getTheme()->getId() ?>" data-widget-options="<?php echo $this->escapeHtml($this->getOptionsJson()); ?>">
-    <form action="" method="post" class="edit-theme-title-form hidden">
+    <form action="" method="post" class="edit-theme-title-form">
         <input type="text" value="<?php echo $themeTitle ?>" data-title-original="<?php echo $themeTitle ?>" required autofocus />
         <?php echo $this->getQuickSaveButton()->toHtml() ?>
     </form>
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/theme/list/available.phtml b/app/code/core/Mage/DesignEditor/view/adminhtml/theme/list/available.phtml
index 4d85757aaf6cd2df162699b59c14e6046b5fc1d1..9dbcf424d9d34f8c83e6709d870cb95001c4e4e1 100644
--- a/app/code/core/Mage/DesignEditor/view/adminhtml/theme/list/available.phtml
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/theme/list/available.phtml
@@ -51,550 +51,3 @@
         });
     })(jQuery);
 </script>
-
-<section class="vde-tools hidden">
-    <header class="vde-tools-header">
-        <div class="vde-tools-header-inner">
-            <button class="action-close" title="<?php echo $this->__('Close Panel'); ?>">
-                <span><?php echo $this->__('Close Panel'); ?></span>
-            </button>
-        </div>
-    </header>
-    <div class="vde-tools-content">
-        <div class="vde-tools-content-inner">
-            <div class="vde-tools-handler-container"></div>
-            <div class="vde-tab-content tab-panel active" id="vde-tab-design">
-                <div class="vde-tab-content-header">
-                    <h4 class="vde-tab-content-title"><?php echo $this->__('Design'); ?></h4>
-                </div>
-                <div class="vde-tab-content-inner">
-                    <div class="vde-tab-data">
-                        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                    </div>
-                </div>
-            </div>
-            <div class="vde-tab-content tab-panel" id="vde-tab-block">
-                <div class="vde-tab-content-header">
-                    <h4 class="vde-tab-content-title"><?php echo $this->__('Block'); ?></h4>
-                </div>
-                <div class="vde-tab-content-inner">
-                    <div class="vde-tab-data">
-                        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                        Design Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                        Design Lorem isum dolor sit amet, t amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                    </div>
-                </div>
-            </div>
-            <div class="vde-tab-content tab-panel" id="vde-tab-settings">
-                <div class="vde-tab-content-header">
-                    <h4 class="vde-tab-content-title"><?php echo $this->__('Settings'); ?></h4>
-                </div>
-                <div class="vde-tab-content-inner">
-                    <div class="vde-tab-data">
-                        Design Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                        Design Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                        Design rem ipsum dolor sit aet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                        Design Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                        Design Lorem ipsum dolor sit amet, t amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                    </div>
-                </div>
-            </div>
-            <div class="vde-tab-content tab-panel" id="vde-tab-code">
-                <div class="vde-tab-content-header">
-                    <h4 class="vde-tab-content-title"><?php echo $this->__('Scripts'); ?></h4>
-
-                    <div class="vde-tools-tabs">
-                        <ul class="vde-tab-controls">
-                            <li class="item active"><a href="#vde-tab-css" data-toggle="tab"><?php echo $this->__('Css'); ?></a></li>
-                            <li class="item"><a href="#vde-tab-js" data-toggle="tab"><?php echo $this->__('JS'); ?></a></li>
-                            <li class="item"><a href="#vde-tab-custom" data-toggle="tab"><?php echo $this->__('Custom'); ?></a></li>
-                        </ul>
-                    </div>
-                </div>
-                <div class="vde-tab-content-inner">
-                    <div class="vde-tab-data">
-                        <div class="tab-panel active" id="vde-tab-css">
-
-                            <div class="vde-message">
-                                <div class="message-inner">
-                                    <div class="message-content">
-                                        Oops! Your upload did not finish. Try checking that thing that you need to check and try again.
-                                    </div>
-                                    <button class="action-close" title="<?php echo $this->__('Close Message'); ?>">
-                                        <span><?php echo $this->__('Close Message'); ?></span>
-                                    </button>
-                                </div>
-                            </div>
-                            <div class="files-wrapper">
-                                <div class="files-list">
-                                    <div class="files-list-header">
-                                        <h5 class="title">Title of Group</h5>
-                                        <a href="#vde-tab-custom" class="action-add" data-toggle="tab" title="<?php echo $this->__('Add Custom'); ?>">
-                                            <span><?php echo $this->__('Add Custom'); ?></span>
-                                        </a>
-                                    </div>
-                                    <div class="files-list-content">
-                                        <ul class="items">
-                                            <li class="item">
-                                                <span class="filename">print.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">styles-ie.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">style.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">widget.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">global_settings.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">custom.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                                <a href="#vde-tab-custom" class="action-edit" title="<?php echo $this->__('Edit Custom CSS'); ?>">
-                                                    <span><?php echo $this->__('Edit Custom CSS'); ?></span>
-                                                </a>
-                                            </li>
-                                        </ul>
-                                    </div>
-                                </div>
-
-                                <div class="files-list">
-                                    <div class="files-list-header">
-                                        <h5 class="title">Title of Group</h5>
-                                        <a href="#vde-tab-custom" class="action-add" data-toggle="tab" title="<?php echo $this->__('Add Custom'); ?>">
-                                            <span><?php echo $this->__('Add Custom'); ?></span>
-                                        </a>
-                                    </div>
-                                    <div class="files-list-content">
-                                        <ul class="items">
-                                            <li class="item">
-                                                <span class="filename">print.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">styles-ie.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">style.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                        </ul>
-                                    </div>
-                                </div>
-
-                                <div class="files-list">
-                                    <div class="files-list-header">
-                                        <h5 class="title">Title of Group</h5>
-                                        <a href="#vde-tab-custom" class="action-add" data-toggle="tab" title="<?php echo $this->__('Add Custom'); ?>">
-                                            <span><?php echo $this->__('Add Custom'); ?></span>
-                                        </a>
-                                    </div>
-                                    <div class="files-list-content">
-                                        <ul class="items">
-                                            <li class="item">
-                                                <span class="filename">print.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">styles-ie.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                        </ul>
-                                    </div>
-                                </div>
-
-                                <div class="files-list">
-                                    <div class="files-list-header">
-                                        <h5 class="title">Title of Group</h5>
-                                        <a href="#vde-tab-custom" class="action-add" data-toggle="tab" title="<?php echo $this->__('Add Custom'); ?>">
-                                            <span><?php echo $this->__('Add Custom'); ?></span>
-                                        </a>
-                                    </div>
-                                    <div class="files-list-content">
-                                        <ul class="items">
-                                            <li class="item">
-                                                <span class="filename">print.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">styles-ie.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                        </ul>
-                                    </div>
-                                </div>
-
-                                <div class="files-list">
-                                    <div class="files-list-header">
-                                        <h5 class="title">Title of Group</h5>
-                                        <a href="#vde-tab-custom" class="action-add" data-toggle="tab" title="<?php echo $this->__('Add Custom'); ?>">
-                                            <span><?php echo $this->__('Add Custom'); ?></span>
-                                        </a>
-                                    </div>
-                                    <div class="files-list-content">
-                                        <ul class="items">
-                                            <li class="item">
-                                                <span class="filename">print.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">styles-ie.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">style.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">widget.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">global_settings.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                        </ul>
-                                    </div>
-                                </div>
-
-                                <div class="files-list">
-                                    <div class="files-list-header">
-                                        <h5 class="title">Title of Group</h5>
-                                        <a href="#vde-tab-custom" class="action-add" data-toggle="tab" title="<?php echo $this->__('Add Custom'); ?>">
-                                            <span><?php echo $this->__('Add Custom'); ?></span>
-                                        </a>
-                                    </div>
-                                    <div class="files-list-content">
-                                        <ul class="items">
-                                            <li class="item">
-                                                <span class="filename">print.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">styles-ie.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">style.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">widget.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">global_settings.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                        </ul>
-                                    </div>
-                                </div>
-
-                                <div class="files-list">
-                                    <div class="files-list-header">
-                                        <h5 class="title">Title of Group</h5>
-                                        <a href="#vde-tab-custom" class="action-add" data-toggle="tab" title="<?php echo $this->__('Add Custom'); ?>">
-                                            <span><?php echo $this->__('Add Custom'); ?></span>
-                                        </a>
-                                    </div>
-                                    <div class="files-list-content">
-                                        <ul class="items">
-                                            <li class="item">
-                                                <span class="filename">print.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">styles-ie.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">style.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">widget.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                            <li class="item">
-                                                <span class="filename">global_settings.css</span>
-                                                <a href="#" class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                                    <span><?php echo $this->__('Download file'); ?></span>
-                                                </a>
-                                            </li>
-                                        </ul>
-                                    </div>
-                                </div>
-                            </div>
-                        </div>
-                        <div class="tab-panel" id="vde-tab-js">
-                            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat nonproident, sunt in culpa qui officia deserunt mollit anim id est laborum.
-                        </div>
-                        <div class="tab-panel" id="vde-tab-custom">
-                            <div class="custom-code-description">
-                                <h5 class="title">Custom CSS</h5>
-                                <p>Update the custom.css file to right in order to overwrite the default styles.</p>
-                                <p>Or, replace, delete or download the file:</p>
-                                <div class="custom-file">
-                                    <span class="filename">custom.css</span>
-
-                                    <button class="action-download" title="<?php echo $this->__('Download file'); ?>">
-                                        <span><?php echo $this->__('Download file'); ?></span>
-                                    </button>
-                                    <button class="action-delete" title="<?php echo $this->__('Delete file'); ?>">
-                                        <span><?php echo $this->__('Delete file'); ?></span>
-                                    </button>
-
-                                    <form action="#" method="post">
-                                        <input type="file" class="action-add" />
-                                    </form>
-                                </div>
-                            </div>
-                            <div class="custom-code">
-                                <form action="#" method="post">
-                                    <div class="textarea-container">
-                                        <textarea name="custom_code" id="custom_code" cols="30" rows="10">.files-list-header > .action-add { display: inline-block; float: right; margin: 6px 0 0 0; width: 16px; height: 16px; line-height: 16px; text-align: center; color: #000; background: #9f978b; border-radius: 4px; text-decoration: none; -moz-transition: background .5s ease; -webkit-transition: background .5s ease; transition: background .5s ease; }</textarea>
-                                    </div>
-                                    <button class="action-update" title="<?php echo $this->__('Update'); ?>"><?php echo $this->__('Update'); ?></button>
-                                </form>
-                            </div>
-                        </div>
-                    </div>
-                </div>
-            </div>
-        </div>
-    </div>
-    <footer class="vde-tools-footer">
-        <div class="vde-tools-footer-inner">
-            <div class="vde-tools-tabs">
-                <ul class="vde-tab-controls">
-                    <li class="item item-design">
-                        <a href="#vde-tab-design" data-toggle="tab" title="<?php echo $this->__('Design'); ?>">
-                            <span><?php echo $this->__('Design'); ?></span>
-                        </a>
-                    </li>
-                    <li class="item item-block">
-                        <a href="#vde-tab-block" data-toggle="tab" title="<?php echo $this->__('Block'); ?>">
-                            <span><?php echo $this->__('Block'); ?></span>
-                        </a>
-                    </li>
-                    <li class="item item-settings">
-                        <a href="#vde-tab-settings" data-toggle="tab" title="<?php echo $this->__('Settings'); ?>">
-                            <span><?php echo $this->__('Settings'); ?></span>
-                        </a>
-                    </li>
-                    <li class="item item-code">
-                        <a href="#vde-tab-code" data-toggle="tab" title="<?php echo $this->__('Code'); ?>">
-                            <span><?php echo $this->__('Code'); ?></span>
-                        </a>
-                    </li>
-                </ul>
-            </div>
-        </div>
-    </footer>
-</section>
-
-<script type="text/javascript">
-    (function($) {
-        'use strict';
-
-        $.widget('vde.toolsPanel', {
-            options: {
-                openedPanelClass: 'opened',
-                activeTabClass: 'active',
-                panelDefaultHeight: 500,
-                showHidePanelAnimationSpeed: 300,
-                resizableArea: '.vde-tools-content',
-                resizableAreaInner: '.vde-tab-content.active .vde-tab-content-inner',
-                panelHeader: '.vde-tab-content-header',
-                panelTab: 'a[data-toggle="tab"]',
-                resizeHandlerControl: '.ui-resizable-handle',
-                resizeHandlerControlContainer: '.vde-tools-handler-container',
-                scrollExistClass: 'hasScroll',
-                mainTabs: '.vde-tools-footer .vde-tab-controls > .item',
-                btnClose: '.vde-tools-header .action-close'
-            },
-
-            _create: function() {
-                this.panel = this.element;
-
-                this.resizableArea = $(this.options.resizableArea);
-                this.resizableAreaInner = $(this.options.resizableAreaInner);
-                this.panelTab = $(this.options.panelTab);
-                this.resizeHandlerControlContainer = $(this.options.resizeHandlerControlContainer);
-                this.panelHeaderHeight = $(this.options.panelHeader).height();
-                this.btnClose = $(this.options.btnClose, this.panel);
-                this.mainTabs = $(this.options.mainTabs);
-
-                this._events();
-            },
-
-            _init: function() {
-                $(this.options.resizeHandlerControl).prependTo(this.resizeHandlerControlContainer);
-                this._recalcDataHeight(this._getResizableAreaHeight());
-            },
-
-            _events: function() {
-                var self = this;
-
-                this.resizableArea
-                    .resizable({
-                        handles: 'n',
-                        minHeight: 100,
-                        maxHeight: 700,
-                        resize: function(event, ui) {
-                            self._recalcDataHeight(ui.size.height);
-                        }
-                    }).bind('resize.vdeToolsResize', function () {
-                        self._recalcDataHeight(self._getResizableAreaHeight());
-                        $(this).css('top', 'auto');
-                    });
-
-                this.panelTab
-                    .on('shown', function () {
-                        if (!self.panel.hasClass(self.options.openedPanelClass)) {
-                            self._show();
-                        } else {
-                            self._recalcDataHeight(self.options.panelDefaultHeight);
-                        }
-                        self.resizableArea.trigger('resize.vdeToolsResize');
-                    });
-
-                this.btnClose
-                    .on('click.hideVDEToolsPanel', $.proxy(this._hide, this));
-            },
-
-            _toggleClassIfScrollBarExist: function(elem) {
-                elem.toggleClass(this.options.scrollExistClass, elem.get(0).scrollHeight > elem.height());
-            },
-
-            _getActiveResizableAreaInner: function() {
-                return $(this.options.resizableAreaInner);
-            },
-
-            _getResizableAreaHeight: function() {
-                return this.resizableArea.height();
-            },
-
-            _recalcDataHeight: function(height) {
-                var elem = this._getActiveResizableAreaInner();
-
-                elem.height(height - this.panelHeaderHeight);
-                this._toggleClassIfScrollBarExist(elem);
-            },
-
-            _show: function() {
-                var self = this;
-
-                this.panel.addClass(this.options.openedPanelClass);
-
-                this.resizableArea.animate({
-                    height: self.options.panelDefaultHeight - self.panelHeaderHeight
-                }, self.options.showHidePanelAnimationSpeed, function() {
-                    self.resizableArea.trigger('resize.vdeToolsResize');
-                });
-            },
-
-            _hide: function() {
-                var self = this;
-
-                this.resizableArea.animate({
-                    height: 0
-                }, self.options.showHidePanelAnimationSpeed, function() {
-                    self.panel
-                        .removeClass(self.options.openedPanelClass);
-
-                    self.mainTabs
-                        .removeClass(self.options.activeTabClass);
-                });
-            }
-        });
-
-        $('.vde-tools').toolsPanel();
-
-        /* Activate "Scripts" tab */
-        $('.vde-tools-footer .item-code > a').tab('show');
-
-        $('[class^="action-"][href="#vde-tab-custom"]')
-            .on('click.activateCustomCodeTab', function() {
-                $('.vde-tab-controls a[href="#vde-tab-custom"]').trigger('click');
-            });
-
-        $('.action-edit[href="#vde-tab-custom"]')
-            .on('click.focusOnCustomCodeTextarea', function() {
-                $('#custom_code').focus();
-            });
-
-    })(window.jQuery);
-</script>
\ No newline at end of file
diff --git a/app/code/core/Mage/DesignEditor/view/frontend/layout.xml b/app/code/core/Mage/DesignEditor/view/frontend/layout.xml
index 4fdb0fe66ed7726437338fef3c36953b04fd9e11..6e2a39009b68ca0625d7a387c189759e27b3c9d0 100644
--- a/app/code/core/Mage/DesignEditor/view/frontend/layout.xml
+++ b/app/code/core/Mage/DesignEditor/view/frontend/layout.xml
@@ -34,7 +34,7 @@
 
         <reference name="vde_head">
             <action method="addJs"><file>jquery/jquery.min.js</file></action>
-            <action method="addJs"><file>jquery/jquery-ui.custom.min.js</file></action>
+            <action method="addJs"><file>jquery/jquery-ui.js</file></action>
             <action method="addJs"><file>mage/jquery-no-conflict.js</file></action>
             <action method="addJs"><file>head.load.min.js</file></action>
             <action method="addJs"><file>mage/mage.js</file></action>
diff --git a/app/code/core/Mage/Directory/view/frontend/js/optional_zip_countries.phtml b/app/code/core/Mage/Directory/view/frontend/js/optional_zip_countries.phtml
index 9188828bbd01d64d404ae89a0601e0b8cdebbe13..288ca4f6b346860c14052bd71be80ee01cf3f58d 100644
--- a/app/code/core/Mage/Directory/view/frontend/js/optional_zip_countries.phtml
+++ b/app/code/core/Mage/Directory/view/frontend/js/optional_zip_countries.phtml
@@ -32,8 +32,3 @@
  * @see Mage_Core_Block_Template
  */
 ?>
-<script type="text/javascript">
-//<![CDATA[
-optionalZipCountries = <?php echo $this->helper('Mage_Directory_Helper_Data')->getCountriesWithOptionalZip(true) ?>;
-//]]>
-</script>
diff --git a/app/code/core/Mage/Downloadable/Helper/File.php b/app/code/core/Mage/Downloadable/Helper/File.php
index 354f75ca70b32c54a22022c66a4d69b89c2729ef..058a14537aee7e945326621e3cd1fcd9eadde033 100644
--- a/app/code/core/Mage/Downloadable/Helper/File.php
+++ b/app/code/core/Mage/Downloadable/Helper/File.php
@@ -33,9 +33,10 @@
  */
 class Mage_Downloadable_Helper_File extends Mage_Core_Helper_Abstract
 {
-    public function __construct()
+    public function __construct(Mage_Core_Model_Translate $translator, Mage_Core_Model_Config $config)
     {
-        $nodes = Mage::getConfig()->getNode('global/mime/types');
+        parent::__construct($translator);
+        $nodes = $config->getNode('global/mime/types');
         if ($nodes) {
             $nodes = (array)$nodes;
             foreach ($nodes as $key => $value) {
diff --git a/app/code/core/Mage/Downloadable/view/frontend/checkout/cart/item/default.phtml b/app/code/core/Mage/Downloadable/view/frontend/checkout/cart/item/default.phtml
index 0f013a36f998a352d1ce6b0aba170c17b4ba8a68..200afa029682164fe647e3da66e22a826b2ed0b1 100644
--- a/app/code/core/Mage/Downloadable/view/frontend/checkout/cart/item/default.phtml
+++ b/app/code/core/Mage/Downloadable/view/frontend/checkout/cart/item/default.phtml
@@ -94,7 +94,7 @@
     <?php if ($this->helper('Mage_Tax_Helper_Data')->displayCartPriceExclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()): ?>
     <td class="a-right">
         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-            <div class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+            <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $_item->getId(); ?>"}'>
         <?php else: ?>
             <div class="cart-price">
         <?php endif; ?>
@@ -127,7 +127,7 @@
             </div>
 
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <div class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $_item->getId(); ?>"}'>
                     <span class="weee"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>: <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_item->getCalculationPrice()+$_item->getWeeeTaxAppliedAmount()+$_item->getWeeeTaxDisposition()); ?></span>
                 </div>
             <?php endif; ?>
@@ -138,7 +138,7 @@
     <td>
         <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getPriceInclTax($_item); ?>
         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-            <div class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+            <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $_item->getId(); ?>"}'>
         <?php else: ?>
             <div class="cart-price">
         <?php endif; ?>
@@ -169,7 +169,7 @@
             </div>
 
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <div class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $_item->getId(); ?>"}'>
                     <span class="weee"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>: <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_incl+$_item->getWeeeTaxAppliedAmount()); ?></span>
                 </div>
             <?php endif; ?>
@@ -183,7 +183,7 @@
     <?php if (($this->helper('Mage_Tax_Helper_Data')->displayCartPriceExclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()) && !$_item->getNoSubtotal()): ?>
     <td class="a-right">
         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-            <div class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+            <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
         <?php else: ?>
             <div class="cart-price">
         <?php endif; ?>
@@ -218,7 +218,7 @@
             </div>
 
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <div class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
                     <span class="weee"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>: <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_item->getRowTotal()+$_item->getWeeeTaxAppliedRowAmount()+$_item->getWeeeTaxRowDisposition()); ?></span>
                 </div>
             <?php endif; ?>
@@ -229,7 +229,7 @@
     <td>
         <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getSubtotalInclTax($_item); ?>
         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-            <div class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+            <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
         <?php else: ?>
             <div class="cart-price">
         <?php endif; ?>
@@ -266,7 +266,7 @@
             </div>
 
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <div class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
                     <span class="weee"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>: <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_incl+$_item->getWeeeTaxAppliedRowAmount()); ?></span>
                 </div>
             <?php endif; ?>
diff --git a/app/code/core/Mage/Downloadable/view/frontend/checkout/onepage/review/item.phtml b/app/code/core/Mage/Downloadable/view/frontend/checkout/onepage/review/item.phtml
index 0b49fe223b849a271682942a33dd3922b21eafe1..1cfbd30c9b4e670ecd8bc0216e99aae2700ff6a5 100644
--- a/app/code/core/Mage/Downloadable/view/frontend/checkout/onepage/review/item.phtml
+++ b/app/code/core/Mage/Downloadable/view/frontend/checkout/onepage/review/item.phtml
@@ -59,7 +59,7 @@
     <?php if ($this->helper('Mage_Tax_Helper_Data')->displayCartPriceExclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()): ?>
     <td class="a-right">
         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-            <div class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+            <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $_item->getId(); ?>"}'>
         <?php else: ?>
             <div class="cart-price">
         <?php endif; ?>
@@ -96,7 +96,7 @@
             </div>
 
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <div class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $_item->getId(); ?>"}'>
                     <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_item->getCalculationPrice()+$_item->getWeeeTaxAppliedAmount()+$_item->getWeeeTaxDisposition()); ?></span>
                 </div>
             <?php endif; ?>
@@ -107,7 +107,7 @@
     <td>
         <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getPriceInclTax($_item); ?>
         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-            <div class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+            <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $_item->getId(); ?>"}'>
         <?php else: ?>
             <div class="cart-price">
         <?php endif; ?>
@@ -142,7 +142,7 @@
             </div>
 
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <div class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $_item->getId(); ?>"}'>
                     <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_incl+$_item->getWeeeTaxAppliedAmount()); ?></span>
                 </div>
             <?php endif; ?>
@@ -153,7 +153,7 @@
     <?php if ($this->helper('Mage_Tax_Helper_Data')->displayCartPriceExclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()): ?>
     <td class="a-right">
         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-            <div class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+            <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
         <?php else: ?>
             <div class="cart-price">
         <?php endif; ?>
@@ -188,7 +188,7 @@
             </div>
 
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <div class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
                     <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_item->getRowTotal()+$_item->getWeeeTaxAppliedRowAmount()+$_item->getWeeeTaxRowDisposition()); ?></span>
                 </div>
             <?php endif; ?>
@@ -199,7 +199,7 @@
     <td>
         <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getSubtotalInclTax($_item); ?>
         <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, array(1, 4), 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-            <div class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+            <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
         <?php else: ?>
             <div class="cart-price">
         <?php endif; ?>
@@ -236,7 +236,7 @@
             </div>
 
             <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($_item, 2, 'sales') && $_item->getWeeeTaxAppliedAmount()): ?>
-                <div class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $_item->getId(); ?>', this, 'cart-tax-total-expanded');">
+                <div class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $_item->getId(); ?>"}'>
                     <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($_incl+$_item->getWeeeTaxAppliedRowAmount()); ?></span>
                 </div>
             <?php endif; ?>
diff --git a/app/code/core/Mage/Downloadable/view/frontend/sales/order/creditmemo/items/renderer/downloadable.phtml b/app/code/core/Mage/Downloadable/view/frontend/sales/order/creditmemo/items/renderer/downloadable.phtml
index f1d89c613389e6a42bb9495e03b777ca32906900..dfe668fd2226b25b747ee30a4d96d8e81909e62c 100644
--- a/app/code/core/Mage/Downloadable/view/frontend/sales/order/creditmemo/items/renderer/downloadable.phtml
+++ b/app/code/core/Mage/Downloadable/view/frontend/sales/order/creditmemo/items/renderer/downloadable.phtml
@@ -81,7 +81,7 @@
                     <?php endif; ?>
                 <?php endif; ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -118,7 +118,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($this->getItem()->getPrice()+$this->getItem()->getWeeeTaxAppliedAmount()+$this->getItem()->getWeeeTaxDisposition()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -139,7 +139,7 @@
                 <?php endif; ?>
                 <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getPriceInclTax($this->getItem()); ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -176,7 +176,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($_incl+$this->getItem()->getWeeeTaxAppliedAmount()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -198,7 +198,7 @@
                     <?php endif; ?>
                 <?php endif; ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -235,7 +235,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($this->getItem()->getRowTotal()+$this->getItem()->getWeeeTaxAppliedRowAmount()+$this->getItem()->getWeeeTaxRowDisposition()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -256,7 +256,7 @@
                 <?php endif; ?>
                 <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getSubtotalInclTax($this->getItem()); ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -291,7 +291,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($_incl+$this->getItem()->getWeeeTaxAppliedRowAmount()); ?></span>
                         </span>
                     <?php endif; ?>
diff --git a/app/code/core/Mage/Downloadable/view/frontend/sales/order/invoice/items/renderer/downloadable.phtml b/app/code/core/Mage/Downloadable/view/frontend/sales/order/invoice/items/renderer/downloadable.phtml
index 7c9b5cba3eecb30e3f13d69795771ccc89054354..9dcdbd8877c9fbc07affbe3ae12a8be616074245 100644
--- a/app/code/core/Mage/Downloadable/view/frontend/sales/order/invoice/items/renderer/downloadable.phtml
+++ b/app/code/core/Mage/Downloadable/view/frontend/sales/order/invoice/items/renderer/downloadable.phtml
@@ -82,7 +82,7 @@
                     <?php endif; ?>
                 <?php endif; ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -119,7 +119,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($this->getItem()->getPrice()+$this->getItem()->getWeeeTaxAppliedAmount()+$this->getItem()->getWeeeTaxDisposition()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -140,7 +140,7 @@
                 <?php endif; ?>
                 <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getPriceInclTax($this->getItem()); ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -177,7 +177,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($_incl+$this->getItem()->getWeeeTaxAppliedAmount()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -199,7 +199,7 @@
                     <?php endif; ?>
                 <?php endif; ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -236,7 +236,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($this->getItem()->getRowTotal()+$this->getItem()->getWeeeTaxAppliedRowAmount()+$this->getItem()->getWeeeTaxRowDisposition()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -257,7 +257,7 @@
                 <?php endif; ?>
                 <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getSubtotalInclTax($this->getItem()); ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -293,7 +293,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($_incl+$this->getItem()->getWeeeTaxAppliedRowAmount()); ?></span>
                         </span>
                     <?php endif; ?>
diff --git a/app/code/core/Mage/Downloadable/view/frontend/sales/order/items/renderer/downloadable.phtml b/app/code/core/Mage/Downloadable/view/frontend/sales/order/items/renderer/downloadable.phtml
index cc0fb76f2f96e585f560c69d6b3029217d495be3..c3b951468221f0fc7e9d8f1890036e9d943abd19 100644
--- a/app/code/core/Mage/Downloadable/view/frontend/sales/order/items/renderer/downloadable.phtml
+++ b/app/code/core/Mage/Downloadable/view/frontend/sales/order/items/renderer/downloadable.phtml
@@ -81,7 +81,7 @@
                     <?php endif; ?>
                 <?php endif; ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -118,7 +118,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($this->getItem()->getPrice()+$this->getItem()->getWeeeTaxAppliedAmount()+$this->getItem()->getWeeeTaxDisposition()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -139,7 +139,7 @@
                 <?php endif; ?>
                 <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getPriceInclTax($this->getItem()); ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -176,7 +176,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($_incl+$this->getItem()->getWeeeTaxAppliedAmount()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -213,7 +213,7 @@
                     <?php endif; ?>
                 <?php endif; ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -250,7 +250,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($this->getItem()->getRowTotal()+$this->getItem()->getWeeeTaxAppliedRowAmount()+$this->getItem()->getWeeeTaxRowDisposition()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -271,7 +271,7 @@
                 <?php endif; ?>
                 <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getSubtotalInclTax($this->getItem()); ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -307,7 +307,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($_incl+$this->getItem()->getWeeeTaxAppliedRowAmount()); ?></span>
                         </span>
                     <?php endif; ?>
diff --git a/app/code/core/Mage/Eav/Block/Adminhtml/Attribute/Edit/Options/Abstract.php b/app/code/core/Mage/Eav/Block/Adminhtml/Attribute/Edit/Options/Abstract.php
index d3ab5db541f0af4eda4fafbbed87a0216ce393f5..1ab7e6708e91fbf20a98b686ae027e7f77729fd7 100644
--- a/app/code/core/Mage/Eav/Block/Adminhtml/Attribute/Edit/Options/Abstract.php
+++ b/app/code/core/Mage/Eav/Block/Adminhtml/Attribute/Edit/Options/Abstract.php
@@ -210,7 +210,7 @@ abstract class Mage_Eav_Block_Adminhtml_Attribute_Edit_Options_Abstract extends
 
         foreach ($this->getStores() as $store) {
             $storeId = $store->getId();
-            $value['store' . $storeId] = $storeId == Mage_Core_Model_App::ADMIN_STORE_ID
+            $value['store' . $storeId] = $storeId == Mage_Core_Model_AppInterface::ADMIN_STORE_ID
                 ? $valuePrefix . $this->escapeHtml($option['label'])
                 : '';
         }
diff --git a/app/code/core/Mage/Eav/Model/Entity/Abstract.php b/app/code/core/Mage/Eav/Model/Entity/Abstract.php
index 3b15a5fc83fd13e064c1c642d0bd5c9b096af13d..4ef3afe88af65407dd5edb869a0c6958b4b3e42d 100644
--- a/app/code/core/Mage/Eav/Model/Entity/Abstract.php
+++ b/app/code/core/Mage/Eav/Model/Entity/Abstract.php
@@ -66,7 +66,7 @@ abstract class Mage_Eav_Model_Entity_Abstract extends Mage_Core_Model_Resource_A
     /**
      * Attributes array by attribute name
      *
-     * @var unknown_type
+     * @var array
      */
     protected $_attributesByCode            = array();
 
@@ -364,6 +364,16 @@ abstract class Mage_Eav_Model_Entity_Abstract extends Mage_Core_Model_Resource_A
         return $this;
     }
 
+    /**
+     * Get EAV config model
+     *
+     * @return Mage_Eav_Model_Config
+     */
+    protected function _getConfig()
+    {
+        return Mage::getSingleton('Mage_Eav_Model_Config');
+    }
+
     /**
      * Retrieve attribute instance by name, id or config node
      *
@@ -377,7 +387,7 @@ abstract class Mage_Eav_Model_Entity_Abstract extends Mage_Core_Model_Resource_A
     public function getAttribute($attribute)
     {
         /** @var $config Mage_Eav_Model_Config */
-        $config = Mage::getSingleton('Mage_Eav_Model_Config');
+        $config = $this->_getConfig();
         if (is_numeric($attribute)) {
             $attributeId = $attribute;
 
diff --git a/app/code/core/Mage/Eav/Model/Entity/Attribute/Frontend/Abstract.php b/app/code/core/Mage/Eav/Model/Entity/Attribute/Frontend/Abstract.php
index d9e6f31d67d7ed81e68cf368e1b44772ad9a6a66..2169cfeaf62054641575bf749f243e6e06b883e2 100644
--- a/app/code/core/Mage/Eav/Model/Entity/Attribute/Frontend/Abstract.php
+++ b/app/code/core/Mage/Eav/Model/Entity/Attribute/Frontend/Abstract.php
@@ -231,13 +231,10 @@ abstract class Mage_Eav_Model_Entity_Attribute_Frontend_Abstract
     /**
      * Retrieve Input Renderer Class
      *
-     * @return string
+     * @return string|null
      */
-    public function getInputRendererClass() {
-        $className = $this->getAttribute()->getData('frontend_input_renderer');
-        if ($className) {
-            return Mage::getConfig()->getBlockClassName($className);
-        }
-        return null;
+    public function getInputRendererClass()
+    {
+        return $this->getAttribute()->getData('frontend_input_renderer');
     }
 }
diff --git a/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php b/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php
index c6b3ee659626cbc887482fc691e251b0e6cc95d0..d60696848a1a311dae72ed2ff68273267fc0b352 100644
--- a/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php
+++ b/app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php
@@ -181,7 +181,7 @@ abstract class Mage_Eav_Model_Entity_Collection_Abstract extends Varien_Data_Col
      */
     protected function _init($model, $entityModel)
     {
-        $this->setItemObjectClass(Mage::getConfig()->getModelClassName($model));
+        $this->setItemObjectClass($model);
         $entity = Mage::getResourceSingleton($entityModel);
         $this->setEntity($entity);
 
diff --git a/app/code/core/Mage/Eav/Model/Entity/Setup.php b/app/code/core/Mage/Eav/Model/Entity/Setup.php
index c457585ee8cc6044065ea50e412fb1bafbde6e51..59587fee20f40d99700363a617b3db08a126c18e 100644
--- a/app/code/core/Mage/Eav/Model/Entity/Setup.php
+++ b/app/code/core/Mage/Eav/Model/Entity/Setup.php
@@ -34,6 +34,34 @@
  */
 class Mage_Eav_Model_Entity_Setup extends Mage_Core_Model_Resource_Setup
 {
+    /**
+     * Application cache model
+     *
+     * @var Mage_Core_Model_Cache
+     */
+    protected $_cache;
+
+    /**
+     * @param Mage_Core_Model_Config_Resource $resourcesConfig
+     * @param Mage_Core_Model_Config_Modules $modulesConfig
+     * @param Mage_Core_Model_Resource $resource
+     * @param Mage_Core_Model_Config_Modules_Reader $modulesReader
+     * @param Mage_Core_Model_Cache $cache
+     * @param string $resourceName
+     */
+    public function __construct(
+        Mage_Core_Model_Config_Resource $resourcesConfig,
+        Mage_Core_Model_Config_Modules $modulesConfig,
+        Mage_Core_Model_Resource $resource,
+        Mage_Core_Model_Config_Modules_Reader $modulesReader,
+        Mage_Core_Model_Cache $cache,
+        $resourceName
+    )
+    {
+        parent::__construct($resourcesConfig, $modulesConfig, $resource, $modulesReader, $resourceName);
+        $this->_cache = $cache;
+    }
+
     /**
      * General Attribute Group Name
      *
@@ -78,7 +106,7 @@ class Mage_Eav_Model_Entity_Setup extends Mage_Core_Model_Resource_Setup
      */
     public function cleanCache()
     {
-        Mage::app()->cleanCache(array('eav'));
+        $this->_cache->clean(array('eav'));
         return $this;
     }
 
diff --git a/app/code/core/Mage/Eav/Model/Form.php b/app/code/core/Mage/Eav/Model/Form.php
index c72495e503659d35f743542a7a7fdb7234ab04a9..7c47d7db799c53b81d1fa32bfdce211128702121 100644
--- a/app/code/core/Mage/Eav/Model/Form.php
+++ b/app/code/core/Mage/Eav/Model/Form.php
@@ -410,7 +410,8 @@ abstract class Mage_Eav_Model_Form
     protected function _getValidator(array $data)
     {
         if (is_null($this->_validator)) {
-            $configFiles = Mage::getConfig()->getModuleConfigurationFiles('validation.xml');
+            $configFiles = Mage::getSingleton('Mage_Core_Model_Config_Modules_Reader')
+                ->getModuleConfigurationFiles('validation.xml');
             $validatorFactory = new Magento_Validator_Config($configFiles);
             $builder = $validatorFactory->createValidatorBuilder('eav_entity', 'form');
 
diff --git a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute.php b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute.php
index 067f928a4db4fa83986572adbf91c9afb7b6771d..97811f359b94c8c37db4233c1abf25017d331030 100755
--- a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute.php
@@ -568,7 +568,7 @@ class Mage_Eav_Model_Resource_Entity_Attribute extends Mage_Core_Model_Resource_
             ." AND %s.store_id = %d";
         $joinCondition = sprintf($joinConditionTemplate,
             'e', 't1', 't1', 't1', 't1',
-            Mage_Core_Model_App::ADMIN_STORE_ID);
+            Mage_Core_Model_AppInterface::ADMIN_STORE_ID);
         if ($attribute->getFlatAddChildData()) {
             $joinCondition .= ' AND e.child_id = t1.entity_id';
         }
diff --git a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option.php b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option.php
index cab9baddd37768dd4c213716e8ee9893ccec9bbc..5b9b6e93553898f2954238ff64e23f5e0cde5b0f 100755
--- a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option.php
@@ -98,7 +98,7 @@ class Mage_Eav_Model_Resource_Entity_Attribute_Option extends Mage_Core_Model_Re
             . " AND %s.attribute_id = " . $attribute->getId()
             . " AND %s.store_id = %d";
         $joinCondition = sprintf($joinConditionTemplate, 'e', 't1', 't1', 't1', 't1',
-            Mage_Core_Model_App::ADMIN_STORE_ID);
+            Mage_Core_Model_AppInterface::ADMIN_STORE_ID);
         if ($attribute->getFlatAddChildData()) {
             $joinCondition .= ' AND e.child_id = t1.entity_id';
         }
diff --git a/app/code/core/Mage/GoogleAnalytics/view/frontend/ga.phtml b/app/code/core/Mage/GoogleAnalytics/view/frontend/ga.phtml
index fddb32fd4c6a328a212ab643ff5f868a8e947066..88d331ae4729ede2a61bb4383eb2a6bd82f998b7 100644
--- a/app/code/core/Mage/GoogleAnalytics/view/frontend/ga.phtml
+++ b/app/code/core/Mage/GoogleAnalytics/view/frontend/ga.phtml
@@ -33,12 +33,9 @@
     <?php echo $this->_getPageTrackingCode($accountId) ?>
     <?php echo $this->_getOrdersTrackingCode() ?>
 
-    (function() {
-        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
-        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
-        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
-    })();
-
+    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
+    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
+    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
 //]]>
 </script>
 <!-- END GOOGLE ANALYTICS CODE -->
diff --git a/app/code/core/Mage/GoogleCheckout/Model/Api/Xml/Abstract.php b/app/code/core/Mage/GoogleCheckout/Model/Api/Xml/Abstract.php
index 97a09bd9b947461dd70ce58f9e26b505f5fa4cd3..c3b2914c2c214a84cd84618f7584bfc84aca3491 100644
--- a/app/code/core/Mage/GoogleCheckout/Model/Api/Xml/Abstract.php
+++ b/app/code/core/Mage/GoogleCheckout/Model/Api/Xml/Abstract.php
@@ -31,6 +31,21 @@ require_once('googlecheckout/googlerequest.php');
 
 abstract class Mage_GoogleCheckout_Model_Api_Xml_Abstract extends Varien_Object
 {
+    /**
+     * @var Mage_Core_Model_Translate
+     */
+    protected $_translator;
+
+    /**
+     * @param Mage_Core_Model_Translate $translator
+     * @param array $data
+     */
+    public function __construct(Mage_Core_Model_Translate $translator, array $data = array())
+    {
+        parent::__construct($data);
+        $this->_translator = $translator;
+    }
+
     public function log($text, $nl=true)
     {
         error_log(print_r($text, 1) . ($nl ? "\n" : ''), 3, Mage::getBaseDir('log') . DS . 'callback.log');
@@ -42,7 +57,7 @@ abstract class Mage_GoogleCheckout_Model_Api_Xml_Abstract extends Varien_Object
         $args = func_get_args();
         $expr = new Mage_Core_Model_Translate_Expr(array_shift($args), 'Mage_GoogleCheckout');
         array_unshift($args, $expr);
-        return Mage::app()->getTranslator()->translate($args);
+        return $this->_translator->translate($args);
     }
 
     public function getMerchantId()
diff --git a/app/code/core/Mage/ImportExport/Model/Import/Entity/Product/Option.php b/app/code/core/Mage/ImportExport/Model/Import/Entity/Product/Option.php
index ef1ccfd42d1c4bfcc977a600ee503d67c31b80db..23c4756bfc7b92384571a1622f6248de61a39f76 100644
--- a/app/code/core/Mage/ImportExport/Model/Import/Entity/Product/Option.php
+++ b/app/code/core/Mage/ImportExport/Model/Import/Entity/Product/Option.php
@@ -725,7 +725,7 @@ class Mage_ImportExport_Model_Import_Entity_Product_Option extends Mage_ImportEx
             $storeCode = $rowData[self::COLUMN_STORE];
             $storeId = $this->_storeCodeToId[$storeCode];
         } else {
-            $storeId = Mage_Core_Model_App::ADMIN_STORE_ID;
+            $storeId = Mage_Core_Model_AppInterface::ADMIN_STORE_ID;
         }
         if (isset($this->_productsSkuToId[$this->_rowProductSku])) {
             // save in existing data array
@@ -1070,18 +1070,21 @@ class Mage_ImportExport_Model_Import_Entity_Product_Option extends Mage_ImportEx
                 $typeValues[$prevOptionId][] = $specificTypeData['value'];
 
                 // ensure default title is set
-                if (!isset($typeTitles[$nextValueId][Mage_Core_Model_App::ADMIN_STORE_ID])) {
-                    $typeTitles[$nextValueId][Mage_Core_Model_App::ADMIN_STORE_ID] = $specificTypeData['title'];
+                if (!isset($typeTitles[$nextValueId][Mage_Core_Model_AppInterface::ADMIN_STORE_ID])) {
+                    $typeTitles[$nextValueId][Mage_Core_Model_AppInterface::ADMIN_STORE_ID]
+                        = $specificTypeData['title'];
                 }
                 $typeTitles[$nextValueId][$this->_rowStoreId] = $specificTypeData['title'];;
 
                 if ($specificTypeData['price']) {
                     if ($this->_isPriceGlobal) {
-                        $typePrices[$nextValueId][Mage_Core_Model_App::ADMIN_STORE_ID] = $specificTypeData['price'];
+                        $typePrices[$nextValueId][Mage_Core_Model_AppInterface::ADMIN_STORE_ID]
+                            = $specificTypeData['price'];
                     } else {
                         // ensure default price is set
-                        if (!isset($typePrices[$nextValueId][Mage_Core_Model_App::ADMIN_STORE_ID])) {
-                            $typePrices[$nextValueId][Mage_Core_Model_App::ADMIN_STORE_ID] = $specificTypeData['price'];
+                        if (!isset($typePrices[$nextValueId][Mage_Core_Model_AppInterface::ADMIN_STORE_ID])) {
+                            $typePrices[$nextValueId][Mage_Core_Model_AppInterface::ADMIN_STORE_ID]
+                                = $specificTypeData['price'];
                         }
                         $typePrices[$nextValueId][$this->_rowStoreId] = $specificTypeData['price'];
                     }
@@ -1102,8 +1105,9 @@ class Mage_ImportExport_Model_Import_Entity_Product_Option extends Mage_ImportEx
     protected function _collectOptionTitle(array $rowData, $prevOptionId, array &$titles)
     {
         if (!empty($rowData[self::COLUMN_TITLE])) {
-            if (!isset($titles[$prevOptionId][Mage_Core_Model_App::ADMIN_STORE_ID])) { // ensure default title is set
-                $titles[$prevOptionId][Mage_Core_Model_App::ADMIN_STORE_ID] = $rowData[self::COLUMN_TITLE];
+            if (!isset($titles[$prevOptionId][Mage_Core_Model_AppInterface::ADMIN_STORE_ID])) {
+                // ensure default title is set
+                $titles[$prevOptionId][Mage_Core_Model_AppInterface::ADMIN_STORE_ID] = $rowData[self::COLUMN_TITLE];
             }
             $titles[$prevOptionId][$this->_rowStoreId] = $rowData[self::COLUMN_TITLE];
         }
diff --git a/app/code/core/Mage/Index/Model/EntryPoint/Indexer.php b/app/code/core/Mage/Index/Model/EntryPoint/Indexer.php
new file mode 100644
index 0000000000000000000000000000000000000000..4beadc5b0b31be33256c5252ad671f29c1ca8e80
--- /dev/null
+++ b/app/code/core/Mage/Index/Model/EntryPoint/Indexer.php
@@ -0,0 +1,61 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Index_Model_EntryPoint_Indexer extends Mage_Core_Model_EntryPointAbstract
+{
+    /**
+     * @var array
+     */
+    protected $_params;
+
+    /**
+     * @param string $baseDir
+     * @param array $params
+     */
+    public function __construct($baseDir, array $params = array())
+    {
+        $this->_params = $params;
+        unset($params['reportDir']);
+        parent::__construct($baseDir, $params);
+    }
+
+    /**
+     * Process request to application
+     */
+    protected function _processRequest()
+    {
+        /* Clean reports */
+        Varien_Io_File::rmdirRecursive($this->_params['reportDir']);
+
+        /* Run all indexer processes */
+        /** @var $indexer Mage_Index_Model_Indexer */
+        $indexer = $this->_objectManager->create('Mage_Index_Model_Indexer');
+        /** @var $process Mage_Index_Model_Process */
+        foreach ($indexer->getProcessesCollection() as $process) {
+            if ($process->getIndexer()->isVisible()) {
+                $process->reindexEverything();
+            }
+        }
+    }
+}
diff --git a/app/code/core/Mage/Index/Model/EntryPoint/Shell.php b/app/code/core/Mage/Index/Model/EntryPoint/Shell.php
new file mode 100644
index 0000000000000000000000000000000000000000..3d1e308e6f536f17cc32c5bc5dc6b7096c835ce5
--- /dev/null
+++ b/app/code/core/Mage/Index/Model/EntryPoint/Shell.php
@@ -0,0 +1,57 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Index_Model_EntryPoint_Shell extends Mage_Core_Model_EntryPointAbstract
+{
+    /**
+     * @param string $baseDir
+     * @param array $params
+     */
+    public function __construct($baseDir, array $params = array())
+    {
+        $entryPoint = $params['entryPoint'];
+        unset($params['entryPoint']);
+        parent::__construct($baseDir, $params);
+        $this->_objectManager->setConfiguration(array(
+            'Mage_Index_Model_Shell' => array(
+                'parameters' => array(
+                    'entryPoint' => $entryPoint,
+                )
+            )
+        ));
+    }
+
+    /**
+     * Process request to application
+     */
+    protected function _processRequest()
+    {
+        /** @var $shell Mage_Index_Model_Shell */
+        $shell = $this->_objectManager->create('Mage_Index_Model_Shell');
+        $shell->run();
+        if ($shell->hasErrors()) {
+            exit(1);
+        }
+    }
+}
diff --git a/app/code/core/Mage/Index/Model/Resource/Setup.php b/app/code/core/Mage/Index/Model/Resource/Setup.php
index 627f51d4ab50cb447cd3c28ad310077a57e9b8f6..4d2979daefcd7c43923ab7ca9bf9a314b59d30df 100755
--- a/app/code/core/Mage/Index/Model/Resource/Setup.php
+++ b/app/code/core/Mage/Index/Model/Resource/Setup.php
@@ -56,7 +56,7 @@ class Mage_Index_Model_Resource_Setup extends Mage_Core_Model_Resource_Setup
         if (!$connection) {
             return $this;
         }
-        $indexes = Mage::getConfig()->getNode(Mage_Index_Model_Process::XML_PATH_INDEXER_DATA);
+        $indexes = $this->_config->getNode(Mage_Index_Model_Process::XML_PATH_INDEXER_DATA);
         $indexCodes = array();
         foreach ($indexes->children() as $code => $index) {
             $indexCodes[] = $code;
diff --git a/app/code/core/Mage/Install/Model/Config.php b/app/code/core/Mage/Install/Model/Config.php
index 6ed540a871b1809f4e8d08a4942ed8da35d34441..6b6b49cab8579bd541d25642d43b637578ea5b2e 100644
--- a/app/code/core/Mage/Install/Model/Config.php
+++ b/app/code/core/Mage/Install/Model/Config.php
@@ -34,16 +34,18 @@
  */
 class Mage_Install_Model_Config extends Varien_Simplexml_Config
 {
-
     const XML_PATH_WIZARD_STEPS     = 'wizard/steps';
     const XML_PATH_CHECK_WRITEABLE  = 'check/filesystem/writeable';
     const XML_PATH_CHECK_EXTENSIONS = 'check/php/extensions';
 
-    public function __construct()
+    /**
+     * @param Mage_Core_Model_Config_Modules_Reader $configReader
+     */
+    public function __construct(Mage_Core_Model_Config_Modules_Reader $configReader)
     {
         parent::__construct();
         $this->loadString('<?xml version="1.0"?><config></config>');
-        Mage::getConfig()->loadModulesConfiguration('install.xml', $this);
+        $configReader->loadModulesConfiguration('install.xml', $this);
     }
 
     /**
diff --git a/app/code/core/Mage/Install/Model/EntryPoint/Console.php b/app/code/core/Mage/Install/Model/EntryPoint/Console.php
new file mode 100644
index 0000000000000000000000000000000000000000..51de68ce936e9fa57a51e8da8255e6856fd4a032
--- /dev/null
+++ b/app/code/core/Mage/Install/Model/EntryPoint/Console.php
@@ -0,0 +1,103 @@
+<?php
+/**
+ * Console entry point
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Install_Model_EntryPoint_Console extends Mage_Core_Model_EntryPointAbstract
+{
+    /**
+     * @param string $baseDir
+     * @param array $params
+     */
+    public function __construct($baseDir, array $params = array())
+    {
+        $this->_params = $this->_buildInitParams($params);
+        parent::__construct($baseDir, $this->_params);
+    }
+
+    /**
+     * Customize application init parameters
+     *
+     * @param array $args
+     * @return array
+     */
+    protected function _buildInitParams(array $args)
+    {
+        if (!empty($args[Mage_Install_Model_Installer_Console::OPTION_URIS])) {
+            $args[MAGE::PARAM_APP_URIS] =
+                unserialize(base64_decode($args[Mage_Install_Model_Installer_Console::OPTION_URIS]));
+        }
+        if (!empty($args[Mage_Install_Model_Installer_Console::OPTION_DIRS])) {
+            $args[Mage::PARAM_APP_DIRS] =
+                unserialize(base64_decode($args[Mage_Install_Model_Installer_Console::OPTION_DIRS]));
+        }
+        return $args;
+    }
+
+    /**
+     * Run http application
+     */
+    protected function _processRequest()
+    {
+        /**
+         * @var $installer Mage_Install_Model_Installer_Console
+         */
+        $installer = $this->_objectManager->get(
+            'Mage_Install_Model_Installer_Console',
+            array('installArgs' => $this->_params)
+        );
+        if (isset($this->_params['show_locales'])) {
+            var_export($installer->getAvailableLocales());
+        } else if (isset($this->_params['show_currencies'])) {
+            var_export($installer->getAvailableCurrencies());
+        } else if (isset($this->_params['show_timezones'])) {
+            var_export($installer->getAvailableTimezones());
+        } else if (isset($this->_params['show_install_options'])) {
+            var_export($installer->getAvailableInstallOptions());
+        } else {
+            if (isset($this->_params['config']) && file_exists($this->_params['config'])) {
+                $config = (array) include($this->_params['config']);
+                $this->_params = array_merge((array)$config, $this->_params);
+            }
+            $isUninstallMode = isset($this->_params['uninstall']);
+            if ($isUninstallMode) {
+                $result = $installer->uninstall();
+            } else {
+                $result = $installer->install($this->_params);
+            }
+            if (!$installer->hasErrors()) {
+                if ($isUninstallMode) {
+                    $msg = $result ?
+                        'Uninstalled successfully' :
+                        'Ignoring attempt to uninstall non-installed application';
+                } else {
+                    $msg = 'Installed successfully' . ($result ? ' (encryption key "' . $result . '")' : '');
+                }
+                echo $msg . PHP_EOL;
+            } else {
+                echo implode(PHP_EOL, $installer->getErrors()) . PHP_EOL;
+                exit(1);
+            }
+        }
+    }
+}
diff --git a/app/code/core/Mage/Install/Model/Installer.php b/app/code/core/Mage/Install/Model/Installer.php
index 2e9c96e6238c4380db77f8b31f5716fd0e4ef181..e349aebd72994b22ac27e419fe8bda5352984db2 100644
--- a/app/code/core/Mage/Install/Model/Installer.php
+++ b/app/code/core/Mage/Install/Model/Installer.php
@@ -34,7 +34,6 @@
  */
 class Mage_Install_Model_Installer extends Varien_Object
 {
-
     /**
      * Installer data model used to store data between installation steps
      *
@@ -42,6 +41,45 @@ class Mage_Install_Model_Installer extends Varien_Object
      */
     protected $_dataModel;
 
+    /**
+     * DB updated model
+     *
+     * @var Mage_Core_Model_Db_UpdaterInterface
+     */
+    protected $_dbUpdater;
+
+    /**
+     * Application chache model
+     *
+     * @var Mage_Core_Model_Cache
+     */
+    protected $_cache;
+
+    /**
+     * Application config model
+     *
+     * @var Mage_Core_Model_ConfigInterface
+     */
+    protected $_config;
+
+    /**
+     * @param Mage_Core_Model_ConfigInterface $config
+     * @param Mage_Core_Model_Db_UpdaterInterface $dbUpdater
+     * @param Mage_Core_Model_Cache $cache
+     * @param array $data
+     */
+    public function __construct(
+        Mage_Core_Model_ConfigInterface $config,
+        Mage_Core_Model_Db_UpdaterInterface $dbUpdater,
+        Mage_Core_Model_Cache $cache,
+        array $data = array()
+    ) {
+        $this->_dbUpdater = $dbUpdater;
+        $this->_config = $config;
+        $this->_cache = $cache;
+        parent::__construct($data);
+    }
+
     /**
      * Checking install status of application
      *
@@ -85,7 +123,7 @@ class Mage_Install_Model_Installer extends Varien_Object
     public function checkDownloads()
     {
         try {
-            $result = Mage::getModel('Mage_Install_Model_Installer_Pear')->checkDownloads();
+            Mage::getModel('Mage_Install_Model_Installer_Pear')->checkDownloads();
             $result = true;
         } catch (Exception $e) {
             $result = false;
@@ -143,7 +181,15 @@ class Mage_Install_Model_Installer extends Varien_Object
             ->setConfigData($data)
             ->install();
 
-        $this->_refreshConfig();
+
+        /** @var $primaryConfig Mage_Core_Model_Config_Primary */
+        $primaryConfig = Mage::getSingleton('Mage_Core_Model_Config_Primary');
+        $primaryConfig->reinit();
+
+        /** @var $moduleConfig  Mage_Core_Model_Config_Modules*/
+        $moduleConfig = Mage::getSingleton('Mage_Core_Model_Config_Modules');
+        $moduleConfig->reinit();
+
         return $this;
     }
 
@@ -154,13 +200,14 @@ class Mage_Install_Model_Installer extends Varien_Object
      */
     public function installDb()
     {
-        Mage_Core_Model_Resource_Setup::applyAllUpdates();
+        $this->_dbUpdater->updateScheme();
         $data = $this->getDataModel()->getConfigData();
 
         /**
          * Saving host information into DB
          */
-        $setupModel = new Mage_Core_Model_Resource_Setup('core_setup');
+        $setupModel = Mage::getObjectManager()
+            ->get('Mage_Core_Model_Resource_Setup', array('resourceName' => 'core_setup'));
 
         if (!empty($data['use_rewrites'])) {
             $setupModel->setConfigData(Mage_Core_Model_Store::XML_PATH_USE_REWRITES, 1);
@@ -293,7 +340,7 @@ class Mage_Install_Model_Installer extends Varien_Object
         foreach (Mage::helper('Mage_Core_Helper_Data')->getCacheTypes() as $type => $label) {
             $cacheData[$type] = 1;
         }
-        Mage::app()->saveUseCache($cacheData);
+        $this->_cache->saveOptions($cacheData);
         return $this;
     }
 
@@ -302,7 +349,7 @@ class Mage_Install_Model_Installer extends Varien_Object
      */
     protected function _refreshConfig()
     {
-        Mage::app()->cleanCache();
-        Mage::app()->getConfig()->reinit();
+        $this->_cache->clean();
+        $this->_config->reinit();
     }
 }
diff --git a/app/code/core/Mage/Install/Model/Installer/Config.php b/app/code/core/Mage/Install/Model/Installer/Config.php
index 63c272038d41c77d6549e43392d1cb19c18726c8..7b439b0ed22f7c3f881ae2695f642582bdca1ccc 100644
--- a/app/code/core/Mage/Install/Model/Installer/Config.php
+++ b/app/code/core/Mage/Install/Model/Installer/Config.php
@@ -47,6 +47,13 @@ class Mage_Install_Model_Installer_Config extends Mage_Install_Model_Installer_A
      */
     protected $_config;
 
+    /**
+     * Resource configuration
+     *
+     * @var Mage_Core_Model_Config_Resource
+     */
+    protected $_resourceConfig;
+
     /**
      * @var Mage_Core_Model_Dir
      */
@@ -60,20 +67,21 @@ class Mage_Install_Model_Installer_Config extends Mage_Install_Model_Installer_A
     protected $_filesystem;
 
     /**
-     * Inject dependencies on config and directories
-     *
      * @param Mage_Core_Model_Config $config
      * @param Mage_Core_Model_Dir $dirs
+     * @param Mage_Core_Model_Config_Resource $resourceConfig
      * @param Magento_Filesystem $filesystem
      */
     public function __construct(
-            Mage_Core_Model_Config $config,
-            Mage_Core_Model_Dir $dirs,
-            Magento_Filesystem $filesystem
+        Mage_Core_Model_Config $config, 
+        Mage_Core_Model_Dir $dirs, 
+        Mage_Core_Model_Config_Resource $resourceConfig,
+        Magento_Filesystem $filesystem
     ) {
         $this->_localConfigFile = $dirs->getDir(Mage_Core_Model_Dir::CONFIG) . DIRECTORY_SEPARATOR . 'local.xml';
-        $this->_config = $config;
         $this->_dirs = $dirs;
+        $this->_config = $config;
+        $this->_resourceConfig = $resourceConfig;
         $this->_filesystem = $filesystem;
     }
 
@@ -160,7 +168,7 @@ class Mage_Install_Model_Installer_Config extends Mage_Install_Model_Installer_A
             $baseSecureUrl = $uri->getUri();
         }
 
-        $connectDefault = $this->_config
+        $connectDefault = $this->_resourceConfig
                 ->getResourceConnectionConfig(Mage_Core_Model_Resource::DEFAULT_SETUP_RESOURCE);
 
         $data = new Varien_Object();
diff --git a/app/code/core/Mage/Install/Model/Installer/Console.php b/app/code/core/Mage/Install/Model/Installer/Console.php
index a7c39168b592a07d6120cdd1f4329c4f886ba81b..28322efc747700a8c73bbc6ea6e673c70ec6a482 100644
--- a/app/code/core/Mage/Install/Model/Installer/Console.php
+++ b/app/code/core/Mage/Install/Model/Installer/Console.php
@@ -85,35 +85,32 @@ class Mage_Install_Model_Installer_Console extends Mage_Install_Model_Installer_
     protected $_dataModel;
 
     /**
-     * Initialize application and "data model"
+     * Resource config
      *
-     * @param Magento_Filesystem $filesystem
-     * @param array $installArgs
+     * @var Mage_Core_Model_Config_Resource
      */
-    public function __construct(Magento_Filesystem $filesystem, array $installArgs)
-    {
-        $this->_filesystem = $filesystem;
-        $params = $this->_buildInitParams($installArgs);
-        Mage::app($params);
-        $this->_getInstaller()->setDataModel($this->_getDataModel());
-    }
+    protected $_resourceConfig;
 
     /**
-     * Customize application init parameters
+     * DB updater
      *
-     * @param array $args
-     * @return array
+     * @var Mage_Core_Model_Db_UpdaterInterface
      */
-    protected function _buildInitParams(array $args)
-    {
-        $result = array();
-        if (!empty($args[self::OPTION_URIS])) {
-            $result[Mage_Core_Model_App::INIT_OPTION_URIS] = unserialize(base64_decode($args[self::OPTION_URIS]));
-        }
-        if (!empty($args[self::OPTION_DIRS])) {
-            $result[Mage_Core_Model_App::INIT_OPTION_DIRS] = unserialize(base64_decode($args[self::OPTION_DIRS]));
-        }
-        return $result;
+    protected $_dbUpdater;
+
+    /**
+     * @param Mage_Core_Model_Config_Resource $resourceConfig
+     * @param Mage_Core_Model_Db_UpdaterInterface $daUpdater
+     */
+    public function __construct(
+        Mage_Core_Model_Config_Resource $resourceConfig,
+        Mage_Core_Model_Db_UpdaterInterface $daUpdater,
+        Magento_Filesystem $filesystem
+    ) {
+        $this->_resourceConfig = $resourceConfig;
+        $this->_dbUpdater = $daUpdater;
+        $this->_getInstaller()->setDataModel($this->_getDataModel());
+        $this->_filesystem = $filesystem;
     }
 
     /**
@@ -308,7 +305,7 @@ class Mage_Install_Model_Installer_Console extends Mage_Install_Model_Installer_
             }
 
             // apply data updates
-            Mage_Core_Model_Resource_Setup::applyAllDataUpdates();
+            $this->_dbUpdater->updateData();
 
             /**
              * Create primary administrator user & install encryption key
@@ -349,7 +346,8 @@ class Mage_Install_Model_Installer_Console extends Mage_Install_Model_Installer_
      */
     protected function _cleanUpDatabase()
     {
-        $dbConfig = Mage::getConfig()->getResourceConnectionConfig(Mage_Core_Model_Resource::DEFAULT_SETUP_RESOURCE);
+        $dbConfig = $this->_resourceConfig
+            ->getResourceConnectionConfig(Mage_Core_Model_Resource::DEFAULT_SETUP_RESOURCE);
         $modelName = 'Mage_Install_Model_Installer_Db_' . ucfirst($dbConfig->model);
 
         if (!class_exists($modelName)) {
diff --git a/app/code/core/Mage/Install/Model/Installer/Db.php b/app/code/core/Mage/Install/Model/Installer/Db.php
index 43a953bcd694fbdae417cd503939be9d628acf9f..e8ce80cc63c9840cc0ae793bd28638fc0257fdba 100644
--- a/app/code/core/Mage/Install/Model/Installer/Db.php
+++ b/app/code/core/Mage/Install/Model/Installer/Db.php
@@ -38,6 +38,21 @@ class Mage_Install_Model_Installer_Db extends Mage_Install_Model_Installer_Abstr
      */
     protected $_dbResource;
 
+    /**
+     * Resource configuration
+     *
+     * @var Mage_Core_Model_Config_Resource
+     */
+    protected $_resourceConfig;
+
+    /**
+     * @param Mage_Core_Model_Config_Resource $resourceConfig
+     */
+    public function __construct(Mage_Core_Model_Config_Resource $resourceConfig)
+    {
+        $this->_resourceConfig = $resourceConfig;
+    }
+
     /**
      * Check database connection
      * and return checked connection data
@@ -129,12 +144,12 @@ class Mage_Install_Model_Installer_Db extends Mage_Install_Model_Installer_Abstr
         }
         //set default db model
         if (!isset($data['db_model']) || empty($data['db_model'])) {
-            $data['db_model'] = Mage::getConfig()
+            $data['db_model'] = $this->_resourceConfig
                 ->getResourceConnectionConfig(Mage_Core_Model_Resource::DEFAULT_SETUP_RESOURCE)->model;
         }
         //set db type according the db model
         if (!isset($data['db_type'])) {
-            $data['db_type'] = (string) Mage::getConfig()
+            $data['db_type'] = (string) Mage::getSingleton('Mage_Core_Model_Config_Modules')
                 ->getNode(sprintf('install/databases/%s/type', $data['db_model']));
         }
 
@@ -142,7 +157,7 @@ class Mage_Install_Model_Installer_Db extends Mage_Install_Model_Installer_Abstr
         $data['db_pdo_type'] = $dbResource->getPdoType();
 
         if (!isset($data['db_init_statements'])) {
-            $data['db_init_statements'] = (string) Mage::getConfig()
+            $data['db_init_statements'] = (string) Mage::getSingleton('Mage_Core_Model_Config_Modules')
                 ->getNode(sprintf('install/databases/%s/initStatements', $data['db_model']));
         }
 
diff --git a/app/code/core/Mage/Install/Model/Installer/Db/Mysql4.php b/app/code/core/Mage/Install/Model/Installer/Db/Mysql4.php
index 13d0a87519c99b69d8f8623cdb5e663d062c0e58..edcf433bcf55a3f42b023c58838ad0e534d932d2 100644
--- a/app/code/core/Mage/Install/Model/Installer/Db/Mysql4.php
+++ b/app/code/core/Mage/Install/Model/Installer/Db/Mysql4.php
@@ -71,7 +71,8 @@ class Mage_Install_Model_Installer_Db_Mysql4 extends Mage_Install_Model_Installe
      */
     public function cleanUpDatabase(SimpleXMLElement $config)
     {
-        $resourceModel = new Mage_Core_Model_Resource();
+        /** @var $resourceModel Mage_Core_Model_Resource */
+        $resourceModel = Mage::getModel('Mage_Core_Model_Resource');
         $connection = $resourceModel->getConnection(Mage_Core_Model_Resource::DEFAULT_SETUP_RESOURCE);
         $dbName = $config->dbname;
 
diff --git a/app/code/core/Mage/Install/controllers/IndexController.php b/app/code/core/Mage/Install/controllers/IndexController.php
index 6ed3afd47d2d95a453392fbff22fb166a650bc50..8456414093320b064223d710bab5949992302143 100644
--- a/app/code/core/Mage/Install/controllers/IndexController.php
+++ b/app/code/core/Mage/Install/controllers/IndexController.php
@@ -48,7 +48,7 @@ class Mage_Install_IndexController extends Mage_Install_Controller_Action
                 Varien_Io_File::rmdirRecursive($dir);
             }
         }
-        return parent::preDispatch();
+        parent::preDispatch();
     }
 
     /**
diff --git a/app/code/core/Mage/Install/controllers/WizardController.php b/app/code/core/Mage/Install/controllers/WizardController.php
index 1dccf7cfde5ee5544447a3d8b8ba1dcad19ec750..0c16d6a18bab2de7db1f75e36d32a7a1598482ee 100644
--- a/app/code/core/Mage/Install/controllers/WizardController.php
+++ b/app/code/core/Mage/Install/controllers/WizardController.php
@@ -116,7 +116,7 @@ class Mage_Install_WizardController extends Mage_Install_Controller_Action
     /**
      * Checking installation status
      *
-     * @return unknown
+     * @return bool
      */
     protected function _checkIfInstalled()
     {
diff --git a/app/code/core/Mage/Install/view/install/page.phtml b/app/code/core/Mage/Install/view/install/page.phtml
index 6cbe9dbfcf6b69b2281cca7aea490135314f46cd..00705e93de0374487fdef0856faf8d542d42cdae 100644
--- a/app/code/core/Mage/Install/view/install/page.phtml
+++ b/app/code/core/Mage/Install/view/install/page.phtml
@@ -39,7 +39,7 @@
     <link rel="shortcut icon" href="<?php echo $this->getViewFileUrl('Mage_Page::favicon.ico') ?>" type="image/x-icon"/>
 
     <script type="text/javascript" src="<?php echo $this->getViewFileUrl('jquery/jquery.min.js') ?>"></script>
-    <script type="text/javascript" src="<?php echo $this->getViewFileUrl('jquery/jquery-ui.custom.min.js') ?>"></script>
+    <script type="text/javascript" src="<?php echo $this->getViewFileUrl('jquery/jquery-ui.js') ?>"></script>
     <script type="text/javascript" src="<?php echo $this->getViewFileUrl('head.load.min.js') ?>"></script>
     <script type="text/javascript" src="<?php echo $this->getViewFileUrl('mage/mage.js') ?>"></script>
     <script type="text/javascript" src="<?php echo $this->getViewFileUrl('mage/translate.js') ?>"></script>
diff --git a/app/code/core/Mage/Log/Model/EntryPoint/Shell.php b/app/code/core/Mage/Log/Model/EntryPoint/Shell.php
new file mode 100644
index 0000000000000000000000000000000000000000..8e76da36c8ee718113cdecd3bc0f711ba9ed2dc6
--- /dev/null
+++ b/app/code/core/Mage/Log/Model/EntryPoint/Shell.php
@@ -0,0 +1,55 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Log_Model_EntryPoint_Shell extends Mage_Core_Model_EntryPointAbstract
+{
+    /**
+     * @param string $baseDir
+     * @param array $params
+     */
+    public function __construct($baseDir, array $params = array())
+    {
+        $entryPoint = $params['entryPoint'];
+        unset($params['entryPoint']);
+        parent::__construct($baseDir, $params);
+        $this->_objectManager->setConfiguration(array(
+            'Mage_Log_Model_Shell' => array(
+                'parameters' => array(
+                    'entryPoint' => $entryPoint,
+                )
+            )
+        ));
+    }
+
+    /**
+     * Process request to application
+     */
+    protected function _processRequest()
+    {
+        /** @var $shell Mage_Log_Model_Shell */
+        $shell = $this->_objectManager->create('Mage_Log_Model_Shell');
+        $shell->run();
+    }
+
+}
diff --git a/app/code/core/Mage/Page/Block/Html/Header.php b/app/code/core/Mage/Page/Block/Html/Header.php
index 79da788a4f6836d1f77c95a7d0be302b50b7d837..1ba0313bab816875551fe98f3bc4e9680911cbfa 100644
--- a/app/code/core/Mage/Page/Block/Html/Header.php
+++ b/app/code/core/Mage/Page/Block/Html/Header.php
@@ -106,7 +106,7 @@ class Mage_Page_Block_Html_Header extends Mage_Core_Block_Template
         if (!is_null($storeLogoPath) && $this->_isFile($absolutePath)) {
             $url = $logoUrl;
         } else {
-            $url = $this->getViewFileUrl('images::logo.gif');
+            $url = $this->getViewFileUrl('images/logo.gif');
         }
 
         return $url;
diff --git a/app/code/core/Mage/Page/Block/Redirect.php b/app/code/core/Mage/Page/Block/Redirect.php
index fc1b72a9f4c751298e8996a0cd6abebfc9aa6284..d5f33e93e7eb416c3066ccf840b2c96b38fdac47 100644
--- a/app/code/core/Mage/Page/Block/Redirect.php
+++ b/app/code/core/Mage/Page/Block/Redirect.php
@@ -70,7 +70,7 @@ class Mage_Page_Block_Redirect extends Mage_Core_Block_Template
         if ($this->isHtmlFormRedirect()) {
             return $this->getHtmlFormRedirect();
         } else {
-            return $this->getJsRedirect();
+            return $this->getRedirect();
         }
     }
 
@@ -79,12 +79,13 @@ class Mage_Page_Block_Redirect extends Mage_Core_Block_Template
      *
      *  @return	  string
      */
-    public function getJsRedirect ()
+    public function getRedirect ()
     {
-        $js  = '<script type="text/javascript">';
-        $js .= 'document.location.href="' . $this->getTargetURL() . '";';
-        $js .= '</script>';
-        return $js;
+        return '<script type="text/javascript">
+            (function($){
+                $($.mage.redirect("' . $this->getTargetURL() . '"));
+            })(jQuery);
+        </script>';
     }
 
     /**
@@ -98,14 +99,13 @@ class Mage_Page_Block_Redirect extends Mage_Core_Block_Template
         $form->setAction($this->getTargetURL())
             ->setId($this->getFormId())
             ->setName($this->getFormId())
+            ->setAttr('data-auto-submit', 'true')
             ->setMethod($this->getMethod())
             ->setUseContainer(true);
         foreach ($this->_getFormFields() as $field => $value) {
             $form->addField($field, 'hidden', array('name' => $field, 'value' => $value));
         }
-        $html = $form->toHtml();
-        $html.= '<script type="text/javascript">document.getElementById("' . $this->getFormId() . '").submit();</script>';
-        return $html;
+        return $form->toHtml();
     }
 
     /**
diff --git a/app/code/core/Mage/Page/view/frontend/js/menu.js b/app/code/core/Mage/Page/view/frontend/js/menu.js
index 668aeaf6789b04fd0a37247c822534479d763ab8..1daabdcb485debe8a9e6f553a771e6fc96b92d3b 100644
--- a/app/code/core/Mage/Page/view/frontend/js/menu.js
+++ b/app/code/core/Mage/Page/view/frontend/js/menu.js
@@ -40,6 +40,11 @@
             }, this));
         },
 
+        /**
+         * Show sub menu by adding shown-sub class
+         * @private
+         * @param subElement
+         */
         _show: function(subElement) {
             if (subElement.data('hideTimeId')) {
                 clearTimeout(subElement.data('hideTimeId'));
@@ -49,6 +54,11 @@
             }), this.options.showDelay);
         },
 
+        /**
+         * Hide sub menu by removing shown-sub class
+         * @private
+         * @param subElement
+         */
         _hide: function(subElement) {
             if (subElement.data('showTimeId')) {
                 clearTimeout(subElement.data('showTimeId'));
diff --git a/app/code/core/Mage/Page/view/frontend/js/row-builder.js b/app/code/core/Mage/Page/view/frontend/js/row-builder.js
new file mode 100644
index 0000000000000000000000000000000000000000..201d183f164e27edf1c55b1d5835b8cf75871634
--- /dev/null
+++ b/app/code/core/Mage/Page/view/frontend/js/row-builder.js
@@ -0,0 +1,222 @@
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Page
+ * @package     mage
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+/*jshint browser:true jquery:true*/
+(function($) {
+    "use strict";
+    $.widget('mage.rowBuilder', {
+
+        /**
+         * options with default values for setting up the template
+         */
+        options: {
+            //Default template options
+            rowTemplate: '#template-registrant',
+            rowContainer: '#registrant-container',
+            //Row index used by the template rows.
+            rowIndex: 0,
+            //Row count: Should not be set externally
+            rowCount: 0,
+            rowParentElem: '<li></li>',
+            rowContainerClass: 'fields',
+            addRowBtn: '#add-registrant-button',
+            btnRemoveIdPrefix: 'btn-remove',
+            btnRemoveSelector: '.btn-remove',
+            rowIdPrefix: 'row',
+            //This class is added to rows added after the first one. Adds the dotted separator
+            additionalRowClass: 'add-row',
+            /*
+             This is provided during widget instantiation. eg :
+             formDataPost : {"formData":formData,"templateFields":['field1-name','field2-name'] }
+             -"formData" is the multi-dimensional array of form field values : [['a','b'],['c','b']]
+             received from the server and encoded
+             -"templateFields" are the input fields in the template with index suffixed after the field name
+             eg field1-name{index}
+             */
+            formDataPost: null,
+            //Default selectors for add element of a template
+            addEventSelector: 'button',
+            //Default selectors for remove markup elements of a template
+            remEventSelector: 'a',
+            //This option allows adding first row delete option and a row separator
+            hideFirstRowAddSeparator: true,
+            //Max rows - This option should be set when instantiating the widget
+            maxRows: 1000,
+            maxRowsMsg: '#max-registrant-message'
+        },
+
+        /**
+         * Initialize create
+         * @private
+         */
+        _create: function() {
+            this.options.rowCount = this.options.rowIndex = 0;
+            //On document ready related tasks
+            $($.proxy(this.ready, this));
+
+            //Binding template-wide events handlers for adding and removing rows
+            this.element.on('click', this.options.addEventSelector + this.options.addRowBtn, $.proxy(this.handleAdd, this));
+            this.element.on('click', this.options.remEventSelector + this.options.btnRemoveSelector, $.proxy(this.handleRemove, this));
+        },
+
+        /**
+         * Initialize template
+         * @public
+         */
+        ready: function() {
+            if (this.options.formDataPost && this.options.formDataPost.formData && this.options.formDataPost.formData.length) {
+                this.processFormDataArr(this.options.formDataPost);
+            } else if (this.options.rowIndex === 0 && this.options.maxRows !== 0) {
+                //If no form data , then add default row
+                this.addRow(0);
+            }
+        },
+
+        /**
+         * Process and loop through all row data to create preselected values. This is used for any error on submit.
+         * For complex implementations the inheriting widget can override this behavior
+         * @public
+         * @param {Object} formDataArr
+         */
+        processFormDataArr: function(formDataArr) {
+            var formData = formDataArr.formData,
+                templateFields = formDataArr.templateFields;
+            for (var i = this.options.rowIndex = 0; i < formData.length; this.options.rowIndex = i++) {
+                this.addRow(i);
+                var formRow = formData[i];
+                for (var j = 0; j < formRow.length; j++) {
+                    this.setFieldById(templateFields[j] + i, formRow[j]);
+                }
+            }
+
+        },
+
+        /**
+         * Initialize and create markup for template row. Add it to the parent container.
+         * The template processing will substitute row index at all places marked with _index_ in the template
+         * using the template
+         * @public
+         * @param {Number} index - current index/count of the created template. This will be used as the id
+         * @return {*}
+         */
+        addRow: function(index) {
+            var row = $(this.options.rowParentElem);
+            row.addClass(this.options.rowContainerClass).attr('id', this.options.rowIdPrefix + index);
+            $(this.options.rowTemplate).tmpl([
+                {_index_: index}
+            ]).appendTo(row);
+            $(this.options.rowContainer).append(row);
+            row.addClass(this.options.additionalRowClass);
+            //Remove 'delete' link and additionalRowClass for first row
+            if (this.options.rowIndex === 0 && this.options.hideFirstRowAddSeparator) {
+                $('#' + this._esc(this.options.btnRemoveIdPrefix) + '0').remove();
+                $('#' + this._esc(this.options.rowIdPrefix) + '0').removeClass(this.options.additionalRowClass);
+            }
+            this.maxRowCheck(++this.options.rowCount);
+            return row;
+        },
+
+        /**
+         * Remove return item information row
+         * @public
+         * @param {*} rowIndex - return item information row index
+         * @return {boolean}
+         */
+        removeRow: function(rowIndex) {
+            $('#' + this._esc(this.options.rowIdPrefix) + rowIndex).remove();
+            this.maxRowCheck(--this.options.rowCount);
+            return false;
+        },
+
+        /**
+         * Function to check if maximum rows are exceeded and render/hide maxMsg and Add btn
+         * @public
+         * @param rowIndex
+         */
+        maxRowCheck: function(rowIndex) {
+            var addRowBtn = $(this.options.addRowBtn),
+                maxRowMsg = $(this.options.maxRowsMsg);
+            //liIndex starts from 0
+            if (rowIndex >= this.options.maxRows) {
+                addRowBtn.hide();
+                maxRowMsg.show();
+            } else if (addRowBtn.is(":hidden")) {
+                addRowBtn.show();
+                maxRowMsg.hide();
+            }
+        },
+
+        /**
+         * Set the value on given element
+         * @public
+         * @param {string} domId
+         * @param {string} value
+         */
+        setFieldById: function(domId, value) {
+            var x = $('#' + this._esc(domId));
+            if (x.length) {
+                if (x.is(':checkbox')) {
+                    x.attr('checked', true);
+                } else if (x.is('option')) {
+                    x.attr('selected', 'selected');
+                } else {
+                    x.val(value);
+                }
+            }
+        },
+
+        /**
+         * Delegated handler for adding a row
+         * @public
+         * @return {boolean}
+         */
+        handleAdd: function() {
+            this.addRow(++this.options.rowIndex);
+            return false;
+        },
+
+        /**
+         * Delegated handler for removing a selected row
+         * @public
+         * @param {Object} e - Native event object
+         * @return {boolean}
+         */
+        handleRemove: function(e) {
+            this.removeRow($(e.currentTarget).closest("[id^='" + this.options.btnRemoveIdPrefix + "']")
+                .attr('id').replace(this.options.btnRemoveIdPrefix, ''));
+            return false;
+        },
+
+        /*
+         * Utility function to add escape chars for jquery selector strings
+         * @private
+         * @param str - string to be processed
+         * @return {string}
+         */
+        _esc: function(str) {
+            return str ? str.replace(/([ ;&,.+*~\':"!\^$\[\]()=>|\/@])/g, '\\$1') : str;
+        }
+    });
+
+})(jQuery);
\ No newline at end of file
diff --git a/app/code/core/Mage/Page/view/frontend/layout_addons.xml b/app/code/core/Mage/Page/view/frontend/layout_addons.xml
index 302f29b9adb57d8aba6f338b2ed02a111e914ada..cddf29c93f914c319fcf8dcbaba119505efe2b58 100644
--- a/app/code/core/Mage/Page/view/frontend/layout_addons.xml
+++ b/app/code/core/Mage/Page/view/frontend/layout_addons.xml
@@ -45,9 +45,11 @@
             <action method="addJs"><file>mage/decorate.js</file></action>
             <action method="addJs"><file>mage/translate.js</file></action>
             <action method="addJs"><file>mage/cookies.js</file></action>
-            <action method="addJs"><file>jquery/jquery-ui.custom.min.js</file></action>
+            <action method="addJs"><file>jquery/jquery-ui.js</file></action>
             <action method="addJs"><file>jquery/jquery.tmpl.min.js</file></action>
             <action method="addJs"><file>Mage_Page::js/global.js</file></action>
+            <action method="addJs"><file>mage/common.js</file></action>
+            <action method="addJs"><file>mage/toggle.js</file></action>
             <action method="addCss"><file>Mage_Page::css/tabs.css</file><params/></action>
             <action method="addJs"><file>mage/loader.js</file></action>
         </reference>
diff --git a/app/code/core/Mage/PageCache/Helper/Data.php b/app/code/core/Mage/PageCache/Helper/Data.php
index a0c5ba9dc4093804f9c134fe48583e342a73b0e6..c9884a707a82c79a1f80cfc089113843c5e63500 100644
--- a/app/code/core/Mage/PageCache/Helper/Data.php
+++ b/app/code/core/Mage/PageCache/Helper/Data.php
@@ -62,9 +62,12 @@ class Mage_PageCache_Helper_Data extends Mage_Core_Helper_Abstract
 
     /**
      * Initialize 'no cache' cookie locking
+     *
+     * @param Mage_Core_Model_Translate $translator
      */
-    function __construct()
+    function __construct(Mage_Core_Model_Translate $translator)
     {
+        parent::__construct($translator);
         $this->_isNoCacheCookieLocked = (bool)$this->_getCookie()->get(self::NO_CACHE_LOCK_COOKIE);
     }
 
diff --git a/app/code/core/Mage/Payment/Helper/Data.php b/app/code/core/Mage/Payment/Helper/Data.php
index 5076d4bad603dc25eb08de868c54513a4b933a6d..0175d599dd3e660d6a267c9fceef2747865c8bfd 100644
--- a/app/code/core/Mage/Payment/Helper/Data.php
+++ b/app/code/core/Mage/Payment/Helper/Data.php
@@ -284,7 +284,7 @@ class Mage_Payment_Helper_Data extends Mage_Core_Helper_Abstract
             if (!isset($data['model'])) {
                 continue;
             }
-            $method = Mage::app()->getConfig()->getModelClassName($data['model']);
+            $method = $data['model'];
             if (in_array($interface, class_implements($method))) {
                 $result[$code] = $data['title'];
             }
diff --git a/app/code/core/Mage/Payment/Model/Config.php b/app/code/core/Mage/Payment/Model/Config.php
index c461584a814e13f318c3a7fdaa0b394ec18abf0a..c1840133d97acf4975c50a37de4a14aa307dd43e 100644
--- a/app/code/core/Mage/Payment/Model/Config.php
+++ b/app/code/core/Mage/Payment/Model/Config.php
@@ -89,8 +89,7 @@ class Mage_Payment_Model_Config
         }
         $modelName = $config['model'];
 
-        $className = Mage::getConfig()->getModelClassName($modelName);
-        if (!class_exists($className)) {
+        if (!class_exists($modelName)) {
             return false;
         }
 
diff --git a/app/code/core/Mage/Paypal/Block/Standard/Form.php b/app/code/core/Mage/Paypal/Block/Standard/Form.php
index 42be2a5f278cccf7d0db085bac60cdaf40eadcc6..1bc9a80db6c3dbd4372da8c372d1791c62655233 100644
--- a/app/code/core/Mage/Paypal/Block/Standard/Form.php
+++ b/app/code/core/Mage/Paypal/Block/Standard/Form.php
@@ -49,8 +49,8 @@ class Mage_Paypal_Block_Standard_Form extends Mage_Payment_Block_Form
     {
         $this->_config = Mage::getModel('Mage_Paypal_Model_Config')->setMethod($this->getMethodCode());
         $locale = Mage::app()->getLocale();
-        $mark = Mage::getConfig()->getBlockClassName('Mage_Core_Block_Template');
-        $mark = Mage::app()->getLayout()->createBlock($mark);
+        /** @var $mark Mage_Core_Block_Template */
+        $mark = Mage::app()->getLayout()->createBlock('Mage_Core_Block_Template');
         $mark->setTemplate('Mage_Paypal::payment/mark.phtml')
             ->setPaymentAcceptanceMarkHref($this->_config->getPaymentMarkWhatIsPaypalUrl($locale))
             ->setPaymentAcceptanceMarkSrc($this->_config->getPaymentMarkImageUrl($locale->getLocaleCode()))
diff --git a/app/code/core/Mage/Paypal/view/frontend/express/review/address.phtml b/app/code/core/Mage/Paypal/view/frontend/express/review/address.phtml
index 90f722d013888f9954ea56fdb5e889ae42daa759..0c99a344b8b267fe63601de41c9440615aa74ff1 100644
--- a/app/code/core/Mage/Paypal/view/frontend/express/review/address.phtml
+++ b/app/code/core/Mage/Paypal/view/frontend/express/review/address.phtml
@@ -84,11 +84,6 @@
                             <select id="<?php echo $prefix ?>:region_id" name="<?php echo $prefix ?>[region_id]" title="<?php echo $this->__('State/Province') ?>" class="validate-select" style="display:none;">
                                 <option value=""><?php echo $this->__('Please select region, state or province') ?></option>
                             </select>
-                            <script type="text/javascript">
-                            //<![CDATA[
-                                $('<?php echo $prefix ?>:region_id').setAttribute('defaultValue',  "<?php echo $this->getAddress()->getRegionId() ?>");
-                            //]]>
-                            </script>
                             <input type="text" id="<?php echo $prefix ?>:region" name="<?php echo $prefix ?>[region]" value="<?php echo $this->escapeHtml($this->getAddress()->getRegion()) ?>"  title="<?php echo $this->__('State/Province') ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('region') ?>" style="display:none;" />
                         </div>
                     </div>
@@ -138,8 +133,22 @@
     </ul>
 </fieldset>
 <script type="text/javascript">
-//<![CDATA[
-    var <?php echo $prefix ?>RegionUpdater = new RegionUpdater('<?php echo $prefix ?>:country_id', '<?php echo $prefix ?>:region', '<?php echo $prefix ?>:region_id', <?php echo $this->helper('Mage_Directory_Helper_Data')->getRegionJson() ?>, undefined, '<?php echo $prefix ?>:postcode');
-    <?php echo $prefix ?>RegionUpdater.update();
-//]]>
+    (function($) {
+        head.js(
+            "<?php echo $this->getViewFileUrl('jquery/jquery.validate.js') ?>",
+            "<?php echo $this->getViewFileUrl('jquery/jquery.metadata.js') ?>",
+            "<?php echo $this->getViewFileUrl('mage/validation.js')?>",
+            "<?php echo $this->getViewFileUrl('mage/validation/validation.js') ?>",
+            "<?php echo $this->getViewFileUrl('Mage_Checkout::js/region-updater.js') ?>",
+            function() {
+                $('#<?php echo $prefix ?>\\:country_id').regionUpdater({
+                    regionListId: '<?php echo $prefix ?>\\:region_id',
+                    regionInputId: '#<?php echo $prefix ?>\\:region',
+                    postcodeId: '#<?php echo $prefix ?>\\:postcode',
+                    regionJson: <?php echo $this->helper('Mage_Directory_Helper_Data')->getRegionJson() ?>,
+                    defaultRegion: "<?php echo $this->getAddress()->getRegionId() ?>",
+                    countriesWithOptionalZip: <?php echo $this->helper('Mage_Directory_Helper_Data')->getCountriesWithOptionalZip(true) ?>
+                });
+            });
+    })(jQuery);
 </script>
diff --git a/app/code/core/Mage/Persistent/view/frontend/checkout/onepage/billing.phtml b/app/code/core/Mage/Persistent/view/frontend/checkout/onepage/billing.phtml
index dd90f7aef6f46289ac6d489be950b2572d16db47..2f777b7c96880df15cc78e67f4b0c8e287f1cc9d 100644
--- a/app/code/core/Mage/Persistent/view/frontend/checkout/onepage/billing.phtml
+++ b/app/code/core/Mage/Persistent/view/frontend/checkout/onepage/billing.phtml
@@ -93,11 +93,6 @@
                             <select id="billing:region_id" name="billing[region_id]" title="<?php echo $this->__('State/Province') ?>" class="validate-select" style="display:none;">
                                 <option value=""><?php echo $this->__('Please select region, state or province') ?></option>
                             </select>
-                            <script type="text/javascript">
-                            //<![CDATA[
-                                $('billing:region_id').setAttribute('defaultValue',  "<?php echo $this->getAddress()->getRegionId() ?>");
-                            //]]>
-                            </script>
                             <input type="text" id="billing:region" name="billing[region]" value="<?php echo $this->escapeHtml($this->getAddress()->getRegion()) ?>"  title="<?php echo $this->__('State/Province') ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('region') ?>" style="display:none;" />
                         </div>
                     </div>
@@ -206,10 +201,8 @@
     var billing = new Billing('co-billing-form', '<?php echo $this->getUrl('checkout/onepage/getAddress') ?>address/', '<?php echo $this->getUrl('checkout/onepage/saveBilling') ?>');
     var billingForm = new VarienForm('co-billing-form');
 
-    //billingForm.setElementsRelation('billing:country_id', 'billing:region', '<?php echo $this->getUrl('directory/json/childRegion') ?>', '<?php echo $this->__('Select State/Province...') ?>');
     $('billing-address-select') && billing.newAddress(!$('billing-address-select').value);
 
-    var billingRegionUpdater = new RegionUpdater('billing:country_id', 'billing:region', 'billing:region_id', <?php echo $this->helper('Mage_Directory_Helper_Data')->getRegionJson() ?>, undefined, 'billing:postcode');
     if ($('onepage-guest-register-button')) {
         Event.observe($('onepage-guest-register-button'), 'click', function(event) {
             var billingRememberMe = $('co-billing-form').select('#remember-me-box');
@@ -224,3 +217,25 @@
     }
 //]]>
 </script>
+<script type="text/javascript">
+    (function($) {
+        head.js(
+            "<?php echo $this->getViewFileUrl('Mage_Checkout::js/region-updater.js') ?>",
+            function() {
+                $('#billing\\:country_id').regionUpdater({
+                    regionListId: '#billing\\:region_id',
+                    regionInputId: '#billing\\:region',
+                    postcodeId: '#billing\\:postcode',
+                    regionJson: <?php echo $this->helper('Mage_Directory_Helper_Data')->getRegionJson() ?>,
+                    defaultRegion: "<?php echo $this->getAddress()->getRegionId() ?>",
+                    countriesWithOptionalZip: <?php echo $this->helper('Mage_Directory_Helper_Data')->getCountriesWithOptionalZip(true) ?>,
+                    clearError: function() {
+                        var selectorArr = ['#billing\\:region_id', '#billing\\:region', '#billing\\:postcode'];
+                        for (var i = 0; i < selectorArr.length; i++) {
+                            $(selectorArr[i]).removeClass('validation-failed').next("div.validation-advice").remove();
+                        }
+                    }
+                });
+            });
+    })(jQuery);
+</script>
\ No newline at end of file
diff --git a/app/code/core/Mage/Persistent/view/frontend/splitbutton.js b/app/code/core/Mage/Persistent/view/frontend/splitbutton.js
new file mode 100644
index 0000000000000000000000000000000000000000..5b0e7f84cb810c7d254ae11515cd96d8ac6cda65
--- /dev/null
+++ b/app/code/core/Mage/Persistent/view/frontend/splitbutton.js
@@ -0,0 +1,74 @@
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_Persistent
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+
+/*jshint browser:true jquery:true*/
+(function($, undefined) {
+    "use strict";
+    $.widget('mage.splitButton', {
+        /**
+         * options with default values
+         */
+        options: {
+            splitButton: '.split-button',
+            arrowButton: '.change',
+            activeClass: 'active'
+        },
+
+        /**
+         * Initialize split button events
+         * @private
+         */
+        _create: function() {
+            $(document).on('click', this.options.splitButton + ' > ' + this.options.arrowButton, $.proxy(this._toggleDropDown, this));
+            $(document).on('click', $.proxy(this._hideDropDown, this));
+        },
+
+        /**
+         * Toggle css class for the split button to hide or show drop down menu
+         * Saves current state of the target. Closes all open drop downs and then
+         * depending on the stored state the target drop down is toggled.
+         * @private
+         * @param {Object} e
+         */
+        _toggleDropDown: function(e) {
+            var state = $(e.target).closest(this.options.splitButton).hasClass(this.options.activeClass);
+            this._hideDropDown();
+            if (state) {
+                this._hideDropDown();
+            } else {
+                $(e.target).closest(this.options.splitButton).addClass(this.options.activeClass);
+            }
+            return false;
+        },
+
+        /**
+         * Hide all the drop down menus when clicked any where on the page
+         * @private
+         */
+        _hideDropDown: function() {
+            $(document).find(this.options.splitButton).removeClass(this.options.activeClass);
+        }
+    });
+})(jQuery);
diff --git a/app/code/core/Mage/ProductAlert/Helper/Data.php b/app/code/core/Mage/ProductAlert/Helper/Data.php
index ea8d13965199137be6e7bfa8a8f1bceccea66d07..2d85838a1cd72aa2b9197fbc1493f7d0c53b35dc 100644
--- a/app/code/core/Mage/ProductAlert/Helper/Data.php
+++ b/app/code/core/Mage/ProductAlert/Helper/Data.php
@@ -84,12 +84,17 @@ class Mage_ProductAlert_Helper_Data extends Mage_Core_Helper_Url
         ));
     }
 
+    /**
+     * Create block instance
+     *
+     * @param string|Mage_Core_Block_Abstract $block
+     * @return Mage_Core_Block_Abstract
+     */
     public function createBlock($block)
     {
         if (is_string($block)) {
-            $block = Mage::getConfig()->getBlockClassName($block);
             if (class_exists($block)) {
-                $block = new $block(array());
+                $block = Mage::getObjectManager()->create($block);
             }
         }
         if (!$block instanceof Mage_Core_Block_Abstract) {
diff --git a/app/code/core/Mage/Reports/Model/Resource/Product/Index/Abstract.php b/app/code/core/Mage/Reports/Model/Resource/Product/Index/Abstract.php
index 16b50a8eea16aa701dfdd2a2ce9e14d103a2c4ef..a06e33d3231a14a632e68003a5925dcfe1ad6b32 100755
--- a/app/code/core/Mage/Reports/Model/Resource/Product/Index/Abstract.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Product/Index/Abstract.php
@@ -67,17 +67,17 @@ abstract class Mage_Reports_Model_Resource_Product_Index_Abstract extends Mage_C
             $idx = $adapter->fetchRow($select);
 
             if ($idx) {
-            /* If we are here it means that we have two rows: one with known customer, but second just visitor is set
+            /**
+             * If we are here it means that we have two rows: one with known customer, but second just visitor is set
              * One row should be updated with customer_id, second should be deleted
-             *
              */
-                $adapter->delete($this->getMainTable(), array('index_id = ?' => $row['index_id']));
-                $where = array('index_id = ?' => $idx['index_id']);
-                $data  = array(
-                    'visitor_id'    => $object->getVisitorId(),
-                    'store_id'      => $object->getStoreId(),
-                    'added_at'      => Varien_Date::now(),
-                );
+                 $adapter->delete($this->getMainTable(), array('index_id = ?' => $row['index_id']));
+                 $where = array('index_id = ?' => $idx['index_id']);
+                 $data  = array(
+                     'visitor_id'    => $object->getVisitorId(),
+                     'store_id'      => $object->getStoreId(),
+                     'added_at'      => Varien_Date::now(),
+                 );
             } else {
                 $where = array('index_id = ?' => $row['index_id']);
                 $data  = array(
@@ -149,7 +149,6 @@ abstract class Mage_Reports_Model_Resource_Product_Index_Abstract extends Mage_C
         return $this;
     }
 
-
     /**
      * Clean index (visitor)
      *
diff --git a/app/code/core/Mage/Reports/Model/Resource/Report/Product/Viewed/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Report/Product/Viewed/Collection.php
index 7241b8b29145b2d1bb96465689e37a7fa2bc9f16..e20b51e24b2d1f98d1c4a4b6da2ec761889905c1 100644
--- a/app/code/core/Mage/Reports/Model/Resource/Report/Product/Viewed/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Report/Product/Viewed/Collection.php
@@ -191,8 +191,8 @@ class Mage_Reports_Model_Resource_Report_Product_Viewed_Collection
             $storeIds = array($storeIds);
         }
         $currentStoreIds = $this->_storesIds;
-        if (isset($currentStoreIds) && $currentStoreIds != Mage_Core_Model_App::ADMIN_STORE_ID
-            && $currentStoreIds != array(Mage_Core_Model_App::ADMIN_STORE_ID)) {
+        if (isset($currentStoreIds) && $currentStoreIds != Mage_Core_Model_AppInterface::ADMIN_STORE_ID
+            && $currentStoreIds != array(Mage_Core_Model_AppInterface::ADMIN_STORE_ID)) {
             if (!is_array($currentStoreIds)) {
                 $currentStoreIds = array($currentStoreIds);
             }
diff --git a/app/code/core/Mage/Reports/view/adminhtml/grid.phtml b/app/code/core/Mage/Reports/view/adminhtml/grid.phtml
index 44ae66b9aee4adbc35087eba8ba4589fcb5fbd5f..aeca15f579185006fccd8fb4b1291e3ea7e68f63 100644
--- a/app/code/core/Mage/Reports/view/adminhtml/grid.phtml
+++ b/app/code/core/Mage/Reports/view/adminhtml/grid.phtml
@@ -30,75 +30,63 @@ $numColumns = sizeof($this->getColumns());
 ?>
 <?php if ($this->getCollection()): ?>
 <?php if ($this->canDisplayContainer()): ?>
-        <div id="<?php echo $this->getId() ?>">
-    <?php else: ?>
-        <?php echo $this->getMessagesBlock()->getGroupedHtml() ?>
+    <div id="<?php echo $this->getId() ?>">
+<?php else: ?>
+    <?php echo $this->getMessagesBlock()->getGroupedHtml() ?>
+<?php endif; ?>
+<?php if ($this->getStoreSwitcherVisibility() || $this->getDateFilterVisibility()): ?>
+    <?php if ($this->getStoreSwitcherVisibility()): ?>
+        <?php echo $this->getStoreSwitcherHtml() ?>
+    <?php endif ?>
+    <div class="grid-actions">
+        <?php if ($this->getChildBlock('grid.export')): ?>
+        <div class="export">
+            <?php echo $this->getChildHtml('grid.export');?>
+        </div>
         <?php endif; ?>
-    <?php if ($this->getStoreSwitcherVisibility() || $this->getDateFilterVisibility()): ?>
-        <?php if ($this->getStoreSwitcherVisibility()): ?>
-            <?php echo $this->getStoreSwitcherHtml() ?>
-            <?php endif ?>
-        <table cellspacing="0" class="actions">
-            <tr>
-                <?php if ($this->getDateFilterVisibility()): ?>
-                <td class="a-left filter" id="<?php echo $this->getSuffixId('period_date_range')?>">
-                    <div class="f-left">
-                        <div><?php echo $this->__('From') ?>:&nbsp;<input class="input-text no-changes required-entry"
-                                                                          type="text"
-                                                                          id="<?php echo $this->getSuffixId('period_date_from')?>"
-                                                                          name="report_from"
-                                                                          value="<?php echo $this->getFilter('report_from') ?>"
-                                                                          style="width:5em"/>&nbsp;&nbsp;</div>
-                        <div id="<?php echo $this->getSuffixId('period_date_from_advice')?>"></div>
-                    </div>
 
-                    <div class="f-left">
-                        <div><?php echo $this->__('To') ?>:&nbsp;<input class="input-text no-changes required-entry"
-                                                                        type="text"
-                                                                        id="<?php echo $this->getSuffixId('period_date_to')?>"
-                                                                        name="report_to"
-                                                                        value="<?php echo $this->getFilter('report_to') ?>"
-                                                                        style="width:5em"/>&nbsp;&nbsp;</div>
-                        <div id="<?php echo $this->getSuffixId('period_date_to_advice')?>"></div>
-                    </div>
+        <?php if ($this->getDateFilterVisibility()): ?>
+        <div class="filter" id="<?php echo $this->getSuffixId('period_date_range')?>">
+            <div class="date">
+                <label class="required"><?php echo $this->__('From') ?>:</label>
+                <input class="input-text no-changes required-entry" type="text" id="<?php echo $this->getSuffixId('period_date_from')?>" name="report_from" value="<?php echo $this->getFilter('report_from') ?>">
+                <div id="<?php echo $this->getSuffixId('period_date_from_advice')?>"></div>
+            </div>
 
-                    <div class="f-left">
-                        <?php echo $this->__('Show By') ?>:
-                        <select name="report_period" id="<?php echo $this->getSuffixId('report_period')?>"
-                                style="width:6em;">
-                            <?php foreach ($this->getPeriods() as $_value => $_label): ?>
-                            <option value="<?php echo $_value ?>" <?php if ($this->getFilter('report_period') == $_value): ?>
-                                    selected<?php endif; ?>><?php echo $_label ?></option>
-                            <?php endforeach; ?>
-                        </select>
-                        <?php echo $this->getRefreshButtonHtml() ?>
-                    </div>
-                    <script type="text/javascript">
-                        (function ($) {
-                            $("#<?php echo $this->getSuffixId('period_date_range') ?>").dateRange({
-                                dateFormat:"<?php echo $this->getDateFormat() ?>",
-                                buttonImage:"<?php echo $this->getViewFileUrl('images/grid-cal.gif') ?>",
-                                buttonText:"<?php echo $this->__('Select Date') ?>",
-                                from:{
-                                    id:"<?php echo $this->getSuffixId('period_date_from')?>"
-                                },
-                                to:{
-                                    id:"<?php echo $this->getSuffixId('period_date_to')?>"
-                                }
-                            })
-                        })(jQuery)
-                    </script>
-                </td>
-                <?php endif; ?>
-                <?php if ($this->getChildBlock('grid.export')): ?>
-                <td class="export a-right">
-                    <?php echo $this->getChildHtml('grid.export');?>
-                </td>
-                <?php endif; ?>
-            </tr>
-        </table>
-        <?php endif; ?>
+            <div class="date">
+                <label class="required"><?php echo $this->__('To') ?>:</label>
+                <input class="input-text no-changes required-entry" type="text" id="<?php echo $this->getSuffixId('period_date_to')?>" name="report_to" value="<?php echo $this->getFilter('report_to') ?>" />
+                <div id="<?php echo $this->getSuffixId('period_date_to_advice')?>"></div>
+            </div>
 
+            <div class="show-by">
+                <?php echo $this->__('Show By') ?>:
+                <select name="report_period" id="<?php echo $this->getSuffixId('report_period')?>">
+                    <?php foreach ($this->getPeriods() as $_value => $_label): ?>
+                    <option value="<?php echo $_value ?>" <?php if ($this->getFilter('report_period') == $_value): ?> selected<?php endif; ?>><?php echo $_label ?></option>
+                    <?php endforeach; ?>
+                </select>
+                <?php echo $this->getRefreshButtonHtml() ?>
+            </div>
+            <script type="text/javascript">
+                (function ($) {
+                    $("#<?php echo $this->getSuffixId('period_date_range') ?>").dateRange({
+                        dateFormat:"<?php echo $this->getDateFormat() ?>",
+                        buttonImage:"<?php echo $this->getViewFileUrl('images/grid-cal.gif') ?>",
+                        buttonText:"<?php echo $this->__('Select Date') ?>",
+                        from:{
+                            id:"<?php echo $this->getSuffixId('period_date_from')?>"
+                        },
+                        to:{
+                            id:"<?php echo $this->getSuffixId('period_date_to')?>"
+                        }
+                    })
+                })(jQuery)
+            </script>
+        </div>
+        <?php endif; ?>
+    </div>
+<?php endif; ?>
     <div class="grid">
         <div class="hor-scroll">
             <table cellspacing="0" class="data" id="<?php echo $this->getId() ?>_table">
diff --git a/app/code/core/Mage/Reports/view/adminhtml/store/switcher.phtml b/app/code/core/Mage/Reports/view/adminhtml/store/switcher.phtml
index 34123f223c7b2545da27ed13f6d78a219268b697..f1d65db5a78125a5da17d8a3fce1ff3bfdb9334e 100644
--- a/app/code/core/Mage/Reports/view/adminhtml/store/switcher.phtml
+++ b/app/code/core/Mage/Reports/view/adminhtml/store/switcher.phtml
@@ -30,33 +30,34 @@
  */
 ?>
 <?php if ($this->isShow()): ?>
-<p class="switcher"><label for="store_switcher"><?php echo $this->__('Show Report For:') ?></label>
-<select name="store_switcher" id="store_switcher" onchange="return switchStore(this);">
-    <option value=""><?php echo $this->__('All Websites') ?></option>
-    <?php foreach ($this->getWebsiteCollection() as $_website): ?>
-        <?php $showWebsite=false; ?>
-        <?php foreach ($this->getGroupCollection($_website) as $_group): ?>
-            <?php $showGroup=false; ?>
-            <?php foreach ($this->getStoreCollection($_group) as $_store): ?>
-                <?php if ($showWebsite == false): ?>
-                    <?php $showWebsite = true; ?>
-                    <option website="true" value="<?php echo $_website->getId() ?>"<?php if($this->getRequest()->getParam('website') == $_website->getId()): ?> selected<?php endif; ?>><?php echo $_website->getName() ?></option>
-                <?php endif; ?>
-                <?php if ($showGroup == false): ?>
-                    <?php $showGroup = true; ?>
-                    <!--optgroup label="&nbsp;&nbsp;&nbsp;<?php echo $_group->getName() ?>"-->
-                    <option group="true" value="<?php echo $_group->getId() ?>"<?php if($this->getRequest()->getParam('group') == $_group->getId()): ?> selected<?php endif; ?>>&nbsp;&nbsp;&nbsp;<?php echo $_group->getName() ?></option>
-                <?php endif; ?>
-                <option value="<?php echo $_store->getId() ?>"<?php if($this->getStoreId() == $_store->getId()): ?> selected<?php endif; ?>>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<?php echo $_store->getName() ?></option>
+<div class="store-switcher">
+    <label for="store_switcher"><?php echo $this->__('Show Report For:') ?></label>
+    <select name="store_switcher" id="store_switcher" onchange="return switchStore(this);">
+        <option value=""><?php echo $this->__('All Websites') ?></option>
+        <?php foreach ($this->getWebsiteCollection() as $_website): ?>
+            <?php $showWebsite=false; ?>
+            <?php foreach ($this->getGroupCollection($_website) as $_group): ?>
+                <?php $showGroup=false; ?>
+                <?php foreach ($this->getStoreCollection($_group) as $_store): ?>
+                    <?php if ($showWebsite == false): ?>
+                        <?php $showWebsite = true; ?>
+                            <option website="true" value="<?php echo $_website->getId() ?>"<?php if($this->getRequest()->getParam('website') == $_website->getId()): ?> selected<?php endif; ?>>
+                                <?php echo $_website->getName() ?>
+                            </option>
+                    <?php endif; ?>
+                    <?php if ($showGroup == false): ?>
+                        <?php $showGroup = true; ?>
+                        <option group="true" value="<?php echo $_group->getId() ?>"<?php if($this->getRequest()->getParam('group') == $_group->getId()): ?> selected<?php endif; ?>>&nbsp;&nbsp;&nbsp;<?php echo $_group->getName() ?></option>
+                    <?php endif; ?>
+                    <option value="<?php echo $_store->getId() ?>"<?php if($this->getStoreId() == $_store->getId()): ?> selected<?php endif; ?>>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<?php echo $_store->getName() ?></option>
+                <?php endforeach; ?>
             <?php endforeach; ?>
-            <?php if ($showGroup): ?>
-                </optgroup>
-            <?php endif; ?>
         <?php endforeach; ?>
-    <?php endforeach; ?>
-</select>
-<?php echo $this->getHintHtml() ?>
-</p>
+    </select>
+    <div class="tooltip">
+        <span class="help"><?php echo $this->getHintHtml() ?></span>
+    </div>
+</div>
 <script type="text/javascript">
     function switchStore(obj){
         if (obj.options[obj.selectedIndex].getAttribute('website') == 'true') {
diff --git a/app/code/core/Mage/Reports/view/adminhtml/store/switcher/enhanced.phtml b/app/code/core/Mage/Reports/view/adminhtml/store/switcher/enhanced.phtml
index b18169cb4efa01c90896a071a0ee02796537198e..311ac05a0299622e84fce3e94997b6f5e01fb9f0 100644
--- a/app/code/core/Mage/Reports/view/adminhtml/store/switcher/enhanced.phtml
+++ b/app/code/core/Mage/Reports/view/adminhtml/store/switcher/enhanced.phtml
@@ -31,32 +31,35 @@
 ?>
 
 <?php if ($this->isShow()): ?>
-<p class="switcher"><label for="store_switcher"><?php echo $this->__('Show Report For:') ?></label>
-<select name="store_switcher" id="store_switcher" onchange="return switchStore(this);">
-    <option value=""><?php echo $this->__('All Websites') ?></option>
-    <?php foreach ($this->getWebsiteCollection() as $_website): ?>
-        <?php $showWebsite=false; ?>
-        <?php foreach ($this->getGroupCollection($_website) as $_group): ?>
-            <?php $showGroup=false; ?>
-            <?php foreach ($this->getStoreCollection($_group) as $_store): ?>
-                <?php if ($showWebsite == false): ?>
-                    <?php $showWebsite = true; ?>
-                    <option website="true" value="<?php echo implode(',', $_website->getStoreIds()) ?>"<?php if($this->getRequest()->getParam('store_ids') == implode(',', $_website->getStoreIds())): ?> selected<?php endif; ?>><?php echo $this->escapeHtml($_website->getName()) ?></option>
+<div class="store-switcher">
+    <label for="store_switcher"><?php echo $this->__('Show Report For:') ?></label>
+    <select name="store_switcher" id="store_switcher" onchange="return switchStore(this);">
+        <option value=""><?php echo $this->__('All Websites') ?></option>
+        <?php foreach ($this->getWebsiteCollection() as $_website): ?>
+            <?php $showWebsite=false; ?>
+            <?php foreach ($this->getGroupCollection($_website) as $_group): ?>
+                <?php $showGroup=false; ?>
+                <?php foreach ($this->getStoreCollection($_group) as $_store): ?>
+                    <?php if ($showWebsite == false): ?>
+                        <?php $showWebsite = true; ?>
+                        <option website="true" value="<?php echo implode(',', $_website->getStoreIds()) ?>"<?php if($this->getRequest()->getParam('store_ids') == implode(',', $_website->getStoreIds())): ?> selected<?php endif; ?>><?php echo $this->escapeHtml($_website->getName()) ?></option>
+                    <?php endif; ?>
+                    <?php if ($showGroup == false): ?>
+                        <?php $showGroup = true; ?>
+                        <option group="true" value="<?php echo implode(',', $_group->getStoreIds()) ?>"<?php if($this->getRequest()->getParam('store_ids') == implode(',', $_group->getStoreIds())): ?> selected<?php endif; ?>>&nbsp;&nbsp;&nbsp;<?php echo $this->escapeHtml($_group->getName()) ?></option>
+                    <?php endif; ?>
+                    <option value="<?php echo $_store->getId() ?>"<?php if($this->getStoreId() == $_store->getId()): ?> selected<?php endif; ?>>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<?php echo $this->escapeHtml($_store->getName()) ?></option>
+                <?php endforeach; ?>
+                <?php if ($showGroup): ?>
+                    </optgroup>
                 <?php endif; ?>
-                <?php if ($showGroup == false): ?>
-                    <?php $showGroup = true; ?>
-                    <option group="true" value="<?php echo implode(',', $_group->getStoreIds()) ?>"<?php if($this->getRequest()->getParam('store_ids') == implode(',', $_group->getStoreIds())): ?> selected<?php endif; ?>>&nbsp;&nbsp;&nbsp;<?php echo $this->escapeHtml($_group->getName()) ?></option>
-                <?php endif; ?>
-                <option value="<?php echo $_store->getId() ?>"<?php if($this->getStoreId() == $_store->getId()): ?> selected<?php endif; ?>>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<?php echo $this->escapeHtml($_store->getName()) ?></option>
             <?php endforeach; ?>
-            <?php if ($showGroup): ?>
-                </optgroup>
-            <?php endif; ?>
         <?php endforeach; ?>
-    <?php endforeach; ?>
-</select>
-<?php echo $this->getHintHtml() ?>
-</p>
+    </select>
+    <div class="tooltip">
+        <span class="help"><?php echo $this->getHintHtml() ?></span>
+    </div>
+</div>
 <script type="text/javascript">
     function switchStore(obj){
         var storeParam = obj.value ? 'store_ids/' + obj.value + '/' : '';
diff --git a/app/code/core/Mage/Review/Model/Resource/Review/Product/Collection.php b/app/code/core/Mage/Review/Model/Resource/Review/Product/Collection.php
index f70c58ffc5c655937856749b2dd05ce5d218762e..94de877e5a0e9f48f5b16ef43045c4c129aeceb0 100755
--- a/app/code/core/Mage/Review/Model/Resource/Review/Product/Collection.php
+++ b/app/code/core/Mage/Review/Model/Resource/Review/Product/Collection.php
@@ -398,7 +398,7 @@ class Mage_Review_Model_Resource_Review_Product_Collection extends Mage_Catalog_
                 if ($condition == 1) {
                     $conditionParts = array(
                         $this->_getConditionSql('rdt.customer_id', array('is' => new Zend_Db_Expr('NULL'))),
-                        $this->_getConditionSql('rdt.store_id', array('eq' => Mage_Core_Model_App::ADMIN_STORE_ID))
+                        $this->_getConditionSql('rdt.store_id', array('eq' => Mage_Core_Model_AppInterface::ADMIN_STORE_ID))
                     );
                     $conditionSql = implode(' AND ', $conditionParts);
                 } elseif ($condition == 2) {
@@ -406,7 +406,7 @@ class Mage_Review_Model_Resource_Review_Product_Collection extends Mage_Catalog_
                 } else {
                     $conditionParts = array(
                         $this->_getConditionSql('rdt.customer_id', array('is' => new Zend_Db_Expr('NULL'))),
-                        $this->_getConditionSql('rdt.store_id', array('neq' => Mage_Core_Model_App::ADMIN_STORE_ID))
+                        $this->_getConditionSql('rdt.store_id', array('neq' => Mage_Core_Model_AppInterface::ADMIN_STORE_ID))
                     );
                     $conditionSql = implode(' AND ', $conditionParts);
                 }
diff --git a/app/code/core/Mage/Review/Model/Resource/Review/Summary/Collection.php b/app/code/core/Mage/Review/Model/Resource/Review/Summary/Collection.php
index 57d973800277581323abf5e80cf5181d302ff848..03081e0d219545220725c63430b721539cc56ed3 100755
--- a/app/code/core/Mage/Review/Model/Resource/Review/Summary/Collection.php
+++ b/app/code/core/Mage/Review/Model/Resource/Review/Summary/Collection.php
@@ -55,7 +55,7 @@ class Mage_Review_Model_Resource_Review_Summary_Collection extends Varien_Data_C
 
         $this->_select->from($this->_summaryTable);
 
-        $this->setItemObjectClass(Mage::getConfig()->getModelClassName('Mage_Review_Model_Review_Summary'));
+        $this->setItemObjectClass('Mage_Review_Model_Review_Summary');
     }
 
     /**
diff --git a/app/code/core/Mage/Review/view/frontend/form.phtml b/app/code/core/Mage/Review/view/frontend/form.phtml
index f3f1d14c77afb150bc00df08f9235f0922655968..70d097c349b735c8c8e34c218a68531111fc53f1 100644
--- a/app/code/core/Mage/Review/view/frontend/form.phtml
+++ b/app/code/core/Mage/Review/view/frontend/form.phtml
@@ -56,7 +56,7 @@
                         <tr>
                             <th><?php echo $this->escapeHtml($_rating->getRatingCode()) ?></th>
                         <?php foreach ($_rating->getOptions() as $_option): ?>
-                            <td class="value"><input type="radio" name="ratings[<?php echo $_rating->getId() ?>]" id="<?php echo $this->escapeHtml($_rating->getRatingCode()) ?>_<?php echo $_option->getValue() ?>" value="<?php echo $_option->getId() ?>" class="radio" /></td>
+                            <td class="value"><input type="radio" name="ratings[<?php echo $_rating->getId() ?>]" id="<?php echo $this->escapeHtml($_rating->getRatingCode()) ?>_<?php echo $_option->getValue() ?>" value="<?php echo $_option->getId() ?>" class="radio" data-validate="{required:true, messages:{required:'Please select one of each of the ratings above.'}}" /></td>
                         <?php endforeach; ?>
                         </tr>
                     <?php endforeach; ?>
@@ -69,19 +69,19 @@
                     <li>
                         <label for="nickname_field" class="required"><em>*</em><?php echo $this->__('Nickname') ?></label>
                         <div class="input-box">
-                            <input type="text" name="nickname" id="nickname_field" class="input-text required-entry" value="<?php echo $this->escapeHtml($data->getNickname()) ?>" />
+                            <input type="text" name="nickname" id="nickname_field" class="input-text" data-validate="{required:true}" value="<?php echo $this->escapeHtml($data->getNickname()) ?>" />
                         </div>
                     </li>
                     <li>
                         <label for="summary_field" class="required"><em>*</em><?php echo $this->__('Summary of Your Review') ?></label>
                         <div class="input-box">
-                            <input type="text" name="title" id="summary_field" class="input-text required-entry" value="<?php echo $this->escapeHtml($data->getTitle()) ?>" />
+                            <input type="text" name="title" id="summary_field" class="input-text" data-validate="{required:true}" value="<?php echo $this->escapeHtml($data->getTitle()) ?>" />
                         </div>
                     </li>
                     <li>
                         <label for="review_field" class="required"><em>*</em><?php echo $this->__('Review') ?></label>
                         <div class="input-box">
-                            <textarea name="detail" id="review_field" cols="5" rows="3" class="required-entry"><?php echo $this->escapeHtml($data->getDetail()) ?></textarea>
+                            <textarea name="detail" id="review_field" cols="5" rows="3"  data-validate="{required:true}"><?php echo $this->escapeHtml($data->getDetail()) ?></textarea>
                         </div>
                     </li>
                 </ul>
@@ -90,39 +90,25 @@
                 <button type="submit" title="<?php echo $this->__('Submit Review') ?>" class="button"><span><span><?php echo $this->__('Submit Review') ?></span></span></button>
             </div>
     </form>
-    <script type="text/javascript">
-    //<![CDATA[
-        var dataForm = new VarienForm('review-form');
-        Validation.addAllThese(
-        [
-               ['validate-rating', '<?php echo $this->__('Please select one of each of the ratings above') ?>', function(v) {
-                    var trs = $('product-review-table').select('tr');
-                    var inputs;
-                    var error = 1;
-
-                    for( var j=0; j < trs.length; j++ ) {
-                        var tr = trs[j];
-                        if( j > 0 ) {
-                            inputs = tr.select('input');
-
-                            for( i in inputs ) {
-                                if( inputs[i].checked == true ) {
-                                    error = 0;
-                                }
-                            }
-
-                            if( error == 1 ) {
-                                return false;
+    <script>
+        (function($) {
+            head.js("<?php echo $this->getViewFileUrl('jquery/jquery.validate.js')?>",
+                "<?php echo $this->getViewFileUrl('jquery/jquery.metadata.js')?>",
+                "<?php echo $this->getViewFileUrl('mage/validation.js')?>",
+                "<?php echo $this->getViewFileUrl('mage/validation/validation.js')?>",
+                function() {
+                    $('#review-form').validation({
+                        errorPlacement: function (error, element) {
+                            if (element.parents('#product-review-table').length) {
+                                $('#product-review-table').siblings(this.errorElement + '.' + this.errorClass).remove();
+                                $('#product-review-table').after(error);
                             } else {
-                                error = 1;
+                                element.after(error);
                             }
                         }
-                    }
-                    return true;
-                }]
-        ]
-        );
-    //]]>
+                    });
+                });
+        })(jQuery);
     </script>
     <?php else: ?>
     <p class="review-nologged" id="review-form">
diff --git a/app/code/core/Mage/Sales/Model/Order.php b/app/code/core/Mage/Sales/Model/Order.php
index a06cf6038199978d5575c97fae271648fbfe1e4d..d6cd814400ca14037b2b7669c5462bfda5af71fe 100644
--- a/app/code/core/Mage/Sales/Model/Order.php
+++ b/app/code/core/Mage/Sales/Model/Order.php
@@ -2002,7 +2002,7 @@ class Mage_Sales_Model_Order extends Mage_Sales_Model_Abstract
         $this->_checkState();
         if (!$this->getId()) {
             $store = $this->getStore();
-            $name = array($store->getWebsite()->getName(),$store->getGroup()->getName(),$store->getName());
+            $name = array($store->getWebsite()->getName(), $store->getGroup()->getName(), $store->getName());
             $this->setStoreName(implode("\n", $name));
         }
 
diff --git a/app/code/core/Mage/Sales/Model/Quote/Item.php b/app/code/core/Mage/Sales/Model/Quote/Item.php
index 98734c3f4ee405e949e01db0943d6b6d21ae98f3..4171690f5a6a81ba5f589229a7582e2f7f8657a7 100644
--- a/app/code/core/Mage/Sales/Model/Quote/Item.php
+++ b/app/code/core/Mage/Sales/Model/Quote/Item.php
@@ -191,7 +191,28 @@ class Mage_Sales_Model_Quote_Item extends Mage_Sales_Model_Quote_Item_Abstract
      *
      * @var Mage_Sales_Model_Status_List
      */
-    protected $_errorInfos = null;
+    protected $_errorInfos;
+
+    /**
+     * @param Mage_Core_Model_Event_Manager $eventDispatcher
+     * @param Mage_Core_Model_Cache $cacheManager
+     * @param Mage_Sales_Model_Status_ListFactory $statusListFactory
+     * @param Mage_Core_Model_Resource_Abstract $resource
+     * @param Varien_Data_Collection_Db $resourceCollection
+     * @param array $data
+     */
+    public function __construct(
+        Mage_Core_Model_Event_Manager $eventDispatcher,
+        Mage_Core_Model_Cache $cacheManager,
+        Mage_Sales_Model_Status_ListFactory $statusListFactory,
+        Mage_Core_Model_Resource_Abstract $resource = null,
+        Varien_Data_Collection_Db $resourceCollection = null,
+        array $data = array()
+    ) {
+        $this->_errorInfos = $statusListFactory->create();
+        parent::__construct($eventDispatcher, $cacheManager, $resource, $resourceCollection, $data);
+    }
+
 
     /**
      * Initialize resource model
@@ -200,7 +221,6 @@ class Mage_Sales_Model_Quote_Item extends Mage_Sales_Model_Quote_Item_Abstract
     protected function _construct()
     {
         $this->_init('Mage_Sales_Model_Resource_Quote_Item');
-        $this->_errorInfos = Mage::getModel('Mage_Sales_Model_Status_List');
     }
 
     /**
diff --git a/app/code/core/Mage/Sales/Model/Resource/Report/Bestsellers.php b/app/code/core/Mage/Sales/Model/Resource/Report/Bestsellers.php
index 05c328afb87fec66877f642b28abc11f3191e7cd..65ce21ceb4820a5dbbae855ff905ca7859e697b7 100755
--- a/app/code/core/Mage/Sales/Model/Resource/Report/Bestsellers.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Report/Bestsellers.php
@@ -226,7 +226,7 @@ class Mage_Sales_Model_Resource_Report_Bestsellers extends Mage_Sales_Model_Reso
 
             $columns = array(
                 'period'                         => 'period',
-                'store_id'                       => new Zend_Db_Expr(Mage_Core_Model_App::ADMIN_STORE_ID),
+                'store_id'                       => new Zend_Db_Expr(Mage_Core_Model_AppInterface::ADMIN_STORE_ID),
                 'product_id'                     => 'product_id',
                 'product_name'                   => new Zend_Db_Expr('MIN(product_name)'),
                 'product_price'                  => new Zend_Db_Expr('MIN(product_price)'),
diff --git a/app/code/core/Mage/Sales/Model/Resource/Report/Bestsellers/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Report/Bestsellers/Collection.php
index fedc347d17c7a5e8bdc9ee3ee240164c6c6e4442..d697d82f33f4128e7ddf0d251e15ed678b380086 100755
--- a/app/code/core/Mage/Sales/Model/Resource/Report/Bestsellers/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Report/Bestsellers/Collection.php
@@ -195,8 +195,8 @@ class Mage_Sales_Model_Resource_Report_Bestsellers_Collection
             $storeIds = array($storeIds);
         }
         $currentStoreIds = $this->_storesIds;
-        if (isset($currentStoreIds) && $currentStoreIds != Mage_Core_Model_App::ADMIN_STORE_ID
-            && $currentStoreIds != array(Mage_Core_Model_App::ADMIN_STORE_ID)) {
+        if (isset($currentStoreIds) && $currentStoreIds != Mage_Core_Model_AppInterface::ADMIN_STORE_ID
+            && $currentStoreIds != array(Mage_Core_Model_AppInterface::ADMIN_STORE_ID)) {
             if (!is_array($currentStoreIds)) {
                 $currentStoreIds = array($currentStoreIds);
             }
diff --git a/app/code/core/Mage/Sales/Model/Resource/Report/Invoiced.php b/app/code/core/Mage/Sales/Model/Resource/Report/Invoiced.php
index 7afbd50c9aab87045c65292647d3d443a822a912..18f54fb895b50323c325a6e05202c154ab5cda8a 100755
--- a/app/code/core/Mage/Sales/Model/Resource/Report/Invoiced.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Report/Invoiced.php
@@ -149,7 +149,7 @@ class Mage_Sales_Model_Resource_Report_Invoiced extends Mage_Sales_Model_Resourc
 
             $columns = array(
                 'period'                => 'period',
-                'store_id'              => new Zend_Db_Expr(Mage_Core_Model_App::ADMIN_STORE_ID),
+                'store_id'              => new Zend_Db_Expr(Mage_Core_Model_AppInterface::ADMIN_STORE_ID),
                 'order_status'          => 'order_status',
                 'orders_count'          => new Zend_Db_Expr('SUM(orders_count)'),
                 'orders_invoiced'       => new Zend_Db_Expr('SUM(orders_invoiced)'),
@@ -265,7 +265,7 @@ class Mage_Sales_Model_Resource_Report_Invoiced extends Mage_Sales_Model_Resourc
 
             $columns = array(
                 'period'                => 'period',
-                'store_id'              => new Zend_Db_Expr(Mage_Core_Model_App::ADMIN_STORE_ID),
+                'store_id'              => new Zend_Db_Expr(Mage_Core_Model_AppInterface::ADMIN_STORE_ID),
                 'order_status'          => 'order_status',
                 'orders_count'          => new Zend_Db_Expr('SUM(orders_count)'),
                 'orders_invoiced'       => new Zend_Db_Expr('SUM(orders_invoiced)'),
diff --git a/app/code/core/Mage/Sales/Model/Resource/Report/Order/Createdat.php b/app/code/core/Mage/Sales/Model/Resource/Report/Order/Createdat.php
index b9bdb0d046f2a116169d8e9da794418569b5487c..1273b6428706871efa52b595623547a1c639fdad 100644
--- a/app/code/core/Mage/Sales/Model/Resource/Report/Order/Createdat.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Report/Order/Createdat.php
@@ -233,7 +233,7 @@ class Mage_Sales_Model_Resource_Report_Order_Createdat extends Mage_Sales_Model_
                 $columns[$k] = new Zend_Db_Expr('SUM(' . $k . ')');
             }
             $columns['period']         = 'period';
-            $columns['store_id']       = new Zend_Db_Expr(Mage_Core_Model_App::ADMIN_STORE_ID);
+            $columns['store_id']       = new Zend_Db_Expr(Mage_Core_Model_AppInterface::ADMIN_STORE_ID);
             $columns['order_status']   = 'order_status';
 
             $select->reset();
diff --git a/app/code/core/Mage/Sales/Model/Resource/Report/Shipping.php b/app/code/core/Mage/Sales/Model/Resource/Report/Shipping.php
index 5022b06e007cc1705c8b2d398e5ef32f6c152ce4..d1c96ebb95824e0279e4a51daf31ccff070be904 100755
--- a/app/code/core/Mage/Sales/Model/Resource/Report/Shipping.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Report/Shipping.php
@@ -132,7 +132,7 @@ class Mage_Sales_Model_Resource_Report_Shipping extends Mage_Sales_Model_Resourc
 
             $columns = array(
                 'period'                => 'period',
-                'store_id'              => new Zend_Db_Expr(Mage_Core_Model_App::ADMIN_STORE_ID),
+                'store_id'              => new Zend_Db_Expr(Mage_Core_Model_AppInterface::ADMIN_STORE_ID),
                 'order_status'          => 'order_status',
                 'shipping_description'  => 'shipping_description',
                 'orders_count'          => new Zend_Db_Expr('SUM(orders_count)'),
@@ -249,7 +249,7 @@ class Mage_Sales_Model_Resource_Report_Shipping extends Mage_Sales_Model_Resourc
 
             $columns = array(
                 'period'                => 'period',
-                'store_id'              => new Zend_Db_Expr(Mage_Core_Model_App::ADMIN_STORE_ID),
+                'store_id'              => new Zend_Db_Expr(Mage_Core_Model_AppInterface::ADMIN_STORE_ID),
                 'order_status'          => 'order_status',
                 'shipping_description'  => 'shipping_description',
                 'orders_count'          => new Zend_Db_Expr('SUM(orders_count)'),
diff --git a/app/code/core/Mage/Sales/Model/Status/ListFactory.php b/app/code/core/Mage/Sales/Model/Status/ListFactory.php
new file mode 100644
index 0000000000000000000000000000000000000000..cfa6530e84e8a96d3c3cd66614a6ab1c30da3f3b
--- /dev/null
+++ b/app/code/core/Mage/Sales/Model/Status/ListFactory.php
@@ -0,0 +1,52 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_Sales
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Sales_Model_Status_ListFactory
+{
+    /**
+     * @var Magento_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * @param Magento_ObjectManager $objectManager
+     */
+    public function __construct(Magento_ObjectManager $objectManager)
+    {
+        $this->_objectManager = $objectManager;
+    }
+
+    /**
+     * Create status list instance
+     *
+     * @param array $arguments
+     * @return Mage_Sales_Model_Status_List
+     */
+    public function create(array $arguments = array())
+    {
+        return $this->_objectManager->create('Mage_Sales_Model_Status_List', $arguments);
+    }
+}
diff --git a/app/code/core/Mage/Sales/view/frontend/guest/form.phtml b/app/code/core/Mage/Sales/view/frontend/guest/form.phtml
index b0386175fdb5d23778bcdf3a41ad9c8f944df707..7b6293148df94c19cd936120551707c142732594 100644
--- a/app/code/core/Mage/Sales/view/frontend/guest/form.phtml
+++ b/app/code/core/Mage/Sales/view/frontend/guest/form.phtml
@@ -27,29 +27,29 @@
 <div class="page-title">
     <h1><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Orders and Returns') ?></h1>
 </div>
-<form id="oar_widget_orders_and_returns_form" action="<?php echo $this->getActionUrl() ?>" method="post" class="search-form" name="guest_post">
+<form id="oar-widget-orders-and-returns-form" action="<?php echo $this->getActionUrl() ?>" method="post" class="search-form" name="guest_post">
     <div class="fieldset">
         <h2 class="legend"><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Order Information') ?></h2>
         <ul class="form-list">
             <li class="fields">
                 <div class="field">
-                    <label for="oar_order_id" class="required"><em>*</em><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Order ID') ?></label>
+                    <label for="oar-order-id" class="required"><em>*</em><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Order ID') ?></label>
                     <div class="input-box">
-                        <input type="text" class="input-text required-entry" id="oar_order_id" name="oar_order_id" />
+                        <input type="text" class="input-text" id="oar-order-id" name="oar_order_id" data-validate="{required:true}"/>
                     </div>
                 </div>
                 <div class="field">
-                    <label for="oar_billing_lastname" class="required"><em>*</em><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Billing Last Name') ?></label>
+                    <label for="oar-billing-lastname" class="required"><em>*</em><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Billing Last Name') ?></label>
                     <div class="input-box">
-                        <input type="text" class="input-text required-entry" id="oar_billing_lastname" name="oar_billing_lastname" />
+                        <input type="text" class="input-text" id="oar-billing-lastname" name="oar_billing_lastname" data-validate="{required:true}"/>
                     </div>
                 </div>
             </li>
             <li class="fields">
                 <div class="field">
-                    <label for="quick_search_type_id" class="required"><em>*</em><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Find Order By:') ?></label>
+                    <label for="quick-search-type-id" class="required"><em>*</em><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Find Order By:') ?></label>
                     <div class="input-box">
-                        <select name="oar_type" id="quick_search_type_id" class="select" onchange="showIdentifyBlock(this.value);">
+                        <select name="oar_type" id="quick-search-type-id" class="select">
                            <option value="email"><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Email Address'); ?></option>
                            <option value="zip"><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('ZIP Code'); ?></option>
                         </select>
@@ -58,13 +58,13 @@
                 <div id="oar-email" class="field">
                     <label for="oar_email" class="required"><em>*</em><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Email Address') ?></label>
                     <div class="input-box">
-                        <input type="text" class="input-text validate-email required-entry" id="oar_email" name="oar_email"/>
+                        <input type="text" class="input-text" id="oar_email" name="oar_email" data-validate="{required:true, 'validate-email':true}"/>
                     </div>
                 </div>
                 <div id="oar-zip" class="field">
                     <label for="oar_zip" class="required"><em>*</em><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Billing ZIP Code') ?></label>
                     <div class="input-box">
-                        <input type="text" class="input-text required-entry" id="oar_zip" name="oar_zip"/>
+                        <input type="text" class="input-text" id="oar_zip" name="oar_zip" data-validate="{required:true}"/>
                     </div>
                 </div>
             </li>
@@ -75,20 +75,11 @@
     </div>
 </form>
 <script type="text/javascript">
-//<![CDATA[
-    var dataForm = new VarienForm('oar_widget_orders_and_returns_form', true);
-
-    function showIdentifyBlock(id)
-    {
-        if (id == 'zip') {
-            $('oar-zip').show();
-            $('oar-email').hide();
-        } else {
-            $('oar-zip').hide();
-            $('oar-email').show();
-        }
-        return false;
-    }
-    showIdentifyBlock($('quick_search_type_id').value);
-//]]>
+    head.js("<?php echo $this->getViewFileUrl('jquery/jquery.validate.js')?>",
+        "<?php echo $this->getViewFileUrl('jquery/jquery.metadata.js')?>",
+        "<?php echo $this->getViewFileUrl('mage/validation.js')?>",
+        "<?php echo $this->getViewFileUrl('mage/validation/validation.js')?>",
+        "<?php echo $this->getViewFileUrl('Mage_Sales::orders-returns.js');?>", function() {
+            jQuery('#oar-widget-orders-and-returns-form').ordersReturns().validation();
+    });
 </script>
diff --git a/app/code/core/Mage/Sales/view/frontend/order/creditmemo/items/renderer/default.phtml b/app/code/core/Mage/Sales/view/frontend/order/creditmemo/items/renderer/default.phtml
index ae01d0fa345adbfde4029138b935aa2b89af6aa4..2c14f267f2f0ee75f3787fd84f907cd499414bc9 100644
--- a/app/code/core/Mage/Sales/view/frontend/order/creditmemo/items/renderer/default.phtml
+++ b/app/code/core/Mage/Sales/view/frontend/order/creditmemo/items/renderer/default.phtml
@@ -73,7 +73,7 @@
                     <?php endif; ?>
                 <?php endif; ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -110,7 +110,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($this->getItem()->getPrice()+$this->getItem()->getWeeeTaxAppliedAmount()+$this->getItem()->getWeeeTaxDisposition()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -131,7 +131,7 @@
                 <?php endif; ?>
                 <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getPriceInclTax($this->getItem()); ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -168,7 +168,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($_incl+$this->getItem()->getWeeeTaxAppliedAmount()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -190,7 +190,7 @@
                     <?php endif; ?>
                 <?php endif; ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -227,7 +227,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($this->getItem()->getRowTotal()+$this->getItem()->getWeeeTaxAppliedRowAmount()+$this->getItem()->getWeeeTaxRowDisposition()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -248,7 +248,7 @@
                 <?php endif; ?>
                 <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getSubtotalInclTax($this->getItem()); ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -284,7 +284,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($_incl+$this->getItem()->getWeeeTaxAppliedRowAmount()); ?></span>
                         </span>
                     <?php endif; ?>
diff --git a/app/code/core/Mage/Sales/view/frontend/order/invoice/items/renderer/default.phtml b/app/code/core/Mage/Sales/view/frontend/order/invoice/items/renderer/default.phtml
index aeb455148d50511dfd3b306135d856f3fec8097b..1044080afcd7f0859fb5b864dcac8a221148c7c2 100644
--- a/app/code/core/Mage/Sales/view/frontend/order/invoice/items/renderer/default.phtml
+++ b/app/code/core/Mage/Sales/view/frontend/order/invoice/items/renderer/default.phtml
@@ -74,7 +74,7 @@
                     <?php endif; ?>
                 <?php endif; ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -111,7 +111,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($this->getItem()->getPrice()+$this->getItem()->getWeeeTaxAppliedAmount()+$this->getItem()->getWeeeTaxDisposition()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -132,7 +132,7 @@
                 <?php endif; ?>
                 <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getPriceInclTax($this->getItem()); ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -169,7 +169,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($_incl+$this->getItem()->getWeeeTaxAppliedAmount()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -191,7 +191,7 @@
                     <?php endif; ?>
                 <?php endif; ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -228,7 +228,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($this->getItem()->getRowTotal()+$this->getItem()->getWeeeTaxAppliedRowAmount()+$this->getItem()->getWeeeTaxRowDisposition()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -249,7 +249,7 @@
                 <?php endif; ?>
                 <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getSubtotalInclTax($this->getItem()); ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -285,7 +285,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($_incl+$this->getItem()->getWeeeTaxAppliedRowAmount()); ?></span>
                         </span>
                     <?php endif; ?>
diff --git a/app/code/core/Mage/Sales/view/frontend/order/items/renderer/default.phtml b/app/code/core/Mage/Sales/view/frontend/order/items/renderer/default.phtml
index f7173b46cedeaf4a8115542ceab6dfdf079137d3..c632ea6d0d58d55cb8bf2f32ef3b3b9bbce1dfa2 100644
--- a/app/code/core/Mage/Sales/view/frontend/order/items/renderer/default.phtml
+++ b/app/code/core/Mage/Sales/view/frontend/order/items/renderer/default.phtml
@@ -75,7 +75,7 @@
                     <?php endif; ?>
                 <?php endif; ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -112,7 +112,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#eunit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($this->getItem()->getPrice()+$this->getItem()->getWeeeTaxAppliedAmount()+$this->getItem()->getWeeeTaxDisposition()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -133,7 +133,7 @@
                 <?php endif; ?>
                 <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getPriceInclTax($this->getItem()); ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -170,7 +170,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('unit-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#unit-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($_incl+$this->getItem()->getWeeeTaxAppliedAmount()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -207,7 +207,7 @@
                     <?php endif; ?>
                 <?php endif; ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -244,7 +244,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#esubtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($this->getItem()->getRowTotal()+$this->getItem()->getWeeeTaxAppliedRowAmount()+$this->getItem()->getWeeeTaxRowDisposition()); ?></span>
                         </span>
                     <?php endif; ?>
@@ -265,7 +265,7 @@
                 <?php endif; ?>
                 <?php $_incl = $this->helper('Mage_Checkout_Helper_Data')->getSubtotalInclTax($this->getItem()); ?>
                 <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), array(1, 4), 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                    <span class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                    <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                 <?php else: ?>
                     <span class="cart-price">
                 <?php endif; ?>
@@ -301,7 +301,7 @@
                     </span>
 
                     <?php if (Mage::helper('Mage_Weee_Helper_Data')->typeOfDisplay($this->getItem(), 2, 'sales') && (float)$this->getItem()->getWeeeTaxAppliedAmount()): ?>
-                        <span class="cart-tax-total" onclick="taxToggle('subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>', this, 'cart-tax-total-expanded');">
+                        <span class="cart-tax-total" data-tax-toggle='{"itemTaxId" : "#subtotal-item-tax-details<?php echo $this->getItem()->getId(); ?>"}'>
                             <span class="nobr"><?php echo Mage::helper('Mage_Weee_Helper_Data')->__('Total incl. tax'); ?>:<br /> <?php echo $this->getOrder()->formatPrice($_incl+$this->getItem()->getWeeeTaxAppliedRowAmount()); ?></span>
                         </span>
                     <?php endif; ?>
diff --git a/app/code/core/Mage/Sales/view/frontend/orders-returns.js b/app/code/core/Mage/Sales/view/frontend/orders-returns.js
new file mode 100644
index 0000000000000000000000000000000000000000..79af9c4a9327498a021d52a323e82e7558de80d4
--- /dev/null
+++ b/app/code/core/Mage/Sales/view/frontend/orders-returns.js
@@ -0,0 +1,50 @@
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Sales Orders and Returns
+ * @package     mage
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+/*jshint browser:true, jquery:true*/
+(function($) {
+    "use strict";
+    $.widget('mage.ordersReturns', {
+        options: {
+            zipCode: '#oar-zip', // Search by zip code.
+            emailAddress: '#oar-email', // Search by email address.
+            searchType: '#quick-search-type-id' // Search element used for choosing between the two.
+        },
+
+        _create: function() {
+            $(this.options.searchType).on('change', $.proxy(this._showIdentifyBlock, this)).trigger('change');
+        },
+
+        /**
+         * Show either the search by zip code option or the search by email address option.
+         * @private
+         * @param e - Change event. Event target value is either 'zip' or 'email'.
+         */
+        _showIdentifyBlock: function(e) {
+            var value = $(e.target).val();
+            $(this.options.zipCode).toggle(value === 'zip');
+            $(this.options.emailAddress).toggle(value === 'email');
+        }
+    });
+})(jQuery);
diff --git a/app/code/core/Mage/Sales/view/frontend/widget/guest/form.phtml b/app/code/core/Mage/Sales/view/frontend/widget/guest/form.phtml
index 2f432ac9993b175518cb03b6672662451c7151a6..0288190759eaa5edacc091c1278ba834926f7ca6 100644
--- a/app/code/core/Mage/Sales/view/frontend/widget/guest/form.phtml
+++ b/app/code/core/Mage/Sales/view/frontend/widget/guest/form.phtml
@@ -32,39 +32,39 @@
                 <h2><?php echo $this->__('Orders and Returns') ?></h2>
             </div>
             <div class="block-content">
-               <form id="oar_widget_orders_and_returns_form" action="<?php echo $this->getActionUrl() ?>" method="post" class="search-form" name="guest_post">
+               <form id="oar-widget-orders-and-returns-form" action="<?php echo $this->getActionUrl() ?>" method="post" class="search-form" name="guest_post">
                    <ul class="form-alt">
                        <li>
                            <label class="required"><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Find Order By:') ?></label>
                            <div class="input-box">
-                               <select name="oar_type" id="quick_search_type_id" class="select" title="" onchange="showIdentifyBlock(this.value);">
+                               <select name="oar_type" id="quick-search-type-id" class="select" title="">
                                    <option value="email"><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Email Address') ?></option>
                                    <option value="zip"><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('ZIP Code') ?></option>
                                </select>
                            </div>
                        </li>
                        <li>
-                           <label for="oar_order_id" class="required"><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Order ID') ?> <em>*</em></label>
+                           <label for="oar-order-id" class="required"><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Order ID') ?> <em>*</em></label>
                            <div class="input-box">
-                               <input type="text" class="input-text required-entry" id="oar_order_id" name="oar_order_id"  autocomplete="off" />
+                               <input type="text" class="input-text" id="oar-order-id" name="oar_order_id"  autocomplete="off" data-validate="{required:true}"/>
                            </div>
                        </li>
                        <li>
-                           <label for="oar_billing_lastname" class="required"><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Billing Last Name') ?> <em>*</em></label>
+                           <label for="oar-billing-lastname" class="required"><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Billing Last Name') ?> <em>*</em></label>
                            <div class="input-box">
-                               <input type="text" class="input-text required-entry" id="oar_billing_lastname" name="oar_billing_lastname" autocomplete="off" />
+                               <input type="text" class="input-text" id="oar-billing-lastname" name="oar_billing_lastname" autocomplete="off" data-validate="{required:true}"/>
                            </div>
                        </li>
                        <li id="oar-email">
                            <label for="oar_email" class="required"><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Email Address') ?> <em>*</em></label>
                            <div class="input-box">
-                               <input type="text" class="input-text validate-email required-entry" id="oar_email" name="oar_email" autocomplete="off" />
+                               <input type="text" class="input-text" id="oar_email" name="oar_email" autocomplete="off" data-validate="{required:true, 'validate-email':true}"/>
                            </div>
                        </li>
                        <li id="oar-zip" style="display:none;">
                            <label for="oar_zip" class="required"><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Billing ZIP Code') ?> <em>*</em></label>
                            <div class="input-box">
-                               <input type="text" class="input-text required-entry" id="oar_zip" name="oar_zip" />
+                               <input type="text" class="input-text" id="oar_zip" name="oar_zip" data-validate="{required:true}"/>
                            </div>
                        </li>
                    </ul>
@@ -76,28 +76,12 @@
         </div>
     </div>
 <script type="text/javascript">
-//<![CDATA[
-    if ($('quick_search_type_id').value == 'zip') {
-        $('oar-zip').show();
-        $('oar-email').hide();
-    } else {
-       $('oar-zip').hide();
-       $('oar-email').show();
-    }
-
-   var dataForm = new VarienForm('oar_widget_orders_and_returns_form', true);
-
-   function showIdentifyBlock(id)
-   {
-       if (id == 'zip') {
-           $('oar-zip').show();
-           $('oar-email').hide();
-       } else if (id == 'email') {
-           $('oar-zip').hide();
-           $('oar-email').show();
-       }
-       return false;
-   }
-//]]>
+    head.js("<?php echo $this->getViewFileUrl('jquery/jquery.validate.js')?>",
+        "<?php echo $this->getViewFileUrl('jquery/jquery.metadata.js')?>",
+        "<?php echo $this->getViewFileUrl('mage/validation.js')?>",
+        "<?php echo $this->getViewFileUrl('mage/validation/validation.js')?>",
+        "<?php echo $this->getViewFileUrl('Mage_Sales::orders-returns.js');?>", function() {
+            jQuery('#oar-widget-orders-and-returns-form').ordersReturns().validation();
+        });
 </script>
 <?php endif; ?>
diff --git a/app/code/core/Mage/Sendfriend/view/frontend/send.phtml b/app/code/core/Mage/Sendfriend/view/frontend/send.phtml
index 4f92cce9e69331f6f4230110e32ef6b886930715..ca44164dc7f97999665121b8b85259796874ef83 100644
--- a/app/code/core/Mage/Sendfriend/view/frontend/send.phtml
+++ b/app/code/core/Mage/Sendfriend/view/frontend/send.phtml
@@ -30,114 +30,93 @@
  * @see Mage_Sendfriend_Block_Send
  */
 ?>
-<script type="text/javascript">
-//<![CDATA[
-    i=0;
-    var recipCount  = 1;
-    var maxRecip    = <?php echo $this->getMaxRecipients() ?>;
-    function remove_recipient(i){
-        $('recipients_name'+i).up(2).remove();
-        recipCount--;
-        if(recipCount<maxRecip && maxRecip != 0) {
-            $('add_recipient_button').show();
-            $('max_recipient_message').hide();
-        }
-        return false;
-    }
-
-    function add_recipient(){
-        ul = $('recipients_options');
-        var li_mail = Element.extend(document.createElement("LI"));
-        li_mail.addClassName('fields additional-row');
-        li_mail.innerHTML = '<p><a href="delete_email" title="<?php echo $this->jsQuoteEscape($this->__('Remove Email')) ?>" onclick="remove_recipient('+i+'); return false" class="btn-remove"><?php echo $this->jsQuoteEscape($this->__('Remove Email')) ?>"<\/a><\/p>'
-        li_mail.innerHTML += '<div class="field"><label for="recipients_name'+i+'" class="required"><em>*<\/em><?php echo $this->jsQuoteEscape($this->__('Name:')) ?><\/label><div class="input-box"><input name="recipients[name][]" type="text" class="input-text required-entry" id="recipients_name'+i+'" /><\/div>';
-        li_mail.innerHTML += '<div class="field"><label for="recipients_email'+i+'" class="required"><em>*<\/em><?php echo $this->jsQuoteEscape($this->__('Email Address:')) ?><\/label><div class="input-box"><input name="recipients[email][]" value="" title="<?php echo $this->jsQuoteEscape($this->__('Email Address')) ?>" id="recipients_email'+i+'" type="text" class="input-text required-entry validate-email" /><\/div><\/div>';
-        i++;
-        recipCount++;
-        if(recipCount>=maxRecip && maxRecip != 0) {
-            $('add_recipient_button').hide();
-            $('max_recipient_message').show();
-        }
-
-        ul.appendChild(li_mail);
-    }
-//]]>
+<script id="add-recipient-tmpl" type="text/x-jQuery-tmpl">
+    <p id="btn-remove${_index_}">
+        <a href="delete_email" class="btn-remove" title="<?php echo $this->jsQuoteEscape($this->__('Remove Email')) ?>"><?php echo $this->jsQuoteEscape($this->__('Remove Email')) ?>"</a>
+    </p>
+    <div class="field">
+        <label for="recipients-name${_index_}" class="required"><em>*</em> <?php echo $this->__('Name:')?></label>
+        <div class="input-box">
+            <input name="recipients[name][${_index_}]" type="text" title="<?php echo $this->__('Name:')?>" class="input-text" id="recipients-name${_index_}" data-validate="{required:true}"/>
+        </div>
+    </div>
+    <div class="field">
+        <label for="recipients-email${_index_}" class="required"><em>*</em> <?php echo $this->__('Email Address:') ?></label>
+        <div class="input-box">
+            <input name="recipients[email][${_index_}]" title="<?php echo $this->__('Email Address:') ?>" id="recipients-email${_index_}" type="text" class="input-text" data-validate="{required:true, 'validate-email':true}"/>
+        </div>
+    </div>
 </script>
-
 <div class="send-friend">
     <?php echo $this->getMessagesBlock()->getGroupedHtml() ?>
     <div class="page-title">
         <h1><?php echo $this->__('Email to a Friend') ?></h1>
     </div>
-    <form action="<?php echo $this->getSendUrl() ?>" method="post" id="product_sendtofriend_form">
+    <form action="<?php echo $this->getSendUrl() ?>" method="post" id="product-sendtofriend-form">
         <div class="fieldset">
             <?php echo $this->getBlockHtml('formkey')?>
             <h2 class="legend"><?php echo $this->__('Sender:') ?></h2>
             <ul class="form-list" id="sender_options">
                 <li class="fields">
                     <div class="field">
-                        <label for="sender_name" class="required"><em>*</em><?php echo $this->__('Name:') ?></label>
+                        <label for="sender-name" class="required"><em>*</em><?php echo $this->__('Name:') ?></label>
                         <div class="input-box">
-                            <input name="sender[name]" value="<?php echo $this->escapeHtml($this->getUserName()) ?>" title="<?php echo $this->__('Name') ?>" id="sender_name" type="text" class="input-text required-entry" />
+                            <input name="sender[name]" value="<?php echo $this->escapeHtml($this->getUserName()) ?>" title="<?php echo $this->__('Name') ?>" id="sender-name" type="text" class="input-text" data-validate="{required:true}"/>
                         </div>
                     </div>
                     <div class="field">
-                       <label for="sender_email" class="required"><em>*</em><?php echo $this->__('Email:') ?></label>
+                       <label for="sender-email" class="required"><em>*</em><?php echo $this->__('Email:') ?></label>
                        <div class="input-box">
-                           <input name="sender[email]" value="<?php echo $this->escapeHtml($this->getEmail()) ?>" title="<?php echo $this->__('Email Address') ?>" id="sender_email" type="text" class="input-text required-entry validate-email" />
+                           <input name="sender[email]" value="<?php echo $this->escapeHtml($this->getEmail()) ?>" title="<?php echo $this->__('Email Address') ?>" id="sender-email" type="text" class="input-text" data-validate="{required:true, 'validate-email':true}"/>
                        </div>
                     </div>
                 </li>
                 <li class="wide">
-                    <label for="sender_message" class="required"><em>*</em><?php echo $this->__('Message:') ?></label>
+                    <label for="sender-message" class="required"><em>*</em><?php echo $this->__('Message:') ?></label>
                     <div class="input-box">
-                        <textarea name="sender[message]" class="input-text required-entry" id="sender_message" cols="3" rows="3"><?php echo $this->escapeHtml($this->getMessage())?></textarea>
+                        <textarea name="sender[message]" class="input-text" id="sender-message" cols="3" rows="3" data-validate="{required:true}"><?php echo $this->escapeHtml($this->getMessage())?></textarea>
                     </div>
                 </li>
             </ul>
         </div>
         <div class="fieldset">
             <h2 class="legend"><?php echo $this->__('Recipient:') ?></h2>
-            <ul class="form-list" id="recipients_options">
-                <li class="fields">
-                    <div class="field">
-                        <label for="recipients_name" class="required"><em>*</em><?php echo $this->__('Name:') ?></label>
-                        <div class="input-box">
-                            <input name="recipients[name][]" type="text" class="input-text required-entry" id="recipients_name" />
-                        </div>
-                    </div>
-                    <div class="field">
-                        <label for="recipients_email" class="required"><em>*</em><?php echo $this->__('Email Address:') ?></label>
-                        <div class="input-box">
-                            <input name="recipients[email][]" value="" title="<?php echo $this->__('Email Address') ?>" id="recipients_email" type="text" class="input-text required-entry validate-email" />
-                        </div>
-                    </div>
-                </li>
+            <ul class="form-list" id="recipients-options">
+                <li class="no-display">&nbsp;</li>
             </ul>
         </div>
         <div class="buttons-set">
-            <p class="back-link"><a href="#" onclick="history.back(); return false;"><small>&laquo; </small><?php echo $this->__('Back') ?></a></p>
+            <p class="back-link"><a href="#" role="back"><small>&laquo; </small><?php echo $this->__('Back') ?></a></p>
             <button type="submit" class="button<?php if (!$this->canSend()):?> disabled<?php endif ?>"<?php if (!$this->canSend()):?> disabled="disabled"<?php endif ?>><span><span><?php echo $this->__('Send Email') ?></span></span></button>
-            <div id="max_recipient_message" style="display:none;">
+            <div id="max-recipient-message" style="display:none;">
                 <?php if ($this->getMaxRecipients()): ?>
                   <p class="limit"><?php echo $this->__('Maximum %d email addresses allowed.', $this->getMaxRecipients()) ?></p>
                 <?php endif; ?>
             </div>
             <?php if (1 < $this->getMaxRecipients()): ?>
-                <p id="add_recipient_button">
-                    <button type="button" onclick="add_recipient();" class="button"><span><span><?php echo $this->__('Add Recipient') ?></span></span></button>
+                <p>
+                    <button type="button" id="add-recipient-button" class="button"><span><span><?php echo $this->__('Add Recipient') ?></span></span></button>
                 </p>
             <?php endif; ?>
         </div>
     </form>
     <script type="text/javascript">
-    //<![CDATA[
-        var productSendtofriendForm = new VarienForm('product_sendtofriend_form');
-        productSendtofriendForm.submit = function() {
-            if(this.validator.validate()) {
-                this.form.submit();
-            }
-        }.bind(productSendtofriendForm);
-    //]]>
+        (function($) {
+            head.js("<?php echo $this->getViewFileUrl('jquery/jquery.validate.js')?>",
+                "<?php echo $this->getViewFileUrl('jquery/jquery.metadata.js')?>",
+                "<?php echo $this->getViewFileUrl('mage/validation.js')?>",
+                "<?php echo $this->getViewFileUrl('mage/validation/validation.js')?>",
+                "<?php echo $this->getViewFileUrl('Mage_Page::js/row-builder.js')?>", function() {
+                    $('#product-sendtofriend-form').rowBuilder({
+                        rowTemplate: '#add-recipient-tmpl',
+                        rowContainer: '#recipients-options',
+                        maxRows: '<?php echo $this->getMaxRecipients() ?>',
+                        maxRowsMsg: '#max-recipient-message',
+                        addRowBtn: '#add-recipient-button',
+                        additionalRowClass: 'additional-row'
+                    }).validation();
+                    $('p.back-link a[role="back"]').on('click', function() { history.back(); return false; });
+                })
+        })(jQuery);
     </script>
 </div>
diff --git a/app/code/core/Mage/Shipping/controllers/TrackingController.php b/app/code/core/Mage/Shipping/controllers/TrackingController.php
index 7d787dec01381f7afd83a955eff264b14d96a0a4..b5ebbf23771f7e7df7fa265f4b4e267d1a808286 100644
--- a/app/code/core/Mage/Shipping/controllers/TrackingController.php
+++ b/app/code/core/Mage/Shipping/controllers/TrackingController.php
@@ -44,8 +44,7 @@ class Mage_Shipping_TrackingController extends Mage_Core_Controller_Front_Action
             $response = '';
             $tracks = $order->getTracksCollection();
 
-            $className = Mage::getConfig()->getBlockClassName('Mage_Core_Block_Template');
-            $block = new $className();
+            $block = $this->_objectManager->create('Mage_Core_Block_Template');
             $block->setType('Mage_Core_Block_Template')
                 ->setTemplate('order/trackinginfo.phtml');
 
diff --git a/app/code/core/Mage/Sitemap/Model/Resource/Catalog/Product.php b/app/code/core/Mage/Sitemap/Model/Resource/Catalog/Product.php
index 23a02ed3265820b81ada698ca9523b31652e4d62..7398d9b7f1921de8b00eecd0f060f20685499b91 100755
--- a/app/code/core/Mage/Sitemap/Model/Resource/Catalog/Product.php
+++ b/app/code/core/Mage/Sitemap/Model/Resource/Catalog/Product.php
@@ -122,7 +122,7 @@ class Mage_Sitemap_Model_Resource_Catalog_Product extends Mage_Core_Model_Resour
             ->joinLeft(
                 array('t1_' . $attributeCode => $attribute['table']),
                 'e.entity_id = t1_' . $attributeCode . '.entity_id AND '
-                . $adapter->quoteInto(' t1_' . $attributeCode . '.store_id = ?', Mage_Core_Model_App::ADMIN_STORE_ID)
+                . $adapter->quoteInto(' t1_' . $attributeCode . '.store_id = ?', Mage_Core_Model_AppInterface::ADMIN_STORE_ID)
                 . $adapter->quoteInto(' AND t1_'.$attributeCode . '.attribute_id = ?', $attribute['attribute_id']),
                 array());
 
diff --git a/app/code/core/Mage/Tax/Helper/Data.php b/app/code/core/Mage/Tax/Helper/Data.php
index 720defc1443e86cb4f8e1c600769dd56868d7755..5789d35467c37418280a1b42f40543d3e79768e6 100644
--- a/app/code/core/Mage/Tax/Helper/Data.php
+++ b/app/code/core/Mage/Tax/Helper/Data.php
@@ -57,8 +57,12 @@ class Mage_Tax_Helper_Data extends Mage_Core_Helper_Abstract
      */
     protected $_postCodeSubStringLength = 10;
 
-    public function  __construct()
+    /**
+     * @param Mage_Core_Model_Translate $translator
+     */
+    public function  __construct(Mage_Core_Model_Translate $translator)
     {
+        parent::__construct($translator);
         $this->_config = Mage::getSingleton('Mage_Tax_Model_Config');
     }
 
diff --git a/app/code/core/Mage/Tax/Model/Resource/Report/Tax/Createdat.php b/app/code/core/Mage/Tax/Model/Resource/Report/Tax/Createdat.php
index 4b15a2d9b1c12ede86ee5f820d0c533e14d4862d..89b85675897185bb1ccac37f26185f537342edf3 100644
--- a/app/code/core/Mage/Tax/Model/Resource/Report/Tax/Createdat.php
+++ b/app/code/core/Mage/Tax/Model/Resource/Report/Tax/Createdat.php
@@ -126,7 +126,7 @@ class Mage_Tax_Model_Resource_Report_Tax_Createdat extends Mage_Reports_Model_Re
 
             $columns = array(
                 'period'                => 'period',
-                'store_id'              => new Zend_Db_Expr(Mage_Core_Model_App::ADMIN_STORE_ID),
+                'store_id'              => new Zend_Db_Expr(Mage_Core_Model_AppInterface::ADMIN_STORE_ID),
                 'code'                  => 'code',
                 'order_status'          => 'order_status',
                 'percent'               => 'MAX(' . $writeAdapter->quoteIdentifier('percent') . ')',
diff --git a/app/code/core/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Form/Element/Links.php b/app/code/core/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Form/Element/Links.php
index e52aab08a1ac96fe47874005af283d1a25ffb976..8d5dd0d78b851ecf86da9eba7b2ff7a248c1a5d4 100644
--- a/app/code/core/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Form/Element/Links.php
+++ b/app/code/core/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Form/Element/Links.php
@@ -26,6 +26,8 @@
 
 /**
  * Form element renderer to display link element
+ *
+ * @method array getValues()
  */
 class Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Form_Element_Links extends Varien_Data_Form_Element_Abstract
 {
@@ -47,18 +49,22 @@ class Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Form_Element_Links ext
      */
     public function getElementHtml()
     {
-        $html = '<div id="'.$this->getHtmlId().'" ' . $this->serialize($this->getHtmlAttributes()) . '>'."\n";
-
         $values = $this->getValues();
-
+        $links = array();
         if ($values) {
             foreach ($values as $option) {
-                $html .= $this->_optionToHtml($option);
+                $links[] = $this->_optionToHtml($option);
             }
         }
 
-        $html.= '</div><br />'."\n";
-        $html.= $this->getAfterElementHtml();
+        $html = sprintf('<div id="%s" %s>%s%s</div><br />%s%s',
+            $this->getHtmlId(),
+            $this->serialize($this->getHtmlAttributes()),
+            PHP_EOL,
+            join('', $links),
+            PHP_EOL,
+            $this->getAfterElementHtml()
+        );
         return $html;
     }
 
@@ -78,10 +84,13 @@ class Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Form_Element_Links ext
             }
             $attributes[] = $title . '="' . $this->_escape($value) . '"';
         }
-        $html = '<a ' . implode(' ', $attributes) . '>';
-        $html .= $this->_escape($option['label']);
-        $html .= '</a>';
-        $html .= isset($option['delimiter']) ? $option['delimiter'] : '';
+
+        $html = sprintf('<a %s>%s</a>%s',
+            join(' ', $attributes),
+            $this->_escape($option['label']),
+            isset($option['delimiter']) ? $option['delimiter'] : ''
+        );
+
         return $html;
     }
 
diff --git a/app/code/core/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Tab/Css.php b/app/code/core/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Tab/Css.php
index 588213d7f6738d19822b76cfec7a299a56ec553c..3e5bfb3ad8634def5c9dea04ed09c59ef5b71658 100644
--- a/app/code/core/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Tab/Css.php
+++ b/app/code/core/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Tab/Css.php
@@ -140,12 +140,15 @@ class Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Tab_Css
             'class'  => 'fieldset-wide'
         ));
         $this->_addElementTypes($themeFieldset);
-        foreach ($this->_getGroupedFiles() as $groupName => $group) {
+        foreach ($this->getFiles() as $groupName => $files) {
+            foreach ($files as &$file) {
+                $file = $this->_convertFileData($file);
+            }
             $themeFieldset->addField('theme_css_view_' . $groupName, 'links', array(
                 'label'       => $groupName,
                 'title'       => $groupName,
                 'name'        => 'links',
-                'values'      => $group,
+                'values'      => $files,
             ));
         }
 
@@ -155,21 +158,15 @@ class Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Tab_Css
     /**
      * Prepare file items for output on page for download
      *
-     * @param string $fileTitle
-     * @param string $filePath
+     * @param Mage_Core_Model_Theme_File $file
      * @return array
      */
-    protected function _getThemeCss($fileTitle, $filePath)
+    protected function _convertFileData($file)
     {
-        $appPath = $this->_dirs->getDir(Mage_Core_Model_Dir::APP);
-        $shownFilePath = str_ireplace($appPath, '', $filePath);
         return array(
-            'href'      => $this->getUrl('*/*/downloadCss', array(
-                'theme_id' => $this->_getCurrentTheme()->getId(),
-                'file'     => $this->_helperFactory->get('Mage_Theme_Helper_Data')->urlEncode($fileTitle))
-            ),
-            'label'     => $fileTitle,
-            'title'     => $shownFilePath,
+            'href'      => $this->getDownloadUrl($file['id'], $this->_getCurrentTheme()->getId()),
+            'label'     => $file['id'],
+            'title'     => $file['safePath'],
             'delimiter' => '<br />'
         );
     }
@@ -298,221 +295,32 @@ class Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Tab_Css
      */
     protected function _getAdditionalElementTypes()
     {
-        $linksElement = $this->_objectManager->get('Mage_Core_Model_Config')
-            ->getBlockClassName('Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Form_Element_Links');
-        $fileElement = $this->_objectManager->get('Mage_Core_Model_Config')
-            ->getBlockClassName('Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Form_Element_File');
+        $linksElement = 'Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Form_Element_Links';
+        $fileElement = 'Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Form_Element_File';
         return array('links' => $linksElement, 'css_file' => $fileElement);
     }
 
     /**
-     * Get files by groups
-     *
-     * @return array
-     */
-    protected function _getGroupedFiles()
-    {
-        $jsDir = $this->_dirs->getDir(Mage_Core_Model_Dir::PUB_LIB);
-        $codeDir = $this->_dirs->getDir(Mage_Core_Model_Dir::MODULES);
-
-        $groups = array();
-        $themes = array();
-        foreach ($this->getFiles() as $fileTitle => $filePath) {
-            /** @var $theme Mage_Core_Model_Theme */
-            list($group, $theme) = $this->_getGroup($filePath);
-            if ($theme) {
-                $themes[$theme->getThemeId()] = $theme;
-            }
-
-            if (!isset($groups[$group])) {
-                $groups[$group] = array();
-            }
-            $groups[$group][] = $this->_getThemeCss($fileTitle, $filePath);
-        }
-
-        if (count($themes) > 1) {
-            $themes = $this->_sortThemesByHierarchy($themes);
-        }
-
-        $order = array_merge(array($codeDir, $jsDir), array_map(function ($theme) {
-            /** @var $theme Mage_Core_Model_Theme */
-            return $theme->getThemeId();
-        }, $themes));
-        $groups = $this->_sortArrayByArray($groups, $order);
-
-        $labels = $this->_getGroupLabels($themes);
-        foreach ($groups as $key => $group) {
-            usort($group, array($this, '_sortGroupFilesCallback'));
-            $groups[$labels[$key]] = $group;
-            unset($groups[$key]);
-        }
-        return $groups;
-    }
-
-    /**
-     * Sort files inside group
-     *
-     * @param array $firstGroup
-     * @param array $secondGroup
-     * @return int
-     */
-    protected function _sortGroupFilesCallback($firstGroup, $secondGroup)
-    {
-        $hasContextFirst = strpos($firstGroup['label'], '::') !== false;
-        $hasContextSecond = strpos($secondGroup['label'], '::') !== false;
-
-        if ($hasContextFirst && $hasContextSecond) {
-            $result = strcmp($firstGroup['label'], $secondGroup['label']);
-        } elseif (!$hasContextFirst && !$hasContextSecond) {
-            $result = strcmp($firstGroup['label'], $secondGroup['label']);
-        } elseif ($hasContextFirst) {
-            //case when first item has module context and second item doesn't
-            $result = 1;
-        } else {
-            //case when second item has module context and first item doesn't
-            $result = -1;
-        }
-        return $result;
-    }
-
-    /**
-     * Get group by filename
-     *
-     * @param string $filename
-     * @return array
-     * @throws Mage_Core_Exception
-     */
-    protected function _getGroup($filename)
-    {
-        $designDir = $this->_dirs->getDir(Mage_Core_Model_Dir::THEMES);
-        $jsDir = $this->_dirs->getDir(Mage_Core_Model_Dir::PUB_LIB);
-        $codeDir = $this->_dirs->getDir(Mage_Core_Model_Dir::MODULES);
-
-        $group = null;
-        $theme = null;
-        if (substr($filename, 0, strlen($designDir)) == $designDir) {
-            $theme = $this->_getThemeByFilename(substr($filename, strlen($designDir)));
-            $group = $theme->getThemeId();
-        } elseif (substr($filename, 0, strlen($jsDir)) == $jsDir) {
-            $group = $jsDir;
-        } elseif (substr($filename, 0, strlen($codeDir)) == $codeDir) {
-            $group = $codeDir;
-        } else {
-            Mage::throwException($this->__('Invalid view file directory "%s"', $filename));
-        }
-
-        return array($group, $theme);
-    }
-
-    /**
-     * Sort themes according to their hierarchy
-     *
-     * @param array $themes
-     * @return array
-     */
-    protected function _sortThemesByHierarchy($themes)
-    {
-        uasort($themes, array($this, '_sortThemesByHierarchyCallback'));
-        return $themes;
-    }
-
-    /**
-     * Sort themes by hierarchy callback
-     *
-     * @param Mage_Core_Model_Theme $firstTheme
-     * @param Mage_Core_Model_Theme $secondTheme
-     * @return int
-     */
-    protected function _sortThemesByHierarchyCallback($firstTheme, $secondTheme)
-    {
-        $parentTheme = $firstTheme->getParentTheme();
-        while ($parentTheme) {
-            if ($parentTheme->getId() == $secondTheme->getId()) {
-                return -1;
-            }
-            $parentTheme = $parentTheme->getParentTheme();
-        }
-        return 1;
-    }
-
-    /**
-     * Get theme object that contains given file
-     *
-     * @param string $filename
-     * @return Mage_Core_Model_Theme
-     * @throws InvalidArgumentException
-     */
-    protected function _getThemeByFilename($filename)
-    {
-        $area = strtok($filename, DIRECTORY_SEPARATOR);
-        $package = strtok(DIRECTORY_SEPARATOR);
-        $theme = strtok(DIRECTORY_SEPARATOR);
-
-        if ($area === false || $package === false || $theme === false) {
-            throw new InvalidArgumentException('Theme path does not recognized');
-        }
-        /** @var $collection Mage_Core_Model_Resource_Theme_Collection */
-        $collection = $this->_objectManager->create('Mage_Core_Model_Resource_Theme_Collection');
-        return $collection->getThemeByFullPath($area . '/' . $package . '/' . $theme);
-    }
-
-    /**
-     * Get group labels
-     *
-     * @param array $themes
-     * @return array
-     */
-    protected function _getGroupLabels($themes)
-    {
-        $labels = array(
-            $this->_dirs->getDir(Mage_Core_Model_Dir::PUB_LIB) => $this->__('Library files'),
-            $this->_dirs->getDir(Mage_Core_Model_Dir::MODULES) => $this->__('Framework files')
-        );
-        foreach ($themes as $theme) {
-            /** @var $theme Mage_Core_Model_Theme */
-            $labels[$theme->getThemeId()] = $this->__('"%s" Theme files', $theme->getThemeTitle());
-        }
-        return $labels;
-    }
-
-    /**
-     * Sort one associative array according to another array
-     *
-     * $groups = array(
-     *     b => item2,
-     *     a => item1,
-     *     c => item3,
-     * );
-     * $order = array(a,b,c);
-     * result: array(
-     *     a => item1,
-     *     b => item2,
-     *     c => item3,
-     * )
+     * Return Tab label
      *
-     * @param array $groups
-     * @param array $order
-     * @return array
+     * @return string
      */
-    protected function _sortArrayByArray($groups, $order)
+    public function getTabLabel()
     {
-        $ordered = array();
-        foreach ($order as $key) {
-            if (array_key_exists($key, $groups)) {
-                $ordered[$key] = $groups[$key];
-                unset($groups[$key]);
-            }
-        }
-        return $ordered + $groups;
+        return $this->__('CSS Editor');
     }
 
     /**
-     * Return Tab label
+     * Get url to downlaod CSS file
      *
+     * @param string $fileId
      * @return string
      */
-    public function getTabLabel()
+    public function getDownloadUrl($fileId, $themeId)
     {
-        return $this->__('CSS Editor');
+        return $this->getUrl('*/*/downloadCss', array(
+            'theme_id' => $themeId,
+            'file'     => $this->_helperFactory->get('Mage_Theme_Helper_Data')->urlEncode($fileId)
+        ));
     }
 }
diff --git a/app/code/core/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Tab/General.php b/app/code/core/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Tab/General.php
index 10e522ef3d4a531a43f564bda4023e5d980c724e..822e9a3bb3f7ab844fdae135a16ced0edc25c44b 100644
--- a/app/code/core/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Tab/General.php
+++ b/app/code/core/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Tab/General.php
@@ -240,8 +240,8 @@ class Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Tab_General
      */
     protected function _getAdditionalElementTypes()
     {
-        $element = $this->_objectManager->get('Mage_Core_Model_Config')
-            ->getBlockClassName('Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Form_Element_Image');
+        $element = 
+            'Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Form_Element_Image';
         return array('image' => $element);
     }
 
diff --git a/app/code/core/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Tab/Js.php b/app/code/core/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Tab/Js.php
index 7076c3aa325e1709863a43717ffb9a3c7bae80af..14a0bcaaddb4989604cf5c8ffb941a3088557061 100644
--- a/app/code/core/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Tab/Js.php
+++ b/app/code/core/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Tab/Js.php
@@ -95,8 +95,7 @@ class Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Tab_Js
      */
     protected function _getAdditionalElementTypes()
     {
-        $fileElement = $this->_objectManager->get('Mage_Core_Model_Config')
-            ->getBlockClassName('Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Form_Element_File');
+        $fileElement = 'Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Form_Element_File';
         return array('js_files' => $fileElement);
     }
 
diff --git a/app/code/core/Mage/Theme/Block/Adminhtml/Wysiwyg/Files/Content.php b/app/code/core/Mage/Theme/Block/Adminhtml/Wysiwyg/Files/Content.php
index 70ab37cdefd81ac1d2f7f54a589f6935e65d6c04..629aa8e8d3759b83edfded293140eff47c17c2d1 100644
--- a/app/code/core/Mage/Theme/Block/Adminhtml/Wysiwyg/Files/Content.php
+++ b/app/code/core/Mage/Theme/Block/Adminhtml/Wysiwyg/Files/Content.php
@@ -31,56 +31,6 @@
  */
 class Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Content extends Mage_Backend_Block_Widget_Container
 {
-    /**
-     * @var Mage_Theme_Helper_Storage
-     */
-    protected $_helperStorage;
-
-    /**
-     * Initialize dependencies
-     *
-     * @param Mage_Core_Controller_Request_Http $request
-     * @param Mage_Core_Model_Layout $layout
-     * @param Mage_Core_Model_Event_Manager $eventManager
-     * @param Mage_Backend_Model_Url $urlBuilder
-     * @param Mage_Core_Model_Translate $translator
-     * @param Mage_Core_Model_Cache $cache
-     * @param Mage_Core_Model_Design_Package $designPackage
-     * @param Mage_Core_Model_Session $session
-     * @param Mage_Core_Model_Store_Config $storeConfig
-     * @param Mage_Core_Controller_Varien_Front $frontController
-     * @param Mage_Core_Model_Factory_Helper $helperFactory
-     * @param Mage_Core_Model_Dir $dirs
-     * @param Mage_Core_Model_Logger $logger
-     * @param Magento_Filesystem $filesystem
-     * @param Mage_Theme_Helper_Storage $helperStorage
-     * @param array $data
-     *
-     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
-     */
-    public function __construct(
-        Mage_Core_Controller_Request_Http $request,
-        Mage_Core_Model_Layout $layout,
-        Mage_Core_Model_Event_Manager $eventManager,
-        Mage_Backend_Model_Url $urlBuilder,
-        Mage_Core_Model_Translate $translator,
-        Mage_Core_Model_Cache $cache,
-        Mage_Core_Model_Design_Package $designPackage,
-        Mage_Core_Model_Session $session,
-        Mage_Core_Model_Store_Config $storeConfig,
-        Mage_Core_Controller_Varien_Front $frontController,
-        Mage_Core_Model_Factory_Helper $helperFactory,
-        Mage_Core_Model_Dir $dirs,
-        Mage_Core_Model_Logger $logger,
-        Magento_Filesystem $filesystem,
-        Mage_Theme_Helper_Storage $helperStorage,
-        array $data = array()
-    ) {
-        $this->_helperStorage = $helperStorage;
-        parent::__construct($request, $layout, $eventManager, $urlBuilder, $translator, $cache, $designPackage,
-            $session, $storeConfig, $frontController, $helperFactory, $dirs, $logger, $filesystem, $data);
-    }
-
     /**
      * Block construction
      */
@@ -129,7 +79,7 @@ class Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Content extends Mage_Backend_Bloc
     public function getContentsUrl()
     {
         return $this->getUrl('*/*/contents', array('type' => $this->getRequest()->getParam('type'))
-            + $this->_helperStorage->getRequestParams());
+            + $this->helper('Mage_Theme_Helper_Storage')->getRequestParams());
     }
 
     /**
@@ -164,7 +114,7 @@ class Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Content extends Mage_Backend_Bloc
      */
     public function getNewfolderUrl()
     {
-        return $this->getUrl('*/*/newFolder', $this->_helperStorage->getRequestParams());
+        return $this->getUrl('*/*/newFolder', $this->helper('Mage_Theme_Helper_Storage')->getRequestParams());
     }
 
     /**
@@ -174,7 +124,7 @@ class Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Content extends Mage_Backend_Bloc
      */
     protected function getDeletefolderUrl()
     {
-        return $this->getUrl('*/*/deleteFolder', $this->_helperStorage->getRequestParams());
+        return $this->getUrl('*/*/deleteFolder', $this->helper('Mage_Theme_Helper_Storage')->getRequestParams());
     }
 
     /**
@@ -184,7 +134,7 @@ class Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Content extends Mage_Backend_Bloc
      */
     public function getDeleteFilesUrl()
     {
-        return $this->getUrl('*/*/deleteFiles', $this->_helperStorage->getRequestParams());
+        return $this->getUrl('*/*/deleteFiles', $this->helper('Mage_Theme_Helper_Storage')->getRequestParams());
     }
 
     /**
@@ -194,7 +144,7 @@ class Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Content extends Mage_Backend_Bloc
      */
     public function getOnInsertUrl()
     {
-        return $this->getUrl('*/*/onInsert', $this->_helperStorage->getRequestParams());
+        return $this->getUrl('*/*/onInsert', $this->helper('Mage_Theme_Helper_Storage')->getRequestParams());
     }
 
     /**
diff --git a/app/code/core/Mage/Theme/Block/Adminhtml/Wysiwyg/Files/Content/Uploader.php b/app/code/core/Mage/Theme/Block/Adminhtml/Wysiwyg/Files/Content/Uploader.php
index a4a21ff6c4b45e759f09d6655d42fddf87d8e02d..6da941274eef4033f45d1669da884c09fa6fbe82 100644
--- a/app/code/core/Mage/Theme/Block/Adminhtml/Wysiwyg/Files/Content/Uploader.php
+++ b/app/code/core/Mage/Theme/Block/Adminhtml/Wysiwyg/Files/Content/Uploader.php
@@ -32,65 +32,23 @@
 class Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Content_Uploader extends Mage_Adminhtml_Block_Media_Uploader
 {
     /**
-     * @var Mage_Theme_Helper_Storage
-     */
-    protected $_helperStorage;
-
-    /**
-     * Initialize dependencies
+     * Path to uploader template
      *
-     * @param Mage_Core_Controller_Request_Http $request
-     * @param Mage_Core_Model_Layout $layout
-     * @param Mage_Core_Model_Event_Manager $eventManager
-     * @param Mage_Backend_Model_Url $urlBuilder
-     * @param Mage_Core_Model_Translate $translator
-     * @param Mage_Core_Model_Cache $cache
-     * @param Mage_Core_Model_Design_Package $designPackage
-     * @param Mage_Core_Model_Session $session
-     * @param Mage_Core_Model_Store_Config $storeConfig
-     * @param Mage_Core_Controller_Varien_Front $frontController
-     * @param Mage_Core_Model_Factory_Helper $helperFactory
-     * @param Mage_Core_Model_Dir $dirs
-     * @param Mage_Core_Model_Logger $logger
-     * @param Magento_Filesystem $filesystem
-     * @param Mage_Theme_Helper_Storage $helperStorage
-     * @param array $data
-     *
-     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
+     * @var string
      */
-    public function __construct(
-        Mage_Core_Controller_Request_Http $request,
-        Mage_Core_Model_Layout $layout,
-        Mage_Core_Model_Event_Manager $eventManager,
-        Mage_Backend_Model_Url $urlBuilder,
-        Mage_Core_Model_Translate $translator,
-        Mage_Core_Model_Cache $cache,
-        Mage_Core_Model_Design_Package $designPackage,
-        Mage_Core_Model_Session $session,
-        Mage_Core_Model_Store_Config $storeConfig,
-        Mage_Core_Controller_Varien_Front $frontController,
-        Mage_Core_Model_Factory_Helper $helperFactory,
-        Mage_Core_Model_Dir $dirs,
-        Mage_Core_Model_Logger $logger,
-        Magento_Filesystem $filesystem,
-        Mage_Theme_Helper_Storage $helperStorage,
-        array $data = array()
-    ) {
-        $this->_helperStorage = $helperStorage;
-        parent::__construct($request, $layout, $eventManager, $urlBuilder, $translator, $cache, $designPackage,
-            $session, $storeConfig, $frontController, $helperFactory, $dirs, $logger, $filesystem, $data);
-    }
+    protected $_template = 'browser/content/uploader.phtml';
 
     /**
-     * Change upload url in configuration
+     * Prepare layout
      *
-     * @return Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Content_Uploader
+     * @return Mage_Adminhtml_Block_Media_Uploader
      */
-    protected function _construct()
+    protected function _prepareLayout()
     {
-        parent::_construct();
-        $this->getConfig()->setUrl($this->getUrl('*/*/upload', $this->_helperStorage->getRequestParams()));
-        return $this;
+        $this->getConfig()->setUrl(
+            $this->getUrl('*/*/upload', $this->helper('Mage_Theme_Helper_Storage')->getRequestParams())
+        );
+        return parent::_prepareLayout();
     }
 
     /**
@@ -100,6 +58,6 @@ class Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Content_Uploader extends Mage_Adm
      */
     public function getHelperStorage()
     {
-        return $this->_helperStorage;
+        return $this->helper('Mage_Theme_Helper_Storage');
     }
 }
diff --git a/app/code/core/Mage/Theme/Block/Adminhtml/Wysiwyg/Files/Tree.php b/app/code/core/Mage/Theme/Block/Adminhtml/Wysiwyg/Files/Tree.php
index 28226ca61c4829cd1ebf8d9492398b8a42c858dd..656ce3df77ca002a3abf3c3323c63cd9b06a272e 100644
--- a/app/code/core/Mage/Theme/Block/Adminhtml/Wysiwyg/Files/Tree.php
+++ b/app/code/core/Mage/Theme/Block/Adminhtml/Wysiwyg/Files/Tree.php
@@ -31,56 +31,6 @@
  */
 class Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Tree extends Mage_Backend_Block_Template
 {
-    /**
-     * @var Mage_Theme_Helper_Storage
-     */
-    protected $_helperStorage;
-
-    /**
-     * Initialize dependencies
-     *
-     * @param Mage_Core_Controller_Request_Http $request
-     * @param Mage_Core_Model_Layout $layout
-     * @param Mage_Core_Model_Event_Manager $eventManager
-     * @param Mage_Backend_Model_Url $urlBuilder
-     * @param Mage_Core_Model_Translate $translator
-     * @param Mage_Core_Model_Cache $cache
-     * @param Mage_Core_Model_Design_Package $designPackage
-     * @param Mage_Core_Model_Session $session
-     * @param Mage_Core_Model_Store_Config $storeConfig
-     * @param Mage_Core_Controller_Varien_Front $frontController
-     * @param Mage_Core_Model_Factory_Helper $helperFactory
-     * @param Mage_Core_Model_Dir $dirs
-     * @param Mage_Core_Model_Logger $logger
-     * @param Magento_Filesystem $filesystem
-     * @param Mage_Theme_Helper_Storage $helperStorage
-     * @param array $data
-     *
-     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
-     */
-    public function __construct(
-        Mage_Core_Controller_Request_Http $request,
-        Mage_Core_Model_Layout $layout,
-        Mage_Core_Model_Event_Manager $eventManager,
-        Mage_Backend_Model_Url $urlBuilder,
-        Mage_Core_Model_Translate $translator,
-        Mage_Core_Model_Cache $cache,
-        Mage_Core_Model_Design_Package $designPackage,
-        Mage_Core_Model_Session $session,
-        Mage_Core_Model_Store_Config $storeConfig,
-        Mage_Core_Controller_Varien_Front $frontController,
-        Mage_Core_Model_Factory_Helper $helperFactory,
-        Mage_Core_Model_Dir $dirs,
-        Mage_Core_Model_Logger $logger,
-        Magento_Filesystem $filesystem,
-        Mage_Theme_Helper_Storage $helperStorage,
-        array $data = array()
-    ) {
-        $this->_helperStorage = $helperStorage;
-        parent::__construct($request, $layout, $eventManager, $urlBuilder, $translator, $cache, $designPackage,
-            $session, $storeConfig, $frontController, $helperFactory, $dirs, $logger, $filesystem, $data);
-    }
-
     /**
      * Json source URL
      *
@@ -88,7 +38,7 @@ class Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Tree extends Mage_Backend_Block_T
      */
     public function getTreeLoaderUrl()
     {
-        return $this->getUrl('*/*/treeJson', $this->_helperStorage->getRequestParams());
+        return $this->getUrl('*/*/treeJson', $this->helper('Mage_Theme_Helper_Storage')->getRequestParams());
     }
 
     /**
@@ -120,14 +70,14 @@ class Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Tree extends Mage_Backend_Block_T
     public function getTreeCurrentPath()
     {
         $treePath = '/root';
-        $path = $this->_helperStorage->getSession()->getCurrentPath();
+        $path = $this->helper('Mage_Theme_Helper_Storage')->getSession()->getCurrentPath();
         if ($path) {
-            $path = str_replace($this->_helperStorage->getStorageRoot(), '', $path);
+            $path = str_replace($this->helper('Mage_Theme_Helper_Storage')->getStorageRoot(), '', $path);
             $relative = '';
             foreach (explode(DIRECTORY_SEPARATOR, $path) as $dirName) {
                 if ($dirName) {
                     $relative .= DIRECTORY_SEPARATOR . $dirName;
-                    $treePath .= '/' . $this->_helperStorage->urlEncode($relative);
+                    $treePath .= '/' . $this->helper('Mage_Theme_Helper_Storage')->urlEncode($relative);
                 }
             }
         }
diff --git a/app/code/core/Mage/Theme/Helper/Storage.php b/app/code/core/Mage/Theme/Helper/Storage.php
index 24681c73cf677330eaf393b7b921b38ee8bcee71..0e700084007c7473593b87b83cb8ba6d0f35b827 100644
--- a/app/code/core/Mage/Theme/Helper/Storage.php
+++ b/app/code/core/Mage/Theme/Helper/Storage.php
@@ -68,7 +68,6 @@ class Mage_Theme_Helper_Storage extends Mage_Core_Helper_Abstract
      */
     protected $_storageRoot;
 
-
     /**
      * Magento filesystem
      *
diff --git a/app/code/core/Mage/Theme/Model/Uploader/Service.php b/app/code/core/Mage/Theme/Model/Uploader/Service.php
index 4e03e9acc0c2d04f4a8b17ff18b66df386eecf8b..eb156959113ff6e133c52b01236ea119dabc1147 100644
--- a/app/code/core/Mage/Theme/Model/Uploader/Service.php
+++ b/app/code/core/Mage/Theme/Model/Uploader/Service.php
@@ -113,14 +113,14 @@ class Mage_Theme_Model_Uploader_Service extends Mage_Core_Model_Abstract
     /**
      * Upload css file
      *
-     * @param string $type
+     * @param string $file - Key in the $_FILES array
      * @return Mage_Theme_Model_Uploader_Service
      * @throws Mage_Core_Exception
      */
-    public function uploadCssFile($type)
+    public function uploadCssFile($file)
     {
         /** @var $fileUploader Mage_Core_Model_File_Uploader */
-        $fileUploader = Mage::getObjectManager()->get('Mage_Core_Model_File_Uploader', array($type));
+        $fileUploader = Mage::getObjectManager()->get('Mage_Core_Model_File_Uploader', array($file));
         $fileUploader->setAllowedExtensions(array('css'));
         $fileUploader->setAllowRenameFiles(true);
         $fileUploader->setAllowCreateFolders(true);
@@ -140,15 +140,16 @@ class Mage_Theme_Model_Uploader_Service extends Mage_Core_Model_Abstract
     /**
      * Upload js file
      *
-     * @param string $type
+     * @param string $file - Key in the $_FILES array
      * @param Mage_Core_Model_Theme $theme
+     * @param bool $saveAsTmp
      * @return Mage_Theme_Model_Uploader_Service
      * @throws Mage_Core_Exception
      */
-    public function uploadJsFile($type, $theme)
+    public function uploadJsFile($file, $theme, $saveAsTmp = true)
     {
         /** @var $fileUploader Mage_Core_Model_File_Uploader */
-        $fileUploader = Mage::getObjectManager()->get('Mage_Core_Model_File_Uploader', array($type));
+        $fileUploader = Mage::getObjectManager()->get('Mage_Core_Model_File_Uploader', array($file));
         $fileUploader->setAllowedExtensions(array('js'));
         $fileUploader->setAllowRenameFiles(true);
         $fileUploader->setAllowCreateFolders(true);
@@ -164,11 +165,21 @@ class Mage_Theme_Model_Uploader_Service extends Mage_Core_Model_Abstract
         $this->setFilePath($file['tmp_name']);
         $file['content'] = $this->getFileContent();
 
-        $this->_filesJs->saveJsFile($theme, $file, true);
+        $this->_filesJs->saveJsFile($theme, $file, $saveAsTmp);
 
         return $this;
     }
 
+    /**
+     * Get js files object
+     *
+     * @return Mage_Core_Model_Theme_Customization_Files_Js
+     */
+    public function getJsFiles()
+    {
+        return $this->_filesJs;
+    }
+
     /**
      * Get uploaded file content
      *
diff --git a/app/code/core/Mage/Theme/controllers/Adminhtml/System/Design/ThemeController.php b/app/code/core/Mage/Theme/controllers/Adminhtml/System/Design/ThemeController.php
index 673a3d9c4499cc087bf0a2790df348150d2ea9aa..3eb8dd2eaff9dd1ff1fd15b38bc3e532c74ad614 100644
--- a/app/code/core/Mage/Theme/controllers/Adminhtml/System/Design/ThemeController.php
+++ b/app/code/core/Mage/Theme/controllers/Adminhtml/System/Design/ThemeController.php
@@ -82,10 +82,9 @@ class Mage_Theme_Adminhtml_System_Design_ThemeController extends Mage_Adminhtml_
             /** @var $tab Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Tab_Css */
             $tab = $this->getLayout()->getBlock('theme_edit_tabs_tab_css_tab');
             if ($tab && $tab->canShowTab()) {
-                /** @var $helper Mage_Theme_Helper_Data */
-                $helper = $this->_objectManager->get('Mage_Theme_Helper_Data');
-
-                $files = $helper->getCssFiles($theme);
+                /** @var $helper Mage_Core_Helper_Theme */
+                $helper = $this->_objectManager->get('Mage_Core_Helper_Theme');
+                $files = $helper->getGroupedCssFiles($theme);
                 $tab->setFiles($files);
             }
             $this->_setActiveMenu('Mage_Adminhtml::system_design_theme');
@@ -106,20 +105,21 @@ class Mage_Theme_Adminhtml_System_Design_ThemeController extends Mage_Adminhtml_
     public function saveAction()
     {
         $redirectBack = (bool)$this->getRequest()->getParam('back', false);
+        $themeData = $this->getRequest()->getParam('theme');
+        $customCssData = $this->getRequest()->getParam('custom_css_content');
+        $uploadJsFiles = (array)$this->getRequest()->getParam('js_uploaded_files');
+        $removeJsFiles = (array)$this->getRequest()->getParam('js_removed_files');
+        $reorderJsFiles = array_keys($this->getRequest()->getParam('js_order', array()));
+
         /** @var $theme Mage_Core_Model_Theme */
         $theme = $this->_objectManager->create('Mage_Core_Model_Theme');
         /** @var $themeCss Mage_Core_Model_Theme_Customization_Files_Css */
         $themeCss = $this->_objectManager->create('Mage_Core_Model_Theme_Customization_Files_Css');
         /** @var $themeJs Mage_Core_Model_Theme_Customization_Files_Js */
         $themeJs = $this->_objectManager->create('Mage_Core_Model_Theme_Customization_Files_Js');
+
         try {
             if ($this->getRequest()->getPost()) {
-                $themeData = $this->getRequest()->getParam('theme');
-                $customCssData = $this->getRequest()->getParam('custom_css_content');
-                $uploadJsFiles = (array)$this->getRequest()->getParam('js_uploaded_files');
-                $removeJsFiles = (array)$this->getRequest()->getParam('js_removed_files');
-                $reorderJsFiles = array_keys($this->getRequest()->getParam('js_order', array()));
-
                 $themeCss->setDataForSave($customCssData);
                 $theme->setCustomization($themeCss);
 
@@ -129,7 +129,6 @@ class Mage_Theme_Adminhtml_System_Design_ThemeController extends Mage_Adminhtml_
                 $theme->setCustomization($themeJs);
 
                 $theme->saveFormData($themeData);
-
                 $this->_getSession()->addSuccess($this->__('The theme has been saved.'));
             }
         } catch (Mage_Core_Exception $e) {
@@ -156,11 +155,11 @@ class Mage_Theme_Adminhtml_System_Design_ThemeController extends Mage_Adminhtml_
                 /** @var $theme Mage_Core_Model_Theme */
                 $theme = $this->_objectManager->create('Mage_Core_Model_Theme')->load($themeId);
                 if (!$theme->getId()) {
-                    throw new InvalidArgumentException($this->__('Theme with id "%d" is not found.', $themeId));
+                    throw new InvalidArgumentException(sprintf('Theme with id "%d" is not found.', $themeId));
                 }
                 if (!$theme->isVirtual()) {
                     throw new InvalidArgumentException(
-                        $this->__('Only virtual theme is possible to delete.', $themeId)
+                        sprintf('Only virtual theme is possible to delete and theme "%s" isn\'t virtual', $themeId)
                     );
                 }
                 $theme->delete();
@@ -275,26 +274,26 @@ class Mage_Theme_Adminhtml_System_Design_ThemeController extends Mage_Adminhtml_
         $themeId = $this->getRequest()->getParam('theme_id');
         $file = $this->getRequest()->getParam('file');
 
-        /** @var $helper Mage_Theme_Helper_Data */
-        $helper = $this->_objectManager->get('Mage_Theme_Helper_Data');
+        /** @var $helper Mage_Core_Helper_Theme */
+        $helper = $this->_objectManager->get('Mage_Core_Helper_Theme');
         $fileName = $helper->urlDecode($file);
         try {
             /** @var $theme Mage_Core_Model_Theme */
             $theme = $this->_objectManager->create('Mage_Core_Model_Theme')->load($themeId);
             if (!$theme->getId()) {
-                throw new InvalidArgumentException($this->__('Theme with id "%d" is not found.', $themeId));
+                throw new InvalidArgumentException(sprintf('Theme with id "%d" is not found.', $themeId));
             }
 
             $themeCss = $helper->getCssFiles($theme);
             if (!isset($themeCss[$fileName])) {
                 throw new InvalidArgumentException(
-                    $this->__('Css file "%s" is not in the theme with id "%d".', $fileName, $themeId)
+                    sprintf('Css file "%s" is not in the theme with id "%d".', $fileName, $themeId)
                 );
             }
 
             $this->_prepareDownloadResponse($fileName, array(
                 'type'  => 'filename',
-                'value' => $themeCss[$fileName]
+                'value' => $themeCss[$fileName]['path']
             ));
         } catch (Exception $e) {
             $this->_getSession()->addException($e, $this->__('File "%s" is not found.', $fileName));
diff --git a/app/code/core/Mage/Theme/controllers/Adminhtml/System/Design/Wysiwyg/FilesController.php b/app/code/core/Mage/Theme/controllers/Adminhtml/System/Design/Wysiwyg/FilesController.php
index 3e0777a96efef4bf00214df1d946eda96c81d340..0ec9e25bf5b1ec12a2f915dac665ac47811302e9 100644
--- a/app/code/core/Mage/Theme/controllers/Adminhtml/System/Design/Wysiwyg/FilesController.php
+++ b/app/code/core/Mage/Theme/controllers/Adminhtml/System/Design/Wysiwyg/FilesController.php
@@ -148,7 +148,7 @@ class Mage_Theme_Adminhtml_System_Design_Wysiwyg_FilesController extends Mage_Ad
     {
         try {
             if (!$this->getRequest()->isPost()) {
-                throw new Exception ('Wrong request.');
+                throw new Exception('Wrong request');
             }
             $files = $this->_objectManager->get('Mage_Core_Helper_Data')->jsonDecode(
                 $this->getRequest()->getParam('files')
diff --git a/app/code/core/Mage/Theme/view/adminhtml/tabs/fieldset/js_items.phtml b/app/code/core/Mage/Theme/view/adminhtml/tabs/fieldset/js_items.phtml
index d4f696d99c1a06230024e3139bb1655748759e35..87a03ea48cbb255d9cafdf567bf9fb15eca168da 100644
--- a/app/code/core/Mage/Theme/view/adminhtml/tabs/fieldset/js_items.phtml
+++ b/app/code/core/Mage/Theme/view/adminhtml/tabs/fieldset/js_items.phtml
@@ -32,7 +32,7 @@
         <li>
             <input class="up" type="button" value="">
             <input class="down" type="button" value="">
-            <input type="hidden" name="js_order[<?php echo $file->getFileName() ?>]" value="1">
+            <input type="hidden" name="js_order[<?php echo $file->getId() ?>]" value="1">
             <div class="js-file">
                 <?php echo $file->getFileName() ?>
                 <div class="remove-js">
diff --git a/app/code/core/Mage/User/Model/User.php b/app/code/core/Mage/User/Model/User.php
index c2e00e33b42a383f78d0e4136318d957b8a2e6d2..f2381d8301defc326eb70c21e8580e1d3c5231ef 100644
--- a/app/code/core/Mage/User/Model/User.php
+++ b/app/code/core/Mage/User/Model/User.php
@@ -61,7 +61,6 @@
 
 /**
  * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
- * @SuppressWarnings(PHPMD.couplingBetweenObjects)
  */
 class Mage_User_Model_User
     extends Mage_Core_Model_Abstract
diff --git a/app/code/core/Mage/User/view/adminhtml/admin/forgotpassword.phtml b/app/code/core/Mage/User/view/adminhtml/admin/forgotpassword.phtml
index 376932092cca7da0e676decfdea44d6d8fe5154e..a6d47db27a7d835daa82b1b0b62c255a9a6a336a 100644
--- a/app/code/core/Mage/User/view/adminhtml/admin/forgotpassword.phtml
+++ b/app/code/core/Mage/User/view/adminhtml/admin/forgotpassword.phtml
@@ -43,7 +43,7 @@
 
     <script src="<?php echo $this->getViewFileUrl('jquery/jquery.min.js') ?>"></script>
     <script src="<?php echo $this->getViewFileUrl('mage/jquery-no-conflict.js') ?>"></script>
-    <script src="<?php echo $this->getViewFileUrl('jquery/jquery-ui.custom.min.js') ?>"></script>
+    <script src="<?php echo $this->getViewFileUrl('jquery/jquery-ui.js') ?>"></script>
     <script src="<?php echo $this->getViewFileUrl('jquery/jquery.tmpl.min.js') ?>"></script>
     <script src="<?php echo $this->getViewFileUrl('jquery/jquery.validate.js') ?>"></script>
     <script src="<?php echo $this->getViewFileUrl('mage/validation.js') ?>"></script>
diff --git a/app/code/core/Mage/User/view/adminhtml/admin/resetforgottenpassword.phtml b/app/code/core/Mage/User/view/adminhtml/admin/resetforgottenpassword.phtml
index 78b5316ebdd3b0562f16b68915a89ddc3ff17070..dd72e12d35d5842a24029d967b1214b30fed3a10 100644
--- a/app/code/core/Mage/User/view/adminhtml/admin/resetforgottenpassword.phtml
+++ b/app/code/core/Mage/User/view/adminhtml/admin/resetforgottenpassword.phtml
@@ -42,7 +42,7 @@
 
     <script src="<?php echo $this->getViewFileUrl('jquery/jquery.min.js') ?>"></script>
     <script src="<?php echo $this->getViewFileUrl('mage/jquery-no-conflict.js') ?>"></script>
-    <script src="<?php echo $this->getViewFileUrl('jquery/jquery-ui.custom.min.js') ?>"></script>
+    <script src="<?php echo $this->getViewFileUrl('jquery/jquery-ui.js') ?>"></script>
     <script src="<?php echo $this->getViewFileUrl('jquery/jquery.tmpl.min.js') ?>"></script>
     <script src="<?php echo $this->getViewFileUrl('jquery/jquery.validate.js') ?>"></script>
     <script src="<?php echo $this->getViewFileUrl('mage/validation.js') ?>"></script>
diff --git a/app/code/core/Mage/Webapi/Helper/Data.php b/app/code/core/Mage/Webapi/Helper/Data.php
index a9aa45f94a597c6b66228c827f9a55e0c880d675..0a5eb6fad39152d8c7f716cb7c68bd787972d586 100644
--- a/app/code/core/Mage/Webapi/Helper/Data.php
+++ b/app/code/core/Mage/Webapi/Helper/Data.php
@@ -31,12 +31,12 @@ class Mage_Webapi_Helper_Data extends Mage_Core_Helper_Abstract
     protected $_configHelper;
 
     /**
-     * Initialize dependencies.
-     *
      * @param Mage_Webapi_Helper_Config $configHelper
+     * @param Mage_Core_Model_Translate $translator
      */
-    public function __construct(Mage_Webapi_Helper_Config $configHelper)
+    public function __construct(Mage_Webapi_Helper_Config $configHelper, Mage_Core_Model_Translate $translator)
     {
+        parent::__construct($translator);
         $this->_configHelper = $configHelper;
     }
 
diff --git a/app/code/core/Mage/Webapi/Model/Authorization/Config.php b/app/code/core/Mage/Webapi/Model/Authorization/Config.php
index 56aabdf35c10620b92d8ac3d08287bb5429f4097..7d3ff55b8bc9efbb3d1a85909ab4971decc3a62a 100644
--- a/app/code/core/Mage/Webapi/Model/Authorization/Config.php
+++ b/app/code/core/Mage/Webapi/Model/Authorization/Config.php
@@ -31,9 +31,11 @@ class Mage_Webapi_Model_Authorization_Config implements Mage_Core_Model_Acl_Conf
     const ACL_VIRTUAL_RESOURCES_XPATH = '/config/mapping/*';
 
     /**
-     * @var Mage_Core_Model_Config
+     * Module configuration reader
+     *
+     * @var Mage_Core_Model_Config_Modules_Reader
      */
-    protected $_config;
+    protected $_moduleReader;
 
     /**
      * @var Magento_Acl_Config_Reader
@@ -46,13 +48,14 @@ class Mage_Webapi_Model_Authorization_Config implements Mage_Core_Model_Acl_Conf
     protected $_readerFactory;
 
     /**
-     * @param Mage_Core_Model_Config $config
+     * @param Mage_Core_Model_Config_Modules_Reader $moduleReader
      * @param Mage_Webapi_Model_Authorization_Config_Reader_Factory $readerFactory
      */
-    public function __construct(Mage_Core_Model_Config $config,
+    public function __construct(
+        Mage_Core_Model_Config_Modules_Reader $moduleReader,
         Mage_Webapi_Model_Authorization_Config_Reader_Factory $readerFactory
     ) {
-        $this->_config = $config;
+        $this->_moduleReader = $moduleReader;
         $this->_readerFactory = $readerFactory;
     }
 
@@ -63,7 +66,7 @@ class Mage_Webapi_Model_Authorization_Config implements Mage_Core_Model_Acl_Conf
      */
     protected function _getAclResourceFiles()
     {
-        $files = $this->_config->getModuleConfigurationFiles('webapi' . DIRECTORY_SEPARATOR . 'acl.xml');
+        $files = $this->_moduleReader->getModuleConfigurationFiles('webapi' . DIRECTORY_SEPARATOR . 'acl.xml');
         return (array)$files;
     }
 
@@ -76,7 +79,7 @@ class Mage_Webapi_Model_Authorization_Config implements Mage_Core_Model_Acl_Conf
     {
         if (is_null($this->_reader)) {
             $aclResourceFiles = $this->_getAclResourceFiles();
-            $this->_reader = $this->_readerFactory->createReader(array('configFiles' => $aclResourceFiles));
+            $this->_reader = $this->_readerFactory->createReader(array('configFiles'  => $aclResourceFiles));
         }
         return $this->_reader;
     }
diff --git a/app/code/core/Mage/Weee/Model/Observer.php b/app/code/core/Mage/Weee/Model/Observer.php
index c32d0087716d63db568f46e16efdd499b3a18d06..b31d9c71c70dae1d2bb41bc5c92cfc50dfcc1fe6 100644
--- a/app/code/core/Mage/Weee/Model/Observer.php
+++ b/app/code/core/Mage/Weee/Model/Observer.php
@@ -153,7 +153,7 @@ class Mage_Weee_Model_Observer extends Mage_Core_Model_Abstract
     {
         $response = $observer->getEvent()->getResponse();
         $types    = $response->getTypes();
-        $types['weee'] = Mage::getConfig()->getBlockClassName('Mage_Weee_Block_Element_Weee_Tax');
+        $types['weee'] = 'Mage_Weee_Block_Element_Weee_Tax';
         $response->setTypes($types);
         return $this;
     }
diff --git a/app/code/core/Mage/Weee/view/frontend/layout.xml b/app/code/core/Mage/Weee/view/frontend/layout.xml
index cb8ba9c221f9715d233db8aa3178dada480185b4..dafe698c0a012657cd094e712f826f921a39aefc 100644
--- a/app/code/core/Mage/Weee/view/frontend/layout.xml
+++ b/app/code/core/Mage/Weee/view/frontend/layout.xml
@@ -29,7 +29,7 @@
 <layout version="0.1.0">
     <default>
         <reference name="head">
-            <action method="addJs"><file>Mage_Weee::tax_toggle.js</file></action>
+            <action method="addJs"><file>Mage_Weee::tax-toggle.js</file></action>
         </reference>
     </default>
 </layout>
\ No newline at end of file
diff --git a/app/code/core/Mage/Weee/view/frontend/tax-toggle.js b/app/code/core/Mage/Weee/view/frontend/tax-toggle.js
new file mode 100644
index 0000000000000000000000000000000000000000..a106d1b09d6076687e9ebb137b66d2576bd04c4b
--- /dev/null
+++ b/app/code/core/Mage/Weee/view/frontend/tax-toggle.js
@@ -0,0 +1,50 @@
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Varien
+ * @package     js
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+/*jshint browser:true jquery:true*/
+(function($) {
+    "use strict";
+    $(function() {
+        $('body').on('click', '[data-tax-toggle]', function() {
+            var currElem = $(this),
+                args = currElem.data("tax-toggle"),
+                expandedClassName = args.expandedClassName ? args.expandedClassName : 'cart-tax-total-expanded';
+            currElem.toggleClass(expandedClassName);
+            $(args.itemTaxId).toggle();
+        });
+    });
+})(jQuery);
+
+/**
+ * NEED TO REMOVE this function once all the references of taxToggle are removed
+ */
+function taxToggle(details, switcher, expandedClassName) {
+    if ($(details).style.display == 'none') {
+        $(details).show();
+        $(switcher).addClassName(expandedClassName);
+    } else {
+        $(details).hide();
+        $(switcher).removeClassName(expandedClassName);
+    }
+}
diff --git a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main/Layout.php b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main/Layout.php
index 45f685cfe3f11ab32c790268f7e853a4b41597f6..56082ba27a2415c44bc3b266e2888c054deaea95 100644
--- a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main/Layout.php
+++ b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main/Layout.php
@@ -263,7 +263,7 @@ class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Main_Layout
             ->setData(array(
                 'label'     => Mage::helper('Mage_Widget_Helper_Data')->__('Add Layout Update'),
                 'onclick'   => 'WidgetInstance.addPageGroup({})',
-                'class'     => 'add'
+                'class'     => 'action-add'
             ));
         return $button->toHtml();
     }
@@ -279,7 +279,7 @@ class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Main_Layout
             ->setData(array(
                 'label'     => $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('Remove Layout Update')),
                 'onclick'   => 'WidgetInstance.removePageGroup(this)',
-                'class'     => 'delete'
+                'class'     => 'action-delete'
             ));
         return $button->toHtml();
     }
diff --git a/app/code/core/Mage/Widget/Model/Widget.php b/app/code/core/Mage/Widget/Model/Widget.php
index 9de67fbc5fadaf4a801b7d67a4b8a3df3cf310cc..402719de0ad48bf17faa595e886eb14f49c765cb 100644
--- a/app/code/core/Mage/Widget/Model/Widget.php
+++ b/app/code/core/Mage/Widget/Model/Widget.php
@@ -46,7 +46,8 @@ class Mage_Widget_Model_Widget extends Varien_Object
         } else {
             $config = new Varien_Simplexml_Config();
             $config->loadString('<?xml version="1.0"?><widgets></widgets>');
-            Mage::getConfig()->loadModulesConfiguration('widget.xml', $config);
+            Mage::getSingleton('Mage_Core_Model_Config_Modules_Reader')
+                ->loadModulesConfiguration('widget.xml', $config);
             $xmlConfig = $config;
             if (Mage::app()->useCache('config')) {
                 Mage::app()->saveCache($config->getXmlString(), 'widget_config',
diff --git a/app/code/core/Mage/Widget/view/adminhtml/instance/edit/layout.phtml b/app/code/core/Mage/Widget/view/adminhtml/instance/edit/layout.phtml
index 32ad397e4861f6e4acecbadf093e8b6b9f5a872a..36fbd4b630ee9b9f253ea73115da68fbf50c9307 100644
--- a/app/code/core/Mage/Widget/view/adminhtml/instance/edit/layout.phtml
+++ b/app/code/core/Mage/Widget/view/adminhtml/instance/edit/layout.phtml
@@ -24,48 +24,45 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 ?>
-<div class="entry-edit-head">
-    <h4><?php echo Mage::helper('Mage_Widget_Helper_Data')->__('Layout Updates') ?></h4>
-    <div class="right"><?php echo $this->getAddLayoutButtonHtml() ?></div>
-</div>
-<div class="fieldset">
-    <div class="hor-scroll">
-            <div id="page_group_container"></div>
+<fieldset class="fieldset">
+    <legend class="legend"><span><?php echo Mage::helper('Mage_Widget_Helper_Data')->__('Layout Updates') ?></span></legend>
+    <br />
+    <div class="widget-layout-updates">
+        <div id="page_group_container"></div>
+        <div class="actions"><?php echo $this->getAddLayoutButtonHtml() ?></div>
     </div>
-</div>
+</fieldset>
 <script type="text/javascript">
 //<![CDATA[
 
-var pageGroupTemplate = '<div class="options-box page_group_container" id="page_group_container_{{id}}">'+
-    '<div class="option-box">'+
-        '<div class="option-title">'+
-            <?php echo Mage::helper('Mage_Core_Helper_Data')->jsonEncode($this->getRemoveLayoutButtonHtml()) ?> +
-            '<label for="widget_instance[{{id}}][page_group]">Display On <span class="required">*</span></label>'+
-            '<?php echo $this->getDisplayOnSelectHtml(); ?>'+
+var pageGroupTemplate = '<div class="fieldset-wrapper page_group_container" id="page_group_container_{{id}}">'+
+    '<div class="fieldset-wrapper-title">'+
+        '<label for="widget_instance[{{id}}][page_group]">Display on <span class="required">*</span></label>'+
+        '<?php echo $this->getDisplayOnSelectHtml(); ?>'+
+        '<div class="actions">'+
+        <?php echo Mage::helper('Mage_Core_Helper_Data')->jsonEncode($this->getRemoveLayoutButtonHtml()) ?> +
         '</div>'+
+    '</div>'+
+    '<div class="fieldset-wrapper-content">'+
 <?php foreach ($this->getDisplayOnContainers() as $container): ?>
     '<div class="no-display <?php echo $container['code'] ?> group_container" id="<?php echo $container['name'] ?>_{{id}}">'+
         '<input type="hidden" class="container_name" name="__[container_name]" value="widget_instance[{{id}}][<?php echo $container['name'] ?>]" />'+
         '<input type="hidden" name="widget_instance[{{id}}][<?php echo $container['name'] ?>][page_id]" value="{{page_id}}" />'+
         '<input type="hidden" class="layout_handle_pattern" name="widget_instance[{{id}}][<?php echo $container['name'] ?>][layout_handle]" value="<?php echo $container['layout_handle'] ?>" />'+
-        '<table cellspacing="0" class="option-header">'+
+        '<table cellspacing="0" class="data-table">'+
             '<col width="200" />'+
-            '<col width="220" />'+
-            '<col width="320" />'+
-            '<col />'+
             '<thead>'+
                 '<tr>'+
                     '<th><label><?php echo $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('%s', $container['label'])) ?></label></th>'+
                     '<th><label><?php echo $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('Container')) ?> <span class="required">*</span></label></th>'+
                     '<th><label><?php echo $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('Template')) ?></label></th>'+
-                    '<th>&nbsp;</th>'+
                 '</tr>'+
             '</thead>'+
             '<tbody>'+
                 '<tr>'+
                     '<td>'+
                         '<input type="radio" class="radio for_all" id="all_<?php echo $container['name'] ?>_{{id}}" name="widget_instance[{{id}}][<?php echo $container['name'] ?>][for]" value="all" onclick="WidgetInstance.togglePageGroupChooser(this)" checked="checked" />&nbsp;'+
-                        '<label for="all_<?php echo $container['name'] ?>_{{id}}"><?php echo $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('All')) ?></label>&nbsp;&nbsp;&nbsp;'+
+                        '<label for="all_<?php echo $container['name'] ?>_{{id}}"><?php echo $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('All')) ?></label><br />'+
                         '<input type="radio" class="radio for_specific" id="specific_<?php echo $container['name'] ?>_{{id}}" name="widget_instance[{{id}}][<?php echo $container['name'] ?>][for]" value="specific" onclick="WidgetInstance.togglePageGroupChooser(this)" />&nbsp;'+
                         '<label for="specific_<?php echo $container['name'] ?>_{{id}}"><?php echo $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('Specific %s', $container['label'])) ?></label>'+
                     '</td>'+
@@ -88,10 +85,10 @@ var pageGroupTemplate = '<div class="options-box page_group_container" id="page_
             '<p>' +
                 '<input type="text" class="input-text entities" name="widget_instance[{{id}}][<?php echo $container['name'] ?>][entities]" value="{{<?php echo $container['name'] ?>_entities}}" readonly="readonly" />&nbsp;' +
                 '<a class="widget-option-chooser" href="javascript:void(0)" onclick="WidgetInstance.displayEntityChooser(\'<?php echo $container['code'] ?>\', \'<?php echo $container['name'] ?>_ids_{{id}}\')"  title="<?php echo $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('Open Chooser')) ?>">' +
-                    '<img src="<?php echo Mage::getDesign()->getViewFileUrl('images/rule_chooser_trigger.gif') ?>" class="v-middle" alt="<?php echo $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('Open Chooser')); ?>" />' +
+                    '<img src="<?php echo Mage::getDesign()->getViewFileUrl('images/rule_chooser_trigger.gif') ?>" alt="<?php echo $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('Open Chooser')); ?>" />' +
                 '</a>&nbsp;' +
                 '<a href="javascript:void(0)" onclick="WidgetInstance.hideEntityChooser(\'<?php echo $container['name'] ?>_ids_{{id}}\')" title="<?php echo $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('Apply')); ?>">' +
-                    '<img src="<?php echo Mage::getDesign()->getViewFileUrl('images/rule_component_apply.gif') ?>" class="v-middle" alt="<?php echo $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('Apply')); ?>" />' +
+                    '<img src="<?php echo Mage::getDesign()->getViewFileUrl('images/rule_component_apply.gif') ?>" alt="<?php echo $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('Apply')); ?>" />' +
                 '</a>' +
             '</p>'+
             '<div class="chooser"></div>'+
@@ -103,10 +100,8 @@ var pageGroupTemplate = '<div class="options-box page_group_container" id="page_
     '<input type="hidden" name="widget_instance[{{id}}][all_pages][page_id]" value="{{page_id}}" />'+
     '<input type="hidden" class="layout_handle_pattern" name="widget_instance[{{id}}][all_pages][layout_handle]" value="default" />'+
     '<input type="hidden" class="for_all" name="widget_instance[{{id}}][all_pages][for]" value="all" />'+
-    '<table cellspacing="0" class="option-header">'+
-        '<col width="220" />'+
-        '<col width="320" />'+
-        '<col />'+
+    '<table cellspacing="0" class="data-table">'+
+        '<col width="200" />'+
         '<thead>'+
             '<tr>'+
                 '<th><label><?php echo $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('Container')) ?> <span class="required">*</span></label></th>'+
@@ -135,17 +130,13 @@ var pageGroupTemplate = '<div class="options-box page_group_container" id="page_
     '<input type="hidden" class="container_name" name="__[container_name]" value="widget_instance[{{id}}][pages]" />'+
     '<input type="hidden" name="widget_instance[{{id}}][pages][page_id]" value="{{page_id}}" />'+
     '<input type="hidden" class="for_all" name="widget_instance[{{id}}][pages][for]" value="all" />'+
-    '<table cellspacing="0" class="option-header">'+
+    '<table cellspacing="0" class="data-table">'+
         '<col width="200" />'+
-        '<col width="220" />'+
-        '<col width="320" />'+
-        '<col />'+
         '<thead>'+
             '<tr>'+
                 '<th><label><?php echo $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('Page')) ?> <span class="required">*</span></label></th>'+
                 '<th><label><?php echo $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('Container')) ?> <span class="required">*</span></label></th>'+
                 '<th><label><?php echo $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('Template')) ?></label></th>'+
-                '<th>&nbsp;</th>'+
             '</tr>'+
         '</thead>'+
         '<tbody>'+
@@ -194,7 +185,7 @@ var WidgetInstance = {
                 }
             }
             pageGroupTemplateObj = new Template(this.pageGroupTemplate, this.templatePattern);
-            Element.insert(pageGroupContainer, {'top':pageGroupTemplateObj.evaluate(data)});
+            Element.insert(pageGroupContainer, {'bottom':pageGroupTemplateObj.evaluate(data)});
             if (data.group) {
                 pageGroup = $(data.group+'_'+data.id);
                 additional = {};
@@ -263,6 +254,7 @@ var WidgetInstance = {
         if (container) {
             container.removeClassName('no-display');
             container.removeClassName('ignore-validate');
+            container.up('.fieldset-wrapper').addClassName('opened');
             container.show();
         }
     },
diff --git a/app/code/core/Mage/Wishlist/view/frontend/cart.js b/app/code/core/Mage/Wishlist/view/frontend/cart.js
deleted file mode 100644
index e9a04c65420bff73cd21cd562d12575a4fbfffbc..0000000000000000000000000000000000000000
--- a/app/code/core/Mage/Wishlist/view/frontend/cart.js
+++ /dev/null
@@ -1,127 +0,0 @@
-/**
- * Magento
- *
- * NOTICE OF LICENSE
- *
- * This source file is subject to the Academic Free License (AFL 3.0)
- * that is bundled with this package in the file LICENSE_AFL.txt.
- * It is also available through the world-wide-web at this URL:
- * http://opensource.org/licenses/afl-3.0.php
- * If you did not receive a copy of the license and are unable to
- * obtain it through the world-wide-web, please send an email
- * to license@magentocommerce.com so we can send you a copy immediately.
- *
- * DISCLAIMER
- *
- * Do not edit or add to this file if you wish to upgrade Magento to newer
- * versions in the future. If you wish to customize Magento for your
- * needs please refer to http://www.magentocommerce.com for more information.
- *
- * @category    frontend product msrp
- * @package     mage
- * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
- * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
- */
-
-/*jshint browser:true jquery:true*/
-(function($, window) {
-    "use strict";
-    $.widget('mage.addWishListToCart', {
-
-        options: {
-            dataAttribute: 'item-id',
-            nameFormat: 'qty[{0}]',
-            wishListFormSelector: '#wishlist-view-form',
-            btnRemoveSelector: '.btn-remove',
-            qtySelector: '.qty',
-            addToCartSelector: '.btn-cart',
-            addAllToCartSelector: '.btn-add',
-            commentInputType: 'textarea'
-        },
-
-        /**
-         * Bind handlers to events
-         */
-        _create: function() {
-            $(this.options.wishListFormSelector)
-                .on('submit', $.proxy(this._addItemsToCart, this))
-                .on('click', this.options.addToCartSelector, $.proxy(this._addItemsToCart, this))
-                .on('click', this.options.btnRemoveSelector, $.proxy(this._confirmRemoveWishlistItem, this))
-                .on('click', this.options.addAllToCartSelector, $.proxy(this._addAllWItemsToCart, this))
-                .on('focusin focusout', this.options.commentInputType, $.proxy(this._focusComment, this));
-        },
-
-        /**
-         * Validate and Redirect
-         * @private
-         * @param {string} url
-         */
-        _validateAndRedirect: function(url) {
-            if ($(this.options.wishListFormSelector).validation({
-                errorPlacement: function(error, element) {
-                    error.insertAfter(element.next());
-                }
-            }).valid()) {
-                $(this.options.wishListFormSelector).prop('action', url);
-                window.location.href = url;
-            }
-        },
-
-        /**
-         * Add items to cart
-         * @private
-         * @param {event} e
-         */
-        _addItemsToCart: function() {
-            $(this.options.addToCartSelector).each($.proxy(function(index, element) {
-                if ($(element).data(this.options.dataAttribute)) {
-                    var itemId = $(element).data(this.options.dataAttribute),
-                        url = this.options.addToCartUrl.replace('%item%', itemId),
-                        inputName = $.validator.format(this.options.nameFormat, itemId),
-                        inputValue = $(this.options.wishListFormSelector).find('[name="' + inputName + '"]').val(),
-                        separator = (url.indexOf('?') >= 0) ? '&' : '?';
-                    url += separator + inputName + '=' + encodeURIComponent(inputValue);
-                    this._validateAndRedirect(url);
-                    return;
-                }
-            }, this));
-        },
-
-        /**
-         * Confirmation window for removing wish list item
-         * @private
-         */
-        _confirmRemoveWishlistItem: function() {
-            return window.confirm(this.options.confirmRemoveMessage);
-        },
-
-        /**
-         * Add all wish list items to cart
-         * @private
-         */
-        _addAllWItemsToCart: function() {
-            var url = this.options.addAllToCartUrl;
-            var separator = (url.indexOf('?') >= 0) ? '&' : '?';
-            $(this.options.wishListFormSelector).find(this.options.qtySelector).each(
-                function(index, elem) {
-                    url += separator + $(elem).prop('name') + '=' + encodeURIComponent($(elem).val());
-                    separator = '&';
-                }
-            );
-
-            this._validateAndRedirect(url);
-        },
-
-        /**
-         * Toggle comment string
-         * @private
-         * @param {event} e
-         */
-        _focusComment: function(e) {
-            var commentInput = e.currentTarget;
-            if (commentInput.value === '' || commentInput.value === this.options.commentString) {
-                commentInput.value = commentInput.value === this.options.commentString ? '' : this.options.commentString;
-            }
-        }
-    });
-})(jQuery, window);
diff --git a/app/code/core/Mage/Wishlist/view/frontend/item/column/cart.phtml b/app/code/core/Mage/Wishlist/view/frontend/item/column/cart.phtml
index 8aaf043c9202e062e17d5e52a5a3c386125e67f4..570262ebd741773d68c91d6ca638aa9705b857c8 100644
--- a/app/code/core/Mage/Wishlist/view/frontend/item/column/cart.phtml
+++ b/app/code/core/Mage/Wishlist/view/frontend/item/column/cart.phtml
@@ -36,40 +36,24 @@ $options = $this->getChildBlock('customer.wishlist.item.options')
     <?php echo $this->getPriceHtml($product, empty($options));?>
     <div class="add-to-cart-alt">
         <?php if ($item->canHaveQty() && $item->getProduct()->isVisibleInSiteVisibility()): ?>
-        <input type="text" class="input-text qty" data-validate="{'validate-greater-than-zero':true}" name="qty[<?php echo $item->getId() ?>]"
-            value="<?php echo $this->getAddToCartQty($item) * 1 ?>"/>
+            <input type="text" class="input-text qty" data-validate="{required:true,'validate-greater-than-zero':true}" name="qty[<?php echo $item->getId() ?>]"
+                   value="<?php echo $this->getAddToCartQty($item) * 1 ?>"/>
         <?php endif; ?>
         <?php if ($product->isSaleable()): ?>
-        <button type="button" title="<?php echo $this->__('Add to Cart') ?>" data-item-id="<?php echo $item->getId()?>" class="button btn-cart"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
+            <button type="button" title="<?php echo $this->__('Add to Cart') ?>" data-item-id="<?php echo $item->getId()?>" class="button btn-cart"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
         <?php else: ?>
             <?php if ($product->getIsSalable()): ?>
-            <p class="availability in-stock"><span><?php echo $this->__('In stock') ?></span></p>
+                <p class="availability in-stock"><span><?php echo $this->__('In stock') ?></span></p>
             <?php else: ?>
-            <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
+                <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
             <?php endif; ?>
         <?php endif; ?>
     </div>
     <?php foreach ($this->getChildNames() as $childName): ?>
-    <?php echo $this->getLayout()->renderElement($childName, false); ?>
+        <?php echo $this->getLayout()->renderElement($childName, false); ?>
     <?php endforeach;?>
     <?php if ($product->isVisibleInSiteVisibility()): ?>
-    <p><a class="link-edit" href="<?php echo $this->getItemConfigureUrl($item) ?>"><?php echo $this->__('Edit') ?></a>
+        <p><a class="link-edit" href="<?php echo $this->getItemConfigureUrl($item) ?>"><?php echo $this->__('Edit') ?></a>
     </p>
     <?php endif ?>
 </div>
-<script>
-    (function($) {
-        head.js("<?php echo $this->getViewFileUrl('jquery/jquery.validate.js')?>",
-            "<?php echo $this->getViewFileUrl('jquery/jquery.metadata.js')?>",
-            "<?php echo $this->getViewFileUrl('mage/validation.js')?>",
-            "<?php echo $this->getViewFileUrl('mage/validation/validation.js')?>",
-            "<?php echo $this->getViewFileUrl('Mage_Wishlist::cart.js')?>", function() {
-            $.mage.addWishListToCart({
-                addToCartUrl: '<?php echo $this->getItemAddToCartUrl('%item%');?>' ,
-                confirmRemoveMessage: '<?php echo $this->__('Are you sure you want to remove this product from your wishlist?') ?>',
-                addAllToCartUrl : '<?php echo $this->getUrl('*/*/allcart', array('wishlist_id' => $this->getWishlistInstance()->getId())) ?>',
-                commentString : '<?php echo $this->helper('Mage_Wishlist_Helper_Data')->defaultCommentString()?>'
-            });
-        });
-    })(jQuery);
-</script>
diff --git a/app/code/core/Mage/Wishlist/view/frontend/item/list.phtml b/app/code/core/Mage/Wishlist/view/frontend/item/list.phtml
index 08cd2a3644c7b8e9cdd4050d3a9c371b29bfd584..a675b20e1a1d00e7e46a52c69d841c554e8c427e 100644
--- a/app/code/core/Mage/Wishlist/view/frontend/item/list.phtml
+++ b/app/code/core/Mage/Wishlist/view/frontend/item/list.phtml
@@ -53,11 +53,5 @@
     <?php echo $column->getAdditionalHtml();?>
 <?php endforeach; ?>
 <script type="text/javascript">
-//<![CDATA[
-    (function($) {$('#wishlist-table').decorate('table')})(jQuery);
-
-<?php foreach ($columns as $column): ?>
-    <?php echo $column->getJs();?>
-<?php endforeach; ?>
-//]]>
-</script>
+    jQuery('#wishlist-table').decorate('table');
+</script>
\ No newline at end of file
diff --git a/app/code/core/Mage/Wishlist/view/frontend/js/search.js b/app/code/core/Mage/Wishlist/view/frontend/js/search.js
new file mode 100644
index 0000000000000000000000000000000000000000..7d0d872e84a3052626765d6db35085454829775e
--- /dev/null
+++ b/app/code/core/Mage/Wishlist/view/frontend/js/search.js
@@ -0,0 +1,57 @@
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    frontend wishlist search
+ * @package     mage
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+
+/*jshint browser:true jquery:true*/
+(function($) {
+    "use strict";
+    $.widget('mage.wishlistSearch', {
+
+        /**
+         * Bind handlers to events
+         */
+        _create: function() {
+            this.element.on('change', $.proxy(this._toggleForm, this));
+        },
+
+        /**
+         * Toggle Form
+         * @private
+         */
+        _toggleForm: function() {
+            switch (this.element.val()) {
+                case 'name':
+                    $(this.options.emailFormSelector).hide();
+                    $(this.options.nameFormSelector).show();
+                    break;
+                case 'email':
+                    $(this.options.nameFormSelector).hide();
+                    $(this.options.emailFormSelector).show();
+                    break;
+                default:
+                    $(this.options.emailFormSelector).add(this.options.nameFormSelector).hide();
+            }
+        }
+    });
+})(jQuery);
diff --git a/app/code/core/Mage/Wishlist/view/frontend/sharing.phtml b/app/code/core/Mage/Wishlist/view/frontend/sharing.phtml
index c3689b846f4a8f70d9eaf0446805416e9bbf94bc..32edd795d01203f3cca4ef0c4aa209ea76994bb5 100644
--- a/app/code/core/Mage/Wishlist/view/frontend/sharing.phtml
+++ b/app/code/core/Mage/Wishlist/view/frontend/sharing.phtml
@@ -36,7 +36,7 @@
             <li class="wide">
                 <label for="email_address" class="required"><em>*</em><?php echo $this->__('Email addresses, separated by commas') ?></label>
                 <div class="input-box">
-                    <textarea name="emails" cols="60" rows="5" id="email_address" class="validate-emails required-entry"><?php echo $this->getEnteredData('emails') ?></textarea>
+                    <textarea name="emails" cols="60" rows="5" id="email_address" data-validate="{required:true,'validate-emails':true}"><?php echo $this->getEnteredData('emails') ?></textarea>
                 </div>
             </li>
             <li class="wide">
@@ -62,25 +62,12 @@
     </div>
 </form>
 <script type="text/javascript">
-//<![CDATA[
-Validation.addAllThese([
-    ['validate-emails', '<?php echo $this->__('Please enter a valid email addresses, separated by commas. For example johndoe@domain.com, johnsmith@domain.com.') ?>', function (v) {
-    if(Validation.get('IsEmpty').test(v)) {
-        return true;
-    }
-
-    var valid_regexp = /^[a-z0-9\._-]{1,30}@([a-z0-9_-]{1,30}\.){1,5}[a-z]{2,4}$/i;
-    var emails = v.split(',');
-
-    for (var i=0; i<emails.length; i++) {
-        if(!valid_regexp.test(emails[i].strip())) {
-            return false;
-        }
-    }
-
-    return true;
-    }]
-]);
-var dataForm = new VarienForm('form-validate', true);
-//]]>
+    (function($) {
+        head.js("<?php echo $this->getViewFileUrl('jquery/jquery.validate.js')?>",
+            "<?php echo $this->getViewFileUrl('jquery/jquery.metadata.js')?>",
+            "<?php echo $this->getViewFileUrl('mage/validation.js')?>",
+            "<?php echo $this->getViewFileUrl('mage/validation/validation.js')?>", function() {
+                $('#form-validate').validation();
+            })
+    })(jQuery);
 </script>
diff --git a/app/code/core/Mage/Wishlist/view/frontend/view.phtml b/app/code/core/Mage/Wishlist/view/frontend/view.phtml
index 693d137c0a406502c0234dcf318e190eb01c4d90..3b5443ce198e6843b3d7f3ee3dc082321d75bb9c 100644
--- a/app/code/core/Mage/Wishlist/view/frontend/view.phtml
+++ b/app/code/core/Mage/Wishlist/view/frontend/view.phtml
@@ -42,7 +42,6 @@
                         <?php echo $this->getBlockHtml('formkey');?>
                         <?php $this->getChildBlock('items')->setItems($this->getWishlistItems()); ?>
                         <?php echo $this->getChildHtml('items');?>
-                        <script type="text/javascript">(function($) {$('#wishlist-table').decorate('table')})(jQuery)</script>
                 <?php else: ?>
                     <p class="wishlist-empty"><?php echo $this->__('You have no items in your wishlist.') ?></p>
                 <?php endif ?>
@@ -51,7 +50,33 @@
                 </div>
             </fieldset>
         </form>
-
+        <script id="form-tmpl" type="text/x-jQuery-tmpl">
+            <form id="wishlist-hidden-form" method="post" action="${url}" class="no-display">
+                {{if itemId}}<input name="item_id" value="${itemId}"/>{{/if}}
+                {{if wishlistId}}<input name="wishlist_id" value="${wishlistId}"/>{{/if}}
+                {{if qty}}<input name="qty" value="${qty}"/>{{/if}}
+                {{if item}}<input name="item" value="${item}"/>{{/if}}
+                {{if entity}}<input name="entity" value="${entity}"/>{{/if}}
+            </form>
+        </script>
+        <script>
+            (function($) {
+                head.js("<?php echo $this->getViewFileUrl('jquery/jquery.validate.js')?>",
+                    "<?php echo $this->getViewFileUrl('jquery/jquery.metadata.js')?>",
+                    "<?php echo $this->getViewFileUrl('mage/validation.js')?>",
+                    "<?php echo $this->getViewFileUrl('mage/validation/validation.js')?>",
+                    "<?php echo $this->getViewFileUrl('Mage_Persistent::splitbutton.js') ?>",
+                    "<?php echo $this->getViewFileUrl('Mage_Wishlist::wishlist.js')?>", function() {
+                        $('#wishlist-view-form').wishlist({
+                            addToCartUrl: '<?php echo $this->getItemAddToCartUrl('%item%');?>' ,
+                            confirmRemoveMessage: '<?php echo $this->__('Are you sure you want to remove this product from your wishlist?') ?>',
+                            addAllToCartUrl : '<?php echo $this->getUrl('*/*/allcart', array('wishlist_id' => $this->getWishlistInstance()->getId())) ?>',
+                            commentString : '<?php echo $this->helper('Mage_Wishlist_Helper_Data')->defaultCommentString()?>'
+                        });
+                        $('body').splitButton();
+                    });
+            })(jQuery);
+        </script>
     </div>
     <?php echo $this->getChildHtml('bottom'); ?>
     <div class="buttons-set">
diff --git a/app/code/core/Mage/Wishlist/view/frontend/wishlist.js b/app/code/core/Mage/Wishlist/view/frontend/wishlist.js
new file mode 100644
index 0000000000000000000000000000000000000000..c83b4440de43706e79bcc96a457186feb4f14dd5
--- /dev/null
+++ b/app/code/core/Mage/Wishlist/view/frontend/wishlist.js
@@ -0,0 +1,208 @@
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    frontend product msrp
+ * @package     mage
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+
+/*jshint browser:true jquery:true sub:true*/
+/*global alert*/
+(function($, window) {
+    "use strict";
+    $.widget('mage.wishlist', {
+        options: {
+            dataAttribute: 'item-id',
+            nameFormat: 'qty[{0}]',
+            btnRemoveSelector: '.btn-remove',
+            qtySelector: '.qty',
+            addToCartSelector: '.btn-cart',
+            addAllToCartSelector: '.btn-add',
+            commentInputType: 'textarea',
+            infoList: false
+        },
+
+        /**
+         * Bind handlers to events.
+         */
+        _create: function() {
+            var _this = this;
+            if (!this.options.infoList) {
+                this.element
+                    .on('click', this.options.addToCartSelector, function() {
+                        $.proxy(_this._addItemsToCart($(this)), _this);
+                    })
+                    .on('addToCart', function(event, context) {
+                        $.proxy(_this._addItemsToCart($(context).parents('.cart-cell').find(_this.options.addToCartSelector)), _this);
+                    })
+                    .on('click', this.options.btnRemoveSelector, $.proxy(this._confirmRemoveWishlistItem, this))
+                    .on('click', this.options.addAllToCartSelector, $.proxy(this._addAllWItemsToCart, this))
+                    .on('focusin focusout', this.options.commentInputType, $.proxy(this._focusComment, this));
+            }
+        },
+
+        /**
+         * Validate and Redirect.
+         * @private
+         * @param {string} url
+         */
+        _validateAndRedirect: function(url) {
+            if (this.element.validation({
+                errorPlacement: function(error, element) {
+                    error.insertAfter(element.next());
+                }
+            }).valid()) {
+                this.element.prop('action', url);
+                window.location.href = url;
+            }
+        },
+
+        /**
+         * Add wish list items to cart.
+         * @private
+         * @param {jQuery object} elem - clicked 'add to cart' button
+         */
+        _addItemsToCart: function(elem) {
+            if (elem.data(this.options.dataAttribute)) {
+                var itemId = elem.data(this.options.dataAttribute),
+                    url = this.options.addToCartUrl.replace('%item%', itemId),
+                    inputName = $.validator.format(this.options.nameFormat, itemId),
+                    inputValue = elem.parent().find('[name="' + inputName + '"]').val(),
+                    separator = (url.indexOf('?') >= 0) ? '&' : '?';
+                url += separator + inputName + '=' + encodeURIComponent(inputValue);
+                this._validateAndRedirect(url);
+                return;
+            }
+
+        },
+
+        /**
+         * Confirmation window for removing wish list item.
+         * @private
+         */
+        _confirmRemoveWishlistItem: function() {
+            return window.confirm(this.options.confirmRemoveMessage);
+        },
+
+        /**
+         * Add all wish list items to cart
+         * @private
+         */
+        _addAllWItemsToCart: function() {
+            var url = this.options.addAllToCartUrl,
+                separator = (url.indexOf('?') >= 0) ? '&' : '?';
+            this.element.find(this.options.qtySelector).each(function(index, element) {
+                url += separator + $(element).prop('name') + '=' + encodeURIComponent($(element).val());
+                separator = '&';
+            });
+            this._validateAndRedirect(url);
+        },
+
+        /**
+         * Toggle comment string.
+         * @private
+         * @param {event} e
+         */
+        _focusComment: function(e) {
+            var commentInput = e.currentTarget;
+            if (commentInput.value === '' || commentInput.value === this.options.commentString) {
+                commentInput.value = commentInput.value === this.options.commentString ?
+                    '' : this.options.commentString;
+            }
+        }
+    });
+
+    // Extension for mage.wishlist - Select All checkbox
+    $.widget('mage.wishlist', $.mage.wishlist, {
+        options: {
+            selectAllCheckbox: '#select-all',
+            parentContainer: '#wishlist-table'
+        },
+
+        _create: function() {
+            this._super();
+            var selectAllCheckboxParent = $(this.options.selectAllCheckbox).parents(this.options.parentContainer),
+                checkboxCount = selectAllCheckboxParent.find('input:checkbox:not(' + this.options.selectAllCheckbox + ')').length;
+            // If Select all checkbox is checked, check all item checkboxes, if unchecked, uncheck all item checkboxes
+            $(this.options.selectAllCheckbox).on('click', function() {
+                selectAllCheckboxParent.find('input:checkbox').attr('checked', $(this).is(':checked'));
+            });
+            // If all item checkboxes are checked, check select all checkbox,
+            // if not all item checkboxes are checked, uncheck select all checkbox
+            selectAllCheckboxParent.on('click', 'input:checkbox:not(' + this.options.selectAllCheckbox + ')', $.proxy(function() {
+                var checkedCount = selectAllCheckboxParent.find('input:checkbox:checked:not(' + this.options.selectAllCheckbox + ')').length;
+                $(this.options.selectAllCheckbox).attr('checked', checkboxCount === checkedCount);
+            }, this));
+        }
+    });
+    // Extension for mage.wishlist info add to cart
+    $.widget('mage.wishlist', $.mage.wishlist, {
+        _create: function() {
+            this._super();
+            if (this.options.infoList) {
+                this.element.on('addToCart', $.proxy(function(event, context) {
+                    this.element.find('input:checkbox').attr('checked', false);
+                    $(context).closest('tr').find('input:checkbox').attr('checked', true);
+                    this.element.submit();
+                }, this));
+                this._checkBoxValidate();
+            }
+        },
+
+        /**
+         * validate checkbox selection.
+         * @private
+         */
+        _checkBoxValidate: function() {
+            this.element.validation({
+                submitHandler: $.proxy(function(form) {
+                    if ($(form).find('input:checkbox:checked').length) {
+                        form.submit();
+                    } else {
+                        alert(this.options.checkBoxValidationMessage);
+                    }
+                }, this)
+            });
+        }
+    });
+    
+    // Extension for mage.wishlist - Add Wishlist item to Gift Registry
+    $.widget('mage.wishlist', $.mage.wishlist, {
+        options: {
+            formTmplSelector: '#form-tmpl',
+            formTmplId: '#wishlist-hidden-form'
+        },
+
+        _create: function() {
+            this._super();
+            var _this = this;
+            this.element.on('click', '[data-wishlist-to-giftregistry]', function() {
+                var json = $(this).data('wishlist-to-giftregistry'),
+                    tmplJson = {
+                        item: json['itemId'],
+                        entity: json['entity'],
+                        url: json['url']
+                    };
+                $(_this.options.formTmplSelector).tmpl(tmplJson).appendTo('body');
+                $(_this.options.formTmplId).submit();
+            });
+        }
+    });
+})(jQuery, window);
diff --git a/app/design/adminhtml/default/backend/Mage_Backend/images/body-bg.jpg b/app/design/adminhtml/default/backend/Mage_Backend/images/body-bg.jpg
index 459ba0af6fdbc40201f14df47cce79c54047cdde..9e684f9b2154eb4ff888c9ac7dbb5e1f1d94d1b7 100644
Binary files a/app/design/adminhtml/default/backend/Mage_Backend/images/body-bg.jpg and b/app/design/adminhtml/default/backend/Mage_Backend/images/body-bg.jpg differ
diff --git a/app/design/adminhtml/default/backend/css/admin.css b/app/design/adminhtml/default/backend/css/admin.css
index fd97da9b1a2cfee002ba11786bea754a2e0ae176..745cc07a397ff9b4cdb8e3e9cb428c20dce24295 100644
--- a/app/design/adminhtml/default/backend/css/admin.css
+++ b/app/design/adminhtml/default/backend/css/admin.css
@@ -205,11 +205,31 @@ button.primary.disabled,
 .action-.delete:active,
 .action-.delete.active,
 .action-.delete:disabled,
+#product-variations-matrix .action-choose,
+#product-variations-matrix .action-choose:hover,
+#product-variations-matrix .action-choose:active,
+#product-variations-matrix .action-choose.active,
+#product-variations-matrix .action-choose:disabled,
 .fieldset-wrapper-title .action-add,
 .fieldset-wrapper-title .action-add:hover,
 .fieldset-wrapper-title .action-add:active,
 .fieldset-wrapper-title .action-add.active,
 .fieldset-wrapper-title .action-add:disabled,
+#store-view-window [class^='action-close'],
+#store-view-window [class^='action-close']:hover,
+#store-view-window [class^='action-close']:active,
+#store-view-window [class^='action-close'].active,
+#store-view-window [class^='action-close']:disabled,
+.custom-file > .action-add,
+.custom-file > .action-add:hover,
+.custom-file > .action-add:active,
+.custom-file > .action-add.active,
+.custom-file > .action-add:disabled,
+.vde-tools-header .action-close,
+.vde-tools-header .action-close:hover,
+.vde-tools-header .action-close:active,
+.vde-tools-header .action-close.active,
+.vde-tools-header .action-close:disabled,
 .action-delete,
 .action-delete:hover,
 .action-delete:active,
@@ -239,6 +259,25 @@ button.primary.disabled,
     text-shadow: none;
 }
 
+/*
+    Fileupload button
+-------------------------------------- */
+.action-upload {
+    position: relative;
+}
+
+.action-upload > span {
+}
+
+.action-upload > input[type="file"] {
+    position: absolute;
+    left: 0;
+    top: 0;
+    right: 0;
+    bottom: 0;
+    opacity: 0;
+}
+
 /*
     Dropdown menu
 -------------------------------------- */
@@ -259,6 +298,10 @@ button.primary.disabled,
     z-index: 1;
 }
 
+.dropdown-menu > li {
+    white-space: nowrap;
+}
+
 .dropdown-menu > li,
 .ui-autocomplete > li {
     padding: 5px;
@@ -312,6 +355,46 @@ button.primary.disabled,
     background: #f5f5f5;
 }
 
+/*
+    Suggest
+-------------------------------------- */
+.mage-suggest {
+    position: relative;
+    display: inline-block;
+    vertical-align: top;
+    margin: 0 6px 6px 0;
+    width: 72.5%;
+    padding: 2px;
+    padding-right: 30px;
+    background-color: #fff;
+    border: 1px solid #ccc;
+    border-radius: 3px;
+    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
+    -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
+    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
+}
+
+.mage-suggest-dropdown {
+    position: absolute;
+    left: 0;
+    right: 0;
+    top: 100%;
+    margin: 3px -1px 0 -1px;
+    border: 1px solid #cac2b5;
+    border-radius: 3px;
+    background: #fff;
+    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
+    z-index: 990;
+}
+
+.mage-suggest-dropdown .jstree {
+    padding: 5px;
+}
+
+.mage-suggest-dropdown .jstree a {
+    line-height: 1.666;
+}
+
 /*
     Actions Split
 -------------------------------------- */
@@ -384,6 +467,11 @@ button.primary.disabled,
     color: #b7b3ad;
 }
 
+.action-.delete:hover:before,
+.action-delete:hover:before {
+    color: #7e7e7e;
+}
+
 input.action-.delete[type="button"],
 input.action-.delete[type="submit"],
 input.action-.delete[type="reset"],
@@ -471,9 +559,7 @@ textarea,
     -moz-box-sizing: border-box;
     -webkit-box-sizing: border-box;
     box-sizing: border-box;
-    border-radius: 3px;
-    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-    -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
+    border-radius: 4px;
     box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
     -webkit-transition: border linear 0.5s, box-shadow linear 0.2s;
     -moz-transition: border linear 0.5s, box-shadow linear 0.2s;
@@ -488,9 +574,15 @@ textarea,
 }
 
 select {
-    padding: 4px;
+    padding: 4px 4px 5px;
     margin: 0 0 8px;
     border: 1px solid #ccc;
+    border-radius: 4px;
+    -webkit-transition: border linear 0.5s, box-shadow linear 0.2s;
+    -moz-transition: border linear 0.5s, box-shadow linear 0.2s;
+    -ms-transition: border linear 0.5s, box-shadow linear 0.2s;
+    -o-transition: border linear 0.5s, box-shadow linear 0.2s;
+    transition: border linear 0.5s, box-shadow linear 0.2s;
 }
 
 select[multiple],
@@ -513,11 +605,10 @@ input[type=url]:focus,
 input[type=search]:focus,
 input[type=tel]:focus,
 input[type=color]:focus,
-textarea:focus {
+textarea:focus,
+select:focus {
     outline: 0;
-    border-color: rgba(82, 168, 236, 0.8);
-    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
-    -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
+    border-color: #75b9f0;
     box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
 }
 
@@ -555,20 +646,22 @@ option.placeholder {
 }
 
 ::-webkit-input-placeholder {
-    font: normal 14px/20px Arial, Helvetica, sans-serif;
     color: #999 !important;
 }
 
 :-moz-placeholder {
-    font: normal 14px/20px Arial, Helvetica, sans-serif;
     color: #999 !important;
 }
 
+.form-inline .control {
+    width: 100%;
+}
+
 .form-inline .label {
     width: 20%;
 }
 
-.form-inline .control {
+.form-inline .label + .control {
     width: 60%;
 }
 
@@ -576,9 +669,9 @@ option.placeholder {
     -moz-box-sizing: border-box;
     -webkit-box-sizing: border-box;
     box-sizing: border-box;
-    float: right;
+    float: left;
     width: 20%;
-    padding-left: 15px;
+    padding: 6px 0 0 15px;
     font-size: 10px;
 }
 
@@ -595,6 +688,10 @@ option.placeholder {
     width: 100%;
 }
 
+.control > input.hasDatepicker {
+    width: 130px;
+}
+
 .control > input[type="radio"],
 .control > input[type="checkbox"] {
     width: auto;
@@ -612,6 +709,12 @@ option.placeholder {
     width: 100%;
 }
 
+/* TODO: remove styles for images when images will be replaced by font icons */
+.control > .hasDatepicker + img {
+    margin: -3px 0 0 5px;
+    vertical-align: middle;
+}
+
 /*
     Forms styles
 -------------------------------------- */
@@ -679,13 +782,13 @@ option.placeholder {
     display: inline-block;
 }
 
-.fieldset-wrapper-title .title[data-toggle="collapse"] {
+.fieldset-wrapper-title > .title[data-toggle="collapse"] {
     position: relative;
     padding-left: 22px;
     cursor: pointer;
 }
 
-.fieldset-wrapper-title .title[data-toggle="collapse"]:before {
+.fieldset-wrapper-title > .title[data-toggle="collapse"]:before {
     position: absolute;
     left: 0;
     top: 7px;
@@ -698,10 +801,111 @@ option.placeholder {
     color: #b2b0ad;
 }
 
-.fieldset-wrapper.opened .fieldset-wrapper-title .title:before {
+.fieldset-wrapper-title > .title[data-toggle="collapse"]:hover:before {
+    color: #7e7e7e;
+}
+
+.fieldset-wrapper.opened > .fieldset-wrapper-title > .title:before {
     content: '\e02c'; /* arrow down icon */
 }
 
+/* Fieldset styles in another fieldset */
+.fieldset .fieldset-wrapper,
+.fieldset-wrapper .fieldset-wrapper {
+    border-color: #cccbca;
+    padding: 0;
+}
+
+.fieldset .fieldset-wrapper .fieldset-wrapper-title,
+.fieldset-wrapper .fieldset-wrapper .fieldset-wrapper-title {
+    background: #f4f2ef;
+    background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIwJSIgeTI9IjEwMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2Y0ZjJlZiIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiNlZWViZTYiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);
+    background: -moz-linear-gradient(top, #f4f2ef 0%, #eeebe6 100%);
+    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #f4f2ef), color-stop(100%, #eeebe6));
+    background: -webkit-linear-gradient(top, #f4f2ef 0%, #eeebe6 100%);
+    background: -o-linear-gradient(top, #f4f2ef 0%, #eeebe6 100%);
+    background: -ms-linear-gradient(top, #f4f2ef 0%, #eeebe6 100%);
+    background: linear-gradient(to bottom, #f4f2ef 0%, #eeebe6 100%);
+    padding: 0 18px;
+    border-radius: 5px;
+}
+
+.eq-ie8 .fieldset .fieldset-wrapper .fieldset-wrapper-title,
+.eq-ie8 .fieldset-wrapper .fieldset-wrapper .fieldset-wrapper-title {
+    background: #f4f2ef;
+}
+
+.fieldset .fieldset-wrapper.opened .fieldset-wrapper-title,
+.fieldset-wrapper .fieldset-wrapper.opened .fieldset-wrapper-title {
+    border-radius: 5px 5px 0 0;
+    border-bottom: 1px solid #cccbca;
+    -webkit-touch-callout: none;
+    -webkit-user-select: none;
+    -khtml-user-select: none;
+    -moz-user-select: none;
+    -ms-user-select: none;
+}
+
+.fieldset .fieldset-wrapper .fieldset-wrapper-title .actions,
+.fieldset-wrapper .fieldset-wrapper .fieldset-wrapper-title .actions {
+    padding: 10px 2px 0 0;
+}
+
+.fieldset .fieldset-wrapper .fieldset-wrapper-title .title,
+.fieldset-wrapper .fieldset-wrapper .fieldset-wrapper-title .title {
+    padding-top: 9px;
+    padding-bottom: 8px;
+    color: #555;
+    font: normal 16px/1.333 Arial, Verdana, sans-serif;
+}
+
+.fieldset .fieldset-wrapper .fieldset-wrapper-title .title:before,
+.fieldset-wrapper .fieldset-wrapper .fieldset-wrapper-title .title:before {
+    top: 9px;
+}
+
+.fieldset .fieldset-wrapper-title .draggable-handle,
+.fieldset-wrapper .fieldset-wrapper-title .draggable-handle {
+    position: absolute;
+    left: 10px;
+    top: 12px;
+    width: 8px;
+    height: 14px;
+    line-height: 14px;
+    background: none;
+    cursor: pointer;
+    color: #b2b0ad;
+}
+
+.fieldset .fieldset-wrapper-title .draggable-handle:hover,
+.fieldset-wrapper .fieldset-wrapper-title .draggable-handle:hover {
+    color: #7e7e7e;
+}
+
+.fieldset .fieldset-wrapper-title .draggable-handle:before,
+.fieldset-wrapper .fieldset-wrapper-title .draggable-handle:before {
+    font-family: 'MUI-Icons';
+    font-style: normal;
+    speak: none;
+    font-weight: normal;
+    -webkit-font-smoothing: antialiased;
+    content: '\e022';
+    font-size: 16px;
+}
+
+.fieldset .fieldset-wrapper .fieldset-wrapper-content,
+.fieldset-wrapper .fieldset-wrapper .fieldset-wrapper-content {
+    padding: 0 10px;
+}
+
+/* Sortable fieldsets */
+.ui-sortable .entry-edit .fieldset-wrapper-title {
+    padding-left: 30px;
+}
+
+.ui-sortable .entry-edit .fieldset-wrapper-title > .title {
+}
+
 .fieldset-wrapper-title > .actions {
     float: right;
 }
@@ -733,20 +937,23 @@ option.placeholder {
     margin-bottom: 0;
 }
 
+.fieldset-wrapper .fieldset:last-child,
+.fieldset .fieldset:last-child,
 .fieldset .field:last-child {
     margin-bottom: 0;
 }
 
 .fieldset .label {
     color: #666;
-    font-weight: bold;
 }
 
 .with-addon .textarea {
     margin: 0 0 6px;
 }
 
-.fieldset .control .textarea {
+.fieldset .control .textarea,
+.fieldset .control .addon .textarea {
+    border-radius: 4px;
     width: 100%;
 }
 
@@ -754,6 +961,26 @@ option.placeholder {
     margin-top: 10px;
 }
 
+/* "Use default" checkbox */
+.use-default {
+
+}
+
+.use-default-control {
+    display: none;
+}
+
+.use-default-label {
+    cursor: pointer;
+    text-decoration: underline;
+    font-size: 11px;
+    color: #a29c94;
+}
+
+.use-default-label:hover {
+    color: #7e7e7e;
+}
+
 /*
     Form item with table
 -------------------------------------- */
@@ -770,6 +997,104 @@ option.placeholder {
     width: 100%;
 }
 
+/*
+    Form currency label
+-------------------------------------- */
+
+.addon input {
+    border-width: 1px 0 1px 1px;
+}
+
+.addon input:focus + label {
+    border-color: #75b9f0;
+    box-shadow: 0 0 8px rgba(82, 168, 236, 0.6);
+    -webkit-transition: border linear 0.5s, box-shadow linear 0.2s;
+    -moz-transition: border linear 0.5s, box-shadow linear 0.2s;
+    -ms-transition: border linear 0.5s, box-shadow linear 0.2s;
+    -o-transition: border linear 0.5s, box-shadow linear 0.2s;
+    transition: border linear 0.5s, box-shadow linear 0.2s;
+}
+
+.addon input + label strong {
+    background: #fff;
+    display: block;
+    line-height: 25px;
+    margin: 1px 3px 0 -2px;
+    padding-left: 4px;
+    padding-right: 4px;
+    position: relative;
+}
+
+.addon input:focus + label strong {
+    margin-top: 0;
+}
+
+.addon .addafter {
+    background: none;
+    color: #a6a6a6;
+    border-width: 1px 1px 1px 0;
+    border-radius: 4px 4px 0 0;
+    padding: 0;
+    box-shadow: 0 1px 0 rgba(0, 0, 0, 0.075) inset;
+}
+
+.field-price .addon,
+.field-special_price .addon,
+.field-msrp .addon {
+    direction: rtl;
+}
+
+.field-price .addon > *,
+.field-special_price .addon > *,
+.field-msrp .addon > * {
+    direction: ltr;
+}
+
+.field-price .addon .addafter,
+.field-special_price .addon .addafter,
+.field-msrp .addon .addafter {
+    border-width: 1px 0 1px 1px;
+    border-radius: 4px 0 0 4px;
+}
+
+.field-price .addon input:first-child,
+.field-special_price .addon input:first-child,
+.field-msrp .addon input:first-child {
+    border-radius: 0 4px 4px 0;
+}
+
+.eq-ie8 .field-price .addon .addafter,
+.eq-ie8 .field-special_price .addon .addafter,
+.eq-ie8 .field-msrp .addon .addafter {
+    border-width: 1px 1px 1px 0;
+}
+
+.field-price input,
+.field-special_price input,
+.field-msrp input {
+    border-width: 1px 1px 1px 0;
+    box-shadow: 0 1px 0 rgba(0, 0, 0, 0.075) inset;
+}
+
+.field-price input:focus,
+.field-special_price input:focus,
+.field-msrp input:focus {
+    box-shadow: 0 0 8px rgba(82, 168, 236, 0.6);
+}
+
+.field-price input:focus + label,
+.field-special_price input:focus + label,
+.field-msrp input:focus + label {
+    box-shadow: 0 0 8px rgba(82, 168, 236, 0.6);
+}
+
+.field-price input + label strong,
+.field-special_price input + label strong,
+.field-msrp input + label strong {
+    margin-left: 3px;
+    margin-right: -2px;
+}
+
 /*
     Calendar
 -------------------------------------- */
@@ -837,6 +1162,13 @@ blockquote small:before {
     content: '\2014 \00A0';
 }
 
+/*
+    Addresses
+-------------------------------------- */
+address {
+    font-style: normal;
+}
+
 /*
     Tables
 -------------------------------------- */
@@ -1153,7 +1485,8 @@ table tbody tr:nth-child(odd):hover th {
 
 /* Old loading popup */
 /* TODO: remove this popup after refactoring of "varienLoader.js" file */
-.loading-old {
+.loading-old,
+.loading-mask {
     border: 1px solid #d85909;
     position: fixed;
     z-index: 1003;
@@ -1170,7 +1503,8 @@ table tbody tr:nth-child(odd):hover th {
     padding: 100px 0 10px;
 }
 
-.loading-old:after {
+.loading-old:after,
+.loading-mask:after {
     position: absolute;
     left: 50%;
     top: 40%;
@@ -1182,13 +1516,19 @@ table tbody tr:nth-child(odd):hover th {
     z-index: 2;
 }
 
-.loading-old .loader {
+.loading-old .loader,
+.loading-mask .loader {
     position: relative !important;
     left: auto !important;
     top: auto !important;
 }
 
-.eq-ie8 .loading-old {
+.loading-mask img {
+    display: none;
+}
+
+.eq-ie8 .loading-old,
+.eq-ie8 .loading-mask {
     background: #fff;
     -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=80)";
 }
@@ -1718,13 +2058,17 @@ table tbody tr:nth-child(odd):hover th {
 -------------------------------------- */
 
 .page-login {
-    padding-top: 50px;
 }
 
 .page-login .fieldset {
     border-color: #B5DCD6;
 }
 
+.page-login .footer-content {
+    min-width: 0;
+    max-width: auto;
+}
+
 .page-login .footer,
 .page-login .form-login {
     width: 600px;
@@ -1735,7 +2079,7 @@ table tbody tr:nth-child(odd):hover th {
 .page-login .header {
     width: 564px;
     margin: 0 auto;
-    padding: 18px;
+    padding: 50px 18px;
 }
 
 .page-login .logo {
@@ -1813,6 +2157,13 @@ table tbody tr:nth-child(odd):hover th {
     margin: 20px 0;
 }
 
+.page-content > .page-title {
+    max-width: 1300px;
+    min-width: 960px;
+    margin-left: auto;
+    margin-right: auto;
+}
+
 .page-title-inner > .title {
     font-family: 'CallunaSans';
     font-size: 26px;
@@ -1850,6 +2201,16 @@ table tbody tr:nth-child(odd):hover th {
     border-bottom: 1px solid #c7c2b6;
 }
 
+.wrapper > .message {
+    padding: 0 20px;
+}
+
+.page-content > .messages {
+    max-width: 1300px;
+    min-width: 960px;
+    margin: 0 auto;
+}
+
 .message:before,
 .message-system .message-inner:before {
     position: absolute;
@@ -2011,6 +2372,21 @@ table tbody tr:nth-child(odd):hover th {
     color: #d87e34;
 }
 
+/*
+    Error message
+-------------------------------------- */
+.message-error {
+    color: #963535;
+    background: #f3dcd8;
+    border: 1px solid #963535;
+    margin-bottom: 20px;
+}
+
+.message-error:before {
+    content: '\e069';
+    color: #963535;
+}
+
 /* TODO: implement styles for all types of messages when the new code is integrated */
 
 /*
@@ -2021,9 +2397,8 @@ table tbody tr:nth-child(odd):hover th {
 }
 
 .page-content {
-    min-width: 960px;
-    max-width: 1300px;
     margin: 0 auto;
+    padding: 0 20px;
 }
 
 .side-col {
@@ -2069,10 +2444,15 @@ table tbody tr:nth-child(odd):hover th {
     background: #f5f2ed;
     border: 1px solid #b7b2a6;
     border-radius: 5px;
+    min-width: 960px;
+    max-width: 1300px;
+    margin: 0 auto;
 }
 
 .col-1-layout {
     padding: 20px;
+    min-width: 920px;
+    max-width: 1260px;
 }
 
 .col-2-left-layout:before {
@@ -2083,8 +2463,6 @@ table tbody tr:nth-child(odd):hover th {
     bottom: 0;
     width: 1px;
     content: '';
-    -webkit-box-shadow: -2px 0 7px #777;
-    -moz-box-shadow: -2px 0 7px #777;
     box-shadow: -2px 0 7px #777;
     z-index: 2;
 }
@@ -2431,18 +2809,18 @@ table tbody tr:nth-child(odd):hover th {
     top: 0;
     left: 0;
     right: 0;
-    z-index: 9999;
+    z-index: 998;
 }
 
 .page-actions.fixed .page-actions-inner {
     background: #f7f2ec;
     background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIwJSIgeTI9IjEwMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIxJSIgc3RvcC1jb2xvcj0iI2Y3ZjJlYyIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjYwJSIgc3RvcC1jb2xvcj0iI2ZjZmFmNyIgc3RvcC1vcGFjaXR5PSIxIi8+CiAgICA8c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiNmZmZmZmYiIHN0b3Atb3BhY2l0eT0iMCIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);
-    background: -moz-linear-gradient(top,  rgba(247,242,236,1) 1%, rgba(252,250,247,1) 70%, rgba(255,255,255,0) 100%);
-    background: -webkit-gradient(linear, left top, left bottom, color-stop(1%,rgba(247,242,236,1)), color-stop(70%,rgba(252,250,247,1)), color-stop(100%,rgba(255,255,255,0)));
-    background: -webkit-linear-gradient(top,  rgba(247,242,236,1) 1%,rgba(252,250,247,1) 70%,rgba(255,255,255,0) 100%);
-    background: -o-linear-gradient(top,  rgba(247,242,236,1) 1%,rgba(252,250,247,1) 70%,rgba(255,255,255,0) 100%);
-    background: -ms-linear-gradient(top,  rgba(247,242,236,1) 1%,rgba(252,250,247,1) 70%,rgba(255,255,255,0) 100%);
-    background: linear-gradient(to bottom,  rgba(247,242,236,1) 1%,rgba(252,250,247,1) 70%,rgba(255,255,255,0) 100%);
+    background: -moz-linear-gradient(top, rgba(247, 242, 236, 1) 1%, rgba(252, 250, 247, 1) 70%, rgba(255, 255, 255, 0) 100%);
+    background: -webkit-gradient(linear, left top, left bottom, color-stop(1%, rgba(247, 242, 236, 1)), color-stop(70%, rgba(252, 250, 247, 1)), color-stop(100%, rgba(255, 255, 255, 0)));
+    background: -webkit-linear-gradient(top, rgba(247, 242, 236, 1) 1%, rgba(252, 250, 247, 1) 70%, rgba(255, 255, 255, 0) 100%);
+    background: -o-linear-gradient(top, rgba(247, 242, 236, 1) 1%, rgba(252, 250, 247, 1) 70%, rgba(255, 255, 255, 0) 100%);
+    background: -ms-linear-gradient(top, rgba(247, 242, 236, 1) 1%, rgba(252, 250, 247, 1) 70%, rgba(255, 255, 255, 0) 100%);
+    background: linear-gradient(to bottom, rgba(247, 242, 236, 1) 1%, rgba(252, 250, 247, 1) 70%, rgba(255, 255, 255, 0) 100%);
     padding: 11px 20px 11px;
     min-height: 36px;
     margin: 0 auto;
@@ -2488,10 +2866,17 @@ table tbody tr:nth-child(odd):hover th {
 }
 
 .grid tr.on-mouse {
-    background: #fff;
     cursor: pointer;
 }
 
+.grid tr.on-mouse td,
+.grid table tbody tr.on-mouse:hover td,
+.grid table tbody tr.on-mouse:hover th,
+.grid table tbody tr.on-mouse:nth-child(odd):hover td,
+.grid table tbody tr.on-mouse:nth-child(odd):hover th {
+    background-color: #fff;
+}
+
 /* Rows mouse-over */
 .grid tr.invalid {
     background-color: #f5d6c7;
@@ -2539,12 +2924,17 @@ table tbody tr:nth-child(odd):hover th {
 }
 
 .grid table td.empty-text {
-    border: 1px solid #c0bbaf;
+    border: solid #c0bbaf;
+    border-width: 0 1px;
     font-size: 15px;
     text-align: center;
     padding: 15px;
 }
 
+.grid table tr:last-child td.empty-text {
+    border-width: 0 1px 1px;
+}
+
 .grid table td.empty-text:hover {
     background: #e6e3de;
 }
@@ -2576,7 +2966,9 @@ table tbody tr:nth-child(odd):hover th {
     font-weight: 400;
 }
 
-/* Grid - Pager and Buttons row */
+/*
+    Grid - Pager and Buttons row
+-------------------------------------- */
 .grid-actions {
     border: 1px solid #c0bbaf;
     border-bottom: 0;
@@ -2599,8 +2991,7 @@ table tbody tr:nth-child(odd):hover th {
 }
 
 .grid-actions select {
-    margin: 0;
-    vertical-align: top;
+    margin: 0 5px;
 }
 
 .grid-actions .export,
@@ -2652,14 +3043,67 @@ table tbody tr:nth-child(odd):hover th {
     color: #7f7f7f;
 }
 
+.grid-actions .date {
+    float: left;
+    margin: 0 15px 0 0;
+    position: relative;
+}
+
+.grid-actions .date input {
+    margin: 0 5px;
+    width: 80px;
+}
+
+.grid-actions .required:after {
+    content: '*';
+    color: red;
+}
+
+/* TODO: remove styles for images when images will be replaced by font icons */
+.grid-actions img {
+    vertical-align: middle;
+    height: 22px;
+    width: 22px;
+}
+
+/* TODO: refactor validation fields styles after approved design comes */
+.grid-actions .validation-advice {
+    background: #f3dcd8;
+    border: 1px solid #963535;
+    border-radius: 3px;
+    color: #963535;
+    margin: 5px 0 0;
+    padding: 3px 7px;
+    position: absolute;
+    white-space: nowrap;
+    z-index: 5;
+}
+
+.grid-actions .validation-advice:before {
+    font-family: 'MUI-Icons';
+    font-style: normal;
+    speak: none;
+    font-weight: normal;
+    -webkit-font-smoothing: antialiased;
+    content: '\e029'; /* user icon */
+    position: absolute;
+    top: -12px;
+    left: 50%;
+    margin-left: -3px;
+}
+
 /* Grid - Headings */
 .grid tr.headings th {
     font-size: 13px;
-    border-right: 1px solid #837F79;
+    border-right: 1px solid #837f79;
     padding: 0 1px;
     vertical-align: bottom;
 }
 
+.grid tr th:first-child {
+    border-left: 1px solid #837f79;
+}
+
 .grid tr.headings th > span {
     display: block;
     border-bottom: 5px solid transparent;
@@ -2670,6 +3114,10 @@ table tbody tr:nth-child(odd):hover th {
     border-color: #504841;
 }
 
+.grid tr.headings th.no-link:hover > span {
+    border-color: transparent;
+}
+
 .grid tr.headings th a span {
     display: block;
     padding-right: 20px;
@@ -2683,37 +3131,41 @@ table tbody tr:nth-child(odd):hover th {
 }
 
 .grid tr.headings th a:after {
-    background: url(../images/grid-sorted-th-arrows.png) no-repeat 0 -12px;
-    content: '';
     display: none;
     height: 8px;
-    width: 12px;
+    width: 15px;
     position: absolute;
-    bottom: 5px;
+    bottom: 4px;
     right: 0;
+    font-family: 'MUI-Icons';
+    font-style: normal;
+    speak: none;
+    font-weight: normal;
+    font-size: 20px;
+    line-height: 8px;
+    -webkit-font-smoothing: antialiased;
+    content: '\e038'; /* arrow down icon */
+    color: #8c8172;
 }
 
 .grid tr.headings th a:hover:after {
-    background-position: 0 -12px;
     display: block;
 }
 
 .grid tr.headings th a.sort-arrow-desc:after {
-    background-position: 0 0;
+    color: #c7b299;
     display: block;
 }
 
 .grid tr.headings th a.sort-arrow-asc:after {
-    background-position: -12px 0;
+    color: #c7b299;
+    content: '\e035'; /* arrow up icon */
     display: block;
 }
 
-.grid tr.headings th a.sort-arrow-desc:hover:after {
-    background-position: 0 -24px;
-}
-
+.grid tr.headings th a.sort-arrow-desc:hover:after,
 .grid tr.headings th a.sort-arrow-asc:hover:after {
-    background-position: -12px -24px;
+    color: #fff;
 }
 
 /* Grid - Filter */
@@ -2857,13 +3309,19 @@ table tbody tr:nth-child(odd):hover th {
 
 /* Grid Footer */
 .grid table tfoot tr {
-    background: #d7e5ef;
+    background: #656156;
 }
 
+.grid table tfoot tr th,
 .grid table tfoot tr td {
-    border-top: 1px solid #9babb9;
-    background: #e5ecf2;
+    border-right: 1px solid #837f79;
     line-height: 1.7em;
+    padding: 3px 10px;
+}
+
+.grid table tfoot tr th:first-child,
+.grid table tfoot tr td:first-child {
+    border-left: 1px solid #837f79;
 }
 
 .grid table.border tfoot tr td {
@@ -2908,6 +3366,13 @@ tr.dynamic-grid input.input-text {
     padding: 0 3%;
 }
 
+/*
+    Table columns styles
+-------------------------------------- */
+.col-no-records {
+    text-align: center;
+}
+
 /*
     Data table
 -------------------------------------- */
@@ -2933,9 +3398,9 @@ tr.dynamic-grid input.input-text {
 .data-table tbody tr:not(:last-child) td,
 .data-table tbody tr td {
     background: #fff;
-    padding: 3px 7px;
+    padding: 5px 7px;
     font-size: 12px;
-    vertical-align: top;
+    vertical-align: middle;
     border: solid #eae8e4;
     border-width: 0 0 1px;
 }
@@ -2954,7 +3419,7 @@ tr.dynamic-grid input.input-text {
     background: #fbfaf6;
 }
 
-.data-table tfoot td:last-child {
+.data-table tfoot tr:last-child td {
     border: 0;
 }
 
@@ -2962,7 +3427,6 @@ tr.dynamic-grid input.input-text {
     width: 98%;
     padding-left: 1%;
     padding-right: 1%;
-    height: 24px;
 }
 
 .data-table select {
@@ -2970,12 +3434,91 @@ tr.dynamic-grid input.input-text {
     -moz-box-sizing: border-box;
     -webkit-box-sizing: border-box;
     box-sizing: border-box;
-    border-radius: 3px;
-    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-    -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
+    border-radius: 4px;
     box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
 }
 
+.data-table .required-entry:after {
+    content: '*';
+    color: red;
+}
+
+.data-table .actions-split {
+    margin-top: 4px;
+}
+
+.data-table .actions-split [class^='action-'] {
+    background: none;
+    border: 1px solid #c8c3b5;
+    padding: 3px 5px;
+    color: #bbb3a6;
+    font-size: 12px;
+}
+
+.data-table .actions-split [class^='action-']:first-child {
+    border-right: 0;
+}
+
+.data-table .actions-split .dropdown-menu {
+    margin-top: -1px;
+}
+
+.data-table .actions-split .dropdown-menu a {
+    display: block;
+    color: #333;
+    text-decoration: none;
+}
+
+.data-table .actions-split.active .action-toggle {
+    position: relative;
+    border-bottom-right-radius: 0;
+    box-shadow: none;
+    background: #fff;
+}
+
+.data-table .actions-split.active .action-toggle:after {
+    position: absolute;
+    top: 100%;
+    left: 0;
+    right: 0;
+    height: 2px;
+    margin-top: -1px;
+    background: #fff;
+    content: '';
+    z-index: 2;
+}
+
+.data-table .actions-split.active .dropdown-menu {
+    border-top-right-radius: 0;
+}
+/*
+    Content alignments in tables
+-------------------------------------- */
+
+/* left */
+.col-name,
+.col-sku,
+.col-color,
+.col-size {
+    text-align: left;
+}
+
+/* center */
+.col-include,
+.col-display,
+.col-image,
+.col-price,
+.col-change-price {
+    text-align: center;
+}
+
+/* right */
+.col-qty,
+.col-weight,
+.col-actions {
+    text-align: right;
+}
+
 /*
     Attribute Information
 -------------------------------------- */
@@ -2990,14 +3533,6 @@ tr.dynamic-grid input.input-text {
     width: 32px;
 }
 
-.data-table .col-price input {
-    width: 60px;
-}
-
-.data-table .col-qty input {
-    width: 50px;
-}
-
 .data-table .col-file {
     white-space: nowrap;
 }
@@ -3045,6 +3580,108 @@ tr.dynamic-grid input.input-text {
     display: none;
 }
 
+/*
+    Customer Reviews
+-------------------------------------- */
+.field-detailed_rating .control-value {
+    width: 100%;
+}
+
+.field-detailed_rating .field-rating .control {
+    unicode-bidi: bidi-override;
+    direction: rtl;
+}
+
+.field-detailed_rating input[type="radio"] {
+    display: none;
+}
+
+.field-detailed_rating .field-rating .control label {
+    color: #ccc;
+    cursor: pointer;
+    font-size: 18px;
+    float: right;
+    overflow: hidden;
+    white-space: nowrap;
+    width: 18px;
+    -webkit-transition: color 150ms linear;
+    -moz-transition: color 150ms linear;
+    -o-transition: color 150ms linear;
+    -ms-transition: color 150ms linear;
+    transition: color 150ms linear;
+}
+
+.field-detailed_rating .field-rating .control input[type="radio"]:checked ~ label:before {
+    color: #333;
+}
+
+.field-detailed_rating .field-rating .control label:hover,
+.field-detailed_rating .field-rating .control label:hover ~ label {
+    color: #f30;
+}
+
+.field-detailed_rating .field-rating .control label:before {
+    content: "\2605\0000a0";
+}
+
+/*
+    Widgets
+-------------------------------------- */
+.widget-layout-updates .fieldset-wrapper,
+.widget-layout-updates .data-table {
+    margin: 0 0 18px;
+}
+
+.widget-layout-updates .fieldset-wrapper-title label {
+    padding: 10px 0 0;
+}
+
+.widget-layout-updates .fieldset-wrapper-title select {
+    margin: 3px 10px 5px;
+}
+
+.widget-layout-updates .fieldset-wrapper-title span,
+.widget-layout-updates .fieldset-wrapper-title select {
+    vertical-align: middle;
+}
+
+.widget-layout-updates .data-table {
+    table-layout: fixed;
+}
+
+.widget-layout-updates .data-table,
+.widget-layout-updates .data-table tr:nth-child(odd) td,
+.widget-layout-updates .data-table tr:nth-child(odd):hover td {
+    background: none;
+    border: none;
+}
+
+.widget-layout-updates .data-table th,
+.widget-layout-updates .data-table tbody td {
+    border: none;
+    padding: 5px 10px;
+    vertical-align: top;
+}
+
+.widget-layout-updates .data-table select {
+    margin: 0;
+    max-width: 99%;
+    overflow: hidden;
+}
+
+.widget-layout-updates .chooser_container {
+    padding: 0 10px 18px;
+}
+
+.widget-layout-updates .chooser_container p {
+    margin: 0;
+}
+
+.widget-layout-updates .chooser_container p img,
+.widget-layout-updates .chooser_container p input {
+    vertical-align: middle;
+}
+
 /*
     Clearfix
 -------------------------------------- */
@@ -3094,4 +3731,3 @@ tr.dynamic-grid input.input-text {
 .grid-actions:after,
 .fieldset-wrapper-title:after {
     clear: both;
-}
diff --git a/app/design/adminhtml/default/backend/css/debug.css b/app/design/adminhtml/default/backend/css/debug.css
index 8705b557d40a0aac2ca2415741e963b55ffc8e73..ce33734e796d2ab4047370f0f7e2071dab22577e 100644
--- a/app/design/adminhtml/default/backend/css/debug.css
+++ b/app/design/adminhtml/default/backend/css/debug.css
@@ -540,4 +540,78 @@ th.required:before {
 -------------------------------------- */
 .adminhtml-catalog-category-edit .category-edit-title {
     float: left;
-}
\ No newline at end of file
+}
+
+/*
+    Catalog Price Rule
+-------------------------------------- */
+.rule-tree-wrapper {
+    line-height: 28px;
+}
+
+.rule-tree ul {
+    list-style: none;
+    padding-left: 16px;
+    border-left: dotted 1px #888;
+}
+
+.rule-tree li {
+    margin: 0 0 10px;
+}
+
+.rule-tree .x-tree ul {
+    padding-left: 0 !important;
+    border-left: none !important;
+}
+
+.rule-param .label {
+    color: #000;
+    float: none;
+    text-align: left;
+    padding: 0;
+    vertical-align: baseline;
+    width: auto;
+}
+
+.rule-param .label-disabled {
+    color: #eee;
+    cursor: default;
+    text-decoration: none;
+}
+
+.rule-chooser,
+.rule-param .element,
+.rule-param-edit .label {
+    display: none;
+}
+
+.rule-param input,
+.rule-param select {
+    width: auto !important;
+    margin: 0;
+    min-width: 170px;
+}
+
+.rule-param-edit .element {
+    display: inline;
+}
+
+.rule-param-edit .element .addafter {
+    padding-left: 5px;
+}
+
+[class^="rule-param-"] img,
+.rule-chooser-trigger img {
+    vertical-align: middle;
+}
+
+.rule-chooser {
+    border: solid 1px #CCC;
+    margin: 20px;
+    padding: 15px 10px 5px;
+}
+
+.rule-param-wait {
+    background: url(../mui/images/ajax-loader-small.gif) no-repeat left center;
+    padding-left: 20px;
+}
diff --git a/app/design/adminhtml/default/backend/css/pages.css b/app/design/adminhtml/default/backend/css/pages.css
index 97238dc745509c650e9671259cd0d62e07fed337..dde4fc07561a92387cd62b885ed96d570092ae80 100644
--- a/app/design/adminhtml/default/backend/css/pages.css
+++ b/app/design/adminhtml/default/backend/css/pages.css
@@ -107,6 +107,16 @@
     text-indent: -999em;
 }
 
+.page-actions .switcher {
+    display: inline-block;
+    vertical-align: top;
+    margin: 6px 6px;
+}
+
+.page-actions .action-.delete {
+    margin-top: 2px;
+}
+
 /* Image Management */
 .images {
     position: relative;
@@ -221,6 +231,12 @@
     background: #fff url('Mage_Adminhtml::images/image-placeholder.png') no-repeat 50% 0%;
 }
 
+.image-placeholder input[type="file"] {
+    position: absolute;
+    opacity: 0;
+    border: 100px solid;
+}
+
 .image-placeholder-text {
     padding: 72px 5px 0;
     font-size: 11px;
@@ -275,6 +291,341 @@
     margin-right: 5px;
 }
 
+/* Variations Search Field */
+#variations-search-field {
+    margin-bottom: 16px;
+}
+
+#variations-search-field > .control {
+    position: relative;
+    width: 42%;
+}
+
+#variations-search-field > .control:after {
+    position: absolute;
+    top: 0;
+    right: 3px;
+    bottom: 0;
+    width: 22px;
+    text-align: center;
+    font-family: 'MUI-Icons';
+    font-style: normal;
+    speak: none;
+    font-weight: normal;
+    -webkit-font-smoothing: antialiased;
+    content: '\e01f'; /* search icon */
+    font-size: 20px;
+    color: #b2b2b2;
+}
+
+#variations-search-field > .control > input {
+    padding-right: 25px;
+}
+
+#configurable-attributes-container .field-variation > .label {
+    margin-left: -7px;
+}
+
+#configurable-attributes-container .field-variation > .control {
+    width: 43%;
+}
+
+#configurable-attributes-container {
+    margin-bottom: 23px;
+}
+
+#configurable-attributes-container .col-name {
+    width: 45%;
+}
+
+#configurable-attributes-container .pricing-value {
+    text-align: right;
+}
+
+#generate-variations-button {
+    margin-bottom: 18px;
+}
+
+#product-variations-matrix > .title {
+    margin-bottom: 10px;
+}
+
+#product-variations-matrix .action-upload {
+    background: #fff;
+    border-radius: 0;
+    border: 1px solid #b7b2a7;
+    padding: 0;
+    width: 31px;
+    height: 31px;
+    line-height: 30px;
+    text-align: center;
+    color: #9f9a91;
+    overflow: hidden;
+}
+
+#product-variations-matrix .action-upload:hover {
+    color: #7e7e7e;
+}
+
+#product-variations-matrix .action-upload:before {
+    font-family: 'MUI-Icons';
+    font-style: normal;
+    speak: none;
+    font-weight: normal;
+    -webkit-font-smoothing: antialiased;
+    content: '\e02d'; /* plus icon */
+    font-size: 22px;
+}
+
+#product-variations-matrix .action-upload span,
+#product-variations-matrix .action-choose span {
+    display: none;
+}
+
+#product-variations-matrix .action-choose {
+    color:#b8b3a7;
+    float: right;
+    margin-left: 5px;
+}
+#product-variations-matrix .action-choose:hover {
+    color:#7e7e7e;
+}
+#product-variations-matrix .action-choose:before {
+    font-family: 'MUI-Icons';
+    font-style: normal;
+    speak: none;
+    font-weight: normal;
+    -webkit-font-smoothing: antialiased;
+    content: '\e040'; /* user icon */
+}
+
+#product-variations-matrix .col-name > a + .action-choose:before {
+    content: '\e03f'; /* user icon */
+    color: #a09a8c;
+}
+
+/*
+    Customer
+---------------------------------------*/
+.customer-iformation:before,
+.customer-iformation:after {
+    content: "";
+    display: table;
+}
+
+.customer-iformation:after {
+    clear: both;
+}
+
+.customer-iformation table,
+.customer-iformation address {
+    width: 48.5%;
+}
+
+.customer-iformation table {
+    float: left;
+    width: 48.5%;
+}
+
+.customer-iformation address {
+    padding-top: 4px;
+    line-height: 2.2;
+    float: right;
+}
+
+.customer-iformation table tbody tr th {
+    font-weight: bold;
+}
+
+.customer-iformation table tbody tr td,
+.customer-iformation table tbody tr th {
+    background-color: #fff;
+    border: 0;
+    padding: 9px 10px 10px;
+    color: #666;
+    vertical-align: top;
+}
+
+.customer-iformation table tbody tr:nth-child(2n+1) td,
+.customer-iformation table tbody tr:nth-child(2n+1) th {
+    background-color: #fbfaf6;
+}
+
+.address-list {
+    list-style: none;
+    width: 278px;
+    margin: 0 0 10px;
+    padding: 0;
+    float: left;
+}
+
+.address-list li {
+    border: 1px solid #d9d2ca;
+    background: #f7f2ec;
+    padding: 10px 10px 15px;
+    cursor: pointer;
+    margin-bottom: -1px;
+}
+
+.address-list li.active {
+    background: #fff;
+    position: relative;
+    box-shadow: 0 1px 1px 0 rgba(217, 210, 202, 1);
+    margin-left: -2px;
+    padding-left: 12px;
+}
+
+.address-list li.active:after {
+    position: absolute;
+    font-family: 'MUI-Icons';
+    font-style: normal;
+    font-weight: normal;
+    font-size: 18px;
+    color: #fff;
+    content: "\e02a";
+    speak: none;
+    line-height: 11px;
+    width: 10px;
+    right: -9px;
+    text-indent: -6px;
+    top: 50%;
+    margin-top: -5px;
+    text-shadow: 2px 0 0 #d9d2ca;
+    z-index: 1;
+}
+
+.address-list li.adress-list-actions {
+    padding: 20px 0 0 0;
+    border: 0;
+    background: none;
+    box-shadow: none;
+    cursor: default;
+}
+
+.address-list li.adress-list-actions:first-child {
+    padding: 0;
+}
+
+.address-list li.adress-list-actions:after {
+    display: none;
+}
+
+.address-list .label {
+    float: none;
+    width: auto;
+    padding: 0 0 0 10px;
+}
+
+.address-list input[type="checkbox"] {
+    float: left;
+}
+
+.address-list address:first-line {
+    /*  its not work  if First Name and Last Name in two lines */
+    font-weight: bold;
+}
+
+.address-list address {
+    margin: 0 20px 15px 0;
+    line-height: 1.5;
+}
+
+.address-list-item-actions {
+    float: right;
+}
+
+.address-list .action-edit {
+    display: none;
+}
+
+.address-list .field {
+    margin-bottom: 15px;
+}
+
+.address-item-edit {
+    margin-left: 277px;
+}
+
+.address-item-edit-content {
+    border: 1px solid #dad1c8;
+    background: #fff;
+    box-shadow: 0 2px 1px 0 rgba(217, 210, 202, 0.5);
+}
+
+.address-item-edit .legend {
+    border-bottom: 0;
+    margin: 0 0 18px;
+    padding-left: 20%;
+}
+
+.address-item-edit .legend span {
+    padding-left: 0;
+}
+
+.address-item-edit-actions {
+    padding: 0 0 18px 20%;
+}
+
+/*
+    CMS -> Polls
+-------------------------------------- */
+
+/* Poll Answers */
+.field-poll_answers_container .control {
+    width: 600px;
+}
+
+.field-poll_answers_container .col-poll_votes_count {
+    width: 90px;
+}
+
+.field-poll_answers_container .action-add {
+    margin-top: 7px;
+}
+
+/*
+    Reports
+-------------------------------------- */
+.reports-title .page-actions {
+    float: right;
+}
+
+.reports-title .store-switcher {
+    padding: 14px 0 18px;
+}
+
+.reports-content select {
+    width: 160px;
+}
+
+.reports-content input.hasDatepicker {
+    width: 133px;
+}
+
+/* TODO: refactor when validation design is ready */
+.reports-content .required .control {
+    position: relative;
+}
+
+.reports-content input.hasDatepicker + label.mage-error {
+    left: 0;
+    position: absolute;
+    top: 30px;
+}
+
+.reports-title:before,
+.reports-title:after {
+    content: "";
+    display: table;
+}
+
+.reports-title:after {
+    clear: both;
+}
+
+/*
+    Clearfix
+-------------------------------------- */
 .images:before,
 .images:after,
 .clearfix:before,
@@ -286,4 +637,4 @@
 .images:after,
 .clearfix:after {
     clear: both;
-}
\ No newline at end of file
+}
diff --git a/app/design/adminhtml/default/backend/images/grid-cal.gif b/app/design/adminhtml/default/backend/images/grid-cal.gif
index 4a4fd50b45862befee0512acbdec747d7fa56a3c..c8cd40cdf593f8b9f89decac4a065ada4786882e 100644
Binary files a/app/design/adminhtml/default/backend/images/grid-cal.gif and b/app/design/adminhtml/default/backend/images/grid-cal.gif differ
diff --git a/app/design/adminhtml/default/backend/images/grid-sorted-th-arrows.png b/app/design/adminhtml/default/backend/images/grid-sorted-th-arrows.png
deleted file mode 100644
index 4d73368ed7079f978887b32163d7352fd73409a3..0000000000000000000000000000000000000000
Binary files a/app/design/adminhtml/default/backend/images/grid-sorted-th-arrows.png and /dev/null differ
diff --git a/app/design/adminhtml/default/backend/js/theme.js b/app/design/adminhtml/default/backend/js/theme.js
index 29dc3561ed14b094005d898d38075c1587f55649..3ffea830977b199f054d234860712889d4667276 100644
--- a/app/design/adminhtml/default/backend/js/theme.js
+++ b/app/design/adminhtml/default/backend/js/theme.js
@@ -254,30 +254,91 @@
         }
     });
 
-    $(document).ready(function() {
-        $('.header-panel .search').globalSearch();
-        $('.navigation').globalNavigation();
-        $('.fade').modalPopup();
-        $('details').details();
+    $.widget('mage.useDefault', {
+        options: {
+            field: '.field',
+            useDefault: '.use-default',
+            checkbox: '.use-default-control',
+            label: '.use-default-label'
+        },
 
-        /* Listen events on "Collapsable" events */
-        $('.collapse')
-            .on('show', function () {
-                var fieldsetWrapper = $(this).closest('.fieldset-wrapper');
+        _create: function() {
+            this.el = this.element;
+            this.field = $(this.el).closest(this.options.field);
+            this.useDefault = $(this.options.useDefault, this.field);
+            this.checkbox = $(this.options.checkbox, this.useDefault);
+            this.label = $(this.options.label, this.useDefault);
+            this.origValue = this.el.attr('data-store-label');
 
-                fieldsetWrapper.addClass('opened');
-            })
-            .on('hide', function () {
-                var fieldsetWrapper = $(this).closest('.fieldset-wrapper');
+            this._events();
+        },
 
-                fieldsetWrapper.removeClass('opened');
-            });
+        _events: function() {
+            var self = this;
 
-        $.each($('.entry-edit'), function(i, entry) {
-            $('.collapse:first', entry).collapse('show');
-        });
+            this.el
+                .on('change.toggleUseDefaultVisibility keyup.toggleUseDefaultVisibility', $.proxy(this._toggleUseDefaultVisibility, this))
+                .trigger('change.toggleUseDefaultVisibility');
+
+            this.checkbox
+                .on('change.setOrigValue', function() {
+                    if ($(this).prop('checked')) {
+                        self.el
+                            .val(self.origValue)
+                            .trigger('change.toggleUseDefaultVisibility');
+
+                        $(this).prop('checked', false);
+                    }
+                });
+        },
+
+        _toggleUseDefaultVisibility: function() {
+            var curValue = this.el.val(),
+                origValue = this.origValue;
+
+            this[curValue != origValue ? '_show' : '_hide']();
+        },
+
+        _show: function() {
+            this.useDefault.show();
+        },
+
+        _hide: function() {
+            this.useDefault.hide();
+        }
+    });
+
+    $.widget('mage.collapsable', {
+        options: {
+            parent: null,
+            openedClass: 'opened',
+            wrapper: '.fieldset-wrapper'
+        },
+
+        _create: function() {
+            this._events();
+        },
+
+        _events: function() {
+            var self = this;
+
+            this.element
+                .on('show', function (e) {
+                    var fieldsetWrapper = $(this).closest(self.options.wrapper);
+
+                    fieldsetWrapper.addClass(self.options.openedClass);
+                    e.stopPropagation();
+                })
+                .on('hide', function (e) {
+                    var fieldsetWrapper = $(this).closest(self.options.wrapper);
 
+                    fieldsetWrapper.removeClass(self.options.openedClass);
+                    e.stopPropagation();
+                });
+        }
+    });
 
+    var switcherForIe8 = function() {
         /* Switcher for IE8 */
         if ($.browser.msie && $.browser.version == '8.0') {
             var checkboxSwitcher = $('.switcher input');
@@ -292,8 +353,26 @@
                     toggleCheckboxState(checkboxSwitcher);
                 });
         }
+    };
 
+    $(document).ready(function() {
+        $('.header-panel .search').globalSearch();
+        $('.navigation').globalNavigation();
+        $('.fade').modalPopup();
+        $('details').details();
         $('.page-actions').floatingHeader();
+        $('[data-store-label]').useDefault();
+        $('.collapse').collapsable();
 
+        $.each($('.entry-edit'), function(i, entry) {
+            $('.collapse:first', entry).collapse('show');
+        });
+
+        switcherForIe8();
+    });
+
+    $(document).on('ajaxComplete', function() {
+        $('details').details();
+        switcherForIe8();
     });
 })(window.jQuery);
\ No newline at end of file
diff --git a/app/design/adminhtml/default/backend/mui/elements.css b/app/design/adminhtml/default/backend/mui/elements.css
index 3afa0e6fb402cd87206b4e743c887b5c4edf999f..1eb6172f2b17b98af05193655af72ec4c3cc2216 100644
--- a/app/design/adminhtml/default/backend/mui/elements.css
+++ b/app/design/adminhtml/default/backend/mui/elements.css
@@ -1333,6 +1333,7 @@ table.loading:after {
 .collapse.in,
 .no-js .collapse {
     height: auto !important;
+    overflow: visible;
 }
 
 .no-js .tabs-nav > li,
diff --git a/app/design/adminhtml/default/backend/mui/form.css b/app/design/adminhtml/default/backend/mui/form.css
index 42aa654cc903a234ae3d18e0c7f344946a5cb731..f2f764396e222a1c34561cf9294dc7d613e85f97 100644
--- a/app/design/adminhtml/default/backend/mui/form.css
+++ b/app/design/adminhtml/default/backend/mui/form.css
@@ -352,9 +352,14 @@ span.required {
     padding-top: 20px;
 }
 
-.form-inline .control .control-value {
+.control .control-value {
     display: inline-block;
-    padding: 8px 0 0;
+    padding: 5px 0 0;
+    vertical-align: top;
+}
+
+.control .control-value.special {
+    font-weight: bold;
 }
 
 /*
diff --git a/app/design/adminhtml/default/backend/mui/utils.css b/app/design/adminhtml/default/backend/mui/utils.css
index a0de0f57d1fa42df68d98cb48569aca80a80cff2..4f4b2d662f57b1146550f58b9c31cb890d7456cb 100644
--- a/app/design/adminhtml/default/backend/mui/utils.css
+++ b/app/design/adminhtml/default/backend/mui/utils.css
@@ -27,7 +27,7 @@
 
 /* Hide from both screenreaders and browsers: h5bp.com/u */
 .hidden {
-    display: none !important;
+    display: none;
     visibility: hidden;
 }
 
diff --git a/app/design/adminhtml/default/basic/boxes.css b/app/design/adminhtml/default/basic/boxes.css
index b094413ced703002fe4c4bddbd8e40aa01ee1292..7e53ce07335d153c2c0eea146345d6fa6bd77c3b 100644
--- a/app/design/adminhtml/default/basic/boxes.css
+++ b/app/design/adminhtml/default/basic/boxes.css
@@ -761,7 +761,7 @@ td.divider              { font-size:1px; line-height:0; }
 .scrollContent              { position:absolute; left:0; top:0; }
 
 /* Horizontal scroll */
-.hor-scroll                 { width:100%; overflow:auto; padding-bottom:4px; margin-bottom:-4px; } /* IE has personal style, see iestyles.css */
+.hor-scroll                 { width:100%; padding-bottom:4px; margin-bottom:-4px; } /* IE has personal style, see iestyles.css */
 
 
 /**/
@@ -872,6 +872,7 @@ div.autocomplete ul li { padding:.5em .7em; min-height:32px; cursor:pointer; tex
 }
 .mage-suggest-dropdown .ui-menu {
     padding: 0px;
+    width: 100%;
 }
 .mage-suggest-dropdown .ui-menu .ui-menu-item a.ui-state-focus {
     background: #ebebeb;
@@ -885,6 +886,7 @@ div.autocomplete ul li { padding:.5em .7em; min-height:32px; cursor:pointer; tex
 .mage-suggest-dropdown {
     overflow: auto;
     max-height: 500px;
+    z-index: 1;
 }
 .mage-suggest.category-select .mage-suggest-inner {background: transparent; position: static; border: none; border-radius: 0px; box-shadow: none;}
 .mage-suggest.category-select .category-selector-choices {background: #fff; border: 1px solid #ddd; border-radius: 5px; box-shadow: none; overflow: hidden;}
diff --git a/app/design/frontend/default/demo/css/styles.css b/app/design/frontend/default/demo/css/styles.css
index 3d01cba7bb7694d95820b25ea97ccf3c4e75a3db..8aa0e2fdd399dec69163334427f491f0a2e83c65 100644
--- a/app/design/frontend/default/demo/css/styles.css
+++ b/app/design/frontend/default/demo/css/styles.css
@@ -30,7 +30,7 @@ body          { background:#496778 url(../images/bkg_body.gif) 50% 0 repeat-y; f
 
 img           { border:0; vertical-align:top; }
 
-a             { color:#1e7ec8; text-decoration:underline; }
+a,.l          { color:#1e7ec8; text-decoration:underline; }
 a:hover       { text-decoration:none; }
 :focus        { outline:0; }
 
@@ -87,6 +87,7 @@ ul,ol         { list-style:none; }
 .no-margin    { margin:0 !important; }
 .no-padding   { padding:0 !important; }
 .no-bg        { background:none !important; }
+.clear        { clear: both; }
 /* ======================================================================================= */
 
 
@@ -130,6 +131,7 @@ ul,ol         { list-style:none; }
 .col4-set .col-2 { float:left; width:23.5%; margin:0 2%; }
 .col4-set .col-3 { float:left; width:23.5%; }
 .col4-set .col-4 { float:right; width:23.5%; }
+
 /* ======================================================================================= */
 
 
diff --git a/app/design/frontend/default/demo_blue/css/styles.css b/app/design/frontend/default/demo_blue/css/styles.css
index c15c7ada09bb34ce35756de8ee0e38d309c557cf..ed756d7f9dd4a1588704fcb8bd91ee60256e510e 100644
--- a/app/design/frontend/default/demo_blue/css/styles.css
+++ b/app/design/frontend/default/demo_blue/css/styles.css
@@ -31,7 +31,7 @@ body          { background:#4c697b url(../images/bkg_body.gif) 0 0 repeat-x; fon
 
 img           { border:0; vertical-align:top; }
 
-a             { color:#1e7ec8; text-decoration:underline; }
+a,.l          { color:#1e7ec8; text-decoration:underline; }
 a:hover       { text-decoration:none; }
 :focus        { outline:0; }
 
@@ -88,6 +88,7 @@ ul,ol         { list-style:none; }
 .no-margin    { margin:0 !important; }
 .no-padding   { padding:0 !important; }
 .no-bg        { background:none !important; }
+.clear        { clear: both; }
 /* ======================================================================================= */
 
 
diff --git a/app/design/frontend/default/modern/css/styles.css b/app/design/frontend/default/modern/css/styles.css
index 7d98d7a319bd87ad1a61266fbdbf15ade6334c75..ebd4fb10e95dc4462d471a6b9b116cad10a06d87 100644
--- a/app/design/frontend/default/modern/css/styles.css
+++ b/app/design/frontend/default/modern/css/styles.css
@@ -30,7 +30,7 @@ body          { background:#f2f2f2 url(../images/bkg_body.gif) 0 0 repeat; font:
 
 img           { border:0; vertical-align:top; }
 
-a             { color:#4f8100; text-decoration:none; }
+a,.l          { color:#4f8100; text-decoration:none; }
 a:hover       { text-decoration:underline; }
 :focus        { outline:0; }
 
@@ -86,6 +86,7 @@ ul,ol         { list-style:none; }
 .no-margin    { margin:0 !important; }
 .no-padding   { padding:0 !important; }
 .no-bg        { background:none !important; }
+.clear        { clear: both; }
 /* ======================================================================================= */
 
 
diff --git a/app/etc/config.xml b/app/etc/config.xml
index 5c02dcabf498fc65cba1b967fc098ed3e072b9ca..d594ec1c2f27d0b7edeb929e79eb8d4202fdb8ad 100644
--- a/app/etc/config.xml
+++ b/app/etc/config.xml
@@ -87,6 +87,21 @@
             <Magento_Data_Structure>
                 <shared>0</shared>
             </Magento_Data_Structure>
+            <Magento_Http_Handler_Composite>
+                <parameters>
+                    <handlers>
+                        <app>
+                            <sortOrder>50</sortOrder>
+                            <class>Mage_Core_Model_App_Handler</class>
+                        </app>
+                    </handlers>
+                </parameters>
+            </Magento_Http_Handler_Composite>
+            <Mage_Core_Helper_Url>
+                <parameters>
+                    <translate>Mage_Core_Model_Translate_Proxy</translate>
+                </parameters>
+            </Mage_Core_Helper_Url>
         </di>
     </global>
     <default>
diff --git a/dev/shell/indexer.php b/dev/shell/indexer.php
index 064bfa238bac57194faeaa31e6de39307b2f220a..641ac5b555a54ae73cc88fa93856d72d2daff4b5 100644
--- a/dev/shell/indexer.php
+++ b/dev/shell/indexer.php
@@ -25,11 +25,10 @@
  */
 
 require_once __DIR__ . '/../../app/bootstrap.php';
-Mage::app('admin', 'store');
-
-/** @var $shell Mage_Index_Model_Shell */
-$shell = Mage::getModel('Mage_Index_Model_Shell', array('entryPoint' => basename(__FILE__)));
-$shell->run();
-if ($shell->hasErrors()) {
-    exit(1);
-}
+$params = array(
+    Mage::PARAM_RUN_CODE => 'admin',
+    Mage::PARAM_RUN_TYPE => 'store',
+    'entryPoint' => basename(__FILE__),
+);
+$entryPoint = new Mage_Index_Model_EntryPoint_Shell(BP, $params);
+$entryPoint->processRequest();
diff --git a/dev/shell/install.php b/dev/shell/install.php
index 557cdf5c1da356c80e310ef3a98ae31a94a3b740..e59a9b9fe3ad32be796ca32962730b587128d577 100644
--- a/dev/shell/install.php
+++ b/dev/shell/install.php
@@ -63,38 +63,5 @@ if (empty($args)) {
 define('BARE_BOOTSTRAP', 1);
 require_once __DIR__ . '/../../app/bootstrap.php';
 
-$installer = new Mage_Install_Model_Installer_Console(
-    new Magento_Filesystem(new Magento_Filesystem_Adapter_Local()),
-    $args
-);
-if (isset($args['show_locales'])) {
-    var_export($installer->getAvailableLocales());
-} else if (isset($args['show_currencies'])) {
-    var_export($installer->getAvailableCurrencies());
-} else if (isset($args['show_timezones'])) {
-    var_export($installer->getAvailableTimezones());
-} else if (isset($args['show_install_options'])) {
-    var_export($installer->getAvailableInstallOptions());
-} else {
-    if (isset($args['config']) && file_exists($args['config'])) {
-        $config = (array) include($args['config']);
-        $args = array_merge((array)$config, $args);
-    }
-    $isUninstallMode = isset($args['uninstall']);
-    if ($isUninstallMode) {
-        $result = $installer->uninstall();
-    } else {
-        $result = $installer->install($args);
-    }
-    if (!$installer->hasErrors()) {
-        if ($isUninstallMode) {
-            $msg = $result ? 'Uninstalled successfully' : 'Ignoring attempt to uninstall non-installed application';
-        } else {
-            $msg = 'Installed successfully' . ($result ? ' (encryption key "' . $result . '")' : '');
-        }
-        echo $msg . PHP_EOL;
-    } else {
-        echo implode(PHP_EOL, $installer->getErrors()) . PHP_EOL;
-        exit(1);
-    }
-}
+$entryPoint = new Mage_Install_Model_EntryPoint_Console(BP, $args);
+$entryPoint->processRequest();
diff --git a/dev/shell/log.php b/dev/shell/log.php
index fd91696dd0a360e21df3336cfa1538cfbe0e0b02..2a2d331d2a79b2804fe2fb9c0978b284fc3908ec 100644
--- a/dev/shell/log.php
+++ b/dev/shell/log.php
@@ -25,8 +25,10 @@
  */
 
 require_once __DIR__ . '/../../app/bootstrap.php';
-Mage::app('admin', 'store');
-
-/** @var $shell Mage_Log_Model_Shell */
-$shell = Mage::getModel('Mage_Log_Model_Shell', array('entryPoint' => basename(__FILE__)));
-$shell->run();
+$params = array(
+    Mage::PARAM_RUN_CODE => 'admin',
+    Mage::PARAM_RUN_TYPE => 'store',
+    'entryPoint' => basename(__FILE__),
+);
+$entryPoint = new Mage_Log_Model_EntryPoint_Shell(BP, $params);
+$entryPoint->processRequest();
diff --git a/dev/tests/integration/framework/Magento/Test/Annotation/ConfigFixture.php b/dev/tests/integration/framework/Magento/Test/Annotation/ConfigFixture.php
index 4052e6c6e865f74d801d1364db9419d70a7402af..f36135bbb57146d7ac5e4f9ed37b6d486d19e63f 100644
--- a/dev/tests/integration/framework/Magento/Test/Annotation/ConfigFixture.php
+++ b/dev/tests/integration/framework/Magento/Test/Annotation/ConfigFixture.php
@@ -82,6 +82,9 @@ class Magento_Test_Annotation_ConfigFixture
     {
         if ($storeCode === false) {
             Mage::getConfig()->setNode($configPath, $value);
+            Mage::getObjectManager()->get('Mage_Core_Model_Config_Modules')->setNode($configPath, $value);
+            Mage::getObjectManager()->get('Mage_Core_Model_Config_Primary')->setNode($configPath, $value);
+            Mage::getObjectManager()->get('Mage_Core_Model_Config_Locales')->setNode($configPath, $value);
         } else {
             Mage::app()->getStore($storeCode)->setConfig($configPath, $value);
         }
diff --git a/dev/tests/integration/framework/Magento/Test/Application.php b/dev/tests/integration/framework/Magento/Test/Application.php
index e3e3ef5a5187e4c62e66358608de5bf20254fe40..75cb909f1b0a5c768cd4c5543e6f0532b3bf0c38 100644
--- a/dev/tests/integration/framework/Magento/Test/Application.php
+++ b/dev/tests/integration/framework/Magento/Test/Application.php
@@ -110,7 +110,7 @@ class Magento_Test_Application
         $this->_installEtcDir = "$installDir/etc";
 
         $this->_initParams = array(
-            Mage_Core_Model_App::INIT_OPTION_DIRS => array(
+            Mage::PARAM_APP_DIRS => array(
                 Mage_Core_Model_Dir::CONFIG     => $this->_installEtcDir,
                 Mage_Core_Model_Dir::VAR_DIR    => $installDir,
                 Mage_Core_Model_Dir::MEDIA      => "$installDir/media",
@@ -163,9 +163,23 @@ class Magento_Test_Application
      */
     public function initialize($overriddenParams = array())
     {
+        $overriddenParams[Mage::PARAM_BASEDIR] = BP;
         Mage::setIsDeveloperMode($this->_isDeveloperMode);
         Mage::$headersSentThrowsException = false;
-        Mage::app($this->_customizeParams($overriddenParams));
+        $config = new Mage_Core_Model_ObjectManager_Config(
+            $this->_customizeParams($overriddenParams)
+        );
+        if (!Mage::getObjectManager()) {
+            /** @var $app Mage_Core_Model_App */
+            new Magento_Test_ObjectManager($config, BP);
+        } else {
+            $config->configure(Mage::getObjectManager());
+        }
+
+        Mage::getObjectManager()->get('Mage_Core_Model_Resource')
+            ->setResourceConfig(Mage::getObjectManager()->get('Mage_Core_Model_Config_Resource'));
+        Mage::getObjectManager()->get('Mage_Core_Model_Resource')
+            ->setCache(Mage::getObjectManager()->get('Mage_Core_Model_Cache'));
     }
 
     /**
@@ -181,12 +195,15 @@ class Magento_Test_Application
 
     /**
      * Run application normally, but with encapsulated initialization options
-     *
-     * @param array $overriddenParams
      */
-    public function run(array $overriddenParams)
+    public function run()
     {
-        Mage::run($this->_customizeParams($overriddenParams));
+        $composer = Mage::getObjectManager();
+        $handler = $composer->get('Magento_Http_Handler_Composite');
+        $handler->handle(
+            isset($params['request']) ? $params['request'] : $composer->get('Mage_Core_Controller_Request_Http'),
+            isset($params['response']) ? $params['response'] : $composer->get('Mage_Core_Controller_Response_Http')
+        );
     }
 
     /**
@@ -240,8 +257,10 @@ class Magento_Test_Application
         $this->initialize();
 
         /* Run all install and data-install scripts */
-        Mage_Core_Model_Resource_Setup::applyAllUpdates();
-        Mage_Core_Model_Resource_Setup::applyAllDataUpdates();
+        /** @var $updater Mage_Core_Model_Db_Updater */
+        $updater = Mage::getObjectManager()->get('Mage_Core_Model_Db_Updater');
+        $updater->updateScheme();
+        $updater->updateData();
 
         /* Enable configuration cache by default in order to improve tests performance */
         Mage::app()->getCacheInstance()->saveOptions(array('config' => 1));
diff --git a/dev/tests/integration/framework/Magento/Test/Cookie.php b/dev/tests/integration/framework/Magento/Test/Cookie.php
index 2c62ca79707859e27d81beaf465db39c61e4e11e..ea38769b510655625a04eb55773c7dedb1b75352 100644
--- a/dev/tests/integration/framework/Magento/Test/Cookie.php
+++ b/dev/tests/integration/framework/Magento/Test/Cookie.php
@@ -30,6 +30,27 @@
  */
 class Magento_Test_Cookie extends Mage_Core_Model_Cookie
 {
+    /**
+     * @var Mage_Core_Controller_Request_Http
+     */
+    protected $_request;
+
+    /**
+     * @param Mage_Core_Controller_Request_Http $request
+     */
+    public function __construct(Mage_Core_Controller_Request_Http $request = null)
+    {
+        $this->_request = $request;
+    }
+
+    /**
+     * @return Mage_Core_Controller_Request_Http
+     */
+    protected function _getRequest()
+    {
+        return $this->_request ?: parent::_getRequest();
+    }
+
     /**
      * Dummy function, which sets value directly to $_COOKIE super-global array instead of calling setcookie()
      *
diff --git a/dev/tests/integration/framework/Magento/Test/ObjectManager.php b/dev/tests/integration/framework/Magento/Test/ObjectManager.php
index e37a4cc610d43b17d018a3332befdb6f37096c3a..7d2794fdf79f9cd68e52cce40c9da65fc05878b4 100644
--- a/dev/tests/integration/framework/Magento/Test/ObjectManager.php
+++ b/dev/tests/integration/framework/Magento/Test/ObjectManager.php
@@ -1,5 +1,7 @@
 <?php
 /**
+ * Test object manager
+ *
  * Magento
  *
  * NOTICE OF LICENSE
@@ -18,15 +20,20 @@
  * versions in the future. If you wish to customize Magento for your
  * needs please refer to http://www.magentocommerce.com for more information.
  *
- * @category    Magento
- * @package     Magento
- * @subpackage  integration_tests
  * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
-
-class Magento_Test_ObjectManager extends Magento_ObjectManager_Zend
+class Magento_Test_ObjectManager extends Mage_Core_Model_ObjectManager
 {
+    /**
+     * Classes with xml properties to explicitly call __destruct() due to https://bugs.php.net/bug.php?id=62468
+     *
+     * @var array
+     */
+    protected $_classesToDestruct = array(
+        'Mage_Core_Model_Layout',
+    );
+
     /**
      * Clear InstanceManager cache
      *
@@ -34,6 +41,17 @@ class Magento_Test_ObjectManager extends Magento_ObjectManager_Zend
      */
     public function clearCache()
     {
+        foreach ($this->_classesToDestruct as $className) {
+            if ($this->_di->instanceManager()->hasSharedInstance($className)) {
+                $object = $this->_di->instanceManager()->getSharedInstance($className);
+                if ($object) {
+                    // force to cleanup circular references
+                    $object->__destruct();
+                }
+            }
+        }
+
+        Mage::getSingleton('Mage_Core_Model_Config_Base')->destroy();
         $instanceManagerNew = new Magento_Di_InstanceManager_Zend();
         $instanceManagerNew->addSharedInstance($this, 'Magento_ObjectManager');
         if ($this->_di->instanceManager()->hasSharedInstance('Mage_Core_Model_Resource')) {
diff --git a/dev/tests/integration/framework/Magento/Test/TestCase/ControllerAbstract.php b/dev/tests/integration/framework/Magento/Test/TestCase/ControllerAbstract.php
index 8d0b8a1e257015560fec43ce75e330629020a3b1..b2c851a0ccb94409cbcb84b5356cffc713f52745 100644
--- a/dev/tests/integration/framework/Magento/Test/TestCase/ControllerAbstract.php
+++ b/dev/tests/integration/framework/Magento/Test/TestCase/ControllerAbstract.php
@@ -76,8 +76,6 @@ abstract class Magento_Test_TestCase_ControllerAbstract extends PHPUnit_Framewor
     {
         $this->_assertSessionErrors = false;
         $this->_objectManager = Mage::getObjectManager();
-        $this->_runOptions[Mage::INIT_OPTION_REQUEST]  = $this->getRequest();
-        $this->_runOptions[Mage::INIT_OPTION_RESPONSE] = $this->getResponse();
     }
 
     protected function tearDown()
@@ -85,7 +83,6 @@ abstract class Magento_Test_TestCase_ControllerAbstract extends PHPUnit_Framewor
         $this->_request = null;
         $this->_response = null;
         $this->_objectManager = null;
-        $this->_runOptions = array();
     }
 
     /**
@@ -107,8 +104,10 @@ abstract class Magento_Test_TestCase_ControllerAbstract extends PHPUnit_Framewor
     public function dispatch($uri)
     {
         $this->getRequest()->setRequestUri($uri);
-        $this->_getBootstrap()->runApp($this->_runOptions);
-        $this->_assertSessionErrors = true;
+        $this->_getBootstrap()->runApp(array(
+            'request' => $this->getRequest(),
+            'response' => $this->getResponse()
+        ));
     }
 
     /**
diff --git a/dev/tests/integration/framework/bootstrap.php b/dev/tests/integration/framework/bootstrap.php
index 3e9283eb325b5478793b5c8b316de5c26725cc8a..60c152b5eddd5ec5c0c37967b20bcb73e9b6f51d 100644
--- a/dev/tests/integration/framework/bootstrap.php
+++ b/dev/tests/integration/framework/bootstrap.php
@@ -37,9 +37,6 @@ Magento_Autoload_IncludePath::addIncludePath(array(
     "$testsBaseDir/testsuite",
 ));
 
-/* Initialize object manager instance */
-Mage::initializeObjectManager(null, new Magento_Test_ObjectManager());
-
 /* Bootstrap the application */
 $invariantSettings = array(
     'TESTS_LOCAL_CONFIG_EXTRA_FILE' => 'etc/integration-tests-config.xml',
diff --git a/dev/tests/integration/framework/tests/unit/framework/bootstrap.php b/dev/tests/integration/framework/tests/unit/framework/bootstrap.php
index dcf132f1016d4cb2e3e8f7a885f31cb68bc236a2..85355e59a35090740323336b474182fd95511cbe 100644
--- a/dev/tests/integration/framework/tests/unit/framework/bootstrap.php
+++ b/dev/tests/integration/framework/tests/unit/framework/bootstrap.php
@@ -28,5 +28,4 @@
 $rootDir = realpath(__DIR__ . '/../../../../../../../');
 require_once $rootDir . '/app/bootstrap.php';
 Magento_Autoload_IncludePath::addIncludePath($rootDir . '/dev/tests/integration/framework');
-
-Mage::initializeObjectManager(null, new Magento_Test_ObjectManager());
+Mage::setIsSerializable(false);
diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/CookieTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/CookieTest.php
index ecec4c0e71d16a45575008387bbebb6af23a143d..add727a2b72b3ec65e91352570887aa65cbc83ef 100644
--- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/CookieTest.php
+++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/CookieTest.php
@@ -39,7 +39,7 @@ class Magento_Test_CookieTest extends PHPUnit_Framework_TestCase
 
     protected function setUp()
     {
-        $this->_model = new Magento_Test_Cookie();
+        $this->_model = new Magento_Test_Cookie(new Mage_Core_Controller_Request_Http());
     }
 
     public function testSet()
diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Helper/BootstrapTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Helper/BootstrapTest.php
index 7c31c89dd4bad93d15a5e81727c03281a16272e3..63b3c460ef28d200b6579d293af6f6ee3e5a5d43 100644
--- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Helper/BootstrapTest.php
+++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Helper/BootstrapTest.php
@@ -51,7 +51,7 @@ class Magento_Test_Helper_BootstrapTest extends PHPUnit_Framework_TestCase
      * @var array
      */
     protected $_fixtureInitParams = array(
-        Mage_Core_Model_App::INIT_OPTION_DIRS => array(
+        Mage::PARAM_APP_DIRS => array(
             Mage_Core_Model_Dir::CONFIG     => __DIR__,
             Mage_Core_Model_Dir::VAR_DIR    => __DIR__,
         ),
diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/ObjectManagerTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/ObjectManagerTest.php
index 6594b5b6c17e3077e8eae02da022375ac280492e..1afcf93eb33f7312f6a872c230bbac229afc9abf 100644
--- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/ObjectManagerTest.php
+++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/ObjectManagerTest.php
@@ -48,7 +48,8 @@ class Magento_Test_ObjectManagerTest extends PHPUnit_Framework_TestCase
         $instanceManager->addSharedInstance($resource, 'Mage_Core_Model_Resource');
 
         $diInstance = new Magento_Di_Zend();
-        $model = new Magento_Test_ObjectManager(null, $diInstance);
+        $config = $this->getMock('Magento_ObjectManager_Configuration');
+        $model = new Magento_Test_ObjectManager($config, null, $diInstance);
 
         $diInstance->setInstanceManager($instanceManager);
         $this->assertSame($model, $model->clearCache());
diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/TestCase/ControllerAbstractTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/TestCase/ControllerAbstractTest.php
index 45346375fe71ca1771d3bc6ae4d3624432cb5206..a2cffc1062d7bfa6cff9a3b386fc0d8fa7e57b1c 100644
--- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/TestCase/ControllerAbstractTest.php
+++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/TestCase/ControllerAbstractTest.php
@@ -59,17 +59,9 @@ class Magento_Test_TestCase_ControllerAbstractTest extends Magento_Test_TestCase
         return $this->_bootstrap;
     }
 
-    public function testSetUp()
-    {
-        $this->assertInternalType('array', $this->_runOptions);
-        $this->assertArrayHasKey('request', $this->_runOptions);
-        $this->assertInstanceOf('Magento_Test_Request', $this->_runOptions['request']);
-        $this->assertArrayHasKey('response', $this->_runOptions);
-        $this->assertInstanceOf('Magento_Test_Response', $this->_runOptions['response']);
-    }
-
     public function testGetRequest()
     {
+        $this->_objectManager = $this->getMock('Magento_ObjectManager');
         $request = $this->getRequest();
         $this->assertInstanceOf('Magento_Test_Request', $request);
         $this->assertSame($request, $this->getRequest());
@@ -77,6 +69,7 @@ class Magento_Test_TestCase_ControllerAbstractTest extends Magento_Test_TestCase
 
     public function testGetResponse()
     {
+        $this->_objectManager = $this->getMock('Magento_ObjectManager');
         $response = $this->getResponse();
         $this->assertInstanceOf('Magento_Test_Response', $response);
         $this->assertSame($response, $this->getResponse());
@@ -87,6 +80,7 @@ class Magento_Test_TestCase_ControllerAbstractTest extends Magento_Test_TestCase
      */
     public function testAssert404NotFound()
     {
+        $this->_objectManager = $this->getMock('Magento_ObjectManager');
         $this->getRequest()->setActionName('noRoute');
         $this->getResponse()->setBody(
             '404 Not Found test <h3>We are sorry, but the page you are looking for cannot be found.</h3>'
@@ -107,6 +101,7 @@ class Magento_Test_TestCase_ControllerAbstractTest extends Magento_Test_TestCase
      */
     public function testAssertRedirectFailure()
     {
+        $this->_objectManager = $this->getMock('Magento_ObjectManager');
         $this->assertRedirect();
     }
 
@@ -115,6 +110,7 @@ class Magento_Test_TestCase_ControllerAbstractTest extends Magento_Test_TestCase
      */
     public function testAssertRedirect()
     {
+        $this->_objectManager = $this->getMock('Magento_ObjectManager');
         /*
          * Prevent calling Mage_Core_Controller_Response_Http::setRedirect() because it executes Mage::dispatchEvent(),
          * which requires fully initialized application environment intentionally not available for unit tests
diff --git a/dev/tests/integration/testsuite/Mage/Adminhtml/Controller/ActionTest.php b/dev/tests/integration/testsuite/Mage/Adminhtml/Controller/ActionTest.php
index 7f323bdb8b7d0c1c8aae342a3f16807c667f5454..bfbe9324b7dfebf24cf97abd595dcf1397364879 100644
--- a/dev/tests/integration/testsuite/Mage/Adminhtml/Controller/ActionTest.php
+++ b/dev/tests/integration/testsuite/Mage/Adminhtml/Controller/ActionTest.php
@@ -39,10 +39,10 @@ class Mage_Adminhtml_Controller_ActionTest extends Magento_Test_TestCase_Control
             array(
                 'request'         => new Magento_Test_Request(),
                 'response'        => new Magento_Test_Response(),
-                'areaCode'        => 'adminhtml',
                 'objectManager'   => Mage::getObjectManager(),
                 'frontController' => Mage::getObjectManager()->get('Mage_Core_Controller_Varien_Front'),
-                'layoutFactory'   => Mage::getObjectManager()->get('Mage_Core_Model_Layout_Factory')
+                'layoutFactory'   => Mage::getObjectManager()->get('Mage_Core_Model_Layout_Factory'),
+                'areaCode'        => 'adminhtml'
             )
         );
     }
diff --git a/dev/tests/integration/testsuite/Mage/Adminhtml/DashboardControllerTest.php b/dev/tests/integration/testsuite/Mage/Adminhtml/DashboardControllerTest.php
index 7ba80adf19762598bbe2ad19d443c67462fcfa2b..3c0fe4e6a160f5d4f365d6ca4e7072861efb61ab 100644
--- a/dev/tests/integration/testsuite/Mage/Adminhtml/DashboardControllerTest.php
+++ b/dev/tests/integration/testsuite/Mage/Adminhtml/DashboardControllerTest.php
@@ -44,7 +44,8 @@ class Mage_Adminhtml_DashboardControllerTest extends Mage_Backend_Utility_Contro
             . 'oZCI7czoxNjoiZTpBQUFBQUFBQWYuQUFBQSI7czo0OiJjaHh0IjtzOjM6IngseSI7czo0OiJjaHhsIjtzOjc0OiIwOnwxMC8xMy8xMnw'
             . 'xMC8xNC8xMnwxMC8xNS8xMnwxMC8xNi8xMnwxMC8xNy8xMnwxMC8xOC8xMnwxMC8xOS8xMnwxOnwwfDF8MiI7czozOiJjaHMiO3M6Nzo'
             . 'iNTg3eDMwMCI7czozOiJjaGciO3M6MjI6IjE2LjY2NjY2NjY2NjY2Nyw1MCwxLDAiO30%3D';
-        $helper = new Mage_Adminhtml_Helper_Dashboard_Data;
+        /** @var $helper Mage_Adminhtml_Helper_Dashboard_Data */
+        $helper = Mage::helper('Mage_Adminhtml_Helper_Dashboard_Data') ;
         $hash = $helper->getChartDataHash($gaFixture);
         $this->getRequest()->setParam('ga', $gaFixture)->setParam('h', $hash);
         $this->dispatch('backend/admin/dashboard/tunnel');
diff --git a/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/Catalog/CategoryControllerTest.php b/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/Catalog/CategoryControllerTest.php
index 8b22b63f0d9e6aa2a0abe5c9a2453a07af948b8d..1b471f245b2a658451807dd6173775a9b1477ee7 100644
--- a/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/Catalog/CategoryControllerTest.php
+++ b/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/Catalog/CategoryControllerTest.php
@@ -115,7 +115,7 @@ class Mage_Adminhtml_Catalog_CategoryControllerTest extends Mage_Backend_Utility
      */
     public static function categoryCreatedFromProductCreationPageDataProvider()
     {
-        /* Keep in sync with /app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/category/new/js.phtml */
+        /* Keep in sync with new-category-dialog.js */
         $postData = array(
             'general' => array (
                 'name' => 'Category Created From Product Creation Page',
@@ -134,7 +134,7 @@ class Mage_Adminhtml_Catalog_CategoryControllerTest extends Mage_Backend_Utility
 
     public function testSuggestCategoriesActionDefaultCategoryFound()
     {
-        $this->getRequest()->setParam('name_part', 'Default');
+        $this->getRequest()->setParam('label_part', 'Default');
         $this->dispatch('backend/admin/catalog_category/suggestCategories');
         $this->assertEquals(
             '[{"id":"2","children":[],"is_active":"1","label":"Default Category"}]',
@@ -144,7 +144,7 @@ class Mage_Adminhtml_Catalog_CategoryControllerTest extends Mage_Backend_Utility
 
     public function testSuggestCategoriesActionNoSuggestions()
     {
-        $this->getRequest()->setParam('name_part', strrev('Default'));
+        $this->getRequest()->setParam('label_part', strrev('Default'));
         $this->dispatch('backend/admin/catalog_category/suggestCategories');
         $this->assertEquals('[]', $this->getResponse()->getBody());
     }
diff --git a/dev/tests/integration/testsuite/Mage/Backend/Block/System/Config/FormTest.php b/dev/tests/integration/testsuite/Mage/Backend/Block/System/Config/FormTest.php
index eddedbb710a81353c1ec2eaba574a019a410c30d..bba0a7aea3df66d6c0ddfc21d7c3509d8d3889d3 100644
--- a/dev/tests/integration/testsuite/Mage/Backend/Block/System/Config/FormTest.php
+++ b/dev/tests/integration/testsuite/Mage/Backend/Block/System/Config/FormTest.php
@@ -30,7 +30,7 @@ class Mage_Backend_Block_System_Config_FormTest extends PHPUnit_Framework_TestCa
     public function testDependenceHtml()
     {
         /** @var $layout Mage_Core_Model_Layout */
-        $layout = Mage::getModel('Mage_Core_Model_Layout');
+        $layout = Mage::getModel('Mage_Core_Model_Layout', array('area' => 'adminhtml'));
         Mage::getConfig()->setCurrentAreaCode('adminhtml');
         /** @var $block Mage_Backend_Block_System_Config_Form */
         $block = $layout->createBlock('Mage_Backend_Block_System_Config_Form', 'block');
@@ -130,25 +130,18 @@ class Mage_Backend_Block_System_Config_FormTest extends PHPUnit_Framework_TestCa
     public function initFieldsInheritCheckboxDataProvider()
     {
         Magento_Test_Helper_Bootstrap::getInstance()->reinitialize(array(
-            'global_ban_use_cache' => true,
+            Mage::PARAM_BAN_CACHE => true,
         ));
         Mage::getConfig()->setCurrentAreaCode('adminhtml');
 
-        $configMock = $this->getMock('Mage_Core_Model_Config', array(), array(), '', false, false);
+        $configMock = $this->getMock('Mage_Core_Model_Config_Modules_Reader', array(), array(), '', false, false);
         $configMock->expects($this->any())->method('getModuleConfigurationFiles')
             ->will($this->returnValue(array(__DIR__ . '/_files/test_section_config.xml')));
-        $configMock->expects($this->any())->method('getAreaConfig')->will($this->returnValue('adminhtml'));
-        $configMock->expects($this->any())
-            ->method('getModuleDir')
-            ->with('etc', 'Mage_Backend')
-            ->will(
-                $this->returnValue(
-                    realpath(__DIR__ . '/../../../../../../../../../app/code/core/Mage/Backend/etc')
-                )
-            );
+        $configMock->expects($this->any())->method('getModuleDir')
+            ->will($this->returnValue(BP . '/app/code/core/Mage/Backend/etc'));
 
         $structureReader = Mage::getSingleton('Mage_Backend_Model_Config_Structure_Reader',
-            array('config' => $configMock)
+            array('moduleReader' => $configMock)
         );
         /** @var Mage_Backend_Model_Config_Structure $structure  */
         $structure = Mage::getSingleton('Mage_Backend_Model_Config_Structure', array(
diff --git a/dev/tests/integration/testsuite/Mage/Backend/Block/Widget/Grid/MassactionTest.php b/dev/tests/integration/testsuite/Mage/Backend/Block/Widget/Grid/MassactionTest.php
index e6beca91d0cd55a893424178d8428640f0184685..0ebf7ddb579f67f9e477a24477e774130b7dc0bf 100644
--- a/dev/tests/integration/testsuite/Mage/Backend/Block/Widget/Grid/MassactionTest.php
+++ b/dev/tests/integration/testsuite/Mage/Backend/Block/Widget/Grid/MassactionTest.php
@@ -42,6 +42,7 @@ class Mage_Backend_Block_Widget_Grid_MassactionTest extends PHPUnit_Framework_Te
 
     protected function setUp()
     {
+        $this->markTestIncomplete('MAGETWO-6406');
         $this->_setFixtureTheme();
 
         $this->_layout = Mage::getModel('Mage_Core_Model_Layout', array('area' => 'adminhtml'));
@@ -58,9 +59,9 @@ class Mage_Backend_Block_Widget_Grid_MassactionTest extends PHPUnit_Framework_Te
     protected function _setFixtureTheme()
     {
         Magento_Test_Helper_Bootstrap::getInstance()->reinitialize(array(
-            Mage_Core_Model_App::INIT_OPTION_SCOPE_TYPE => 'store',
-            Mage_Core_Model_App::INIT_OPTION_SCOPE_CODE => 'admin',
-            Mage_Core_Model_App::INIT_OPTION_DIRS => array(
+            Mage::PARAM_RUN_CODE => 'admin',
+            Mage::PARAM_RUN_TYPE => 'store',
+            Mage::PARAM_APP_DIRS => array(
                 Mage_Core_Model_Dir::THEMES => __DIR__ . '/../../_files/design'
             ),
         ));
diff --git a/dev/tests/integration/testsuite/Mage/Backend/Block/Widget/GridTest.php b/dev/tests/integration/testsuite/Mage/Backend/Block/Widget/GridTest.php
index 7afde5b2fbce6892a9670d82a4c10b6ac888f215..e220c67654b6fc46bdc9b3d828720e44fea6055f 100644
--- a/dev/tests/integration/testsuite/Mage/Backend/Block/Widget/GridTest.php
+++ b/dev/tests/integration/testsuite/Mage/Backend/Block/Widget/GridTest.php
@@ -60,6 +60,10 @@ class Mage_Backend_Block_Widget_GridTest extends PHPUnit_Framework_TestCase
         $this->_layoutMock->expects($this->any())->method('createBlock')
             ->with('Mage_Backend_Block_Widget_Button')
             ->will($this->returnValue(Mage::app()->getLayout()->createBlock('Mage_Backend_Block_Widget_Button')));
+        $this->_layoutMock->expects($this->any())->method('helper')
+            ->with('Mage_Core_Helper_Data')
+            ->will($this->returnValue(Mage::helper('Mage_Core_Helper_Data')));
+
 
         $this->_block = Mage::app()->getLayout()->createBlock('Mage_Backend_Block_Widget_Grid');
         $this->_block->setLayout($this->_layoutMock);
@@ -92,7 +96,7 @@ class Mage_Backend_Block_Widget_GridTest extends PHPUnit_Framework_TestCase
             Mage::getModel('Mage_Core_Model_Store_Config'),
             Mage::getModel('Mage_Core_Controller_Varien_Front'),
             Mage::getModel('Mage_Core_Model_Factory_Helper'),
-            new Mage_Core_Model_Dir(__DIR__),
+            new Mage_Core_Model_Dir(__DIR__, new Varien_Io_File()),
             Mage::getModel('Mage_Core_Model_Logger'),
             new Magento_Filesystem(new Magento_Filesystem_Adapter_Local),
             Mage::getModel('Mage_Backend_Helper_Data'),
diff --git a/dev/tests/integration/testsuite/Mage/Backend/Block/_files/backend_theme.php b/dev/tests/integration/testsuite/Mage/Backend/Block/_files/backend_theme.php
index 12d815266586f74ad871b616dccffa0c8e9deb81..50d28c0679c6c38a0dea345c73480d8d5fda8eb4 100644
--- a/dev/tests/integration/testsuite/Mage/Backend/Block/_files/backend_theme.php
+++ b/dev/tests/integration/testsuite/Mage/Backend/Block/_files/backend_theme.php
@@ -22,6 +22,7 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 /** @var $registration Mage_Core_Model_Theme_Registration */
+Mage::app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_ADMINHTML, Mage_Core_Model_App_Area::PART_CONFIG);
 $registration = Mage::getModel('Mage_Core_Model_Theme_Registration');
 $registration->register(
     __DIR__ . DIRECTORY_SEPARATOR . 'design',
diff --git a/dev/tests/integration/testsuite/Mage/Backend/Controller/ActionAbstractTest.php b/dev/tests/integration/testsuite/Mage/Backend/Controller/ActionAbstractTest.php
index 64472064956d25d51c2e3f7d8684b550394b96da..44f5fa237e28f6acaa77de61fe0ca2c6c57e9744 100644
--- a/dev/tests/integration/testsuite/Mage/Backend/Controller/ActionAbstractTest.php
+++ b/dev/tests/integration/testsuite/Mage/Backend/Controller/ActionAbstractTest.php
@@ -60,8 +60,8 @@ class Mage_Backend_Controller_ActionAbstractTest extends Mage_Backend_Utility_Co
             'password' => Magento_Test_Bootstrap::ADMIN_PASSWORD
         ));
 
-        $this->getRequest()->setPost($postLogin);
         $url = Mage::getSingleton('Mage_Backend_Model_Url')->getUrl('adminhtml/system_account/index');
+        $this->getRequest()->setPost($postLogin);
         $this->dispatch($url);
 
         $expected = 'backend/admin/system_account/index';
diff --git a/dev/tests/integration/testsuite/Mage/Backend/Model/AuthTest.php b/dev/tests/integration/testsuite/Mage/Backend/Model/AuthTest.php
index 7ee5078cd9a019e71b4ba1c128a734b552192ceb..5f772eb7028461aaebc676f271ab43865d705129 100644
--- a/dev/tests/integration/testsuite/Mage/Backend/Model/AuthTest.php
+++ b/dev/tests/integration/testsuite/Mage/Backend/Model/AuthTest.php
@@ -37,6 +37,7 @@ class Mage_Backend_Model_AuthTest extends PHPUnit_Framework_TestCase
 
     public function setUp()
     {
+        Mage::app()->loadArea(Mage_Core_Model_App_Area::AREA_ADMINHTML);
         $this->_model = Mage::getModel('Mage_Backend_Model_Auth');
     }
 
diff --git a/dev/tests/integration/testsuite/Mage/Backend/Model/MenuTest.php b/dev/tests/integration/testsuite/Mage/Backend/Model/MenuTest.php
index 9d0849e59eceff420ef5d81238db42a8ec7ef9ab..a3cf69b69bef33531d123eeca1314f2a44fbae86 100644
--- a/dev/tests/integration/testsuite/Mage/Backend/Model/MenuTest.php
+++ b/dev/tests/integration/testsuite/Mage/Backend/Model/MenuTest.php
@@ -37,6 +37,7 @@ class Mage_Backend_Model_MenuTest extends PHPUnit_Framework_TestCase
 
     public function setUp()
     {
+        Mage::app()->loadArea(Mage_Core_Model_App_Area::AREA_ADMINHTML);
         $this->_model = Mage::getModel('Mage_Backend_Model_Auth');
         Mage::getConfig()->setCurrentAreaCode(Mage::helper('Mage_Backend_Helper_Data')->getAreaCode());
     }
diff --git a/dev/tests/integration/testsuite/Mage/Backend/Utility/Controller.php b/dev/tests/integration/testsuite/Mage/Backend/Utility/Controller.php
index ccd2e1b8b04abb1b27b7f4959ca1704c53073fc2..ad6daa82b4fe3db9746540a0b59473f335a4aabb 100644
--- a/dev/tests/integration/testsuite/Mage/Backend/Utility/Controller.php
+++ b/dev/tests/integration/testsuite/Mage/Backend/Utility/Controller.php
@@ -46,6 +46,7 @@ class Mage_Backend_Utility_Controller extends Magento_Test_TestCase_ControllerAb
     {
         parent::setUp();
 
+        Mage::app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_ADMINHTML, Mage_Core_Model_App_Area::PART_CONFIG);
         Mage::getSingleton('Mage_Backend_Model_Url')->turnOffSecretKey();
 
         $this->_auth = Mage::getModel('Mage_Backend_Model_Auth');
diff --git a/dev/tests/integration/testsuite/Mage/Bundle/Model/ProductTest.php b/dev/tests/integration/testsuite/Mage/Bundle/Model/ProductTest.php
index d061f8cfae23887ee1c7afdb3201e82b97049934..0d6042564565c5bf8f1d987a92fa389e7b9c87ef 100644
--- a/dev/tests/integration/testsuite/Mage/Bundle/Model/ProductTest.php
+++ b/dev/tests/integration/testsuite/Mage/Bundle/Model/ProductTest.php
@@ -76,7 +76,7 @@ class Mage_Bundle_Model_ProductTest extends PHPUnit_Framework_TestCase
      */
     public function testCRUD()
     {
-        Mage::app()->setCurrentStore(Mage::app()->getStore(Mage_Core_Model_App::ADMIN_STORE_ID));
+        Mage::app()->setCurrentStore(Mage::app()->getStore(Mage_Core_Model_AppInterface::ADMIN_STORE_ID));
         $this->_model->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_BUNDLE)
             ->setAttributeSetId(4)
             ->setName('Bundle Product')->setSku(uniqid())->setPrice(10)
diff --git a/dev/tests/integration/testsuite/Mage/Captcha/Block/Captcha/ZendTest.php b/dev/tests/integration/testsuite/Mage/Captcha/Block/Captcha/DefaultTest.php
similarity index 90%
rename from dev/tests/integration/testsuite/Mage/Captcha/Block/Captcha/ZendTest.php
rename to dev/tests/integration/testsuite/Mage/Captcha/Block/Captcha/DefaultTest.php
index 66f8d75995836cb9d64b1933b1538c1b4568a0f8..de36e1f3a786fcb66d1273db3486c703a847d8c3 100644
--- a/dev/tests/integration/testsuite/Mage/Captcha/Block/Captcha/ZendTest.php
+++ b/dev/tests/integration/testsuite/Mage/Captcha/Block/Captcha/DefaultTest.php
@@ -24,17 +24,17 @@
  * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
-class Mage_Captcha_Block_Captcha_ZendTest extends PHPUnit_Framework_TestCase
+class Mage_Captcha_Block_Captcha_DefaultTest extends PHPUnit_Framework_TestCase
 {
     /**
-     * @var Mage_Captcha_Block_Captcha_Zend
+     * @var Mage_Captcha_Block_Captcha_Default
      */
     protected $_block;
 
     public function setUp()
     {
          $this->_block = Mage::app()->getLayout()
-            ->createBlock('Mage_Captcha_Block_Captcha_Zend');
+            ->createBlock('Mage_Captcha_Block_Captcha_Default');
     }
 
     /**
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/Helper/Product/ViewTest.php b/dev/tests/integration/testsuite/Mage/Catalog/Helper/Product/ViewTest.php
index d4ccf225f6a13e535381fe7dd7a41b9111cea446..bd56fe28d6f2bb32c3f962a076f1aa3dcedc0c33 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/Helper/Product/ViewTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Helper/Product/ViewTest.php
@@ -52,10 +52,10 @@ class Mage_Catalog_Helper_Product_ViewTest extends PHPUnit_Framework_TestCase
             array(
                 $request,
                 new Magento_Test_Response(),
-                'frontend',
                 Mage::getObjectManager(),
                 Mage::getObjectManager()->get('Mage_Core_Controller_Varien_Front'),
-                Mage::getObjectManager()->get('Mage_Core_Model_Layout_Factory')
+                Mage::getObjectManager()->get('Mage_Core_Model_Layout_Factory'),
+                'frontend'
             )
         );
     }
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/Model/AbstractTest.php b/dev/tests/integration/testsuite/Mage/Catalog/Model/AbstractTest.php
index 3d307dc6659bf2da57b3d3cdc923e020189a721a..5c1cf372f1462fb8ead96e36cb3e937d1bb74945 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/Model/AbstractTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Model/AbstractTest.php
@@ -57,7 +57,7 @@ class Mage_Catalog_Model_AbstractTest extends PHPUnit_Framework_TestCase
         $resourceProperty->setAccessible(true);
         $resourceProperty->setValue($this->_model, 'Mage_Catalog_Model_Resource_Product');
 
-        $collectionProperty = new ReflectionProperty(get_class($this->_model), '_resourceCollectionName');
+        $collectionProperty = new ReflectionProperty(get_class($this->_model), '_collectionName');
         $collectionProperty->setAccessible(true);
         $collectionProperty->setValue($this->_model, 'Mage_Catalog_Model_Resource_Product_Collection');
     }
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/Model/CategoryTest.php b/dev/tests/integration/testsuite/Mage/Catalog/Model/CategoryTest.php
index 0e5e9b2b971f194178d51666f757c8836872714a..23d15db71fbcf21a7a55a9f6604f160ec88f8855 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/Model/CategoryTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Model/CategoryTest.php
@@ -223,6 +223,23 @@ class Mage_Catalog_Model_CategoryTest extends PHPUnit_Framework_TestCase
         $this->assertEquals(1000, $this->_model->getStoreId());
     }
 
+    /**
+     * @magentoDataFixture Mage/Core/_files/store.php
+     * @magentoAppIsolation enabled
+     */
+    public function testSetStoreIdWithNonNumericValue()
+    {
+        /** @var $store Mage_Core_Model_Store */
+        $store = Mage::getModel('Mage_Core_Model_Store');
+        $store->load('fixturestore');
+
+        $this->assertNotEquals($this->_model->getStoreId(), $store->getId());
+
+        $this->_model->setStoreId('fixturestore');
+
+        $this->assertEquals($this->_model->getStoreId(), $store->getId());
+    }
+
     public function testGetUrl()
     {
         $this->assertStringEndsWith('catalog/category/view/', $this->_model->getUrl());
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/ItemTest.php b/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/ItemTest.php
index d8ff47f3c2b2f827d51a23f4dd1cf22e353aa835..927986fa2c411902af684fa642361d63569fe5ae 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/ItemTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/ItemTest.php
@@ -74,10 +74,10 @@ class Mage_Catalog_Model_Layer_Filter_ItemTest extends PHPUnit_Framework_TestCas
             array(
                 new Magento_Test_Request(),
                 new Magento_Test_Response(),
-                'frontend',
                 Mage::getObjectManager(),
                 Mage::getObjectManager()->get('Mage_Core_Controller_Varien_Front'),
-                Mage::getObjectManager()->get('Mage_Core_Model_Layout_Factory')
+                Mage::getObjectManager()->get('Mage_Core_Model_Layout_Factory'),
+                'frontend'
             )
         );
         Mage::app()->getFrontController()->setAction($action); // done in action's constructor
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/Model/Product/Api/_files/ProductWithOptionCrud.php b/dev/tests/integration/testsuite/Mage/Catalog/Model/Product/Api/_files/ProductWithOptionCrud.php
index 471627dbe2af3501c35980b8c378d3d05267ed99..c23ce14ecde6083d64b88b551eb517ac303265b0 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/Model/Product/Api/_files/ProductWithOptionCrud.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Model/Product/Api/_files/ProductWithOptionCrud.php
@@ -24,7 +24,7 @@
 
 $data = require dirname(__FILE__) . '/ProductAttributeData.php';
 // add product attributes via installer
-$installer = new Mage_Catalog_Model_Resource_Setup('core_setup');
+$installer = Mage::getModel('Mage_Catalog_Model_Resource_Setup', array('resourceName' => 'core_setup'));
 $installer->addAttribute(
     'catalog_product',
     $data['create_text_installer']['code'],
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/Model/Product/Attribute/Backend/TierpriceTest.php b/dev/tests/integration/testsuite/Mage/Catalog/Model/Product/Attribute/Backend/TierpriceTest.php
index b4fbb51bc61ca6fa98d5ed32d0f758cf5346393a..0711f76503fc8ea2a48a7f3e872bf56d0fa2fed3 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/Model/Product/Attribute/Backend/TierpriceTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Model/Product/Attribute/Backend/TierpriceTest.php
@@ -122,7 +122,7 @@ class Mage_Catalog_Model_Product_Attribute_Backend_TierpriceTest extends PHPUnit
 
     public function testAfterSave()
     {
-        Mage::app()->setCurrentStore(Mage::app()->getStore(Mage_Core_Model_App::ADMIN_STORE_ID));
+        Mage::app()->setCurrentStore(Mage::app()->getStore(Mage_Core_Model_AppInterface::ADMIN_STORE_ID));
         /** @var $product Mage_Catalog_Model_Product */
         $product = Mage::getModel('Mage_Catalog_Model_Product');
         $product->load(1);
@@ -149,7 +149,7 @@ class Mage_Catalog_Model_Product_Attribute_Backend_TierpriceTest extends PHPUnit
      */
     public function testAfterSaveEmpty()
     {
-        Mage::app()->setCurrentStore(Mage::app()->getStore(Mage_Core_Model_App::ADMIN_STORE_ID));
+        Mage::app()->setCurrentStore(Mage::app()->getStore(Mage_Core_Model_AppInterface::ADMIN_STORE_ID));
         /** @var $product Mage_Catalog_Model_Product */
         $product = Mage::getModel('Mage_Catalog_Model_Product');
         $product->load(1);
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/Model/ProductTest.php b/dev/tests/integration/testsuite/Mage/Catalog/Model/ProductTest.php
index e498dea0576c1a6d118ee85c4a55464d3aa12dad..c6309577d88d4310b3916e7586c6801f0639fa12 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/Model/ProductTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Model/ProductTest.php
@@ -73,7 +73,7 @@ class Mage_Catalog_Model_ProductTest extends PHPUnit_Framework_TestCase
      */
     public function testCRUD()
     {
-        Mage::app()->setCurrentStore(Mage::app()->getStore(Mage_Core_Model_App::ADMIN_STORE_ID));
+        Mage::app()->setCurrentStore(Mage::app()->getStore(Mage_Core_Model_AppInterface::ADMIN_STORE_ID));
         $this->_model->setTypeId('simple')->setAttributeSetId(4)
             ->setName('Simple Product')->setSku(uniqid())->setPrice(10)
             ->setMetaTitle('meta title')->setMetaKeyword('meta keyword')->setMetaDescription('meta description')
@@ -163,7 +163,7 @@ class Mage_Catalog_Model_ProductTest extends PHPUnit_Framework_TestCase
      */
     protected function _undo($duplicate)
     {
-        Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
+        Mage::app()->getStore()->setId(Mage_Core_Model_AppInterface::ADMIN_STORE_ID);
         $duplicate->delete();
     }
 
@@ -346,7 +346,7 @@ class Mage_Catalog_Model_ProductTest extends PHPUnit_Framework_TestCase
         $this->assertEmpty($this->_model->getOrigData());
 
         $storeId = Mage::app()->getStore()->getId();
-        Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
+        Mage::app()->getStore()->setId(Mage_Core_Model_AppInterface::ADMIN_STORE_ID);
         try {
             $this->_model->setOrigData('key', 'value');
             $this->assertEquals('value', $this->_model->getOrigData('key'));
diff --git a/dev/tests/integration/testsuite/Mage/CatalogSearch/Helper/DataTest.php b/dev/tests/integration/testsuite/Mage/CatalogSearch/Helper/DataTest.php
index 9278bb2ce8ae974929c4345f8fcc03caa3b1cc68..5ed7e986c6678cd6292235574ebc01a503705dcd 100644
--- a/dev/tests/integration/testsuite/Mage/CatalogSearch/Helper/DataTest.php
+++ b/dev/tests/integration/testsuite/Mage/CatalogSearch/Helper/DataTest.php
@@ -67,7 +67,10 @@ class Mage_CatalogSearch_Helper_DataTest extends PHPUnit_Framework_TestCase
     public function testCheckNotesEscapesHtmlWhenQueryIsCut()
     {
         /** @var $mock Mage_CatalogSearch_Helper_Data */
-        $mock = $this->getMock('Mage_CatalogSearch_Helper_Data', array('getQueryText'));
+        $mock = $this->getMock(
+            'Mage_CatalogSearch_Helper_Data',
+            array('getQueryText'), array(Mage::getObjectManager()->get('Mage_Core_Model_Translate'))
+        );
         $mock->expects($this->any())
             ->method('getQueryText')
             ->will($this->returnValue('five <words> here <being> tested'));
diff --git a/dev/tests/integration/testsuite/Mage/Cms/Controller/RouterTest.php b/dev/tests/integration/testsuite/Mage/Cms/Controller/RouterTest.php
index f90b1acf4c42eca6ac9ddb7636cf2d1cf50d4399..f023b666e8e3592bccc8c7f1d7f116bd98e31fd1 100644
--- a/dev/tests/integration/testsuite/Mage/Cms/Controller/RouterTest.php
+++ b/dev/tests/integration/testsuite/Mage/Cms/Controller/RouterTest.php
@@ -36,7 +36,10 @@ class Mage_Cms_Controller_RouterTest extends PHPUnit_Framework_TestCase
     {
         $this->_model = new Mage_Cms_Controller_Router(
             Mage::getObjectManager()->get('Mage_Core_Controller_Varien_Action_Factory'),
-            new Mage_Core_Model_Event_ManagerStub()
+            new Mage_Core_Model_Event_ManagerStub(
+                $this->getMock('Mage_Core_Model_ObserverFactory', array(), array(), '', false),
+                $this->getMock('Mage_Core_Model_Event_Config', array(), array(), '', false)
+            )
         );
     }
 
@@ -47,6 +50,8 @@ class Mage_Cms_Controller_RouterTest extends PHPUnit_Framework_TestCase
     {
         $request = new Mage_Core_Controller_Request_Http();
         //Open Node
+        Mage::getObjectManager()->get('Mage_Core_Controller_Response_Http')
+            ->headersSentThrowsException = Mage::$headersSentThrowsException;
         $request->setPathInfo('parent_node');
         $controller = $this->_model->match($request);
         $this->assertInstanceOf('Mage_Core_Controller_Varien_Action_Redirect', $controller);
diff --git a/dev/tests/integration/testsuite/Mage/Cms/Helper/PageTest.php b/dev/tests/integration/testsuite/Mage/Cms/Helper/PageTest.php
index 95a7a1e0b2a13e0fe995c328cfa66dbb354de398..82b6bd785a73ff9b41bf5255ef20fcf29b800680 100644
--- a/dev/tests/integration/testsuite/Mage/Cms/Helper/PageTest.php
+++ b/dev/tests/integration/testsuite/Mage/Cms/Helper/PageTest.php
@@ -43,10 +43,10 @@ class Mage_Cms_Helper_PageTest extends PHPUnit_Framework_TestCase
                 array(
                     new Magento_Test_Request(),
                     new Magento_Test_Response(),
-                    'frontend',
                     Mage::getObjectManager(),
                     Mage::getObjectManager()->get('Mage_Core_Controller_Varien_Front'),
-                    Mage::getObjectManager()->get('Mage_Core_Model_Layout_Factory')
+                    Mage::getObjectManager()->get('Mage_Core_Model_Layout_Factory'),
+                    'frontend'
                 )
             ),
             $page->getId()
diff --git a/dev/tests/integration/testsuite/Mage/Cms/Helper/Wysiwyg/ImagesTest.php b/dev/tests/integration/testsuite/Mage/Cms/Helper/Wysiwyg/ImagesTest.php
index f86f67588693ec2fa723018f9655f9d2307be226..22b134a35ca68008aa7976f861a2450075feb885 100644
--- a/dev/tests/integration/testsuite/Mage/Cms/Helper/Wysiwyg/ImagesTest.php
+++ b/dev/tests/integration/testsuite/Mage/Cms/Helper/Wysiwyg/ImagesTest.php
@@ -27,15 +27,13 @@ class Mage_Cms_Helper_Wysiwyg_ImagesTest extends PHPUnit_Framework_TestCase
     {
         /** @var $dir Mage_Core_Model_Dir */
         $dir = Mage::getObjectManager()->get('Mage_Core_Model_Dir');
-        $filesystem = new Magento_Filesystem(new Magento_Filesystem_Adapter_Local);
-        $helper = new Mage_Cms_Helper_Wysiwyg_Images($filesystem);
+        $helper = Mage::getObjectManager()->create('Mage_Cms_Helper_Wysiwyg_Images');
         $this->assertStringStartsWith($dir->getDir(Mage_Core_Model_Dir::MEDIA), $helper->getStorageRoot());
     }
 
     public function testGetCurrentUrl()
     {
-        $filesystem = new Magento_Filesystem(new Magento_Filesystem_Adapter_Local);
-        $helper = new Mage_Cms_Helper_Wysiwyg_Images($filesystem);
+        $helper = Mage::getObjectManager()->create('Mage_Cms_Helper_Wysiwyg_Images');
         $this->assertStringStartsWith('http://localhost/', $helper->getCurrentUrl());
     }
 }
diff --git a/dev/tests/integration/testsuite/Mage/Core/Block/AbstractTest.php b/dev/tests/integration/testsuite/Mage/Core/Block/AbstractTest.php
index e0afd191df77f3eb8f5b124ca2a4e0a1872041d5..e2fbd1dbe058173e8435f261ddcb5e6271fae45e 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Block/AbstractTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Block/AbstractTest.php
@@ -511,8 +511,9 @@ class Mage_Core_Block_AbstractTest extends PHPUnit_Framework_TestCase
      */
     public function testGetViewUrl()
     {
-        $this->assertStringStartsWith('http://localhost/pub/media/theme/static/frontend/',
-            $this->_block->getViewFileUrl());
+        $this->assertStringStartsWith(
+            'http://localhost/pub/media/theme/static/frontend/', $this->_block->getViewFileUrl()
+        );
         $this->assertStringEndsWith('css/styles.css', $this->_block->getViewFileUrl('css/styles.css'));
 
         /**
diff --git a/dev/tests/integration/testsuite/Mage/Core/Controller/Varien/ActionTest.php b/dev/tests/integration/testsuite/Mage/Core/Controller/Varien/ActionTest.php
index 1080fb681f7693552cfdef4062078f8e633e2b9e..2406e0bce5bf47c710b61ee409a2baa7f20001f3 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Controller/Varien/ActionTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Controller/Varien/ActionTest.php
@@ -41,10 +41,10 @@ class Mage_Core_Controller_Varien_ActionTest extends PHPUnit_Framework_TestCase
             array(
                 new Magento_Test_Request(),
                 new Magento_Test_Response(),
-                'frontend',
                 Mage::getObjectManager(),
                 Mage::getObjectManager()->get('Mage_Core_Controller_Varien_Front'),
-                Mage::getObjectManager()->get('Mage_Core_Model_Layout_Factory')
+                Mage::getObjectManager()->get('Mage_Core_Model_Layout_Factory'),
+                'frontend'
             )
         );
     }
diff --git a/dev/tests/integration/testsuite/Mage/Core/Controller/Varien/FrontTest.php b/dev/tests/integration/testsuite/Mage/Core/Controller/Varien/FrontTest.php
index 72099eea1818d6274c6fdb4d4530eefbbe291de2..1e8d24db3ef79d7dfde1fd5e903a67066e3d565b 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Controller/Varien/FrontTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Controller/Varien/FrontTest.php
@@ -60,6 +60,7 @@ class Mage_Core_Controller_Varien_FrontTest extends PHPUnit_Framework_TestCase
 
     public function testGetResponse()
     {
+        Mage::app()->setResponse(Mage::getSingleton('Mage_Core_Controller_Response_Http'));
         if (!Magento_Test_Helper_Bootstrap::canTestHeaders()) {
             $this->markTestSkipped('Can\'t test get response without sending headers');
         }
diff --git a/dev/tests/integration/testsuite/Mage/Core/Helper/AbstractTest.php b/dev/tests/integration/testsuite/Mage/Core/Helper/AbstractTest.php
index 10a93691ef29abf098e2e65d864399eeb406f57d..88dd01337fdbd5ee08a13f60848b17732bf10f01 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Helper/AbstractTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Helper/AbstractTest.php
@@ -34,7 +34,9 @@ class Mage_Core_Helper_AbstractTest extends PHPUnit_Framework_TestCase
 
     protected function setUp()
     {
-        $this->_helper = $this->getMock('Mage_Core_Helper_Abstract', array('_getModuleName'));
+        $this->_helper = $this->getMock('Mage_Core_Helper_Abstract',
+            array('_getModuleName'), array(Mage::getObjectManager()->get('Mage_Core_Model_Translate'))
+        );
         $this->_helper
             ->expects($this->any())
             ->method('_getModuleName')
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/AppTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/AppTest.php
index a0b5c2a11c1d853088c3dde44cac4a8313195c9a..1849c7e23adb464b3c63a4a3477959fbc37d8476 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/AppTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/AppTest.php
@@ -59,58 +59,6 @@ class Mage_Core_Model_AppTest extends PHPUnit_Framework_TestCase
         $this->_mageModel = null;
     }
 
-    /**
-     * @covers Mage_Core_Model_App::_initCache
-     *
-     * @magentoAppIsolation enabled
-     */
-    public function testInit()
-    {
-        $this->assertNull($this->_model->getConfig());
-        $this->_model->init(Magento_Test_Helper_Bootstrap::getInstance()->getAppInitParams());
-        $this->assertInstanceOf('Mage_Core_Model_Config', $this->_model->getConfig());
-        $this->assertNotEmpty($this->_model->getConfig()->getNode());
-        $this->assertContains(Mage_Core_Model_App::ADMIN_STORE_ID, array_keys($this->_model->getStores(true)));
-
-        // Check that we have shared cache object inside of object manager
-        $objectManager = Mage::getObjectManager();
-        /** @var $cache Mage_Core_Model_Cache */
-        $cache = $objectManager->get('Mage_Core_Model_Cache');
-        $appCache = $this->_model->getCacheInstance();
-        $this->assertSame($appCache, $cache);
-    }
-
-    /**
-     * @magentoAppIsolation enabled
-     */
-    public function testBaseInit()
-    {
-        $this->assertNull($this->_model->getConfig());
-        $this->_model->baseInit(Magento_Test_Helper_Bootstrap::getInstance()->getAppInitParams());
-        $this->assertInstanceOf('Mage_Core_Model_Config', $this->_model->getConfig());
-        $this->assertNotEmpty($this->_model->getConfig()->getNode());
-    }
-
-    /**
-     * @magentoAppIsolation enabled
-     */
-    public function testRun()
-    {
-        if (!Magento_Test_Helper_Bootstrap::canTestHeaders()) {
-            $this->markTestSkipped('Can\'t test application run without sending headers');
-        }
-        $request = new Magento_Test_Request();
-        $request->setRequestUri('core/index/index');
-        $this->_mageModel->setRequest($request);
-        $this->_mageModel->run(Magento_Test_Helper_Bootstrap::getInstance()->getAppInitParams());
-        $this->assertTrue($request->isDispatched());
-    }
-
-    public function testIsInstalled()
-    {
-        $this->assertTrue($this->_mageModel->isInstalled());
-    }
-
     public function testGetCookie()
     {
         $this->assertInstanceOf('Mage_Core_Model_Cookie', $this->_model->getCookie());
@@ -134,12 +82,17 @@ class Mage_Core_Model_AppTest extends PHPUnit_Framework_TestCase
         $this->assertFalse($this->_mageModel->isSingleStoreMode());;
     }
 
+    /**
+     * @magentoAppIsolation enabled
+     */
     public function testHasSingleStore()
     {
-        $this->assertNull($this->_model->hasSingleStore());
         $this->assertTrue($this->_mageModel->hasSingleStore());
     }
 
+    /**
+     * @magentoAppIsolation enabled
+     */
     public function testSetCurrentStore()
     {
         $store = Mage::getModel('Mage_Core_Model_Store');
@@ -147,21 +100,6 @@ class Mage_Core_Model_AppTest extends PHPUnit_Framework_TestCase
         $this->assertSame($store, $this->_model->getStore());
     }
 
-    public function testSetErrorHandler()
-    {
-        $this->_model->setErrorHandler(array($this, 'errorHandler'));
-        try {
-            trigger_error('test', E_USER_NOTICE);
-            if (!$this->_errorCatchFlag) {
-                $this->fail('Error handler is not working');
-            }
-            restore_error_handler();
-        } catch (Exception $e) {
-            restore_error_handler();
-            throw $e;
-        }
-    }
-
     public function errorHandler()
     {
         $this->_errorCatchFlag = true;
@@ -173,7 +111,8 @@ class Mage_Core_Model_AppTest extends PHPUnit_Framework_TestCase
      */
     public function testLoadArea()
     {
-        $translator = Mage::app()->getTranslator();
+        /** @var $translator Mage_Core_Model_Translate */
+        $translator = Mage::getSingleton('Mage_Core_Model_Translate');
         $this->assertEmpty($translator->getConfig(Mage_Core_Model_Translate::CONFIG_KEY_LOCALE));
         $this->_model->loadArea('frontend');
         $this->assertEquals('de_DE', $translator->getConfig(Mage_Core_Model_Translate::CONFIG_KEY_LOCALE));
@@ -203,8 +142,12 @@ class Mage_Core_Model_AppTest extends PHPUnit_Framework_TestCase
     public function testGetStores()
     {
         $this->assertNotEmpty($this->_mageModel->getStores());
-        $this->assertNotContains(Mage_Core_Model_App::ADMIN_STORE_ID, array_keys($this->_mageModel->getStores()));
-        $this->assertContains(Mage_Core_Model_App::ADMIN_STORE_ID, array_keys($this->_mageModel->getStores(true)));
+        $this->assertNotContains(
+            Mage_Core_Model_AppInterface::ADMIN_STORE_ID, array_keys($this->_mageModel->getStores())
+        );
+        $this->assertContains(
+            Mage_Core_Model_AppInterface::ADMIN_STORE_ID, array_keys($this->_mageModel->getStores(true))
+        );
     }
 
     public function testGetDefaultStoreView()
@@ -215,7 +158,7 @@ class Mage_Core_Model_AppTest extends PHPUnit_Framework_TestCase
 
     public function testGetDistroLocaleCode()
     {
-        $this->assertEquals(Mage_Core_Model_App::DISTRO_LOCALE_CODE, $this->_model->getDistroLocaleCode());
+        $this->assertEquals(Mage_Core_Model_AppInterface::DISTRO_LOCALE_CODE, $this->_model->getDistroLocaleCode());
     }
 
     /**
@@ -250,11 +193,11 @@ class Mage_Core_Model_AppTest extends PHPUnit_Framework_TestCase
         $this->assertSame($locale, $this->_model->getLocale());
     }
 
-    public function testGetTranslator()
+    public function testGetLayout()
     {
-        $translate = $this->_model->getTranslator();
-        $this->assertInstanceOf('Mage_Core_Model_Translate', $translate);
-        $this->assertSame($translate, $this->_model->getTranslator());
+        $layout = $this->_mageModel->getLayout();
+        $this->assertInstanceOf('Mage_Core_Model_Layout', $layout);
+        $this->assertSame($layout, $this->_mageModel->getLayout());
     }
 
     /**
@@ -278,12 +221,6 @@ class Mage_Core_Model_AppTest extends PHPUnit_Framework_TestCase
         $this->assertEquals('USD', $this->_model->getBaseCurrencyCode());
     }
 
-    public function testGetConfig()
-    {
-        $this->assertNull($this->_model->getConfig());
-        $this->assertInstanceOf('Mage_Core_Model_Config', $this->_mageModel->getConfig());
-    }
-
     public function testGetFrontController()
     {
         $front = $this->_mageModel->getFrontController();
@@ -334,23 +271,6 @@ class Mage_Core_Model_AppTest extends PHPUnit_Framework_TestCase
         $this->assertInstanceOf('Magento_Test_Request', $this->_model->getRequest());
     }
 
-    public function testSetGetResponse()
-    {
-        if (!Magento_Test_Helper_Bootstrap::canTestHeaders()) {
-            $this->markTestSkipped('Can\'t test get response without sending headers');
-        }
-        $this->assertInstanceOf('Mage_Core_Controller_Response_Http', $this->_model->getResponse());
-        $this->_model->setResponse(new Magento_Test_Response());
-        $this->assertInstanceOf('Magento_Test_Response', $this->_model->getResponse());
-    }
-
-    public function testSetGetUpdateMode()
-    {
-        $this->assertFalse($this->_model->getUpdateMode());
-        $this->_model->setUpdateMode(true);
-        $this->assertTrue($this->_model->getUpdateMode());
-    }
-
     /**
      * @expectedException Mage_Core_Model_Store_Exception
      */
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Config/DataTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Config/DataTest.php
index 9cc61eab1cee8726921b5eb937844a395181d225..7f97a6b54d25b18e84f5284e65c73f094b3ca155 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Config/DataTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Config/DataTest.php
@@ -37,13 +37,14 @@ class Mage_Core_Model_Config_DataTest extends PHPUnit_Framework_TestCase
 
     public static function setUpBeforeClass()
     {
-        Mage::app()->getConfig()->saveConfig(self::SAMPLE_CONFIG_PATH, self::SAMPLE_VALUE);
+        Mage::getObjectManager()->get('Mage_Core_Model_Config_Storage_Writer_Db')
+            ->save(self::SAMPLE_CONFIG_PATH, self::SAMPLE_VALUE);
         self::_refreshConfiguration();
     }
 
     public static function tearDownAfterClass()
     {
-        Mage::app()->getConfig()->deleteConfig(self::SAMPLE_CONFIG_PATH);
+        Mage::getObjectManager()->get('Mage_Core_Model_Config_Storage_Writer_Db')->delete(self::SAMPLE_CONFIG_PATH);
         self::_refreshConfiguration();
     }
 
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/ConfigFactoryTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/ConfigFactoryTest.php
index 77afd5eaad2eab42652fbfe1af09248f54cf679d..ce5c150da4c6c246b59df434f40c57a4c2e431e8 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/ConfigFactoryTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/ConfigFactoryTest.php
@@ -39,7 +39,6 @@ class Mage_Core_Model_ConfigFactoryTest extends PHPUnit_Framework_TestCase
     public function setUp()
     {
         $this->_model = Mage::getModel('Mage_Core_Model_Config');
-        $this->_model->init();
     }
 
     protected function tearDown()
@@ -47,57 +46,11 @@ class Mage_Core_Model_ConfigFactoryTest extends PHPUnit_Framework_TestCase
         $this->_model = null;
     }
 
-    /**
-     * @dataProvider classNameRewriteDataProvider
-     */
-    public function testClassNameRewrite($originalClass, $expectedClass, $classNameGetter)
-    {
-        $this->_model->setNode("global/rewrites/$originalClass", $expectedClass);
-        $this->assertEquals($expectedClass, $this->_model->$classNameGetter($originalClass));
-    }
-
-    public function classNameRewriteDataProvider()
-    {
-        return array(
-            'block'          => array('My_Module_Block_Class', 'Another_Module_Block_Class', 'getBlockClassName'),
-            'helper'         => array('My_Module_Helper_Data', 'Another_Module_Helper_Data', 'getHelperClassName'),
-            'model'          => array('My_Module_Model_Class', 'Another_Module_Model_Class', 'getModelClassName'),
-            'resource model' => array(
-                'My_Module_Model_Resource_Collection',
-                'Another_Module_Model_Resource_Collection_New',
-                'getResourceModelClassName'
-            ),
-        );
-    }
-
-    public function testGetBlockClassName()
-    {
-        $this->assertEquals('Mage_Core_Block_Template', $this->_model->getBlockClassName('Mage_Core_Block_Template'));
-    }
-
-    public function testGetHelperClassName()
-    {
-        $this->assertEquals('Mage_Core_Helper_Http', $this->_model->getHelperClassName('Mage_Core_Helper_Http'));
-    }
-
-    public function testGetModelClassName()
-    {
-        $this->assertEquals('Mage_Core_Model_Config', $this->_model->getModelClassName('Mage_Core_Model_Config'));
-    }
-
     public function testGetModelInstance()
     {
         $this->assertInstanceOf('Mage_Core_Model_Config', $this->_model->getModelInstance('Mage_Core_Model_Config'));
     }
 
-    public function testGetResourceModelClassName()
-    {
-        $this->assertEquals(
-            'Mage_Core_Model_Resource_Config',
-            $this->_model->getResourceModelClassName('Mage_Core_Model_Resource_Config')
-        );
-    }
-
     public function testGetResourceModelInstance()
     {
         $this->assertInstanceOf(
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/ConfigTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/ConfigTest.php
index fe85a66c8ee963e90d31e45511a345115d5f0a64..f9ac503486adc224aa4a3558c9a4e625b6204063 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/ConfigTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/ConfigTest.php
@@ -39,304 +39,9 @@ class Mage_Core_Model_ConfigTest extends PHPUnit_Framework_TestCase
         Mage::app()->getCacheInstance()->banUse('config');
     }
 
-    public function testGetResourceModel()
-    {
-        $this->assertInstanceOf('Mage_Core_Model_Resource_Config', $this->_createModel(true)->getResourceModel());
-    }
-
-    public function testInit()
-    {
-        $model = $this->_createModel();
-        $this->assertFalse($model->getNode());
-        $model->init();
-        $this->assertInstanceOf('Varien_Simplexml_Element', $model->getNode());
-    }
-
-    public function testLoadBase()
-    {
-        $model = $this->_createModel();
-        $this->assertFalse($model->getNode());
-        $model->loadBase();
-        $this->assertInstanceOf('Varien_Simplexml_Element', $model->getNode('global'));
-    }
-
-    /**
-     * @param string $etcDir
-     * @param array $configOptions
-     * @param string $expectedValue
-     * @param string $expectedNode
-     * @dataProvider loadBaseLocalConfigDataProvider
-     */
-    public function testLoadBaseLocalConfig($etcDir, array $configOptions, $expectedValue,
-        $expectedNode = 'global/resources/core_setup/connection/model'
-    ) {
-        $configOptions[Mage_Core_Model_App::INIT_OPTION_DIRS] = array(
-            Mage_Core_Model_Dir::CONFIG => __DIR__ . "/_files/local_config/{$etcDir}",
-        );
-        $model = $this->_createModelWithApp($configOptions);
-
-        $model->loadBase();
-        $this->assertInstanceOf('Varien_Simplexml_Element', $model->getNode($expectedNode));
-        $this->assertEquals($expectedValue, (string)$model->getNode($expectedNode));
-    }
-
-    /**
-     * @return array
-     */
-    public function loadBaseLocalConfigDataProvider()
-    {
-        $extraConfigData = '
-            <root>
-                <global>
-                    <resources>
-                        <core_setup>
-                            <connection>
-                                <model>overridden</model>
-                            </connection>
-                        </core_setup>
-                    </resources>
-                </global>
-            </root>
-        ';
-        return array(
-            'no local config file & no custom config file' => array(
-                'no_local_config',
-                array(),
-                'b',
-            ),
-            'no local config file & custom config file' => array(
-                'no_local_config',
-                array(Mage_Core_Model_Config::INIT_OPTION_EXTRA_FILE => 'custom/local.xml'),
-                'b',
-            ),
-            'no local config file & custom config data' => array(
-                'no_local_config',
-                array(Mage_Core_Model_Config::INIT_OPTION_EXTRA_DATA => $extraConfigData),
-                'overridden',
-            ),
-            'local config file & no custom config file' => array(
-                'local_config',
-                array(),
-                'local',
-            ),
-            'local config file & custom config file' => array(
-                'local_config',
-                array(Mage_Core_Model_Config::INIT_OPTION_EXTRA_FILE => 'custom/local.xml'),
-                'custom',
-            ),
-            'local config file & prohibited custom config file' => array(
-                'local_config',
-                array(Mage_Core_Model_Config::INIT_OPTION_EXTRA_FILE => 'custom/prohibited.filename.xml'),
-                'local',
-            ),
-            'local config file & custom config data' => array(
-                'local_config',
-                array(Mage_Core_Model_Config::INIT_OPTION_EXTRA_DATA => $extraConfigData),
-                'overridden',
-            ),
-            'local config file & custom config file & custom config data' => array(
-                'local_config',
-                array(
-                    Mage_Core_Model_Config::INIT_OPTION_EXTRA_FILE => 'custom/local.xml',
-                    Mage_Core_Model_Config::INIT_OPTION_EXTRA_DATA => $extraConfigData,
-                ),
-                'overridden',
-            ),
-        );
-    }
-
-    public function testLoadBaseInstallDate()
-    {
-        if (date_default_timezone_get() != 'UTC') {
-            $this->markTestSkipped('Test requires "UTC" to be the default timezone.');
-        }
-
-        $options = array(
-            Mage_Core_Model_Config::INIT_OPTION_EXTRA_DATA
-                => sprintf(Mage_Core_Model_Config::CONFIG_TEMPLATE_INSTALL_DATE, 'Fri, 21 Dec 2012 00:00:00 +0000')
-        );
-        $model = $this->_createModelWithApp($options);
-
-        $model->loadBase();
-        $this->assertEquals(1356048000, $model->getInstallDate());
-    }
-
-    public function testLoadBaseInstallDateInvalid()
-    {
-        $options = array(
-            Mage_Core_Model_Config::INIT_OPTION_EXTRA_DATA
-                => sprintf(Mage_Core_Model_Config::CONFIG_TEMPLATE_INSTALL_DATE, 'invalid')
-        );
-        $model = $this->_createModelWithApp($options);
-
-        $model->loadBase();
-        $this->assertEmpty($model->getInstallDate());
-    }
-
-    public function testLoadLocales()
-    {
-        $options = array(
-            Mage_Core_Model_App::INIT_OPTION_DIRS => array(
-                Mage_Core_Model_Dir::LOCALE => __DIR__ . '/_files/locale',
-            )
-        );
-        $model = $this->_createModelWithApp($options);
-
-        $model->loadBase();
-        $model->loadLocales();
-        $this->assertInstanceOf('Mage_Core_Model_Config_Element', $model->getNode('global/locale'));
-    }
-
-    /**
-     * @magentoAppIsolation enabled
-     */
-    public function testLoadModulesCache()
-    {
-        $options = array(
-            Mage_Core_Model_Config::INIT_OPTION_EXTRA_DATA
-                => sprintf(Mage_Core_Model_Config::CONFIG_TEMPLATE_INSTALL_DATE, 'Wed, 21 Nov 2012 03:26:00 +0000')
-        );
-        $model = $this->_createModelWithApp($options);
-
-        Mage::app()->getCacheInstance()->allowUse('config');
-
-        $model->loadBase();
-        $this->assertTrue($model->loadModulesCache());
-        $this->assertInstanceOf('Mage_Core_Model_Config_Element', $model->getNode());
-    }
-
-    public function testLoadModules()
-    {
-        $model = $this->_createModel();
-        $model->loadBase();
-        $this->assertFalse($model->getNode('modules'));
-        $model->loadModules();
-        $moduleNode = $model->getNode('modules/Mage_Core');
-        $this->assertInstanceOf('Mage_Core_Model_Config_Element', $moduleNode);
-        $this->assertTrue($moduleNode->is('active'));
-    }
-
-    public function testLoadModulesLocalConfigPrevails()
-    {
-        $options = array(
-            Mage_Core_Model_Config::INIT_OPTION_EXTRA_DATA
-                => '<config><modules><Mage_Core><active>false</active></Mage_Core></modules></config>'
-        );
-        $model = $this->_createModelWithApp($options);
-
-        $model->loadBase();
-        $model->loadModules();
-
-        $moduleNode = $model->getNode('modules/Mage_Core');
-        $this->assertInstanceOf('Mage_Core_Model_Config_Element', $moduleNode);
-        $this->assertFalse($moduleNode->is('active'), 'Local configuration must prevail over modules configuration.');
-    }
-
-    public function testIsLocalConfigLoaded()
-    {
-        $model = $this->_createModel();
-        $this->assertFalse($model->isLocalConfigLoaded());
-        $model->loadBase();
-        $this->assertTrue($model->isLocalConfigLoaded());
-    }
-
-    public function testLoadDb()
-    {
-        $samplePath = 'general/locale/firstday';
-
-        // emulate a system config value in database
-        $configResource = Mage::getResourceModel('Mage_Core_Model_Resource_Config');
-        $configResource->saveConfig($samplePath, 1, 'default', 0);
-
-        try {
-            $model = $this->_createModel();
-            $model->loadBase();
-            $model->loadModules();
-
-            // load and assert value
-            $model->loadDb();
-            $this->assertEquals('1', (string)$model->getNode("default/{$samplePath}"));
-            $configResource->deleteConfig($samplePath, 'default', 0);
-        } catch (Exception $e) {
-            $configResource->deleteConfig($samplePath, 'default', 0);
-            throw $e;
-        }
-    }
-
-    public function testReinitBaseConfig()
-    {
-        $options = Magento_Test_Helper_Bootstrap::getInstance()->getAppInitParams();
-        $options[Mage_Core_Model_Config::INIT_OPTION_EXTRA_DATA] = '<config><test>old_value</test></config>';
-
-        $objectManager = new Magento_Test_ObjectManager();
-        $model = $this->_createModelWithApp($options, $objectManager);
-
-        /** @var $app Mage_Core_Model_App */
-        $app = $objectManager->get('Mage_Core_Model_App');
-
-        $model->loadBase();
-        $this->assertEquals('old_value', $model->getNode('test'));
-
-        $options[Mage_Core_Model_Config::INIT_OPTION_EXTRA_DATA] = '<config><test>new_value</test></config>';
-        $app->init($options);
-
-        $model->reinit();
-        $this->assertEquals('new_value', $model->getNode('test'));
-    }
-
-    public function testGetCache()
-    {
-        $this->assertInstanceOf('Varien_Cache_Core', $this->_createModel()->getCache());
-    }
-
-    /**
-     * @magentoAppIsolation enabled
-     */
-    public function testSaveCache()
-    {
-        Mage::app()->getCacheInstance()->allowUse('config');
-
-        $model = $this->_createModel(true);
-        $model->removeCache();
-        $this->assertFalse($model->loadCache());
-
-        $model->saveCache(array(Mage_Core_Model_Cache::OPTIONS_CACHE_ID));
-        $this->assertTrue($model->loadCache());
-        $this->assertInstanceOf('Mage_Core_Model_Config_Element', $model->getNode());
-    }
-
-    /**
-     * @magentoAppIsolation enabled
-     */
-    public function testRemoveCache()
-    {
-        Mage::app()->getCacheInstance()->allowUse('config');
-
-        $model = $this->_createModel();
-        $model->removeCache();
-        $this->assertFalse($model->loadCache());
-    }
-
-    public function testGetSectionNode()
-    {
-        $this->assertInstanceOf(
-            'Mage_Core_Model_Config_Element', $this->_createModel(true)->getSectionNode(array('admin'))
-        );
-    }
-
-    public function testGetNode()
-    {
-        $model = $this->_createModel();
-        $this->assertFalse($model->getNode());
-        $model->init();
-        $this->assertInstanceOf('Mage_Core_Model_Config_Element', $model->getNode());
-        $this->assertInstanceOf('Mage_Core_Model_Config_Element', $model->getNode(null, 'store', 1));
-        $this->assertInstanceOf('Mage_Core_Model_Config_Element', $model->getNode(null, 'website', 1));
-    }
-
     public function testSetNode()
     {
-        $model = $this->_createModel(true);
+        $model = $this->_createModel();
         /* some existing node should be used */
         $model->setNode('admin/routers/adminhtml/use', 'test');
         $this->assertEquals('test', (string) $model->getNode('admin/routers/adminhtml/use'));
@@ -344,24 +49,13 @@ class Mage_Core_Model_ConfigTest extends PHPUnit_Framework_TestCase
 
     public function testDetermineOmittedNamespace()
     {
-        $model = $this->_createModel(true);
+        $model = $this->_createModel();
         $this->assertEquals('cms', $model->determineOmittedNamespace('cms'));
         $this->assertEquals('Mage_Cms', $model->determineOmittedNamespace('cms', true));
         $this->assertEquals('', $model->determineOmittedNamespace('nonexistent'));
         $this->assertEquals('', $model->determineOmittedNamespace('nonexistent', true));
     }
 
-    public function testGetModuleConfigurationFiles()
-    {
-        $files = $this->_createModel(true)->getModuleConfigurationFiles('config.xml');
-        $this->assertInternalType('array', $files);
-        $this->assertNotEmpty($files);
-        foreach ($files as $file) {
-            $this->assertStringEndsWith(DIRECTORY_SEPARATOR . 'config.xml', $file);
-            $this->assertFileExists($file);
-        }
-    }
-
     public function testGetDistroBaseUrl()
     {
         $_SERVER['SCRIPT_NAME'] = __FILE__;
@@ -371,26 +65,20 @@ class Mage_Core_Model_ConfigTest extends PHPUnit_Framework_TestCase
 
     public function testGetModuleConfig()
     {
-        $model = $this->_createModel(true);
+        $model = $this->_createModel();
         $this->assertInstanceOf('Mage_Core_Model_Config_Element', $model->getModuleConfig());
         $this->assertInstanceOf('Mage_Core_Model_Config_Element', $model->getModuleConfig('Mage_Core'));
     }
 
     public function testGetModuleDir()
     {
-        $model = $this->_createModel(true);
+        $model = $this->_createModel();
         foreach (array('etc', 'controllers', 'sql', 'data', 'locale') as $type) {
             $dir = $model->getModuleDir($type, 'Mage_Core');
             $this->assertStringEndsWith($type, $dir);
             $this->assertContains('Mage' . DIRECTORY_SEPARATOR . 'Core', $dir);
         }
-        $this->assertTrue(is_dir($this->_createModel(true)->getModuleDir('etc', 'Mage_Core')));
-    }
-
-    public function testLoadEventObservers()
-    {
-        $this->_createModel(true)->loadEventObservers('global');
-        $this->assertArrayHasKey('log_log_clean_after', Mage::getEvents()->getAllEvents());
+        $this->assertTrue(is_dir($this->_createModel()->getModuleDir('etc', 'Mage_Core')));
     }
 
     public function testGetPathVars()
@@ -400,30 +88,9 @@ class Mage_Core_Model_ConfigTest extends PHPUnit_Framework_TestCase
         $this->assertArrayHasKey('baseSecureUrl', $result);
     }
 
-    public function testGetResourceConfig()
-    {
-        $this->assertInstanceOf(
-            'Mage_Core_Model_Config_Element', $this->_createModel(true)->getResourceConfig('cms_setup')
-        );
-    }
-
-    public function testGetResourceConnectionConfig()
-    {
-        $this->assertInstanceOf(
-            'Mage_Core_Model_Config_Element', $this->_createModel(true)->getResourceConnectionConfig('core_read')
-        );
-    }
-
-    public function testGetResourceTypeConfig()
-    {
-        $this->assertInstanceOf(
-            'Mage_Core_Model_Config_Element', $this->_createModel(true)->getResourceTypeConfig('pdo_mysql')
-        );
-    }
-
     public function testGetStoresConfigByPath()
     {
-        $model = $this->_createModel(true);
+        $model = $this->_createModel();
 
         // default
         $baseUrl = $model->getStoresConfigByPath('web/unsecure/base_url');
@@ -452,7 +119,7 @@ class Mage_Core_Model_ConfigTest extends PHPUnit_Framework_TestCase
      */
     public function testShouldUrlBeSecureWhenSecureUsedInFrontend()
     {
-        $model = $this->_createModel(true);
+        $model = $this->_createModel();
         $this->assertFalse($model->shouldUrlBeSecure('/'));
         $this->assertTrue($model->shouldUrlBeSecure('/checkout/onepage'));
     }
@@ -464,87 +131,23 @@ class Mage_Core_Model_ConfigTest extends PHPUnit_Framework_TestCase
      */
     public function testShouldUrlBeSecureWhenSecureNotUsedInFrontend()
     {
-        $model = $this->_createModel(true);
+        $model = $this->_createModel();
         $this->assertFalse($model->shouldUrlBeSecure('/'));
         $this->assertFalse($model->shouldUrlBeSecure('/checkout/onepage'));
     }
 
-    public function testGetTablePrefix()
-    {
-        $_prefix = 'prefix_';
-        $_model = $this->_createModel(true);
-        $_model->setNode('global/resources/db/table_prefix', $_prefix);
-        $this->assertEquals($_prefix, (string)$_model->getTablePrefix());
-    }
-
-    public function testGetEventConfig()
-    {
-        $this->assertInstanceOf('Mage_Core_Model_Config_Element',
-            $this->_createModel(true)->getEventConfig('global', 'controller_front_init_routers')
-        );
-    }
-
-    public function testSaveDeleteConfig()
-    {
-        $model = $this->_createModel(true);
-        $model->saveConfig('web/url/redirect_to_base', 0);
-        try {
-            $model->reinit();
-            $this->assertEquals('0', (string)$model->getNode('default/web/url/redirect_to_base'));
 
-            $model->deleteConfig('web/url/redirect_to_base');
-            $model->reinit();
-            $this->assertEquals('1', (string)$model->getNode('default/web/url/redirect_to_base'));
-        } catch (Exception $e) {
-            $model->deleteConfig('web/url/redirect_to_base');
-            throw $e;
-        }
-    }
-
-    public function testGetFieldset()
-    {
-        $fieldset = $this->_createModel(true)->getFieldset('customer_account');
-        $this->assertObjectHasAttribute('prefix', $fieldset);
-        $this->assertObjectHasAttribute('firstname', $fieldset);
-        $this->assertObjectHasAttribute('middlename', $fieldset);
-        $this->assertObjectHasAttribute('lastname', $fieldset);
-        $this->assertObjectHasAttribute('suffix', $fieldset);
-        $this->assertObjectHasAttribute('email', $fieldset);
-        $this->assertObjectHasAttribute('password', $fieldset);
-    }
-
-    /**
-     * Creates Mage_Core_Model_Config model with initialized Mage_Core_Model_App
-     *
-     * @param array $appOptions
-     * @param Magento_Test_ObjectManager $objectManager
-     * @return Mage_Core_Model_Config
-     */
-    protected function _createModelWithApp(array $appOptions, Magento_Test_ObjectManager $objectManager = null)
-    {
-        $baseOptions = Magento_Test_Helper_Bootstrap::getInstance()->getAppInitParams();
-        $appOptions = array_replace_recursive($baseOptions, $appOptions);
-        $objectManager = $objectManager ?: new Magento_Test_ObjectManager();
-        /** @var $app Mage_Core_Model_App */
-        $app = $objectManager->get('Mage_Core_Model_App');
-        $app->init($appOptions);
-        return $objectManager->create('Mage_Core_Model_Config');
-    }
 
     /**
      * Instantiate Mage_Core_Model_Config and initialize (load configuration) if needed
      *
-     * @param bool $initialize
      * @param array $arguments
      * @return Mage_Core_Model_Config
      */
-    protected function _createModel($initialize = false, array $arguments = array())
+    protected function _createModel(array $arguments = array())
     {
         /** @var $model Mage_Core_Model_Config */
         $model = Mage::getModel('Mage_Core_Model_Config', $arguments);
-        if ($initialize) {
-            $model->init();
-        }
         return $model;
     }
 
@@ -562,7 +165,8 @@ class Mage_Core_Model_ConfigTest extends PHPUnit_Framework_TestCase
      */
     public function testGetAreas()
     {
-        $model = $this->_createModel(true, array('sourceData' => __DIR__ . '/../_files/etc/config.xml'));
+        $this->markTestIncomplete('MAGETWO-6406');
+        $model = $this->_createModel(array('sourceData' => __DIR__ . '/../_files/etc/config.xml'));
 
         $allowedAreas = $model->getAreas();
         $this->assertNotEmpty($allowedAreas, 'Areas are not initialized');
@@ -594,7 +198,8 @@ class Mage_Core_Model_ConfigTest extends PHPUnit_Framework_TestCase
      */
     public function testGetRouters()
     {
-        $model = $this->_createModel(true, array('sourceData' => __DIR__ . '/../_files/etc/config.xml'));
+        $this->markTestIncomplete('MAGETWO-6406');
+        $model = $this->_createModel(array('sourceData' => __DIR__ . '/../_files/etc/config.xml'));
 
         $loadedRouters = $model->getRouters();
         $this->assertArrayHasKey('test_router1', $loadedRouters, 'Test router #1 is not initialized in test area.');
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Design/FallbackTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Design/FallbackTest.php
index 96f3153e80bacdd14b55172d8217f011c0b56198..07c8548d3d4f7511e69a3dc97c7afff0fa222ca6 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Design/FallbackTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Design/FallbackTest.php
@@ -32,7 +32,7 @@ class Mage_Core_Model_Design_FallbackTest extends PHPUnit_Framework_TestCase
      */
     public function testConstructException()
     {
-        $dirs = new Mage_Core_Model_Dir(__DIR__);
+        $dirs = new Mage_Core_Model_Dir(__DIR__, new Varien_Io_File());
         Mage::getObjectManager()->create(
             'Mage_Core_Model_Design_Fallback',
             array(
@@ -59,7 +59,7 @@ class Mage_Core_Model_Design_FallbackTest extends PHPUnit_Framework_TestCase
             ->method('getThemePath')
             ->will($this->returnValue($theme));
 
-        $dirs = new Mage_Core_Model_Dir(__DIR__);
+        $dirs = new Mage_Core_Model_Dir(__DIR__, $this->getMock('Varien_Io_File'));
         $stub = array(
             'themeConfig' => 'stub',
             'area' => 'a',
@@ -91,7 +91,9 @@ class Mage_Core_Model_Design_FallbackTest extends PHPUnit_Framework_TestCase
         // Prepare config with directories
         $baseDir = dirname(__DIR__) . DIRECTORY_SEPARATOR .  '_files' . DIRECTORY_SEPARATOR . 'fallback';
         $viewDir = $baseDir . DIRECTORY_SEPARATOR . 'design';
-        $dirs = new Mage_Core_Model_Dir($baseDir, array(), array(Mage_Core_Model_Dir::THEMES => $viewDir));
+        $dirs = new Mage_Core_Model_Dir(
+            $baseDir, $this->getMock('Varien_Io_File'), array(), array(Mage_Core_Model_Dir::THEMES => $viewDir)
+        );
 
         /** @var $collection Mage_Core_Model_Theme_Collection */
         $collection = Mage::getModel('Mage_Core_Model_Theme_Collection');
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Design/PackageFallbackTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Design/PackageFallbackTest.php
index 4658bd81a9104aebd7a558bde38d7d7025ac341d..a9832589513e6e11aa01cfd8d22cb3efc843bc3f 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Design/PackageFallbackTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Design/PackageFallbackTest.php
@@ -39,11 +39,11 @@ class Mage_Core_Model_Design_PackageFallbackTest extends PHPUnit_Framework_TestC
     protected function setUp()
     {
         Magento_Test_Helper_Bootstrap::getInstance()->reinitialize(array(
-            Mage_Core_Model_App::INIT_OPTION_DIRS => array(
+            Mage::PARAM_APP_DIRS => array(
                 Mage_Core_Model_Dir::THEMES => dirname(__DIR__) . '/_files/design'
             )
         ));
-        $this->_model = new Mage_Core_Model_Design_Package(Mage::getObjectManager()->create('Magento_Filesystem'));
+        $this->_model = Mage::getObjectManager()->create('Mage_Core_Model_Design_Package');
         $this->_model->setDesignTheme('test/default');
     }
 
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Design/PackageMergingTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Design/PackageMergingTest.php
index 7f6ff1ed093203cd1ef65eaaa1f0c0e9f384b761..69792277a5c37e87a82b8f964c3aadbae6aa75b4 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Design/PackageMergingTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Design/PackageMergingTest.php
@@ -58,12 +58,11 @@ class Mage_Core_Model_Design_PackageMergingTest extends PHPUnit_Framework_TestCa
     protected function setUp()
     {
         Magento_Test_Helper_Bootstrap::getInstance()->reinitialize(array(
-            Mage_Core_Model_App::INIT_OPTION_DIRS => array(
+            Mage::PARAM_APP_DIRS => array(
                 Mage_Core_Model_Dir::THEMES => dirname(__DIR__) . '/_files/design'
             )
         ));
-        $filesystem = Mage::getObjectManager()->create('Magento_Filesystem');
-        $this->_model = new Mage_Core_Model_Design_Package($filesystem);
+        $this->_model = Mage::getSingleton('Mage_Core_Model_Design_Package');
         $this->_model->setDesignTheme('package/default');
     }
 
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Design/PackagePublicationTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Design/PackagePublicationTest.php
index ec3ea3431bbe08e2ece30da388e219299ed22fac..a9f9d3d0d341fe53f11ff22365ec7afe7984d56e 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Design/PackagePublicationTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Design/PackagePublicationTest.php
@@ -445,7 +445,7 @@ class Mage_Core_Model_Design_PackagePublicationTest extends PHPUnit_Framework_Te
     {
         $appInstallDir = Magento_Test_Helper_Bootstrap::getInstance()->getAppInstallDir();
         Magento_Test_Helper_Bootstrap::getInstance()->reinitialize(array(
-            Mage_Core_Model_App::INIT_OPTION_DIRS => array(
+            Mage::PARAM_APP_DIRS => array(
                 Mage_Core_Model_Dir::THEMES => "$appInstallDir/media_for_change",
             )
         ));
@@ -520,7 +520,7 @@ class Mage_Core_Model_Design_PackagePublicationTest extends PHPUnit_Framework_Te
     {
         $appInstallDir = Magento_Test_Helper_Bootstrap::getInstance()->getAppInstallDir();
         Magento_Test_Helper_Bootstrap::getInstance()->reinitialize(array(
-            Mage_Core_Model_App::INIT_OPTION_DIRS => array(
+            Mage::PARAM_APP_DIRS => array(
                 Mage_Core_Model_Dir::THEMES => "$appInstallDir/media_for_change",
             )
         ));
@@ -554,7 +554,7 @@ class Mage_Core_Model_Design_PackagePublicationTest extends PHPUnit_Framework_Te
     protected function _initTestTheme()
     {
         Magento_Test_Helper_Bootstrap::getInstance()->reinitialize(array(
-            Mage_Core_Model_App::INIT_OPTION_DIRS => array(
+            Mage::PARAM_APP_DIRS => array(
                 Mage_Core_Model_Dir::THEMES => dirname(__DIR__) . '/_files/design/'
             )
         ));
@@ -570,10 +570,11 @@ class Mage_Core_Model_Design_PackagePublicationTest extends PHPUnit_Framework_Te
     public function testCssWithBase64Data()
     {
         Magento_Test_Helper_Bootstrap::getInstance()->reinitialize(array(
-            Mage_Core_Model_App::INIT_OPTION_DIRS => array(
+            Mage::PARAM_APP_DIRS => array(
                 Mage_Core_Model_Dir::THEMES => dirname(__DIR__) . '/_files/design/'
             )
         ));
+        Mage::app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_ADMINHTML, Mage_COre_Model_App_Area::PART_CONFIG);
 
         /** @var $themeModel Mage_Core_Model_Theme */
         $themeModel = Mage::getObjectManager()->create('Mage_Core_Model_Theme');
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Design/PackageTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Design/PackageTest.php
index 1799fd401c2346804d650e828a7cecb46fc3db67..8ddae5cdc5ea5fde2df6ac643ed2bca810e31c4f 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Design/PackageTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Design/PackageTest.php
@@ -57,7 +57,7 @@ class Mage_Core_Model_Design_PackageTest extends PHPUnit_Framework_TestCase
 
     protected function setUp()
     {
-        $this->_model = new Mage_Core_Model_Design_Package(Mage::getObjectManager()->create('Magento_Filesystem'));
+        $this->_model = Mage::getModel('Mage_Core_Model_Design_Package');
     }
 
     protected function tearDown()
@@ -73,10 +73,11 @@ class Mage_Core_Model_Design_PackageTest extends PHPUnit_Framework_TestCase
     protected function _emulateFixtureTheme($themePath = 'test/default')
     {
         Magento_Test_Helper_Bootstrap::getInstance()->reinitialize(array(
-            Mage_Core_Model_App::INIT_OPTION_DIRS => array(
+            Mage::PARAM_APP_DIRS => array(
                 Mage_Core_Model_Dir::THEMES => realpath(__DIR__ . '/../_files/design'),
             ),
         ));
+        $this->_model = Mage::getModel('Mage_Core_Model_Design_Package');
         $this->_model->setDesignTheme($themePath);
     }
 
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Email/Template/FilterTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Email/Template/FilterTest.php
index 0888cd2bdb72882f4104f77483d23ad5ae8ff05a..1cc31c4dde5fb4e92cf8a078ba5a426c80b53ab5 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Email/Template/FilterTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Email/Template/FilterTest.php
@@ -112,7 +112,7 @@ class Mage_Core_Model_Email_Template_FilterTest extends PHPUnit_Framework_TestCa
     public function testLayoutDirective($area, $directiveParams, $expectedOutput)
     {
         Magento_Test_Helper_Bootstrap::getInstance()->reinitialize(array(
-            Mage_Core_Model_App::INIT_OPTION_DIRS => array(
+            Mage::PARAM_APP_DIRS => array(
                 Mage_Core_Model_Dir::THEMES => dirname(__DIR__) . '/_files/design'
             )
         ));
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Email/_files/themes.php b/dev/tests/integration/testsuite/Mage/Core/Model/Email/_files/themes.php
index bfcc7910940f2d6aaa0f96a01b0c87eadae2d475..70bee1c51dd23c1d635ab39275aef1ba573f5c59 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Email/_files/themes.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Email/_files/themes.php
@@ -21,6 +21,7 @@
  * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
+Mage::app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_ADMINHTML, Mage_Core_Model_App_Area::PART_CONFIG);
 /** @var $registration Mage_Core_Model_Theme_Registration */
 $registration = Mage::getModel('Mage_Core_Model_Theme_Registration');
 $registration->register(
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Layout/MergeTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Layout/MergeTest.php
index 9cd4e31e847755134c9b8a2cf829eefb798cf3ca..787f6fc13130d7680a2b1c536ff3b4b48df21cd2 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Layout/MergeTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Layout/MergeTest.php
@@ -38,7 +38,7 @@ class Mage_Core_Model_Layout_MergeTest extends PHPUnit_Framework_TestCase
         Mage::app()->getCacheInstance()->banUse('layout');
 
         Magento_Test_Helper_Bootstrap::getInstance()->reinitialize(array(
-            Mage_Core_Model_App::INIT_OPTION_DIRS => array(
+            Mage::PARAM_APP_DIRS => array(
                 Mage_Core_Model_Dir::THEMES => dirname(__DIR__) . '/_files/design'
             )
         ));
@@ -326,8 +326,7 @@ class Mage_Core_Model_Layout_MergeTest extends PHPUnit_Framework_TestCase
     {
         /* Erase existing layout updates */
         unset(Mage::app()->getConfig()->getNode("{$area}/layout")->updates);
-        /* Setup layout updates fixture */
-        Mage::app()->getConfig()->extend(new Varien_Simplexml_Config("
+        $updates = new Varien_Simplexml_Config("
             <config>
                 <{$area}>
                     <layout>
@@ -337,7 +336,9 @@ class Mage_Core_Model_Layout_MergeTest extends PHPUnit_Framework_TestCase
                     </layout>
                 </{$area}>
             </config>
-        "));
+        ");
+        /* Setup layout updates fixture */
+        Mage::app()->getConfig()->getNode()->extend($updates->getNode());
     }
 
     /**
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Resource/Db/ProfilerTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Resource/Db/ProfilerTest.php
index e4d3033adbf934956f38c8fe9e64eb2f3368e62d..d1eb7654532ffea4870ed6cc5441ff354936e49f 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Resource/Db/ProfilerTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Resource/Db/ProfilerTest.php
@@ -57,7 +57,9 @@ class Mage_Core_Model_Resource_Db_ProfilerTest extends PHPUnit_Framework_TestCas
      */
     protected function _getConnectionReadConfig()
     {
-        $connReadConfig = Mage::getConfig()->getResourceConnectionConfig('core_read');
+        $connReadConfig = Mage::getObjectManager()
+            ->get('Mage_Core_Model_Config_Resource')
+            ->getResourceConnectionConfig('core_read');
         $profilerConfig = $connReadConfig->addChild('profiler');
         $profilerConfig->addChild('class', 'Mage_Core_Model_Resource_Db_Profiler');
         $profilerConfig->addChild('enabled', 'true');
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Resource/SetupTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Resource/SetupTest.php
index b1a2f7fc9240ca3b3e18f1a467850983b1dca5de..1f00b55ae1a52e5ccf605424e21479d1318c75c6 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Resource/SetupTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Resource/SetupTest.php
@@ -50,10 +50,6 @@ class Mage_Core_Model_Resource_SetupTest extends PHPUnit_Framework_TestCase
         $this->assertEquals('test_real_name', $this->_model->getTable('test_name'));
     }
 
-    /**
-     * @covers Mage_Core_Model_Resource_Setup::applyAllUpdates
-     * @covers Mage_Core_Model_Resource_Setup::applyAllDataUpdates
-     */
     public function testApplyAllDataUpdates()
     {
         /*reset versions*/
@@ -61,9 +57,11 @@ class Mage_Core_Model_Resource_SetupTest extends PHPUnit_Framework_TestCase
         Mage::getResourceModel('Mage_Core_Model_Resource_Resource')->setDataVersion('adminnotification_setup', false);
         $this->_model->deleteTableRow('core_resource', 'code', 'adminnotification_setup');
         $this->_model->getConnection()->dropTable($this->_model->getTable('adminnotification_inbox'));
+        /** @var $updater Mage_Core_Model_Db_Updater */
+        $updater = Mage::getSingleton('Mage_Core_Model_Db_Updater');
         try {
-            $this->_model->applyAllUpdates();
-            $this->_model->applyAllDataUpdates();
+            $updater->updateScheme();
+            $updater->updateData();
         } catch (Exception $e) {
             $this->fail("Impossible to continue other tests, because database is broken: {$e}");
         }
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Resource/Store/CollectionTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Resource/Store/CollectionTest.php
index 26bd36f8aad6b507bd33bddcb8ef6128c513ecd7..7cf065032420ab0e90b292ece61bbb896fd853a1 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Resource/Store/CollectionTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Resource/Store/CollectionTest.php
@@ -149,7 +149,7 @@ class Mage_Core_Model_Resource_Store_CollectionTest extends PHPUnit_Framework_Te
      */
     public function testGetAllIds()
     {
-        $this->assertContains(Mage_Core_Model_App::ADMIN_STORE_ID, $this->_collection->getAllIds());
+        $this->assertContains(Mage_Core_Model_AppInterface::ADMIN_STORE_ID, $this->_collection->getAllIds());
     }
 
     /**
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Resource/Theme/CollectionTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Resource/Theme/CollectionTest.php
index 9ad08ba0cdd8a27193628e118a99e20262418daa..f6180a00f9e2914ff0ecd2be15ef685b697991ad 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Resource/Theme/CollectionTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Resource/Theme/CollectionTest.php
@@ -40,6 +40,7 @@ class Mage_Core_Model_Resource_Theme_CollectionTest extends PHPUnit_Framework_Te
      */
     public function testCollection()
     {
+        Mage::getConfig();
         $oldTotalRecords = self::_getThemesCollection()->getSize();
 
         $collection = $this->setThemeFixture();
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Resource/TransactionTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Resource/TransactionTest.php
index ea400edce254ca91f544bd5a747f3f59320607fd..63f5b1ab17c7ab132b07d3fa24aba7ac04c144a8 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Resource/TransactionTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Resource/TransactionTest.php
@@ -71,7 +71,7 @@ class Mage_Core_Model_Resource_TransactionTest extends PHPUnit_Framework_TestCas
         $this->assertNotEmpty($first->getId());
         $this->assertNotEmpty($second->getId());
 
-        Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
+        Mage::app()->getStore()->setId(Mage_Core_Model_AppInterface::ADMIN_STORE_ID);
         $this->_model->delete();
 
         $test  = Mage::getModel('Mage_Core_Model_Store_Group');
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/ResourceTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/ResourceTest.php
index c07b9fefa88756aa6f22b5f30b49de1209436a9e..67ea705eb7691070e92a9e7d049067af95d55f6e 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/ResourceTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/ResourceTest.php
@@ -60,7 +60,8 @@ class Mage_Core_Model_ResourceTest extends PHPUnit_Framework_TestCase
      */
     public function testProfilerInit()
     {
-        $connReadConfig = Mage::getConfig()->getResourceConnectionConfig('core_read');
+        $connReadConfig = Mage::getSingleton('Mage_Core_Model_Config_Resource')
+            ->getResourceConnectionConfig('core_read');
         $profilerConfig = $connReadConfig->addChild('profiler');
         $profilerConfig->addChild('class', 'Mage_Core_Model_Resource_Db_Profiler');
         $profilerConfig->addChild('enabled', 'true');
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/StoreTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/StoreTest.php
index 2f7b8a740718fcaf4faa430a05d2cc8fba218a42..dd613146361a0f526c3b0d658dec72da6c30b314 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/StoreTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/StoreTest.php
@@ -158,7 +158,7 @@ class Mage_Core_Model_StoreTest extends PHPUnit_Framework_TestCase
     public function testGetBaseUrlInPub()
     {
         Magento_Test_Helper_Bootstrap::getInstance()->reinitialize(array(
-            Mage_Core_Model_App::INIT_OPTION_URIS => array(Mage_Core_Model_Dir::PUB => '')
+            Mage::PARAM_APP_URIS => array(Mage_Core_Model_Dir::PUB => '')
         ));
         $this->_model->load('default');
 
@@ -265,7 +265,7 @@ class Mage_Core_Model_StoreTest extends PHPUnit_Framework_TestCase
         );
 
         /* emulate admin store */
-        Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
+        Mage::app()->getStore()->setId(Mage_Core_Model_AppInterface::ADMIN_STORE_ID);
         $crud = new Magento_Test_Entity($this->_model, array('name' => 'new name'));
         $crud->testCrud();
     }
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Theme/ServiceTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Theme/ServiceTest.php
index cbed9dda70af1e67b097f59f17e15a2a5056d342..574e7478212aad958a42233de8ed42c93452a786 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Theme/ServiceTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Theme/ServiceTest.php
@@ -35,6 +35,7 @@ class Mage_Core_Model_Theme_ServiceTest extends PHPUnit_Framework_TestCase
      */
     public function testGetThemes()
     {
+        Mage::getConfig();
         /** @var $themeService Mage_Core_Model_Theme_Service */
         $themeService = Mage::getObjectManager()->create('Mage_Core_Model_Theme_Service');
         $collection = $themeService->getThemes(1, Mage_Core_Model_Resource_Theme_Collection::DEFAULT_PAGE_SIZE);
@@ -69,7 +70,7 @@ class Mage_Core_Model_Theme_ServiceTest extends PHPUnit_Framework_TestCase
         $themeService->assignThemeToStores($physicalTheme->getId(), array($storeView));
         $this->assertEquals($originalCount + 1, $this->_getThemeCollection()->count());
 
-        $configItem = Mage::app()->getConfig()->getConfigDataModel()->getCollection()
+        $configItem = Mage::getSingleton('Mage_Core_Model_Config_Data')->getCollection()
             ->addFieldToSelect(array('value'))
             ->addFieldToFilter('scope', Mage_Core_Model_Config::SCOPE_STORES)
             ->addFieldToFilter('scope_id', $storeView)
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/ThemeTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/ThemeTest.php
index 2a6933750f0670be61cee45912009b6f1fb487a1..d5e008008232289aa1172849583a795043b6da6a 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/ThemeTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/ThemeTest.php
@@ -34,6 +34,7 @@ class Mage_Core_Model_ThemeTest extends PHPUnit_Framework_TestCase
      */
     public function testCrud()
     {
+        Mage::getConfig();
         /** @var $themeModel Mage_Core_Model_Theme */
         $themeModel = Mage::getObjectManager()->create('Mage_Core_Model_Theme');
         $themeModel->setData($this->_getThemeValidData());
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/TranslateTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/TranslateTest.php
index 9a0c255d28d1fed647e37f0248dd4d2757e70c12..72898162dd3e341589c32bf3be4919fde66efdbb 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/TranslateTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/TranslateTest.php
@@ -45,9 +45,14 @@ class Mage_Core_Model_TranslateTest extends PHPUnit_Framework_TestCase
         $pathChunks = array(dirname(__FILE__), '_files', 'design', 'frontend', 'test', 'default', 'locale', 'en_US',
             'translate.csv');
 
-        $filesystem = new Magento_Filesystem(new Magento_Filesystem_Adapter_Local);
-        $this->_designModel = $this->getMock('Mage_Core_Model_Design_Package',
-            array('getLocaleFileName'), array($filesystem));
+        $this->_designModel = $this->getMock(
+            'Mage_Core_Model_Design_Package',
+            array('getLocaleFileName'),
+            array(
+                Mage::getSingleton('Mage_Core_Model_Config_Modules_Reader'),
+                Mage::getSingleton('Magento_Filesystem'),
+            )
+        );
         $this->_designModel->expects($this->any())
             ->method('getLocaleFileName')
             ->will($this->returnValue(implode(DIRECTORY_SEPARATOR, $pathChunks)));
@@ -142,7 +147,9 @@ class Mage_Core_Model_TranslateTest extends PHPUnit_Framework_TestCase
 
         $filesystem = new Magento_Filesystem(new Magento_Filesystem_Adapter_Local);
         $this->_designModel = $this->getMock('Mage_Core_Model_Design_Package',
-            array('getLocaleFileName', 'getDesignTheme'), array($filesystem));
+            array('getLocaleFileName', 'getDesignTheme'),
+            array(Mage::getSingleton('Mage_Core_Model_Config_Modules_Reader'), $filesystem)
+        );
         $this->_designModel->expects($this->any())
             ->method('getLocaleFileName')
             ->will($this->returnValue(implode(DIRECTORY_SEPARATOR, $pathChunks)));
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/UrlTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/UrlTest.php
index d3869c0467622f42263015582464592015b4daac..9de2a0cbc272f884bcac4177db219cdbe9611b12 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/UrlTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/UrlTest.php
@@ -113,7 +113,7 @@ class Mage_Core_Model_UrlTest extends PHPUnit_Framework_TestCase
         $this->assertFalse($this->_model->isSecure());
         $this->_model->setSecureIsForced(1);
         $this->assertTrue(is_bool($this->_model->isSecure()));
-        Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
+        Mage::app()->getStore()->setId(Mage_Core_Model_AppInterface::ADMIN_STORE_ID);
         $this->assertFalse($this->_model->isSecure());
     }
 
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/WebsiteTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/WebsiteTest.php
index a129faffa9c319beb16df1bf5762e5719e1a8f99..03b3e4742f8b8a986ac23a99cce8ffb95ed1ce38 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/WebsiteTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/WebsiteTest.php
@@ -194,7 +194,7 @@ class Mage_Core_Model_WebsiteTest extends PHPUnit_Framework_TestCase
         );
 
         /* emulate admin store */
-        Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
+        Mage::app()->getStore()->setId(Mage_Core_Model_AppInterface::ADMIN_STORE_ID);
         $crud = new Magento_Test_Entity($this->_model, array('name' => 'new name'));
         $crud->testCrud();
     }
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/themes.php b/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/themes.php
index c0082d1d77e3d4c435322ec40756e39180833177..04c48e3ec7d92c94084c0a94cabb16214c82b6a6 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/themes.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/themes.php
@@ -24,7 +24,7 @@
  * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
-
+Mage::app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_ADMINHTML, Mage_Core_Model_App_Area::PART_CONFIG);
 /** @var $registration Mage_Core_Model_Theme_Registration */
 $registration = Mage::getModel('Mage_Core_Model_Theme_Registration');
 $registration->register(
diff --git a/dev/tests/integration/testsuite/Mage/Core/_files/layout_update.php b/dev/tests/integration/testsuite/Mage/Core/_files/layout_update.php
index 096118ec0ce059bc0c9e54dc2a73ca6153e660a9..12afe9838e624eea49ebca60b50e161fdc809eb7 100644
--- a/dev/tests/integration/testsuite/Mage/Core/_files/layout_update.php
+++ b/dev/tests/integration/testsuite/Mage/Core/_files/layout_update.php
@@ -27,7 +27,7 @@
 
 /** @var $objectManager Magento_ObjectManager */
 $objectManager = Mage::getObjectManager();
-
+Mage::app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_ADMINHTML, Mage_COre_Model_App_Area::PART_CONFIG);
 /** @var $theme Mage_Core_Model_Theme */
 $theme = $objectManager->create('Mage_Core_Model_Theme');
 $theme->setThemePath('test/test')
diff --git a/dev/tests/integration/testsuite/Mage/Core/_files/media_for_change.php b/dev/tests/integration/testsuite/Mage/Core/_files/media_for_change.php
index 374e81cd36d3a81b300ed0f83ad9156fa03b07ec..6be003d01b986ea9b1caee7039149308d8f636ec 100644
--- a/dev/tests/integration/testsuite/Mage/Core/_files/media_for_change.php
+++ b/dev/tests/integration/testsuite/Mage/Core/_files/media_for_change.php
@@ -24,7 +24,7 @@
  * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
-
+Mage::app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_ADMINHTML, Mage_Core_Model_App_Area::PART_CONFIG);
 $designDir = Magento_Test_Helper_Bootstrap::getInstance()->getAppInstallDir() . '/media_for_change';
 $themeDir = $designDir . DIRECTORY_SEPARATOR . '/frontend/test/default';
 $sourcePath = dirname(__DIR__) . '/Model/_files/design/frontend/test/publication/';
diff --git a/dev/tests/integration/testsuite/Mage/Customer/Service/CustomerTest.php b/dev/tests/integration/testsuite/Mage/Customer/Service/CustomerTest.php
index cc830e089762493854ce152cf211a33b5d23a0c8..efc723944fd96a168955e533884f25ee75d26a64 100644
--- a/dev/tests/integration/testsuite/Mage/Customer/Service/CustomerTest.php
+++ b/dev/tests/integration/testsuite/Mage/Customer/Service/CustomerTest.php
@@ -55,7 +55,7 @@ class Mage_Customer_Service_CustomerTest extends PHPUnit_Framework_TestCase
     protected function tearDown()
     {
         $previousStoreId = Mage::app()->getStore();
-        Mage::app()->setCurrentStore(Mage::app()->getStore(Mage_Core_Model_App::ADMIN_STORE_ID));
+        Mage::app()->setCurrentStore(Mage::app()->getStore(Mage_Core_Model_AppInterface::ADMIN_STORE_ID));
         if ($this->_createdCustomer && $this->_createdCustomer->getId() > 0) {
             $this->_createdCustomer->getAddressesCollection()->delete();
             $this->_createdCustomer->delete();
@@ -112,7 +112,7 @@ class Mage_Customer_Service_CustomerTest extends PHPUnit_Framework_TestCase
                 'password' => '123123q',
                 'default_billing' => null,
                 'default_shipping' => null,
-                'store_id' => Mage_Core_Model_App::ADMIN_STORE_ID
+                'store_id' => Mage_Core_Model_AppInterface::ADMIN_STORE_ID
             )),
             'Mandatory data' => array(array(
                 'firstname' => 'SomeName',
@@ -150,7 +150,7 @@ class Mage_Customer_Service_CustomerTest extends PHPUnit_Framework_TestCase
                 'suffix' => null,
                 'email' => 'test' . mt_rand(1000, 9999) . '@mail.com',
                 'password' => '123123q',
-                'store_id' => Mage_Core_Model_App::ADMIN_STORE_ID
+                'store_id' => Mage_Core_Model_AppInterface::ADMIN_STORE_ID
             ), 'Magento_Validator_Exception'),
             'Invalid email' => array(array(
                 'website_id' => 0,
@@ -162,7 +162,7 @@ class Mage_Customer_Service_CustomerTest extends PHPUnit_Framework_TestCase
                 'suffix' => null,
                 'email' => '111@111',
                 'password' => '123123q',
-                'store_id' => Mage_Core_Model_App::ADMIN_STORE_ID
+                'store_id' => Mage_Core_Model_AppInterface::ADMIN_STORE_ID
             ), 'Magento_Validator_Exception'),
             'Invalid password' => array(array(
                 'website_id' => 0,
@@ -174,7 +174,7 @@ class Mage_Customer_Service_CustomerTest extends PHPUnit_Framework_TestCase
                 'suffix' => null,
                 'email' => 'test' . mt_rand(1000, 9999) . '@mail.com',
                 'password' => '123',
-                'store_id' => Mage_Core_Model_App::ADMIN_STORE_ID
+                'store_id' => Mage_Core_Model_AppInterface::ADMIN_STORE_ID
             ), 'Mage_Eav_Model_Entity_Attribute_Exception', 'The password must have at least 6 characters.')
         );
     }
@@ -351,7 +351,7 @@ class Mage_Customer_Service_CustomerTest extends PHPUnit_Framework_TestCase
                 'email' => 'test' . mt_rand(1000, 9999) . '@mail.com',
                 'dob' => date('Y-m-d H:i:s'),
                 'gender' => 1,
-                'store_id' => Mage_Core_Model_App::ADMIN_STORE_ID
+                'store_id' => Mage_Core_Model_AppInterface::ADMIN_STORE_ID
             ))
         );
     }
diff --git a/dev/tests/integration/testsuite/Mage/Customer/_files/address_formats.php b/dev/tests/integration/testsuite/Mage/Customer/_files/address_formats.php
index e47dea917f0f8cfd41e21ac30700ac51eb4d5144..2fe0081de8ab31b29b7ad66da38ffd46e83ea438 100644
--- a/dev/tests/integration/testsuite/Mage/Customer/_files/address_formats.php
+++ b/dev/tests/integration/testsuite/Mage/Customer/_files/address_formats.php
@@ -63,4 +63,4 @@ $configXml = <<<EOD
 EOD;
 
 $config = Mage::getModel('Mage_Core_Model_Config_Base', array('sourceData' => $configXml));
-Mage::getConfig()->extend($config);
+Mage::getConfig()->getNode()->extend($config->getNode());
diff --git a/dev/tests/integration/testsuite/Mage/DesignEditor/Model/Resource/Layout/UpdateTest.php b/dev/tests/integration/testsuite/Mage/DesignEditor/Model/Resource/Layout/UpdateTest.php
index c00793f30715dbe563cb3adf4731d8037182a22f..e40abad0591d7ee288f155b34e5c6a62fc502d0f 100644
--- a/dev/tests/integration/testsuite/Mage/DesignEditor/Model/Resource/Layout/UpdateTest.php
+++ b/dev/tests/integration/testsuite/Mage/DesignEditor/Model/Resource/Layout/UpdateTest.php
@@ -83,7 +83,7 @@ class Mage_DesignEditor_Model_Resource_Layout_UpdateTest extends PHPUnit_Framewo
         /** @var $vdeLayoutUpdate Mage_DesignEditor_Model_Resource_Layout_Update */
         $vdeLayoutUpdate = $this->_objectManager->create('Mage_DesignEditor_Model_Resource_Layout_Update');
         $vdeLayoutUpdate->makeTemporaryLayoutUpdatesPermanent($this->_design->getDesignTheme()->getThemeId(),
-            array(Mage_Core_Model_App::ADMIN_STORE_ID)
+            array(Mage_Core_Model_AppInterface::ADMIN_STORE_ID)
         );
 
         $resultAfter = $coreLayoutUpdate->fetchUpdatesByHandle('test_handle');
diff --git a/dev/tests/integration/testsuite/Mage/DesignEditor/_files/design_editor_active.php b/dev/tests/integration/testsuite/Mage/DesignEditor/_files/design_editor_active.php
new file mode 100644
index 0000000000000000000000000000000000000000..ebefd9c4699efea617870621101a2165256d636d
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/DesignEditor/_files/design_editor_active.php
@@ -0,0 +1,51 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Magento
+ * @package     Mage_DesignEditor
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+Mage::setCurrentArea('adminhtml');
+/** @var $session Mage_DesignEditor_Model_Session */
+$session = Mage::getModel('Mage_DesignEditor_Model_Session');
+/** @var $auth Mage_Backend_Model_Auth */
+$auth = Mage::getModel('Mage_Backend_Model_Auth');
+$auth->setAuthStorage($session);
+$auth->login(Magento_Test_Bootstrap::ADMIN_NAME, Magento_Test_Bootstrap::ADMIN_PASSWORD);
+$session->activateDesignEditor();
+
+/** @var $theme Mage_Core_Model_Theme */
+$theme = Mage::getModel('Mage_Core_Model_Theme');
+$theme->setData(array(
+    'theme_code'           => 'blank',
+    'area'                 => 'frontend',
+    'parent_id'            => null,
+    'theme_path'           => 'default/blank',
+    'theme_version'        => '2.0.0.0',
+    'theme_title'          => 'Default',
+    'preview_image'        => 'media/preview_image.jpg',
+    'magento_version_from' => '2.0.0.0-dev1',
+    'magento_version_to'   => '*',
+    'is_featured'          => '0'
+));
+$theme->save();
+$session->setThemeId($theme->getId());
diff --git a/dev/tests/integration/testsuite/Mage/Downloadable/Model/Product/TypeTest.php b/dev/tests/integration/testsuite/Mage/Downloadable/Model/Product/TypeTest.php
index 2de79e238914ec8e11d45dbceda5960dfb60f9f9..4636c03cbd1f1465d274b0a482ec586d3973e545 100644
--- a/dev/tests/integration/testsuite/Mage/Downloadable/Model/Product/TypeTest.php
+++ b/dev/tests/integration/testsuite/Mage/Downloadable/Model/Product/TypeTest.php
@@ -47,7 +47,7 @@ class Mage_Downloadable_Model_Product_TypeTest extends PHPUnit_Framework_TestCas
     {
         $product = Mage::getModel('Mage_Catalog_Model_Product');
         $product->load(1);
-        Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
+        Mage::app()->setCurrentStore(Mage_Core_Model_AppInterface::ADMIN_STORE_ID);
         $product->setOrigData();
         $downloadableData = array();
 
diff --git a/dev/tests/integration/testsuite/Mage/Install/Model/Installer/ConfigTest.php b/dev/tests/integration/testsuite/Mage/Install/Model/Installer/ConfigTest.php
index fe5a40f947f2307751f2677b8b89be07b053f4bf..3477eaaa7c4208f68e84335341e18233262df785 100644
--- a/dev/tests/integration/testsuite/Mage/Install/Model/Installer/ConfigTest.php
+++ b/dev/tests/integration/testsuite/Mage/Install/Model/Installer/ConfigTest.php
@@ -47,11 +47,15 @@ class Mage_Install_Model_Installer_ConfigTest extends PHPUnit_Framework_TestCase
         $config = $this->getMock('Mage_Core_Model_Config', array('getDistroBaseUrl'), array(), '', false);
         $config->expects($this->once())->method('getDistroBaseUrl')->will($this->returnValue('http://example.com/'));
         $expectedContents = "test; <![CDATA[d-d-d-d-d]]>; <![CDATA[http://example.com/]]>; {{unknown}}";
-        $dirs = new Mage_Core_Model_Dir(self::$_tmpDir, array(), array(Mage_Core_Model_Dir::CONFIG => self::$_tmpDir));
+        $dirs = new Mage_Core_Model_Dir(
+            self::$_tmpDir, new Varien_Io_File(), array(), array(Mage_Core_Model_Dir::CONFIG => self::$_tmpDir)
+        );
 
         $this->assertFileNotExists($expectedFile);
         $filesystem = new Magento_Filesystem(new Magento_Filesystem_Adapter_Local);
-        $model = new Mage_Install_Model_Installer_Config($config, $dirs, $filesystem);
+        $model = Mage::getModel('Mage_Install_Model_Installer_Config', array(
+            'config' => $config, 'dirs' => $dirs, 'filesystem' => $filesystem
+        ));
         $model->install();
         $this->assertFileExists($expectedFile);
         $this->assertStringEqualsFile($expectedFile, $expectedContents);
diff --git a/dev/tests/integration/testsuite/Mage/Install/Model/InstallerTest.php b/dev/tests/integration/testsuite/Mage/Install/Model/InstallerTest.php
index 4411afe3658102f3da3a2e4e2ff457caa1bdec11..0e98405a5cd4e1735190568928f6e6ae1cd241f4 100644
--- a/dev/tests/integration/testsuite/Mage/Install/Model/InstallerTest.php
+++ b/dev/tests/integration/testsuite/Mage/Install/Model/InstallerTest.php
@@ -56,7 +56,7 @@ class Mage_Install_Model_InstallerTest extends PHPUnit_Framework_TestCase
 
     protected function setUp()
     {
-        $this->_model = new Mage_Install_Model_Installer();
+        $this->_model = Mage::getModel('Mage_Install_Model_Installer');
     }
 
     protected function tearDown()
@@ -75,7 +75,8 @@ class Mage_Install_Model_InstallerTest extends PHPUnit_Framework_TestCase
         $objectManager = Mage::getObjectManager();
         $installerConfig = new Mage_Install_Model_Installer_Config(
             $objectManager->get('Mage_Core_Model_Config'),
-            new Mage_Core_Model_Dir(__DIR__, array(), array(Mage_Core_Model_Dir::CONFIG => $dir)),
+            new Mage_Core_Model_Dir(__DIR__, new Varien_Io_File(), array(), array(Mage_Core_Model_Dir::CONFIG => $dir)),
+            $objectManager->get('Mage_Core_Model_Config_Resource'),
             new Magento_Filesystem(new Magento_Filesystem_Adapter_Local())
         );
         $objectManager->addSharedInstance($installerConfig, 'Mage_Install_Model_Installer_Config');
diff --git a/dev/tests/integration/testsuite/Mage/Install/controllers/WizardControllerTest.php b/dev/tests/integration/testsuite/Mage/Install/controllers/WizardControllerTest.php
index bc7771d6842e53abb79b96b4199ddbbc2c494bb0..7e0a5dd9fcda96dc5e003174d7bc176c9aace9f2 100644
--- a/dev/tests/integration/testsuite/Mage/Install/controllers/WizardControllerTest.php
+++ b/dev/tests/integration/testsuite/Mage/Install/controllers/WizardControllerTest.php
@@ -46,10 +46,12 @@ class Mage_Install_WizardControllerTest extends Magento_Test_TestCase_Controller
 
     public function setUp()
     {
-        parent::setUp();
         // emulate non-installed application
-        $this->_runOptions[Mage_Core_Model_Config::INIT_OPTION_EXTRA_DATA]
-            = sprintf(Mage_Core_Model_Config::CONFIG_TEMPLATE_INSTALL_DATE, 'invalid');
+        Magento_Test_Helper_Bootstrap::getInstance()->reinitialize(array(
+            Mage::PARAM_CUSTOM_LOCAL_CONFIG
+                => sprintf(Mage_Core_Model_Config_Primary::CONFIG_TEMPLATE_INSTALL_DATE, 'invalid')
+        ));
+        parent::setUp();
     }
 
     public function tearDown()
diff --git a/dev/tests/integration/testsuite/Mage/Sitemap/Helper/DataTest.php b/dev/tests/integration/testsuite/Mage/Sitemap/Helper/DataTest.php
index 61b6047a215f93570d30d8ef2d47203dae9726ee..b96f4301f7f53971d9ad6b5ed49a9a2396d7e6b3 100644
--- a/dev/tests/integration/testsuite/Mage/Sitemap/Helper/DataTest.php
+++ b/dev/tests/integration/testsuite/Mage/Sitemap/Helper/DataTest.php
@@ -47,8 +47,8 @@ class Mage_Sitemap_Helper_DataTest extends PHPUnit_Framework_TestCase
      */
     public function testGetMaximumLinesNumber()
     {
-        $this->assertEquals(50000, $this->_helper->getMaximumLinesNumber(Mage_Core_Model_App::ADMIN_STORE_ID));
-        $this->assertEquals(10, $this->_helper->getMaximumLinesNumber(Mage_Core_Model_App::DISTRO_STORE_ID));
+        $this->assertEquals(50000, $this->_helper->getMaximumLinesNumber(Mage_Core_Model_AppInterface::ADMIN_STORE_ID));
+        $this->assertEquals(10, $this->_helper->getMaximumLinesNumber(Mage_Core_Model_AppInterface::DISTRO_STORE_ID));
     }
 
     /**
@@ -56,8 +56,10 @@ class Mage_Sitemap_Helper_DataTest extends PHPUnit_Framework_TestCase
      */
     public function testGetMaximumFileSize()
     {
-        $this->assertEquals(10485760, $this->_helper->getMaximumFileSize(Mage_Core_Model_App::ADMIN_STORE_ID));
-        $this->assertEquals(1024, $this->_helper->getMaximumFileSize(Mage_Core_Model_App::DISTRO_STORE_ID));
+        $this->assertEquals(
+            10485760, $this->_helper->getMaximumFileSize(Mage_Core_Model_AppInterface::ADMIN_STORE_ID)
+        );
+        $this->assertEquals(1024, $this->_helper->getMaximumFileSize(Mage_Core_Model_AppInterface::DISTRO_STORE_ID));
     }
 
     /**
@@ -65,8 +67,12 @@ class Mage_Sitemap_Helper_DataTest extends PHPUnit_Framework_TestCase
      */
     public function testGetCategoryChangefreq()
     {
-        $this->assertEquals('daily', $this->_helper->getCategoryChangefreq(Mage_Core_Model_App::ADMIN_STORE_ID));
-        $this->assertEquals('montly', $this->_helper->getCategoryChangefreq(Mage_Core_Model_App::DISTRO_STORE_ID));
+        $this->assertEquals(
+            'daily', $this->_helper->getCategoryChangefreq(Mage_Core_Model_AppInterface::ADMIN_STORE_ID)
+        );
+        $this->assertEquals(
+            'montly', $this->_helper->getCategoryChangefreq(Mage_Core_Model_AppInterface::DISTRO_STORE_ID)
+        );
     }
 
     /**
@@ -74,8 +80,12 @@ class Mage_Sitemap_Helper_DataTest extends PHPUnit_Framework_TestCase
      */
     public function testGetProductChangefreq()
     {
-        $this->assertEquals('daily', $this->_helper->getProductChangefreq(Mage_Core_Model_App::ADMIN_STORE_ID));
-        $this->assertEquals('montly', $this->_helper->getProductChangefreq(Mage_Core_Model_App::DISTRO_STORE_ID));
+        $this->assertEquals(
+            'daily', $this->_helper->getProductChangefreq(Mage_Core_Model_AppInterface::ADMIN_STORE_ID)
+        );
+        $this->assertEquals(
+            'montly', $this->_helper->getProductChangefreq(Mage_Core_Model_AppInterface::DISTRO_STORE_ID)
+        );
     }
 
     /**
@@ -83,8 +93,8 @@ class Mage_Sitemap_Helper_DataTest extends PHPUnit_Framework_TestCase
      */
     public function testGetPageChangefreq()
     {
-        $this->assertEquals('daily', $this->_helper->getPageChangefreq(Mage_Core_Model_App::ADMIN_STORE_ID));
-        $this->assertEquals('montly', $this->_helper->getPageChangefreq(Mage_Core_Model_App::DISTRO_STORE_ID));
+        $this->assertEquals('daily', $this->_helper->getPageChangefreq(Mage_Core_Model_AppInterface::ADMIN_STORE_ID));
+        $this->assertEquals('montly', $this->_helper->getPageChangefreq(Mage_Core_Model_AppInterface::DISTRO_STORE_ID));
     }
 
     /**
@@ -92,8 +102,8 @@ class Mage_Sitemap_Helper_DataTest extends PHPUnit_Framework_TestCase
      */
     public function testGetCategoryPriority()
     {
-        $this->assertEquals(0.5, $this->_helper->getCategoryPriority(Mage_Core_Model_App::ADMIN_STORE_ID));
-        $this->assertEquals(100, $this->_helper->getCategoryPriority(Mage_Core_Model_App::DISTRO_STORE_ID));
+        $this->assertEquals(0.5, $this->_helper->getCategoryPriority(Mage_Core_Model_AppInterface::ADMIN_STORE_ID));
+        $this->assertEquals(100, $this->_helper->getCategoryPriority(Mage_Core_Model_AppInterface::DISTRO_STORE_ID));
     }
 
     /**
@@ -101,8 +111,8 @@ class Mage_Sitemap_Helper_DataTest extends PHPUnit_Framework_TestCase
      */
     public function testGetProductPriority()
     {
-        $this->assertEquals(1, $this->_helper->getProductPriority(Mage_Core_Model_App::ADMIN_STORE_ID));
-        $this->assertEquals(100, $this->_helper->getProductPriority(Mage_Core_Model_App::DISTRO_STORE_ID));
+        $this->assertEquals(1, $this->_helper->getProductPriority(Mage_Core_Model_AppInterface::ADMIN_STORE_ID));
+        $this->assertEquals(100, $this->_helper->getProductPriority(Mage_Core_Model_AppInterface::DISTRO_STORE_ID));
     }
 
     /**
@@ -110,8 +120,8 @@ class Mage_Sitemap_Helper_DataTest extends PHPUnit_Framework_TestCase
      */
     public function testGetPagePriority()
     {
-        $this->assertEquals(0.25, $this->_helper->getPagePriority(Mage_Core_Model_App::ADMIN_STORE_ID));
-        $this->assertEquals(100, $this->_helper->getPagePriority(Mage_Core_Model_App::DISTRO_STORE_ID));
+        $this->assertEquals(0.25, $this->_helper->getPagePriority(Mage_Core_Model_AppInterface::ADMIN_STORE_ID));
+        $this->assertEquals(100, $this->_helper->getPagePriority(Mage_Core_Model_AppInterface::DISTRO_STORE_ID));
     }
 
     /**
@@ -119,8 +129,10 @@ class Mage_Sitemap_Helper_DataTest extends PHPUnit_Framework_TestCase
      */
     public function testGetEnableSubmissionRobots()
     {
-        $this->assertEquals(0, $this->_helper->getEnableSubmissionRobots(Mage_Core_Model_App::ADMIN_STORE_ID));
-        $this->assertEquals(1, $this->_helper->getEnableSubmissionRobots(Mage_Core_Model_App::DISTRO_STORE_ID));
+        $this->assertEquals(0, $this->_helper->getEnableSubmissionRobots(Mage_Core_Model_AppInterface::ADMIN_STORE_ID));
+        $this->assertEquals(
+            1, $this->_helper->getEnableSubmissionRobots(Mage_Core_Model_AppInterface::DISTRO_STORE_ID)
+        );
     }
 
     /**
@@ -128,7 +140,11 @@ class Mage_Sitemap_Helper_DataTest extends PHPUnit_Framework_TestCase
      */
     public function testGetProductImageIncludePolicy()
     {
-        $this->assertEquals('all', $this->_helper->getProductImageIncludePolicy(Mage_Core_Model_App::ADMIN_STORE_ID));
-        $this->assertEquals('base', $this->_helper->getProductImageIncludePolicy(Mage_Core_Model_App::DISTRO_STORE_ID));
+        $this->assertEquals(
+            'all', $this->_helper->getProductImageIncludePolicy(Mage_Core_Model_AppInterface::ADMIN_STORE_ID)
+        );
+        $this->assertEquals(
+            'base', $this->_helper->getProductImageIncludePolicy(Mage_Core_Model_AppInterface::DISTRO_STORE_ID)
+        );
     }
 }
diff --git a/dev/tests/integration/testsuite/Mage/Sitemap/Model/Resource/Catalog/ProductTest.php b/dev/tests/integration/testsuite/Mage/Sitemap/Model/Resource/Catalog/ProductTest.php
index efac2a414ea5f323f417e53acfdf39ffba57ed51..9959452dd742c979426f7e2e5e55858ccecc8879 100644
--- a/dev/tests/integration/testsuite/Mage/Sitemap/Model/Resource/Catalog/ProductTest.php
+++ b/dev/tests/integration/testsuite/Mage/Sitemap/Model/Resource/Catalog/ProductTest.php
@@ -43,7 +43,7 @@ class Mage_Sitemap_Model_Resource_Catalog_ProductTest extends PHPUnit_Framework_
     public function testGetCollectionNone()
     {
         $model = Mage::getResourceModel('Mage_Sitemap_Model_Resource_Catalog_Product');
-        $products = $model->getCollection(Mage_Core_Model_App::DISTRO_STORE_ID);
+        $products = $model->getCollection(Mage_Core_Model_AppInterface::DISTRO_STORE_ID);
 
         $this->_checkProductCollection($products, 3, array(1, 4, 5));
 
@@ -68,7 +68,7 @@ class Mage_Sitemap_Model_Resource_Catalog_ProductTest extends PHPUnit_Framework_
     public function testGetCollectionAll()
     {
         $model = Mage::getResourceModel('Mage_Sitemap_Model_Resource_Catalog_Product');
-        $products = $model->getCollection(Mage_Core_Model_App::DISTRO_STORE_ID);
+        $products = $model->getCollection(Mage_Core_Model_AppInterface::DISTRO_STORE_ID);
 
         $this->_checkProductCollection($products, 3, array(1, 4, 5));
 
@@ -119,7 +119,7 @@ class Mage_Sitemap_Model_Resource_Catalog_ProductTest extends PHPUnit_Framework_
     public function testGetCollectionBase()
     {
         $model = Mage::getResourceModel('Mage_Sitemap_Model_Resource_Catalog_Product');
-        $products = $model->getCollection(Mage_Core_Model_App::DISTRO_STORE_ID);
+        $products = $model->getCollection(Mage_Core_Model_AppInterface::DISTRO_STORE_ID);
 
         $this->_checkProductCollection($products, 3, array(1, 4, 5));
 
diff --git a/dev/tests/integration/testsuite/Mage/Tag/Model/TagTest.php b/dev/tests/integration/testsuite/Mage/Tag/Model/TagTest.php
index d8a0229a269ab492b7a12ee9e3a5f98c0bfa83d2..e0381196c8ac52943bacc177717c8406b833b872 100644
--- a/dev/tests/integration/testsuite/Mage/Tag/Model/TagTest.php
+++ b/dev/tests/integration/testsuite/Mage/Tag/Model/TagTest.php
@@ -47,7 +47,7 @@ class Mage_Tag_Model_TagTest extends PHPUnit_Framework_TestCase
      */
     public function testCRUD()
     {
-        Mage::app()->setCurrentStore(Mage::app()->getStore(Mage_Core_Model_App::ADMIN_STORE_ID));
+        Mage::app()->setCurrentStore(Mage::app()->getStore(Mage_Core_Model_AppInterface::ADMIN_STORE_ID));
         $this->_model->setName('test');
         $crud = new Magento_Test_Entity($this->_model, array('name' => uniqid()));
         $crud->testCrud();
diff --git a/dev/tests/integration/testsuite/Mage/Tax/Helper/DataTest.php b/dev/tests/integration/testsuite/Mage/Tax/Helper/DataTest.php
index eb608428d02449c1e489f71bcfc0bc6d21c72349..39149b70ea7c14eda084c954d1d68be9b021b5d6 100644
--- a/dev/tests/integration/testsuite/Mage/Tax/Helper/DataTest.php
+++ b/dev/tests/integration/testsuite/Mage/Tax/Helper/DataTest.php
@@ -32,7 +32,8 @@ class Mage_Tax_Helper_DataTest extends PHPUnit_Framework_TestCase
      */
     public function testGetDefaultCustomerTaxClass()
     {
-        $helper = new Mage_Tax_Helper_Data();
+        /** @var $helper Mage_Tax_Helper_Data */
+        $helper = Mage::helper('Mage_Tax_Helper_Data');
         $this->assertEquals(1, $helper->getDefaultCustomerTaxClass());
     }
 
@@ -41,8 +42,9 @@ class Mage_Tax_Helper_DataTest extends PHPUnit_Framework_TestCase
      */
     public function testGetDefaultProductTaxClass()
     {
-        $helper = new Mage_Tax_Helper_Data();
+        /** @var $helper Mage_Tax_Helper_Data */
+        $helper = Mage::helper('Mage_Tax_Helper_Data');
         $this->assertEquals(1, $helper->getDefaultProductTaxClass());
     }
 
-}
\ No newline at end of file
+}
diff --git a/dev/tests/integration/testsuite/Mage/Theme/Model/Wysiwyg/StorageTest.php b/dev/tests/integration/testsuite/Mage/Theme/Model/Wysiwyg/StorageTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..b6bb92cd13e062e6478188c76352e36c7a205630
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Theme/Model/Wysiwyg/StorageTest.php
@@ -0,0 +1,132 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_Theme
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Storage model test
+ */
+class Mage_Theme_Model_Wysiwyg_StorageTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Controller_Request_Http|PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_request;
+
+    /**
+     * @var Magento_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * @var Mage_Theme_Helper_Storage
+     */
+    protected $_helperStorage;
+
+    /**
+     * @var Magento_Filesystem
+     */
+    protected $_filesystem;
+
+    /**
+     * @var Mage_Theme_Model_Wysiwyg_Storage
+     */
+    protected $_storageModel;
+
+    public function setUp()
+    {
+        $this->_objectManager = Mage::getObjectManager();
+        $this->_filesystem = $this->_objectManager->get('Magento_Filesystem');
+        $this->_filesystem->setIsAllowCreateDirectories(true);
+
+        /** @var $theme Mage_Core_Model_Theme */
+        $theme = $this->_objectManager->create('Mage_Core_Model_Theme')->getCollection()->getFirstItem();
+
+        /** @var $request Mage_Core_Controller_Request_Http */
+        $request = $this->_objectManager->get('Mage_Core_Controller_Request_Http');
+        $request->setParam(Mage_Theme_Helper_Storage::PARAM_THEME_ID, $theme->getId());
+        $request->setParam(Mage_Theme_Helper_Storage::PARAM_CONTENT_TYPE, Mage_Theme_Model_Wysiwyg_Storage::TYPE_IMAGE);
+
+        $this->_helperStorage = $this->_objectManager->get('Mage_Theme_Helper_Storage');
+
+        $this->_storageModel = $this->_objectManager->create('Mage_Theme_Model_Wysiwyg_Storage', array(
+            'helper' => $this->_helperStorage
+        ));
+    }
+
+    public function tearDown()
+    {
+        $this->_filesystem->delete($this->_helperStorage->getStorageRoot());
+    }
+
+    /**
+     * @covers Mage_Theme_Model_Wysiwyg_Storage::_createThumbnail
+     */
+    public function testCreateThumbnail()
+    {
+        $image = 'some_image.jpg';
+        $imagePath = $this->_filesystem->getAbsolutePath(
+            implode(DIRECTORY_SEPARATOR, array(realpath(__DIR__), '_files', 'theme' , 'image', $image))
+        );
+        $tmpImagePath = $this->_copyFileToTmpCustomizationPath($imagePath);
+
+        $method = $this->_getMethod('_createThumbnail');
+        $result = $method->invokeArgs($this->_storageModel, array($tmpImagePath));
+
+        $expectedResult = $this->_helperStorage->getThumbnailDirectory($tmpImagePath)
+            . Magento_Filesystem::DIRECTORY_SEPARATOR . $image;
+
+        $this->assertEquals($expectedResult, $result);
+        $this->assertFileExists($result);
+    }
+
+    /**
+     * @param string $name
+     * @return ReflectionMethod
+     */
+    protected function _getMethod($name)
+    {
+        $class = new ReflectionClass('Mage_Theme_Model_Wysiwyg_Storage');
+        $method = $class->getMethod($name);
+        $method->setAccessible(true);
+        return $method;
+    }
+
+    /**
+     * Copy file to tmp theme customization path
+     *
+     * @param string $sourceFile
+     * @return string
+     */
+    protected function _copyFileToTmpCustomizationPath($sourceFile)
+    {
+        $targetFile = $this->_helperStorage->getStorageRoot()
+            . Magento_Filesystem::DIRECTORY_SEPARATOR
+            . basename($sourceFile);
+
+        $this->_filesystem->ensureDirectoryExists(pathinfo($targetFile, PATHINFO_DIRNAME));
+        $this->_filesystem->copy($sourceFile, $targetFile);
+        return $targetFile;
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Theme/Model/Wysiwyg/_files/theme/image/some_image.jpg b/dev/tests/integration/testsuite/Mage/Theme/Model/Wysiwyg/_files/theme/image/some_image.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..8cf9655aa2dbe11ea02fed51e6e802910657d746
Binary files /dev/null and b/dev/tests/integration/testsuite/Mage/Theme/Model/Wysiwyg/_files/theme/image/some_image.jpg differ
diff --git a/dev/tests/integration/testsuite/Mage/Webapi/Helper/ConfigTest.php b/dev/tests/integration/testsuite/Mage/Webapi/Helper/ConfigTest.php
index 049cb051766e816358bd539cdeb9e8ddb2d8d733..0f3a28664432bf299b38936c81d14c7390288c21 100644
--- a/dev/tests/integration/testsuite/Mage/Webapi/Helper/ConfigTest.php
+++ b/dev/tests/integration/testsuite/Mage/Webapi/Helper/ConfigTest.php
@@ -38,7 +38,7 @@ class Mage_Webapi_Helper_ConfigTest extends PHPUnit_Framework_TestCase
      */
     protected function setUp()
     {
-        $objectManager = new Magento_Test_ObjectManager();
+        $objectManager = Mage::getObjectManager();
         $this->_helper = $objectManager->get('Mage_Webapi_Helper_Config');
         parent::setUp();
     }
diff --git a/dev/tests/integration/testsuite/Mage/Webapi/Helper/DataTest.php b/dev/tests/integration/testsuite/Mage/Webapi/Helper/DataTest.php
index 6def23b3b88cf3bb5aa70803731cbd9f53c56c8a..f8e6b43ac7dab21a9427d9764a96a86497e205ea 100644
--- a/dev/tests/integration/testsuite/Mage/Webapi/Helper/DataTest.php
+++ b/dev/tests/integration/testsuite/Mage/Webapi/Helper/DataTest.php
@@ -56,7 +56,7 @@ class Mage_Webapi_Helper_DataTest extends PHPUnit_Framework_TestCase
     protected function _getApiConfig()
     {
         if (!self::$_apiConfig) {
-            $objectManager = new Magento_Test_ObjectManager();
+            $objectManager = Mage::getObjectManager();
             /** Prepare arguments for SUT constructor. */
             $pathToFixtures = __DIR__ . '/../_files/autodiscovery';
             /** @var Mage_Webapi_Model_Config_Reader_Soap $reader */
diff --git a/dev/tests/integration/testsuite/Mage/Webapi/Model/Config/Reader/Rest/RouteGeneratorTest.php b/dev/tests/integration/testsuite/Mage/Webapi/Model/Config/Reader/Rest/RouteGeneratorTest.php
index 5f88e81087a91bd7b60004dce3ffce4a47fe9c5e..7a40b108e9abe9962bb3ca3932cd97a4d5f3320f 100644
--- a/dev/tests/integration/testsuite/Mage/Webapi/Model/Config/Reader/Rest/RouteGeneratorTest.php
+++ b/dev/tests/integration/testsuite/Mage/Webapi/Model/Config/Reader/Rest/RouteGeneratorTest.php
@@ -43,7 +43,11 @@ class Mage_Webapi_Model_Config_Reader_Rest_RouteGeneratorTest extends PHPUnit_Fr
 
     protected function setUp()
     {
-        $helper = $this->getMock('Mage_Webapi_Helper_Config', array('__'));
+        $helper = $this->getMock(
+            'Mage_Webapi_Helper_Config',
+            array('__'),
+            array(Mage::getObjectManager()->get('Mage_Core_Model_Translate'))
+        );
         $this->_model = new Mage_Webapi_Model_Config_Reader_Rest_RouteGenerator($helper);
     }
 
diff --git a/dev/tests/integration/testsuite/Mage/Webapi/Model/Config/RestTest.php b/dev/tests/integration/testsuite/Mage/Webapi/Model/Config/RestTest.php
index 473e39df3923932e113eed560e7855ebb1c2f621..11fef66ce4fb4714195ee38277c4495eee0e4b9e 100644
--- a/dev/tests/integration/testsuite/Mage/Webapi/Model/Config/RestTest.php
+++ b/dev/tests/integration/testsuite/Mage/Webapi/Model/Config/RestTest.php
@@ -167,7 +167,7 @@ class Mage_Webapi_Model_Config_RestTest extends PHPUnit_Framework_TestCase
      */
     protected function _createResourceConfig($pathToResources)
     {
-        $objectManager = new Magento_Test_ObjectManager();
+        $objectManager = Mage::getObjectManager();
         /** Prepare arguments for SUT constructor. */
         /** @var Mage_Core_Model_Cache $cache */
         $cache = $this->getMockBuilder('Mage_Core_Model_Cache')->disableOriginalConstructor()->getMock();
diff --git a/dev/tests/integration/testsuite/Mage/Webapi/Model/Config/Soap/DataTest.php b/dev/tests/integration/testsuite/Mage/Webapi/Model/Config/Soap/DataTest.php
index b6c65bcf2e0366333ac97a8e89002f9ef6cdbf69..dde8592d4ef5bdbb7b5ea611d08f3db5fc1a40f9 100644
--- a/dev/tests/integration/testsuite/Mage/Webapi/Model/Config/Soap/DataTest.php
+++ b/dev/tests/integration/testsuite/Mage/Webapi/Model/Config/Soap/DataTest.php
@@ -55,7 +55,7 @@ class Mage_Webapi_Model_Config_Soap_DataTest extends PHPUnit_Framework_TestCase
         /** @var Mage_Core_Model_App $app */
         $app = $this->getMockBuilder('Mage_Core_Model_App')->disableOriginalConstructor()->getMock();
         $appConfig = Mage::app()->getConfig();
-        $objectManager = new Magento_Test_ObjectManager();
+        $objectManager = Mage::getObjectManager();
         /** @var Mage_Webapi_Helper_Config $helper */
         $helper = $objectManager->get('Mage_Webapi_Helper_Config');
         /** @var Mage_Webapi_Model_Config_Reader_Soap_ClassReflector $classReflector */
diff --git a/dev/tests/integration/testsuite/Mage/Webapi/Model/Config/SoapTest.php b/dev/tests/integration/testsuite/Mage/Webapi/Model/Config/SoapTest.php
index a53f1e51f91a9135321225288372a8a2eec22461..f5dfec47c84640f024b467ce1a6c351e1795803b 100644
--- a/dev/tests/integration/testsuite/Mage/Webapi/Model/Config/SoapTest.php
+++ b/dev/tests/integration/testsuite/Mage/Webapi/Model/Config/SoapTest.php
@@ -548,7 +548,7 @@ class Mage_Webapi_Model_Config_SoapTest extends PHPUnit_Framework_TestCase
      */
     protected function _createResourceConfig($pathToResources)
     {
-        $objectManager = new Magento_Test_ObjectManager();
+        $objectManager = Mage::getObjectManager();
         /** Prepare arguments for SUT constructor. */
         /** @var Mage_Core_Model_Cache $cache */
         $cache = $this->getMockBuilder('Mage_Core_Model_Cache')->disableOriginalConstructor()->getMock();
diff --git a/dev/tests/integration/testsuite/Mage/Webapi/Model/Soap/AutoDiscoverTest.php b/dev/tests/integration/testsuite/Mage/Webapi/Model/Soap/AutoDiscoverTest.php
index 032f01ae7fc659922dc10d65a0a12d189121bf67..f5c96eb0a5b2110d6613ede1c74a1855d0ec8636 100644
--- a/dev/tests/integration/testsuite/Mage/Webapi/Model/Soap/AutoDiscoverTest.php
+++ b/dev/tests/integration/testsuite/Mage/Webapi/Model/Soap/AutoDiscoverTest.php
@@ -85,7 +85,7 @@ class Mage_Webapi_Model_Soap_AutoDiscoverTest extends PHPUnit_Framework_TestCase
         $directoryScanner = new \Zend\Code\Scanner\DirectoryScanner($fixtureDir);
         /** @var Mage_Core_Model_App $app */
         $app = $this->getMockBuilder('Mage_Core_Model_App')->disableOriginalConstructor()->getMock();
-        $objectManager = new Magento_Test_ObjectManager();
+        $objectManager = Mage::getObjectManager();
         $this->_helper = $objectManager->get('Mage_Webapi_Helper_Config');
         $reader = $objectManager->get(
             'Mage_Webapi_Model_Config_Reader_Soap',
@@ -117,6 +117,18 @@ class Mage_Webapi_Model_Soap_AutoDiscoverTest extends PHPUnit_Framework_TestCase
         parent::setUp();
     }
 
+    protected function tearDown()
+    {
+        $this->_config = null;
+        $this->_autoDiscover = null;
+        $this->_helper = null;
+        $this->_resourceName = null;
+        $this->_resourceData = null;
+        $this->_dom = null;
+        $this->_xpath = null;
+    }
+
+
     /**
      * Test WSDL operations Generation.
      * Generate WSDL XML using AutoDiscover and prepared config.
@@ -124,6 +136,8 @@ class Mage_Webapi_Model_Soap_AutoDiscoverTest extends PHPUnit_Framework_TestCase
      * Assert that service, portType and binding have been generated correctly for resource.
      * Assert that each method from controller has generated operations in portType and binding nodes.
      * Assert that each method has input and output messages and complexTypes generated correctly.
+     *
+     * @magentoAppIsolation enabled
      */
     public function testGenerateOperations()
     {
@@ -182,6 +196,8 @@ class Mage_Webapi_Model_Soap_AutoDiscoverTest extends PHPUnit_Framework_TestCase
     /**
      * Test that complexType for Data structures has been generated correctly in WSDL.
      * See /_files/controllers/AutoDiscover/ModuleB/SubresourceData.php
+     *
+     * @magentoAppIsolation enabled
      */
     public function testGenerateDataStructureComplexTypes()
     {
diff --git a/dev/tests/integration/testsuite/Mage/Webapi/Model/Soap/Security/UsernameTokenTest.php b/dev/tests/integration/testsuite/Mage/Webapi/Model/Soap/Security/UsernameTokenTest.php
index 112cfe7bb6e209713283cb6d299c74a92099cc9e..4a213b5c279412d1662baec90dd6e2eb2b1bec9c 100644
--- a/dev/tests/integration/testsuite/Mage/Webapi/Model/Soap/Security/UsernameTokenTest.php
+++ b/dev/tests/integration/testsuite/Mage/Webapi/Model/Soap/Security/UsernameTokenTest.php
@@ -43,7 +43,7 @@ class Mage_Webapi_Model_Soap_Security_UsernameTokenTest extends PHPUnit_Framewor
      */
     protected function setUp()
     {
-        $this->_objectManager = new Magento_Test_ObjectManager();
+        $this->_objectManager = Mage::getObjectManager();
         $this->_objectManager->addSharedInstance(
             Mage::getObjectManager()->get('Mage_Core_Model_Dir'),
             'Mage_Core_Model_Dir'
diff --git a/dev/tests/integration/testsuite/Mage/Widget/Model/WidgetTest.php b/dev/tests/integration/testsuite/Mage/Widget/Model/WidgetTest.php
index e505da62dc03d85851bfc2925bb203a2f928252d..d0251795f31b0f77e55e440f645100ef2cb63b86 100644
--- a/dev/tests/integration/testsuite/Mage/Widget/Model/WidgetTest.php
+++ b/dev/tests/integration/testsuite/Mage/Widget/Model/WidgetTest.php
@@ -103,7 +103,7 @@ class Mage_Widget_Model_WidgetTest extends PHPUnit_Framework_TestCase
     public function testGetPlaceholderImageUrlAtTheme()
     {
         Magento_Test_Helper_Bootstrap::getInstance()->reinitialize(array(
-            Mage_Core_Model_App::INIT_OPTION_DIRS => array(
+            Mage::PARAM_APP_DIRS => array(
                 Mage_Core_Model_Dir::THEMES => dirname(__DIR__) . '/_files/design'
             )
         ));
diff --git a/dev/tests/integration/testsuite/Mage/Widget/_files/themes.php b/dev/tests/integration/testsuite/Mage/Widget/_files/themes.php
index 947fbd4ff83f9966271af3070eb7b194f90baf3d..e60083986c03286a1989b1f4229ed34df61a14e9 100644
--- a/dev/tests/integration/testsuite/Mage/Widget/_files/themes.php
+++ b/dev/tests/integration/testsuite/Mage/Widget/_files/themes.php
@@ -24,7 +24,7 @@
  * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
-
+Mage::app()->loadAreaPart(Mage_Core_Model_App_Area::AREA_ADMINHTML, Mage_Core_Model_App_Area::PART_CONFIG);
 /** @var $registration Mage_Core_Model_Theme_Registration */
 $registration = Mage::getModel('Mage_Core_Model_Theme_Registration');
 $registration->register(
diff --git a/dev/tests/integration/testsuite/MageTest.php b/dev/tests/integration/testsuite/MageTest.php
index 67bc97a728bb8e5eeab85291f94fcaad22c9d7d5..c1540fb3cdb8e3ef3bf558f544ddd0432e9a552d 100644
--- a/dev/tests/integration/testsuite/MageTest.php
+++ b/dev/tests/integration/testsuite/MageTest.php
@@ -45,22 +45,19 @@ class MageTest extends PHPUnit_Framework_TestCase
     public function testLog($level, $file, $forceLog, $expectedLevel, $expectedKey, $expectsAddLog)
     {
         $message = uniqid();
-        $objectManager = Mage::getObjectManager();
-        /** @var $objectManager Magento_ObjectManager_Zend|PHPUnit_Framework_MockObject_MockObject */
-        $mock = $this->getMock('Magento_ObjectManager_Zend', array('get'), array(), '', false);
         /** @var $logger Mage_Core_Model_Logger|PHPUnit_Framework_MockObject_MockObject */
         $logger = $this->getMock('Mage_Core_Model_Logger', array('log', 'addStreamLog'), array(), '', false);
-        Mage::initializeObjectManager(null, $mock);
+        $realLogger = Mage::getObjectManager()->get('Mage_Core_Model_Logger');
+        Mage::getObjectManager()->addSharedInstance($logger, 'Mage_Core_Model_Logger');
         try {
-            $mock->expects($this->any())->method('get')->will($this->returnValue($logger));
             $logger->expects($this->once())->method('log')->with($message, $expectedLevel, $expectedKey);
             if ($expectsAddLog) {
                 $logger->expects($this->once())->method('addStreamLog');
             }
             Mage::log($message, $level, $file, $forceLog);
-            Mage::initializeObjectManager(null, $objectManager);
+            Mage::getObjectManager()->addSharedInstance($realLogger, 'Mage_Core_Model_Logger');
         } catch (Exception $e) {
-            Mage::initializeObjectManager(null, $objectManager);
+            Mage::getObjectManager()->addSharedInstance($realLogger, 'Mage_Core_Model_Logger');
             throw $e;
         }
 
@@ -90,6 +87,7 @@ class MageTest extends PHPUnit_Framework_TestCase
         // @magentoConfigFixture is applied after initialization, so we need to do this again
         Magento_Test_Helper_Bootstrap::getInstance()->reinitialize();
         $this->expectOutputRegex('/test/');
+        Mage::app()->getStore(true);
         Mage::log('test');
     }
 
@@ -127,6 +125,7 @@ class MageTest extends PHPUnit_Framework_TestCase
     {
         // reinitialization is needed here, too
         Magento_Test_Helper_Bootstrap::getInstance()->reinitialize();
+        Mage::app()->getStore(true);
         $msg = uniqid();
         $exception = new Exception((string)$msg);
         Mage::logException($exception);
diff --git a/dev/tests/integration/testsuite/integrity/Mage/Payment/MethodsTest.php b/dev/tests/integration/testsuite/integrity/Mage/Payment/MethodsTest.php
index efec01268b98de69225a5f487b742cbe9e2c3ee8..a4763ef30b7363d2de767d0e2c77866b793c9232 100644
--- a/dev/tests/integration/testsuite/integrity/Mage/Payment/MethodsTest.php
+++ b/dev/tests/integration/testsuite/integrity/Mage/Payment/MethodsTest.php
@@ -58,7 +58,7 @@ class Integrity_Mage_Payment_MethodsTest extends PHPUnit_Framework_TestCase
             $this->assertFileExists($block->getTemplateFile(), $message);
             if ($model->canUseInternal()) {
                 try {
-                    Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
+                    Mage::app()->getStore()->setId(Mage_Core_Model_AppInterface::ADMIN_STORE_ID);
                     $block->setArea('adminhtml');
                     $this->assertFileExists($block->getTemplateFile(), $message);
                     Mage::app()->getStore()->setId($storeId);
diff --git a/dev/tests/integration/testsuite/integrity/Mage/Widget/TemplateFilesTest.php b/dev/tests/integration/testsuite/integrity/Mage/Widget/TemplateFilesTest.php
index 94c14dc92f5df07401c5ccbc0f152a5f99b03707..cc144b420f0611c8171fcb73f90566d3b5df4563 100644
--- a/dev/tests/integration/testsuite/integrity/Mage/Widget/TemplateFilesTest.php
+++ b/dev/tests/integration/testsuite/integrity/Mage/Widget/TemplateFilesTest.php
@@ -59,7 +59,7 @@ class Integrity_Mage_Widget_TemplateFilesTest extends PHPUnit_Framework_TestCase
             /** @var $instance Mage_Widget_Model_Widget_Instance */
             $instance = Mage::getModel('Mage_Widget_Model_Widget_Instance');
             $config = $instance->setType($row['type'])->getWidgetConfig();
-            $class = Mage::getConfig()->getBlockClassName($row['type']);
+            $class = $row['type'];
             if (is_subclass_of($class, 'Mage_Core_Block_Template')) {
                 $templates = $config->xpath('/widgets/' . $row['code'] . '/parameters/template/values/*/value');
                 foreach ($templates as $template) {
diff --git a/dev/tests/integration/testsuite/integrity/modular/SystemConfigFilesTest.php b/dev/tests/integration/testsuite/integrity/modular/SystemConfigFilesTest.php
index e18a7df392c3c64463f725fdb56dc924d9ea6f11..754543609eb01469146ce9d6fc5bbce828526029 100644
--- a/dev/tests/integration/testsuite/integrity/modular/SystemConfigFilesTest.php
+++ b/dev/tests/integration/testsuite/integrity/modular/SystemConfigFilesTest.php
@@ -29,15 +29,25 @@ class Integrity_Modular_SystemConfigFilesTest extends PHPUnit_Framework_TestCase
 {
     public function testConfiguration()
     {
+        $fileList = glob(Mage::getBaseDir('app') . '/*/*/*/*/etc/adminhtml/system.xml');
         try {
-            $config = Mage::getConfig();
+            $configMock = $this->getMock(
+                'Mage_Core_Model_Config_Modules_Reader', array('getModuleConfigurationFiles', 'getModuleDir'),
+                array(), '', false
+            );
+            $configMock->expects($this->any())
+                ->method('getModuleConfigurationFiles')
+                ->will($this->returnValue($fileList));
+            $configMock->expects($this->any())
+                ->method('getModuleDir')
+                ->will($this->returnValue(Mage::getBaseDir('app') . '/code/core/Mage/Backend/etc'));
             $cacheMock = $this->getMock('Mage_Core_Model_Cache', array(), array(), '', false);
             $cacheMock->expects($this->any())->method('canUse')->will($this->returnValue(false));
             $converter = new Mage_Backend_Model_Config_Structure_Converter(
                 new Mage_Backend_Model_Config_Structure_Mapper_Factory(Mage::getObjectManager())
             );
             new Mage_Backend_Model_Config_Structure_Reader(
-                $config, $cacheMock, $converter, true
+                $cacheMock, $configMock, $converter, true
             );
         } catch (Magento_Exception $exp) {
             $this->fail($exp->getMessage());
diff --git a/dev/tests/integration/testsuite/integrity/modular/TemplateFilesTest.php b/dev/tests/integration/testsuite/integrity/modular/TemplateFilesTest.php
index 8776c14317eda7d85ca0d9a4532b35d42c75d341..54e3ead532e92c0c36f88fc965e3de9ca68e492e 100644
--- a/dev/tests/integration/testsuite/integrity/modular/TemplateFilesTest.php
+++ b/dev/tests/integration/testsuite/integrity/modular/TemplateFilesTest.php
@@ -62,9 +62,6 @@ class Integrity_Modular_TemplateFilesTest extends Magento_Test_TestCase_Integrit
 
             $templates = array();
             foreach (Utility_Classes::collectModuleClasses('Block') as $blockClass => $module) {
-                if ($this->_isClassBroken($blockClass)) {
-                    continue;
-                }
                 if (!in_array($module, $this->_getEnabledModules())) {
                     continue;
                 }
@@ -83,7 +80,10 @@ class Integrity_Modular_TemplateFilesTest extends Magento_Test_TestCase_Integrit
                     $area = 'adminhtml';
                 }
 
-                Mage::getConfig()->setCurrentAreaCode($area);
+            Mage::app()->loadAreaPart(
+                Mage_Core_Model_App_Area::AREA_ADMINHTML, Mage_Core_Model_App_Area::AREA_ADMINHTML
+            );
+            Mage::getConfig()->setCurrentAreaCode($area);
 
                 $block = Mage::getModel($blockClass);
                 $template = $block->getTemplate();
@@ -99,22 +99,6 @@ class Integrity_Modular_TemplateFilesTest extends Magento_Test_TestCase_Integrit
         }
     }
 
-    /**
-     * Temporary stub for classes that trigger errors on attempt to instantiate
-     *
-     * @bug MAGETWO-7377
-     * @param string $class
-     * @return bool
-     */
-    private function _isClassBroken($class)
-    {
-        return in_array($class, array(
-            'Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Content',
-            'Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Tree',
-            'Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Content_Uploader',
-        ));
-    }
-
     /**
      * @param string $blockClass
      * @param string $parentClass
diff --git a/dev/tests/integration/testsuite/integrity/modular/ViewConfigFilesTest.php b/dev/tests/integration/testsuite/integrity/modular/ViewConfigFilesTest.php
index a901f8630b230bc3d4aa0ca7e38c365b8701f99e..692fd6e33a33f426f03368920e7a3668ac39acec 100644
--- a/dev/tests/integration/testsuite/integrity/modular/ViewConfigFilesTest.php
+++ b/dev/tests/integration/testsuite/integrity/modular/ViewConfigFilesTest.php
@@ -48,7 +48,9 @@ class Integrity_Modular_ViewConfigFilesTest extends PHPUnit_Framework_TestCase
     public function viewConfigFileDataProvider()
     {
         $result = array();
-        foreach (Mage::getConfig()->getModuleConfigurationFiles('view.xml') as $file) {
+        $files = Mage::getObjectManager()->get('Mage_Core_Model_Config_Modules_Reader')
+            ->getModuleConfigurationFiles('view.xml');
+        foreach ($files as $file) {
             $result[] = array($file);
         }
         return $result;
diff --git a/dev/tests/integration/testsuite/integrity/theme/TemplateFilesTest.php b/dev/tests/integration/testsuite/integrity/theme/TemplateFilesTest.php
index a42d7e17e2cdc38bed11ebe767975bebeb712948..ad5d5c970c9c08cb9efd6cd3a56aecda7e183c4b 100644
--- a/dev/tests/integration/testsuite/integrity/theme/TemplateFilesTest.php
+++ b/dev/tests/integration/testsuite/integrity/theme/TemplateFilesTest.php
@@ -137,9 +137,9 @@ class Integrity_Theme_TemplateFilesTest extends Magento_Test_TestCase_IntegrityA
     {
         $attributes = $xmlNode->attributes();
         if (isset($attributes['type'])) {
-            $class = Mage::getConfig()->getBlockClassName((string) $attributes['type']);
+            $class = (string) $attributes['type'];
         } else {
-            $class = Mage::getConfig()->getBlockClassName((string) $xmlNode);
+            $class = (string) $xmlNode;
         }
         $blockModule = substr($class, 0, strpos($class, '_Block'));
         return $blockModule;
diff --git a/dev/tests/js/jsTestDriverOrder.php b/dev/tests/js/jsTestDriverOrder.php
index d7b445faa905a49b6b398e1569f682483b6b4a44..890906167c86da53a7d8c3c4cebf19fccaceac51 100644
--- a/dev/tests/js/jsTestDriverOrder.php
+++ b/dev/tests/js/jsTestDriverOrder.php
@@ -30,7 +30,7 @@
  */
 return array(
     '/pub/lib/jquery/jquery.min.js',
-    '/pub/lib/jquery/jquery-ui.custom.min.js',
+    '/pub/lib/jquery/jquery-ui.js',
     '/pub/lib/jquery/jquery.cookie.js',
     '/pub/lib/head.load.min.js',
     '/pub/lib/mage/mage.js',
diff --git a/dev/tests/performance/framework/Magento/Application.php b/dev/tests/performance/framework/Magento/Application.php
index 79ec25fa7bbdea170b1ecf4e84a19c338032f0e7..da859ccb36338f5460df9a192d8be0266f51631b 100644
--- a/dev/tests/performance/framework/Magento/Application.php
+++ b/dev/tests/performance/framework/Magento/Application.php
@@ -195,7 +195,8 @@ class Magento_Application
      */
     protected function _bootstrap()
     {
-        Mage::app();
+        /** @var $app Mage_Core_Model_App */
+        Mage::getObjectManager()->get('Mage_Core_Model_App');
         return $this;
     }
 
diff --git a/dev/tests/performance/testsuite/backend.jmx b/dev/tests/performance/testsuite/backend.jmx
index e940642aacc520ebfbd3623cb5dbdd816037842b..f184294e4a02f5adc60f5a825ec6506a2b8e203d 100644
--- a/dev/tests/performance/testsuite/backend.jmx
+++ b/dev/tests/performance/testsuite/backend.jmx
@@ -25,7 +25,7 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 -->
-<jmeterTestPlan version="1.2" properties="2.3">
+<jmeterTestPlan version="1.2" properties="2.4" jmeter="2.9 r1437961">
   <hashTree>
     <TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="Backend High Load Testing" enabled="true">
       <stringProp name="TestPlan.comments"></stringProp>
@@ -125,7 +125,7 @@
         <hashTree>
           <ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="Assert Total Number of Products" enabled="true">
             <collectionProp name="Asserion.test_strings">
-              <stringProp name="131458462">&lt;h3 class=&quot;icon-head head-products&quot;&gt;Manage Products&lt;/h3&gt;</stringProp>
+              <stringProp name="-1786510475">&lt;h1 class=&quot;title&quot;&gt;Manage Products&lt;/h1&gt;</stringProp>
               <stringProp name="-1952867632">Total ${products_number} records found</stringProp>
             </collectionProp>
             <stringProp name="Assertion.test_field">Assertion.response_data</stringProp>
@@ -157,7 +157,7 @@
         <hashTree>
           <ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="Assert Total Number of Customers" enabled="true">
             <collectionProp name="Asserion.test_strings">
-              <stringProp name="2077718991">&lt;h3 class=&quot;icon-head head-customer&quot;&gt;Manage Customers&lt;/h3&gt;</stringProp>
+              <stringProp name="-5737002">&lt;h1 class=&quot;title&quot;&gt;Manage Customers&lt;/h1&gt;</stringProp>
               <stringProp name="1843270971">Total ${customers_number} records found</stringProp>
             </collectionProp>
             <stringProp name="Assertion.test_field">Assertion.response_data</stringProp>
@@ -189,7 +189,7 @@
         <hashTree>
           <ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="Assert Total Number of Orders" enabled="true">
             <collectionProp name="Asserion.test_strings">
-              <stringProp name="1454492943">&lt;h3 class=&quot;icon-head head-sales-order&quot;&gt;Orders&lt;/h3&gt;</stringProp>
+              <stringProp name="-1043496309">&lt;h1 class=&quot;title&quot;&gt;Orders&lt;/h1&gt;</stringProp>
               <stringProp name="1043238481">Total ${orders_number} records found</stringProp>
             </collectionProp>
             <stringProp name="Assertion.test_field">Assertion.response_data</stringProp>
diff --git a/dev/tests/performance/testsuite/reusable/admin_login.jmx b/dev/tests/performance/testsuite/reusable/admin_login.jmx
index 7840da94a0e1e19480bd2997bccdeeab9e432e6a..44c4d24c26d9c549228a23d128322a61b185bacf 100644
--- a/dev/tests/performance/testsuite/reusable/admin_login.jmx
+++ b/dev/tests/performance/testsuite/reusable/admin_login.jmx
@@ -25,7 +25,7 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 -->
-<jmeterTestPlan version="1.2" properties="2.3">
+<jmeterTestPlan version="1.2" properties="2.4" jmeter="2.9 r1437961">
   <hashTree>
     <TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="Admin - Login" enabled="true">
       <stringProp name="TestPlan.comments">Reusable scenario to log-in to admin backend. Needs: HOST, ADMIN_PATH, ADMIN_USERNAME, ADMIN_PASSWORD, Http Cookie Manager</stringProp>
@@ -128,7 +128,9 @@
         <hashTree>
           <ResponseAssertion guiclass="AssertionGui" testclass="ResponseAssertion" testname="Assert logged-in" enabled="true">
             <collectionProp name="Asserion.test_strings">
-              <stringProp name="-1356192049">Logged in as ${ADMIN_USERNAME}</stringProp>
+              <stringProp name="934841248">${ADMIN_USERNAME}</stringProp>
+              <stringProp name="-989788387">Account Setting</stringProp>
+              <stringProp name="374398571">Sign Out</stringProp>
             </collectionProp>
             <stringProp name="Assertion.test_field">Assertion.response_data</stringProp>
             <boolProp name="Assertion.assume_success">false</boolProp>
diff --git a/dev/tests/static/testsuite/Integrity/ClassesTest.php b/dev/tests/static/testsuite/Integrity/ClassesTest.php
index 27f89db5a5f5ee97c1854c1c5766a9e4aa537f1c..45a34da0292d756fef77b4e67068fe2f99ef16a4 100644
--- a/dev/tests/static/testsuite/Integrity/ClassesTest.php
+++ b/dev/tests/static/testsuite/Integrity/ClassesTest.php
@@ -47,7 +47,7 @@ class Integrity_ClassesTest extends PHPUnit_Framework_TestCase
             \:\:get(?:ResourceModel | BlockSingleton | Model | Singleton)?\(\s*[\'"]([a-z\d_]+)[\'"]\s*[\),]
 
             # various methods, first argument
-            | \->(?:initReport | addBlock | createBlock | setDataHelperName | getBlockClassName | _?initLayoutMessages
+            | \->(?:initReport | addBlock | createBlock | setDataHelperName | _?initLayoutMessages
                 | setAttributeModel | setBackendModel | setFrontendModel | setSourceModel | setModel
             )\(\s*\'([a-z\d_]+)\'\s*[\),]
 
diff --git a/dev/tests/static/testsuite/Js/_files/blacklist/core.txt b/dev/tests/static/testsuite/Js/_files/blacklist/core.txt
index a198a22a28a11a41b5b2f4b729695c6526496b3b..57aab4e622aa2920926d36e640be050e02b067f9 100644
--- a/dev/tests/static/testsuite/Js/_files/blacklist/core.txt
+++ b/dev/tests/static/testsuite/Js/_files/blacklist/core.txt
@@ -10,10 +10,7 @@ app/code/core/Mage/Checkout/view/frontend/multishipping/payment.js
 app/code/core/Mage/Checkout/view/frontend/onepage/accordion.js
 app/code/core/Mage/Checkout/view/frontend/opcheckout.js
 app/code/core/Mage/Captcha/view/frontend/onepage.js
-app/code/core/Mage/Adminhtml/view/adminhtml/catalog/base-image-uploader.js
 app/code/core/Mage/Adminhtml/view/adminhtml/catalog/category/edit.js
-app/code/core/Mage/Adminhtml/view/adminhtml/catalog/jquery.base-image-uploader.js
-app/code/core/Mage/Adminhtml/view/adminhtml/catalog/jquery.category-selector.js
 app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/composite/configure.js
 app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product.js
 app/code/core/Mage/Adminhtml/view/adminhtml/promo/rules.js
diff --git a/dev/tests/static/testsuite/Legacy/ClassesTest.php b/dev/tests/static/testsuite/Legacy/ClassesTest.php
index f62b6820d262fd1780b34c79311a3b2823d0b4f8..ae075b50c22282d459105715ba4e73bb8f4be08e 100644
--- a/dev/tests/static/testsuite/Legacy/ClassesTest.php
+++ b/dev/tests/static/testsuite/Legacy/ClassesTest.php
@@ -61,8 +61,8 @@ class Legacy_ClassesTest extends PHPUnit_Framework_TestCase
             # ::getModel ::getSingleton ::getResourceModel ::getResourceSingleton
             \:\:get(?:Resource)?(?:Model | Singleton)\(\s*[\'"]([^\'"]+)[\'"]\s*[\),]
 
-            # addBlock createBlock getBlockClassName getBlockSingleton
-            | (?:addBlock | createBlock | getBlockClassName | getBlockSingleton)\(\s*[\'"]([^\'"]+)[\'"]\s*[\),]
+            # addBlock createBlock getBlockSingleton
+            | (?:addBlock | createBlock | getBlockSingleton)\(\s*[\'"]([^\'"]+)[\'"]\s*[\),]
 
             # Mage::helper ->helper
             | (?:Mage\:\:|\->)helper\(\s*[\'"]([^\'"]+)[\'"]\s*\)
diff --git a/dev/tests/static/testsuite/Legacy/ObsoleteCodeTest.php b/dev/tests/static/testsuite/Legacy/ObsoleteCodeTest.php
index 1a6fd978b7caf70deb68ad4eb8ff49665de055b1..b7c9325d7059eee448b68e6ea8f0c0f88f2165e0 100644
--- a/dev/tests/static/testsuite/Legacy/ObsoleteCodeTest.php
+++ b/dev/tests/static/testsuite/Legacy/ObsoleteCodeTest.php
@@ -223,9 +223,10 @@ class Legacy_ObsoleteCodeTest extends PHPUnit_Framework_TestCase
         foreach (self::$_methods as $row) {
             list($method, $class, $suggestion) = $row;
             if (!$this->_isClassSkipped($content, $class)) {
-                $this->_assertNotRegExp('/[^a-z\d_]' . preg_quote($method, '/') . '\s*\(/iS', $content,
-                    sprintf("Method '%s' is obsolete. Replacement suggestion: %s", $method, $suggestion)
-                );
+                $message = sprintf("Method '%s' is obsolete. Replacement suggestion: %s", $method, $suggestion);
+                 $this->_assertNotRegExp('/this->' . preg_quote($method, '/') . '\s*\(/iS', $content, $message);
+                $this->_assertNotRegExp('/ion\s*' . preg_quote($method, '/') . '\s*\(/iS', $content, $message);
+                $this->_assertNotRegExp('/self::\s*' . preg_quote($method, '/') . '\s*\(/iS', $content, $message);
             }
         }
     }
diff --git a/dev/tests/static/testsuite/Legacy/_files/obsolete_classes.php b/dev/tests/static/testsuite/Legacy/_files/obsolete_classes.php
index bf6dca5ff6399f16c304aa241e73bf930d68b2dd..829ae06698275f4e9a05a3e28b8b2022b1a2f306 100644
--- a/dev/tests/static/testsuite/Legacy/_files/obsolete_classes.php
+++ b/dev/tests/static/testsuite/Legacy/_files/obsolete_classes.php
@@ -570,6 +570,7 @@ return array(
     array('Mage_Core_Controller_Varien_Router_Admin', 'Mage_Backend_Controller_Router_Default'),
     array('Mage_Core_Model_Convert'),
     array('Mage_Core_Model_Config_Options', 'Mage_Core_Model_Dir'),
+    array('Mage_Core_Model_Config_Module'),
     array('Mage_Core_Model_Config_System'),
     array('Mage_Core_Model_Design_Source_Apply'),
     array('Mage_Core_Model_Language'),
diff --git a/dev/tests/static/testsuite/Legacy/_files/obsolete_constants.php b/dev/tests/static/testsuite/Legacy/_files/obsolete_constants.php
index be48adab35af3bc50933994d92b7f4d2c6f4222e..5b3cf31f12bf9287ea343e1e8e9ed30b57d2701a 100644
--- a/dev/tests/static/testsuite/Legacy/_files/obsolete_constants.php
+++ b/dev/tests/static/testsuite/Legacy/_files/obsolete_constants.php
@@ -26,44 +26,66 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 return array(
-    array('GALLERY_IMAGE_TABLE', 'Mage_Catalog_Model_Resource_Product_Attribute_Backend_Media'),
-    array('DEFAULT_VALUE_TABLE_PREFIX'),
+    array('BACKORDERS_BELOW'),
+    array('BACKORDERS_YES'),
+    array('CATEGORY_APPLY_CATEGORY_AND_PRODUCT_ONLY'),
     array('CATEGORY_APPLY_CATEGORY_AND_PRODUCT_RECURSIVE'),
     array('CATEGORY_APPLY_CATEGORY_ONLY'),
-    array('CATEGORY_APPLY_CATEGORY_AND_PRODUCT_ONLY'),
     array('CATEGORY_APPLY_CATEGORY_RECURSIVE'),
-    array('BACKORDERS_BELOW'),
-    array('BACKORDERS_YES'),
-    array('XML_PATH_DEFAULT_COUNTRY', 'Mage_Core_Model_Locale'),
-    array('XML_PATH_SENDING_SET_RETURN_PATH', 'Mage_Newsletter_Model_Subscriber'),
-    array('CHECKSUM_KEY_NAME'),
-    array('XML_PATH_COUNTRY_DEFAULT', 'Mage_Paypal_Model_System_Config_Backend_MerchantCountry'),
-    array('ENTITY_PRODUCT', 'Mage_Review_Model_Review'),
-    array('CHECKOUT_METHOD_REGISTER'),
     array('CHECKOUT_METHOD_GUEST'),
-    array('CONFIG_XML_PATH_SHOW_IN_CATALOG'),
+    array('CHECKOUT_METHOD_REGISTER'),
+    array('CHECKSUM_KEY_NAME'),
+    array('CONFIG_TEMPLATE_INSTALL_DATE', 'Mage_Core_Model_Config',
+        'Mage_Core_Model_Config_Primary::CONFIG_TEMPLATE_INSTALL_DATE'
+    ),
     array('CONFIG_XML_PATH_DEFAULT_PRODUCT_TAX_GROUP'),
-    array('CONFIG_XML_PATH_DISPLAY_TAX_COLUMN'),
     array('CONFIG_XML_PATH_DISPLAY_FULL_SUMMARY'),
+    array('CONFIG_XML_PATH_DISPLAY_TAX_COLUMN'),
     array('CONFIG_XML_PATH_DISPLAY_ZERO_TAX'),
+    array('CONFIG_XML_PATH_SHOW_IN_CATALOG'),
+    array('DEFAULT_ERROR_HANDLER', 'Mage_Core_Model_App', 'Mage::DEFAULT_ERROR_HANDLER'),
+    array('DEFAULT_THEME_NAME', 'Mage_Core_Model_Design_Package'),
+    array('DEFAULT_VALUE_TABLE_PREFIX'),
+    array('ENTITY_PRODUCT', 'Mage_Review_Model_Review'),
     array('EXCEPTION_CODE_IS_GROUPED_PRODUCT'),
+    array('GALLERY_IMAGE_TABLE', 'Mage_Catalog_Model_Resource_Product_Attribute_Backend_Media'),
+    array('HASH_ALGO'),
+    array('INIT_OPTION_DIRS', 'Mage_Core_Model_App', 'Mage::PARAM_APP_DIRS'),
+    array('INIT_OPTION_REQUEST', 'Mage'),
+    array('INIT_OPTION_REQUEST', 'Mage_Core_Model_App'),
+    array('INIT_OPTION_RESPONSE', 'Mage'),
+    array('INIT_OPTION_RESPONSE', 'Mage_Core_Model_App'),
+    array('INIT_OPTION_SCOPE_CODE', 'Mage_Core_Model_App', 'Mage::PARAM_RUN_CODE'),
+    array('INIT_OPTION_SCOPE_TYPE', 'Mage_Core_Model_App', 'Mage::PARAM_RUN_TYPE'),
+    array('INIT_OPTION_URIS', 'Mage_Core_Model_App', 'Mage::PARAM_APP_URIS'),
+    array('INSTALLER_HOST_RESPONSE', 'Mage_Install_Model_Installer'),
     array('Mage_Rss_Block_Catalog_NotifyStock::CACHE_TAG'),
     array('Mage_Rss_Block_Catalog_Review::CACHE_TAG'),
     array('Mage_Rss_Block_Order_New::CACHE_TAG'),
     array('REGISTRY_FORM_PARAMS_KEY', null, 'direct value'),
-    array('TYPE_TINYINT', null, 'Varien_Db_Ddl_Table::TYPE_SMALLINT'),
+    array('SCOPE_TYPE_GROUP', 'Mage_Core_Model_App', 'Mage_Core_Model_StoreManagerInterface::SCOPE_TYPE_GROUP'),
+    array('SCOPE_TYPE_STORE', 'Mage_Core_Model_App', 'Mage_Core_Model_StoreManagerInterface::SCOPE_TYPE_STORE'),
+    array('SCOPE_TYPE_WEBSITE', 'Mage_Core_Model_App', 'Mage_Core_Model_StoreManagerInterface::SCOPE_TYPE_WEBSITE'),
+    array('SEESION_MAX_COOKIE_LIFETIME'),
+    array('TYPE_BINARY', null, 'Varien_Db_Ddl_Table::TYPE_BLOB'),
     array('TYPE_CHAR', null, 'Varien_Db_Ddl_Table::TYPE_TEXT'),
-    array('TYPE_VARCHAR', null, 'Varien_Db_Ddl_Table::TYPE_TEXT'),
-    array('TYPE_LONGVARCHAR', null, 'Varien_Db_Ddl_Table::TYPE_TEXT'),
     array('TYPE_CLOB', null, 'Varien_Db_Ddl_Table::TYPE_TEXT'),
     array('TYPE_DOUBLE', null, 'Varien_Db_Ddl_Table::TYPE_FLOAT'),
+    array('TYPE_LONGVARBINARY', null, 'Varien_Db_Ddl_Table::TYPE_BLOB'),
+    array('TYPE_LONGVARCHAR', null, 'Varien_Db_Ddl_Table::TYPE_TEXT'),
     array('TYPE_REAL', null, 'Varien_Db_Ddl_Table::TYPE_FLOAT'),
     array('TYPE_TIME', null, 'Varien_Db_Ddl_Table::TYPE_TIMESTAMP'),
-    array('TYPE_BINARY', null, 'Varien_Db_Ddl_Table::TYPE_BLOB'),
-    array('TYPE_LONGVARBINARY', null, 'Varien_Db_Ddl_Table::TYPE_BLOB'),
-    array('HASH_ALGO'),
-    array('SEESION_MAX_COOKIE_LIFETIME'),
+    array('TYPE_TINYINT', null, 'Varien_Db_Ddl_Table::TYPE_SMALLINT'),
+    array('TYPE_VARCHAR', null, 'Varien_Db_Ddl_Table::TYPE_TEXT'),
     array('URL_TYPE_SKIN'),
-    array('INSTALLER_HOST_RESPONSE', 'Mage_Install_Model_Installer'),
-    array('DEFAULT_THEME_NAME', 'Mage_Core_Model_Design_Package'),
+    array('XML_PATH_COUNTRY_DEFAULT', 'Mage_Paypal_Model_System_Config_Backend_MerchantCountry'),
+    array('XML_PATH_DEFAULT_COUNTRY', 'Mage_Core_Model_Locale'),
+    array('XML_PATH_INSTALL_DATE', 'Mage_Core_Model_App', 'Mage_Core_Model_Config_Primary::XML_PATH_INSTALL_DATE'),
+    array('XML_PATH_LOCALE_INHERITANCE', 'Mage_Core_Model_Translate',
+        'Mage_Core_Model_Locale_Hierarchy_Loader::XML_PATH_LOCALE_INHERITANCE'
+    ),
+    array('XML_PATH_SENDING_SET_RETURN_PATH', 'Mage_Newsletter_Model_Subscriber'),
+    array('XML_PATH_SKIP_PROCESS_MODULES_UPDATES', 'Mage_Core_Model_App',
+        'Mage_Core_Model_Db_UpdaterInterface::XML_PATH_SKIP_PROCESS_MODULES_UPDATES'
+    ),
 );
diff --git a/dev/tests/static/testsuite/Legacy/_files/obsolete_methods.php b/dev/tests/static/testsuite/Legacy/_files/obsolete_methods.php
index 8fdd3b373742d37033523ea17a97d3c0b4c6824a..65ffea7c36167e4baa62b940ba32dd7dd7f3d6f9 100644
--- a/dev/tests/static/testsuite/Legacy/_files/obsolete_methods.php
+++ b/dev/tests/static/testsuite/Legacy/_files/obsolete_methods.php
@@ -35,14 +35,19 @@ return array(
     array('_aggregateByOrderCreatedAt', 'Mage_SalesRule_Model_Resource_Report_Rule'),
     array('_amountByCookies', 'Mage_Sendfriend_Model_Sendfriend'),
     array('_amountByIp', 'Mage_Sendfriend_Model_Sendfriend'),
+    array('_applyClassRewrites', 'Mage_Core_Model_Config'),
     array('_applyCustomDesignSettings'),
-    array('_applyDesign', 'Mage_Catalog_Model_Design'),
     array('_applyDesignRecursively', 'Mage_Catalog_Model_Design'),
+    array('_applyDesign', 'Mage_Catalog_Model_Design'),
     array('_avoidDoubleTransactionProcessing'),
     array('_beforeChildToHtml'),
+    array('_bytesToMbytes', 'Mage_Catalog_Model_Product_Option_Type_File'),
     array('_calculatePrice', 'Mage_Sales_Model_Quote_Item_Abstract'),
     array('_canShowField', 'Mage_Backend_Block_System_Config_Form'),
+    array('_canUseCacheForInit', 'Mage_Core_Model_Config'),
     array('_canUseLocalModules'),
+    array('_checkCookieStore', 'Mage_Core_Model_App'),
+    array('_checkGetStore', 'Mage_Core_Model_App'),
     array('_checkUrlSettings', 'Mage_Adminhtml_Controller_Action'),
     array('_collectOrigData', 'Mage_Catalog_Model_Resource_Abstract'),
     array('_decodeInput', 'Mage_Adminhtml_Catalog_ProductController'),
@@ -50,18 +55,21 @@ return array(
     array('_escapeValue', 'Mage_Adminhtml_Block_Widget_Grid_Column_Filter_Abstract'),
     array('_getAddressTaxRequest', 'Mage_Tax_Model_Sales_Total_Quote_Shipping'),
     array('_getAggregationPerStoreView'),
-    array('_getAttributeFilterBlockName', 'Mage_Catalog_Block_Layer_View'),
-    array('_getAttributeFilterBlockName', 'Mage_CatalogSearch_Block_Layer'),
     array('_getAttributeFilterBlockName'),
+    array('_getAttributeFilterBlockName', 'Mage_CatalogSearch_Block_Layer'),
+    array('_getAttributeFilterBlockName', 'Mage_Catalog_Block_Layer_View'),
     array('_getAvailable', 'Mage_GiftMessage_Model_Observer'),
+    array('_getBytesIniValue', 'Mage_Catalog_Model_Product_Option_Type_File'),
     array('_getCacheId', 'Mage_Core_Model_App'),
     array('_getCacheKey', 'Mage_Catalog_Model_Layer_Filter_Price'),
+    array('_getCacheLockId', 'Mage_Core_Model_Config'),
     array('_getCacheTags', 'Mage_Core_Model_App'),
     array('_getChildHtml'),
     array('_getCollapseState', 'Mage_Backend_Block_System_Config_Form_Fieldset', '_isCollapseState'),
     array('_getCollectionNames', 'Mage_Adminhtml_Report_SalesController'),
     array('_getConnenctionType', 'Mage_Install_Model_Installer_Db'),
     array('_getDateFromToHtml', 'Mage_ImportExport_Block_Adminhtml_Export_Filter'),
+    array('_getDeclaredModuleFiles', 'Mage_Core_Model_Config'),
     array('_getExistingBasePopularity'),
     array('_getFieldTableAlias', 'Mage_Newsletter_Model_Resource_Subscriber_Collection'),
     array('_getForeignKeyName', 'Varien_Db_Adapter_Pdo_Mysql'),
@@ -72,28 +80,49 @@ return array(
     array('_getLabelForStore', 'Mage_Catalog_Model_Resource_Eav_Attribute'),
     array('_getMultiSelectHtml', 'Mage_ImportExport_Block_Adminhtml_Export_Filter'),
     array('_getNumberFromToHtml', 'Mage_ImportExport_Block_Adminhtml_Export_Filter'),
+    array('_getPathInScope', 'Mage_Core_Model_Config'),
     array('_getPriceFilter', 'Mage_Catalog_Block_Layer_View'),
+    array('_getProcessor', 'Mage_Core_Model_Cache'),
     array('_getProductQtyForCheck', 'Mage_CatalogInventory_Model_Observer'),
     array('_getRangeByType', 'Mage_Log_Model_Resource_Visitor_Collection'),
     array('_getRecentProductsCollection'),
+    array('_getSHAInSet', '', 'Mage_Ogone_Model_Api::getHash'),
+    array('_getScopeCode', 'Mage_Core_Model_Config'),
+    array('_getSectionConfig', 'Mage_Core_Model_Config'),
     array('_getSelectHtml', 'Mage_ImportExport_Block_Adminhtml_Export_Filter'),
     array('_getSetData', 'Mage_Adminhtml_Block_Catalog_Product_Attribute_Set_Main'),
-    array('_getSHAInSet', null, 'Mage_Ogone_Model_Api::getHash'),
+    array('_getStoreByGroup', 'Mage_Core_Model_App'),
+    array('_getStoreByWebsite', 'Mage_Core_Model_App'),
     array('_getStoreTaxRequest', 'Mage_Tax_Model_Sales_Total_Quote_Shipping'),
+    array('_getUploadMaxFilesize', 'Mage_Catalog_Model_Product_Option_Type_File'),
     array('_importAddress', 'Mage_Paypal_Model_Api_Nvp'),
     array('_inheritDesign', 'Mage_Catalog_Model_Design'),
+    array('_initBaseConfig', 'Mage_Core_Model_App'),
+    array('_initCache', 'Mage_Core_Model_App'),
+    array('_initCurrentStore', 'Mage_Core_Model_App'),
+    array('_initFileSystem', 'Mage_Core_Model_App'),
+    array('_initLogger', 'Mage_Core_Model_App'),
+    array('_initModulesPreNamespaces', 'Mage_Core_Model_Config'),
+    array('_initModules', 'Mage_Core_Model_App'),
     array('_initOrder', 'Mage_Shipping_Block_Tracking_Popup'),
     array('_initShipment', 'Mage_Shipping_Block_Tracking_Popup'),
-    array('_inludeControllerClass', null, '_includeControllerClass'),
+    array('_initStores', 'Mage_Core_Model_App'),
+    array('_inludeControllerClass', '', '_includeControllerClass'),
     array('_isApplyDesign', 'Mage_Catalog_Model_Design'),
     array('_isApplyFor', 'Mage_Catalog_Model_Design'),
     array('_isPositiveDecimalNumber', 'Mage_Shipping_Model_Resource_Carrier_Tablerate'),
+    array('_loadCache', 'Mage_Core_Model_Config'),
+    array('_loadDeclaredModules', 'Mage_Core_Model_Config'),
+    array('_loadInstallDate', 'Mage_Core_Model_Config'),
+    array('_loadLocalConfig', 'Mage_Core_Model_Config'),
     array('_loadOldRates', 'Mage_Tax_Model_Resource_Setup'),
+    array('_loadSectionCache', 'Mage_Core_Model_Config'),
     array('_needSubtractShippingTax'),
     array('_needSubtractTax'),
     array('_needToAddDummy'),
     array('_needToAddDummyForShipment'),
     array('_parseDescription', 'Mage_Sales_Model_Order_Pdf_Items_Abstract'),
+    array('_parsePackageTheme', 'Mage_Widget_Model_Widget_Instance'),
     array('_parseXmlTrackingResponse', 'Mage_Usa_Model_Shipping_Carrier_Fedex'),
     array('_prepareCondition', 'Mage_CatalogSearch_Model_Advanced'),
     array('_prepareConfigurableProductData', 'Mage_ImportExport_Model_Export_Entity_Product'),
@@ -106,22 +135,30 @@ return array(
     array('_putCustomerIntoQuote', 'Mage_Adminhtml_Model_Sales_Order_Create'),
     array('_quoteRow', 'Mage_Backup_Model_Resource_Db'),
     array('_recollectItem', 'Mage_Tax_Model_Sales_Total_Quote_Subtotal'),
+    array('_removeCache', 'Mage_Core_Model_Config'),
     array('_resetItemPriceInclTax'),
+    array('_saveCache', 'Mage_Core_Model_Config'),
     array('_saveCustomerAfterOrder', 'Mage_Adminhtml_Model_Sales_Order_Create'),
     array('_saveCustomers', 'Mage_Adminhtml_Model_Sales_Order_Create'),
+    array('_saveSectionCache', 'Mage_Core_Model_Config'),
     array('_sendUploadResponse', 'Mage_Adminhtml_CustomerController'),
     array('_sendUploadResponse', 'Mage_Adminhtml_Newsletter_SubscriberController'),
     array('_setAttribteValue'),
+    array('_shouldSkipProcessUpdates', 'Mage_Core_Model_App'),
     array('_sort', 'Mage_Backend_Model_Config_Structure_Converter'),
     array('_updateMediaPathUseRewrites', 'Mage_Core_Model_Store', '_getMediaScriptUrl'),
     array('_usePriceIncludeTax'),
+    array('addAllowedModules', 'Mage_Core_Model_Config'),
     array('addBackupedFilter'),
     array('addConfigField', 'Mage_Core_Model_Resource_Setup'),
     array('addConstraint', 'Varien_Db_Adapter_Pdo_Mysql'),
-    array('addCustomersToAlertQueueAction'),
     array('addCustomerToSegments'),
+    array('addCustomersToAlertQueueAction'),
     array('addGroupByTag', 'Mage_Tag_Model_Resource_Reports_Collection'),
+    array('addHandle', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
     array('addKey', 'Varien_Db_Adapter_Pdo_Mysql'),
+    array('addObserver', 'Mage'),
+    array('addPageHandles', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
     array('addSaleableFilterToCollection'),
     array('addSearchQfFilter'),
     array('addStoresFilter', 'Mage_Poll_Model_Resource_Poll_Collection'),
@@ -130,25 +167,36 @@ return array(
     array('addTemplateData', 'Mage_Newsletter_Model_Queue'),
     array('addToAlersAction'),
     array('addToChildGroup'),
+    array('addUpdate', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
     array('addVisibleFilterToCollection', 'Mage_Catalog_Model_Product_Status'),
-    array('addVisibleInCatalogFilterToCollection', null,
-        '$collection->setVisibility(Mage_Catalog_Model_Product_Visibility->getVisibleInCatalogIds());'),
-    array('addVisibleInSearchFilterToCollection', null,
-        '$collection->setVisibility(Mage_Catalog_Model_Product_Visibility->getVisibleInSearchIds());'),
-    array('addVisibleInSiteFilterToCollection', null,
-        '$collection->setVisibility(Mage_Catalog_Model_Product_Visibility->getVisibleInSiteIds());'),
-    array('addWishlistLink', 'Mage_Wishlist_Block_Links'),
+    array('addVisibleInCatalogFilterToCollection', '',
+        '$collection->setVisibility(Mage_Catalog_Model_Product_Visibility->getVisibleInCatalogIds());'
+    ),
+    array('addVisibleInSearchFilterToCollection', '',
+        '$collection->setVisibility(Mage_Catalog_Model_Product_Visibility->getVisibleInSearchIds());'
+    ),
+    array('addVisibleInSiteFilterToCollection', '',
+        '$collection->setVisibility(Mage_Catalog_Model_Product_Visibility->getVisibleInSiteIds());'
+    ),
     array('addWishListSortOrder', 'Mage_Wishlist_Model_Resource_Item_Collection'),
+    array('addWishlistLink', 'Mage_Wishlist_Block_Links'),
     array('aggregate', 'Mage_Tag_Model_Resource_Tag'),
     array('aggregate', 'Mage_Tag_Model_Tag'),
+    array('applyAllDataUpdates', 'Mage_Core_Model_Resource_Setup'),
+    array('applyAllUpdates', 'Mage_Core_Model_Resource_Setup'),
     array('applyDesign', 'Mage_Catalog_Model_Design'),
+    array('asArray', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
+    array('asSimplexml', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
+    array('asString', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
     array('authAdmin'),
-    array('authFailed', null, 'Mage_Core_Helper_Http::failHttpAuthentication()'),
+    array('authFailed', '', 'Mage_Core_Helper_Http::failHttpAuthentication()'),
     array('authFrontend'),
-    array('authValidate', null, 'Mage_Core_Helper_Http::getHttpAuthCredentials()'),
+    array('authValidate', '', 'Mage_Core_Helper_Http::getHttpAuthCredentials()'),
+    array('baseInit', 'Mage_Core_Model_App'),
     array('bundlesAction', 'Mage_Adminhtml_Catalog_ProductController'),
     array('calcTaxAmount', 'Mage_Sales_Model_Quote_Item_Abstract'),
     array('canPrint', 'Mage_Checkout_Block_Onepage_Success'),
+    array('canTestHeaders', 'Magento_Test_Bootstrap', 'Magento_Test_Helper_Bootstrap::canTestHeaders'),
     array('catalogCategoryChangeProducts', 'Mage_Catalog_Model_Product_Flat_Observer'),
     array('catalogEventProductCollectionAfterLoad', 'Mage_GiftMessage_Model_Observer'),
     array('catalogProductLoadAfter', 'Mage_Bundle_Model_Observer'),
@@ -156,22 +204,25 @@ return array(
     array('checkConfigurableProducts', 'Mage_Eav_Model_Resource_Entity_Attribute_Collection'),
     array('checkDatabase', 'Mage_Install_Model_Installer_Db'),
     array('checkDateTime', 'Mage_Core_Model_Date'),
+    array('cleanCache', 'Mage_Core_Model_Config'),
     array('cleanDbRow', 'Mage_Core_Model_Resource'),
-    array('cleanVarFolder', null, 'Varien_Io_File::rmdirRecursive()'),
-    array('cleanVarSubFolders', null, 'glob() on Mage::getBaseDir(Mage_Core_Model_App_Dir::VAR_DIR)'),
+    array('cleanVarFolder', '', 'Varien_Io_File::rmdirRecursive()'),
+    array('cleanVarSubFolders', '', 'glob() on Mage::getBaseDir(Mage_Core_Model_App_Dir::VAR_DIR)'),
     array('cloneIndexTable', 'Mage_Index_Model_Resource_Abstract'),
+    array('composeLocaleHierarchy', 'Mage_Core_Helper_Translate'),
     array('convertOldTaxData', 'Mage_Tax_Model_Resource_Setup'),
     array('convertOldTreeToNew', 'Mage_Catalog_Model_Resource_Setup'),
     array('countChildren', 'Mage_Core_Block_Abstract'),
     array('crear'),
-    array('createDirIfNotExists', null, 'mkdir()'),
+    array('createDirIfNotExists', '', 'mkdir()'),
     array('createOrderItem', 'Mage_CatalogInventory_Model_Observer'),
     array('debugRequest', 'Mage_Paypal_Model_Api_Standard'),
+    array('deleteConfig', 'Mage_Core_Model_Config'),
     array('deleteProductPrices', 'Mage_Catalog_Model_Resource_Product_Attribute_Backend_Tierprice'),
-    array('display', 'Varien_Image_Adapter_Abstract', 'getImage()'),
     array('displayFullSummary', 'Mage_Tax_Model_Config'),
     array('displayTaxColumn', 'Mage_Tax_Model_Config'),
     array('displayZeroTax', 'Mage_Tax_Model_Config'),
+    array('display', 'Varien_Image_Adapter_Abstract', 'getImage()'),
     array('drawItem', 'Mage_Catalog_Block_Navigation'),
     array('dropKey', 'Varien_Db_Adapter_Pdo_Mysql'),
     array('editAction', 'Mage_Tag_CustomerController'),
@@ -180,8 +231,9 @@ return array(
     array('exportOrderedExcelAction'),
     array('fetchItemsCount', 'Mage_Wishlist_Model_Resource_Wishlist'),
     array('fetchRuleRatesForCustomerTaxClass'),
+    array('fetchUpdatesByHandle', 'Mage_Core_Model_Resource_Layout', 'Mage_Core_Model_Resource_Layout_Update'),
     array('forsedSave'),
-    array('generateBlocks', null, 'generateElements()'),
+    array('generateBlocks', '', 'generateElements()'),
     array('getAccount', 'Mage_GoogleAnalytics_Block_Ga'),
     array('getAclAssert', 'Mage_Admin_Model_Config'),
     array('getAclPrivilegeSet', 'Mage_Admin_Model_Config'),
@@ -189,7 +241,7 @@ return array(
     array('getAclResourceTree', 'Mage_Admin_Model_Config'),
     array('getAddNewButtonHtml', 'Mage_Adminhtml_Block_Catalog_Product'),
     array('getAddToCartItemUrl', 'Mage_Wishlist_Block_Customer_Sidebar'),
-    array('getAddToCartUrlBase64', null, '_getAddToCartUrl'),
+    array('getAddToCartUrlBase64', '', '_getAddToCartUrl'),
     array('getAllEntityIds', 'Mage_Rss_Model_Resource_Order'),
     array('getAllEntityTypeCommentIds', 'Mage_Rss_Model_Resource_Order'),
     array('getAllOrderEntityIds', 'Mage_Rss_Model_Resource_Order'),
@@ -197,25 +249,48 @@ return array(
     array('getAnonSuffix'),
     array('getAttributesJson', 'Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Super_Config', 'getAttributes'),
     array('getBaseTaxAmount', 'Mage_Sales_Model_Quote_Item_Abstract'),
+    array('getBlockClassName', 'Mage_Core_Model_Config'),
+    array('getButtonsHtml', 'Mage_Bundle_Block_Adminhtml_Catalog_Product_Edit_Tab_Bundle_Option_Search'),
+    array('getCache', 'Mage_Core_Model_Config'),
     array('getCheckoutMehod', 'Mage_Checkout_Model_Type_Onepage'),
-    array('getChildGroup', null, 'Mage_Core_Block_Abstract::getGroupChildNames()'),
+    array('getChildGroup', '', 'Mage_Core_Block_Abstract::getGroupChildNames()'),
+    array('getConfigDataModel', 'Mage_Core_Model_Config'),
+    array('getConfig', 'Mage_Captcha_Helper_Data'),
     array('getConfig', 'Mage_Eav_Model_Entity_Attribute_Abstract'),
+    array('getContainers', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
+    array('getControllerInstance', 'Mage'),
     array('getCustomerData', 'Mage_Adminhtml_Block_Sales_Order_Create_Form_Account'),
     array('getDataForSave', 'Mage_Wishlist_Model_Item'),
+    array('getDataMaxSize'),
+    array('getDataMaxSizeInBytes', 'Mage_Adminhtml_Block_Media_Uploader', 'Magento_File_Size::getMaxFileSize()'),
+    array('getDbVendorName', 'Magento_Test_Bootstrap', 'Magento_Test_Helper_Bootstrap::getDbVendorName'),
     array('getDebug', 'Mage_Ogone_Model_Api'),
     array('getDebug', 'Mage_Paypal_Model_Api_Abstract'),
     array('getDefaultBasePath', 'Mage_Core_Model_Store'),
     array('getDirectOutput', 'Mage_Core_Model_Layout'),
     array('getDistroServerVars', 'Mage_Core_Model_Config', 'getDistroBaseUrl'),
+    array('getElementClass', 'Mage_Core_Model_Layout_Update'),
     array('getEntityIdsToIncrementIds', 'Mage_Rss_Model_Resource_Order'),
     array('getEntityTypeIdsToTypes', 'Mage_Rss_Model_Resource_Order'),
+    array('getEventConfig', 'Mage_Core_Model_Config'),
+    array('getEvents', 'Mage'),
     array('getFacets'),
     array('getFallbackTheme'),
-    array('getFormated', null, 'getFormated(true) -> format(\'html\'), getFormated() -> format(\'text\')'),
+    array('getFileLayoutUpdatesXml', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
     array('getFormObject', 'Mage_Adminhtml_Block_Widget_Form'),
+    array('getFormated', '', "getFormated(true) -> format('html'), getFormated() -> format('text')"),
     array('getGiftmessageHtml', 'Mage_Adminhtml_Block_Sales_Order_View_Tab_Info'),
+    array('getHandles', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
+    array('getHeaderCssClass', 'Mage_Bundle_Block_Adminhtml_Catalog_Product_Edit_Tab_Bundle_Option_Search'),
+    array('getHeaderText', 'Mage_Bundle_Block_Adminhtml_Catalog_Product_Edit_Tab_Bundle_Option_Search'),
+    array('getHelperClassName', 'Mage_Core_Model_Config'),
     array('getHtmlFormat', 'Mage_Customer_Model_Address_Abstract'),
-    array('getIsActiveAanalytics', null, 'getOnsubmitJs'),
+    array('getInitParam', 'Mage_Core_Model_App'),
+    array('getInitParams', 'Magento_Test_Bootstrap', 'Magento_Test_Helper_Bootstrap::getAppInitParams'),
+    array('getInstallDate', 'Mage_Core_Model_Config'),
+    array('getInstallDir', 'Magento_Test_Bootstrap', 'Magento_Test_Helper_Bootstrap::getAppInstallDir'),
+    array('getInstance', 'Magento_Test_Bootstrap', 'Magento_Test_Helper_Bootstrap::getInstance'),
+    array('getIsActiveAanalytics', '', 'getOnsubmitJs'),
     array('getIsAjaxRequest', 'Mage_Core_Model_Translate_Inline'),
     array('getIsEngineAvailable'),
     array('getIsGlobal', 'Mage_Eav_Model_Entity_Attribute_Abstract'),
@@ -226,151 +301,225 @@ return array(
     array('getJoinFlag', 'Mage_Tag_Model_Resource_Tag_Collection'),
     array('getKeyList', 'Varien_Db_Adapter_Pdo_Mysql'),
     array('getLanguages', 'Mage_Install_Block_Begin'),
-    array('getLayoutFilename', null, 'getFilename'),
+    array('getLayoutFilename', '', 'getFilename'),
     array('getLifeTime', 'Mage_Core_Model_Resource_Session'),
     array('getLocaleBaseDir', 'Mage_Core_Model_Design_Package'),
     array('getMail', 'Mage_Newsletter_Model_Template'),
     array('getMaxQueryLenght'),
+    array('getMaxUploadSize', 'Mage_ImportExport_Helper_Data', 'getMaxUploadSizeMessage'),
     array('getMenuItemLabel', 'Mage_Admin_Model_Config'),
     array('getMergedCssUrl'),
     array('getMergedJsUrl'),
     array('getMinQueryLenght'),
-    array('getNeedUsePriceExcludeTax', null, 'Mage_Tax_Model_Config::priceIncludesTax()'),
+    array('getModelClassName', 'Mage_Core_Model_Config'),
+    array('getModuleConfigurationFiles', 'Mage_Core_Model_Config'),
+    array('getModuleSetup', 'Mage_Core_Model_Config'),
+    array('getNeedUsePriceExcludeTax', '', 'Mage_Tax_Model_Config::priceIncludesTax()'),
     array('getOneBalanceTotal'),
     array('getOption', 'Mage_Captcha_Helper_Data', 'Mage_Core_Model_Dir::getDir()'),
     array('getOptions', 'Mage_Core_Model_Config'),
+    array('getOptions', 'Mage_Core_Model_Design_Source_Design', 'Mage_Core_Model_Theme::getThemeCollectionOptionArray'),
     array('getOrderHtml', 'Mage_GoogleAnalytics_Block_Ga'),
     array('getOrderId', 'Mage_Checkout_Block_Onepage_Success'),
     array('getOrderId', 'Mage_Shipping_Block_Tracking_Popup'),
-    array('getOriginalHeigh', null, 'getOriginalHeight'),
+    array('getOriginalHeigh', '', 'getOriginalHeight'),
+    array('getPackageTheme', 'Mage_Widget_Model_Widget_Instance', 'getThemeId'),
+    array('getPackage', 'Mage_Widget_Model_Widget_Instance'),
+    array('getPageHandleLabel', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
+    array('getPageHandleParents', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
+    array('getPageHandleType', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
+    array('getPageHandlesHierarchy', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
+    array('getPageHandles', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
     array('getParentProductIds', 'Mage_Catalog_Model_Resource_Product'),
+    array('getPostMaxSize', 'Mage_Adminhtml_Block_Media_Uploader', 'Magento_File_Size::getPostMaxSize()'),
     array('getPriceFormatted', 'Mage_Adminhtml_Block_Customer_Edit_Tab_View_Sales'),
-    array('getPrices', 'Mage_Bundle_Model_Product_Price'),
     array('getPricesDependingOnTax', 'Mage_Bundle_Model_Product_Price'),
+    array('getPrices', 'Mage_Bundle_Model_Product_Price'),
     array('getPrintUrl', 'Mage_Checkout_Block_Onepage_Success'),
     array('getPrintUrl', 'Mage_Sales_Block_Order_Info'),
     array('getProductCollection', 'Mage_Wishlist_Helper_Data'),
     array('getProductCollection', 'Mage_Wishlist_Model_Wishlist'),
     array('getProductsNotInStoreIds'),
     array('getProfile', 'Varien_Convert_Container_Abstract'),
-    array('getQuoteItem', 'Mage_Catalog_Model_Product_Option_Type_Default'),
     array('getQuoteItemOption', 'Mage_Catalog_Model_Product_Option_Type_Default'),
+    array('getQuoteItem', 'Mage_Catalog_Model_Product_Option_Type_Default'),
     array('getQuoteOrdersHtml', 'Mage_GoogleAnalytics_Block_Ga'),
     array('getRemoveItemUrl', 'Mage_Wishlist_Block_Customer_Sidebar'),
     array('getReorderUrl', 'Mage_Sales_Block_Order_Info'),
+    array('getResourceConfig', 'Mage_Config_Model_Config', 'Mage_Config_Model_Config_Resource::getResourceConfig'),
+    array('getResourceConfig', 'Mage_Core_Model_Config'),
+    array('getResourceConnectionConfig', 'Mage_Config_Model_Config',
+        'Mage_Config_Model_Config_Resource::getResourceConnectionConfig'
+    ),
+    array('getResourceConnectionConfig', 'Mage_Core_Model_Config'),
+    array('getResourceConnectionModel', 'Mage_Config_Model_Config',
+        'Mage_Config_Model_Config_Resource::getResourceConnectionModel'
+    ),
+    array('getResourceConnectionModel', 'Mage_Core_Model_Config'),
+    array('getResourceModelClassName', 'Mage_Core_Model_Config'),
+    array('getResourceModel', 'Mage_Core_Model_Config'),
+    array('getResourceTypeConfig', 'Mage_Config_Model_Config',
+        'Mage_Config_Model_Config_Resource::getResourceTypeConfig'
+    ),
+    array('getResourceTypeConfig', 'Mage_Core_Model_Config'),
     array('getRowId', 'Mage_Adminhtml_Block_Sales_Order_Create_Customer_Grid'),
     array('getRowId', 'Mage_Adminhtml_Block_Widget_Grid'),
     array('getSaveTemplateFlag', 'Mage_Newsletter_Model_Queue'),
-    array('getSelectionFinalPrice', 'Mage_Bundle_Model_Product_Price'),
-    array('getSecure', 'Mage_Core_Model_Url', 'isSecure'),
+    array('getSectionNode', 'Mage_Core_Model_Config'),
     array('getSecure', 'Mage_Backend_Model_Url', 'isSecure'),
+    array('getSecure', 'Mage_Core_Model_Url', 'isSecure'),
+    array('getSelectionFinalPrice', 'Mage_Bundle_Model_Product_Price'),
     array('getShipId', 'Mage_Shipping_Block_Tracking_Popup'),
-    array('getSortedChildren', null, 'getChildNames'),
-    array('getSortedChildBlocks', null, 'getChildNames() + $this->getLayout()->getBlock($name)'),
+    array('getSortedChildBlocks', '', 'getChildNames() + $this->getLayout()->getBlock($name)'),
+    array('getSortedChildren', '', 'getChildNames'),
     array('getStatrupPageUrl'),
     array('getStoreButtonsHtml', 'Mage_Backend_Block_System_Config_Tabs'),
     array('getStoreCurrency', 'Mage_Sales_Model_Order'),
     array('getStoreSelectOptions', 'Mage_Backend_Block_System_Config_Tabs'),
+    array('getStore', 'Mage_Captcha_Helper_Data'),
     array('getSuggestedZeroDate'),
     array('getSuggestionsByQuery'),
     array('getSysTmpDir'),
+    array('getTablePrefix', 'Mage_Core_Model_Config'),
     array('getTaxAmount', 'Mage_Sales_Model_Quote_Item_Abstract'),
-    array('getTaxRatesByProductClass', null, '_getAllRatesByProductClass'),
-    array('getTemplateFilename', null, 'getFilename'),
+    array('getTaxRatesByProductClass', '', '_getAllRatesByProductClass'),
     array('getTempVarDir', 'Mage_Core_Model_Config', 'Mage_Core_Model_Dir::getDir()'),
+    array('getTemplateFilename', '', 'getFilename'),
+    array('getTestsDir', 'Magento_Test_Bootstrap'),
+    array('getThemeOptions', 'Mage_Core_Model_Design_Source_Design',
+        'Mage_Core_Model_Theme::getThemeCollectionOptionArray'
+    ),
+    array('getTheme', 'Mage_Widget_Model_Widget_Instance'),
     array('getTotalModels', 'Mage_Sales_Model_Quote_Address'),
     array('getTrackId', 'Mage_Shipping_Block_Tracking_Popup'),
     array('getTrackingInfoByOrder', 'Mage_Shipping_Block_Tracking_Popup'),
     array('getTrackingInfoByShip', 'Mage_Shipping_Block_Tracking_Popup'),
     array('getTrackingInfoByTrackId', 'Mage_Shipping_Block_Tracking_Popup'),
-    array('getTrackingPopUpUrlByOrderId', null, 'getTrackingPopupUrlBySalesModel'),
-    array('getTrackingPopUpUrlByShipId', null, 'getTrackingPopupUrlBySalesModel'),
-    array('getTrackingPopUpUrlByTrackId', null, 'getTrackingPopupUrlBySalesModel'),
+    array('getTrackingPopUpUrlByOrderId', '', 'getTrackingPopupUrlBySalesModel'),
+    array('getTrackingPopUpUrlByShipId', '', 'getTrackingPopupUrlBySalesModel'),
+    array('getTrackingPopUpUrlByTrackId', '', 'getTrackingPopupUrlBySalesModel'),
+    array('getUploadMaxSize', 'Mage_Adminhtml_Block_Media_Uploader', 'Magento_File_Size::getUploadMaxSize()'),
     array('getUseCacheFilename', 'Mage_Core_Model_App'),
-    array('getValidator', 'Mage_SalesRule_Model_Observer'),
     array('getValidatorData', 'Mage_Core_Model_Session_Abstract', 'use _getSessionEnvironment method'),
+    array('getValidator', 'Mage_SalesRule_Model_Observer'),
     array('getValueTable'),
     array('getVarDir', 'Mage_Core_Model_Config', 'Mage_Core_Model_Dir::getDir()'),
     array('getViewOrderUrl', 'Mage_Checkout_Block_Onepage_Success'),
+    array('getWatermarkHeigth', '', 'getWatermarkHeight'),
+    array('getWebsite', 'Mage_Captcha_Helper_Data'),
     array('getWidgetSupportedBlocks', 'Mage_Widget_Model_Widget_Instance'),
     array('getWidgetSupportedTemplatesByBlock', 'Mage_Widget_Model_Widget_Instance'),
     array('hasItems', 'Mage_Wishlist_Helper_Data'),
-    array('htmlEscape', null, 'escapeHtml'),
+    array('htmlEscape', '', 'escapeHtml'),
     array('imageAction', 'Mage_Catalog_ProductController'),
     array('importFromTextArray'),
     array('initLabels', 'Mage_Catalog_Model_Resource_Eav_Attribute'),
+    array('initSpecified', 'Mage_Core_Model_App'),
+    array('init', 'Mage'),
+    array('init', 'Mage_Core_Model_App'),
+    array('init', 'Mage_Core_Model_Config'),
     array('insertProductPrice', 'Mage_Catalog_Model_Resource_Product_Attribute_Backend_Tierprice'),
     array('isAllowedGuestCheckout', 'Mage_Sales_Model_Quote'),
     array('isAutomaticCleaningAvailable', 'Varien_Cache_Backend_Eaccelerator'),
     array('isCheckoutAvailable', 'Mage_Checkout_Model_Type_Multishipping'),
     array('isFulAmountCovered'),
+    array('isInstalled', 'Mage_Core_Model_App'),
     array('isLeyeredNavigationAllowed'),
+    array('isLocalConfigLoaded', 'Mage_Core_Model_Config'),
     array('isReadablePopupObject'),
     array('isTemplateAllowedForApplication'),
+    array('isThemeCompatible', 'Mage_Core_Model_Design_Package', 'Mage_Core_Model_Theme::isThemeCompatible'),
+    array('isVerbose', 'Magento_Shell'),
+    array('loadBase', 'Mage_Core_Model_Config'),
+    array('loadDb', 'Mage_Core_Model_Config'),
+    array('loadDiConfiguration', 'Mage_Core_Model_Config'),
+    array('loadEventObservers', 'Mage_Core_Model_Config'),
     array('loadLabel', 'Mage_Catalog_Model_Resource_Product_Type_Configurable_Attribute'),
+    array('loadModulesCache', 'Mage_Core_Model_Config'),
+    array('loadModulesConfiguration', 'Mage_Core_Model_Config'),
+    array('loadModules', 'Mage_Core_Model_Config'),
     array('loadParentProductIds', 'Mage_Catalog_Model_Product'),
     array('loadPrices', 'Mage_Catalog_Model_Resource_Product_Type_Configurable_Attribute'),
     array('loadProductPrices', 'Mage_Catalog_Model_Resource_Product_Attribute_Backend_Tierprice'),
+    array('load', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
     array('lockOrderInventoryData', 'Mage_CatalogInventory_Model_Observer'),
     array('logEncryptionKeySave'),
     array('logInvitationSave'),
     array('mergeFiles', 'Mage_Core_Helper_Data'),
     array('order_success_page_view', 'Mage_GoogleAnalytics_Model_Observer'),
     array('orderedAction', 'Mage_Adminhtml_Report_ProductController'),
+    array('output', 'Magento_Shell'),
+    array('pageHandleExists', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
     array('parseDateTime', 'Mage_Core_Model_Date'),
     array('postDispatchMyAccountSave'),
     array('postDispatchSystemImportExportRun'),
+    array('prepareAttributesForSave', 'Mage_ImportExport_Model_Import_Entity_Product'),
     array('prepareCacheId', 'Mage_Core_Model_App'),
     array('prepareGoogleOptimizerScripts'),
+    array('prepareRedirect', 'Mage_Core_Controller_Varien_Exception'),
     array('preprocess', 'Mage_Newsletter_Model_Template'),
     array('processBeacon'),
     array('processBeforeVoid', 'Mage_Payment_Model_Method_Abstract'),
+    array('processRequest', 'Mage_Core_Model_Cache'),
     array('processSubst', 'Mage_Core_Model_Store'),
     array('productEventAggregate'),
     array('push', 'Mage_Catalog_Model_Product_Image'),
     array('rebuildCategoryLevels', 'Mage_Catalog_Model_Resource_Setup'),
-    array('regenerateSessionId', 'Mage_Core_Model_Session_Abstract'),
     array('refundOrderItem', 'Mage_CatalogInventory_Model_Observer'),
-    array('renderView', null, 'Mage_Core_Block_Template::_toHtml()'),
+    array('regenerateSessionId', 'Mage_Core_Model_Session_Abstract'),
+    array('reinitialize', 'Magento_Test_Bootstrap', 'Magento_Test_Helper_Bootstrap::reinitialize'),
     array('removeCustomerFromSegments'),
+    array('removeHandle', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
+    array('renderView', '', 'Mage_Core_Block_Template::_toHtml()'),
     array('revalidateCookie', 'Mage_Core_Model_Session_Abstract_Varien'),
+    array('runApp', 'Magento_Test_Bootstrap', 'Magento_Test_Helper_Bootstrap::runApp'),
+    array('run', 'Mage'),
+    array('salesOrderPaymentPlaceEnd'),
     array('sales_order_afterPlace'),
     array('sales_quote_address_discount_item'),
-    array('salesOrderPaymentPlaceEnd'),
-    array('saveRow__OLD'),
     array('saveAction', 'Mage_Tag_CustomerController'),
+    array('saveCache', 'Mage_Core_Model_Config'),
+    array('saveConfig', 'Mage_Core_Model_Config'),
+    array('saveRow__OLD'),
     array('saveSegmentCustomersFromSelect'),
-    array('send', 'Mage_Newsletter_Model_Template'),
     array('sendNewPasswordEmail'),
+    array('send', 'Mage_Newsletter_Model_Template'),
     array('setAnonSuffix'),
     array('setAttributeSetExcludeFilter', 'Mage_Eav_Model_Resource_Entity_Attribute_Collection'),
     array('setBlockAlias'),
+    array('setConfig', 'Mage_Captcha_Helper_Data'),
+    array('setCurrentArea', 'Mage'),
     array('setCustomerId', 'Mage_Customer_Model_Resource_Address'),
+    array('setInstance', 'Magento_Test_Bootstrap', 'Magento_Test_Helper_Bootstrap::setInstance'),
     array('setIsAjaxRequest', 'Mage_Core_Model_Translate_Inline'),
     array('setJoinFlag', 'Mage_Tag_Model_Resource_Customer_Collection'),
     array('setJoinFlag', 'Mage_Tag_Model_Resource_Product_Collection'),
     array('setJoinFlag', 'Mage_Tag_Model_Resource_Tag_Collection'),
+    array('setNeedUsePriceExcludeTax', '', 'Mage_Tax_Model_Config::setPriceIncludesTax()'),
     array('setOption', 'Mage_Captcha_Helper_Data'),
-    array('setOrderId', 'Mage_Shipping_Block_Tracking_Popup'),
-    array('setNeedUsePriceExcludeTax', null, 'Mage_Tax_Model_Config::setPriceIncludesTax()'),
-    array('setScriptPath', 'Mage_Core_Block_Template'),
-    array('setVarSubFolders'),
-    array('setWatermarkHeigth', null, 'setWatermarkHeight'),
-    array('getWatermarkHeigth', null, 'getWatermarkHeight'),
     array('setOptions', 'Mage_Core_Model_Config'),
+    array('setOrderId', 'Mage_Shipping_Block_Tracking_Popup'),
+    array('setPackageTheme', 'Mage_Widget_Model_Widget_Instance', 'setThemeId'),
     array('setParentBlock'),
     array('setProfile', 'Varien_Convert_Container_Abstract'),
     array('setSaveTemplateFlag', 'Mage_Newsletter_Model_Queue'),
     array('setScriptPath'),
+    array('setScriptPath', 'Mage_Core_Block_Template'),
     array('setShipId', 'Mage_Shipping_Block_Tracking_Popup'),
+    array('setStore', 'Mage_Captcha_Helper_Data'),
     array('setTaxGroupFilter'),
     array('setTrackId', 'Mage_Shipping_Block_Tracking_Popup'),
-    array('shaCrypt', null, 'Mage_Ogone_Model_Api::getHash'),
-    array('shaCryptValidation', null, 'Mage_Ogone_Model_Api::getHash'),
+    array('setVarSubFolders'),
+    array('setVerbose', 'Magento_Shell'),
+    array('setWatermarkHeigth', '', 'setWatermarkHeight'),
+    array('setWebsite', 'Mage_Captcha_Helper_Data'),
+    array('shaCrypt', '', 'Mage_Ogone_Model_Api::getHash'),
+    array('shaCryptValidation', '', 'Mage_Ogone_Model_Api::getHash'),
     array('shouldCustomerHaveOneBalance'),
     array('shouldShowOneBalance'),
-    array('substDistroServerVars', 'Mage_Core_Model_Config'),
     array('sortChildren'),
+    array('substDistroServerVars', 'Mage_Core_Model_Config'),
+    array('superGroupGridOnlyAction', 'Mage_Adminhtml_Catalog_ProductController'),
     array('toOptionArray', 'Mage_Cms_Model_Resource_Page_Collection'),
     array('toOptionArray', 'Mage_Sendfriend_Model_Sendfriend'),
     array('truncate', 'Varien_Db_Adapter_Pdo_Mysql'),
@@ -378,70 +527,14 @@ return array(
     array('unsetJoinFlag', 'Mage_Tag_Model_Resource_Customer_Collection'),
     array('unsetJoinFlag', 'Mage_Tag_Model_Resource_Product_Collection'),
     array('unsetJoinFlag', 'Mage_Tag_Model_Resource_Tag_Collection'),
-    array('useValidateRemoteAddr', 'Mage_Core_Model_Session_Abstract'),
-    array('useValidateHttpVia', 'Mage_Core_Model_Session_Abstract'),
-    array('useValidateHttpXForwardedFor', 'Mage_Core_Model_Session_Abstract'),
-    array('useValidateHttpUserAgent', 'Mage_Core_Model_Session_Abstract'),
     array('updateCofigurableProductOptions', 'Mage_Weee_Model_Observer', 'updateConfigurableProductOptions'),
     array('updateTable', 'Mage_Core_Model_Resource_Setup'),
-    array('urlEscape', null, 'escapeUrl'),
+    array('urlEscape', '', 'escapeUrl'),
+    array('useValidateHttpUserAgent', 'Mage_Core_Model_Session_Abstract'),
+    array('useValidateHttpVia', 'Mage_Core_Model_Session_Abstract'),
+    array('useValidateHttpXForwardedFor', 'Mage_Core_Model_Session_Abstract'),
+    array('useValidateRemoteAddr', 'Mage_Core_Model_Session_Abstract'),
     array('validateDataArray', 'Varien_Convert_Container_Abstract'),
     array('validateFile', 'Mage_Core_Model_Design_Package'),
     array('validateOrder', 'Mage_Checkout_Model_Type_Onepage'),
-    array('prepareAttributesForSave', 'Mage_ImportExport_Model_Import_Entity_Product'),
-    array('fetchUpdatesByHandle', 'Mage_Core_Model_Resource_Layout',
-        'Mage_Core_Model_Resource_Layout_Update'),
-    array('getElementClass', 'Mage_Core_Model_Layout_Update'),
-    array('addUpdate', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
-    array('asArray', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
-    array('asString', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
-    array('addHandle', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
-    array('removeHandle', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
-    array('getHandles', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
-    array('addPageHandles', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
-    array('getPageHandleParents', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
-    array('pageHandleExists', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
-    array('getPageHandles', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
-    array('getPageHandlesHierarchy', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
-    array('getPageHandleLabel', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
-    array('getPageHandleType', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
-    array('load', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
-    array('asSimplexml', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
-    array('getFileLayoutUpdatesXml', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
-    array('getContainers', 'Mage_Core_Model_Layout_Update', 'Mage_Core_Model_Layout_Merge'),
-    array('getDataMaxSize'),
-    array('getDataMaxSizeInBytes', 'Mage_Adminhtml_Block_Media_Uploader', 'Magento_File_Size::getMaxFileSize()'),
-    array('getPostMaxSize', 'Mage_Adminhtml_Block_Media_Uploader', 'Magento_File_Size::getPostMaxSize()'),
-    array('getUploadMaxSize', 'Mage_Adminhtml_Block_Media_Uploader', 'Magento_File_Size::getUploadMaxSize()'),
-    array('_getBytesIniValue', 'Mage_Catalog_Model_Product_Option_Type_File'),
-    array('_getUploadMaxFilesize', 'Mage_Catalog_Model_Product_Option_Type_File'),
-    array('_bytesToMbytes', 'Mage_Catalog_Model_Product_Option_Type_File'),
-    array('getMaxUploadSize', 'Mage_ImportExport_Helper_Data', 'getMaxUploadSizeMessage'),
-    array('prepareRedirect', 'Mage_Core_Controller_Varien_Exception'),
-    array('getOptions', 'Mage_Core_Model_Design_Source_Design',
-        'Mage_Core_Model_Theme::getThemeCollectionOptionArray'),
-    array('getThemeOptions', 'Mage_Core_Model_Design_Source_Design',
-        'Mage_Core_Model_Theme::getThemeCollectionOptionArray'),
-    array('isThemeCompatible', 'Mage_Core_Model_Design_Package', 'Mage_Core_Model_Theme::isThemeCompatible'),
-    array('setPackageTheme', 'Mage_Widget_Model_Widget_Instance', 'setThemeId'),
-    array('getPackageTheme', 'Mage_Widget_Model_Widget_Instance', 'getThemeId'),
-    array('getPackage', 'Mage_Widget_Model_Widget_Instance'),
-    array('getTheme', 'Mage_Widget_Model_Widget_Instance'),
-    array('_parsePackageTheme', 'Mage_Widget_Model_Widget_Instance'),
-    array('isVerbose', 'Magento_Shell'),
-    array('setVerbose', 'Magento_Shell'),
-    array('output', 'Magento_Shell'),
-    array('getHeaderText', 'Mage_Bundle_Block_Adminhtml_Catalog_Product_Edit_Tab_Bundle_Option_Search'),
-    array('getButtonsHtml', 'Mage_Bundle_Block_Adminhtml_Catalog_Product_Edit_Tab_Bundle_Option_Search'),
-    array('getHeaderCssClass', 'Mage_Bundle_Block_Adminhtml_Catalog_Product_Edit_Tab_Bundle_Option_Search'),
-    array('superGroupGridOnlyAction', 'Mage_Adminhtml_Catalog_ProductController'),
-    array('getInstance', 'Magento_Test_Bootstrap', 'Magento_Test_Helper_Bootstrap::getInstance'),
-    array('setInstance', 'Magento_Test_Bootstrap', 'Magento_Test_Helper_Bootstrap::setInstance'),
-    array('canTestHeaders', 'Magento_Test_Bootstrap', 'Magento_Test_Helper_Bootstrap::canTestHeaders'),
-    array('getInstallDir', 'Magento_Test_Bootstrap', 'Magento_Test_Helper_Bootstrap::getAppInstallDir'),
-    array('getInitParams', 'Magento_Test_Bootstrap', 'Magento_Test_Helper_Bootstrap::getAppInitParams'),
-    array('getDbVendorName', 'Magento_Test_Bootstrap', 'Magento_Test_Helper_Bootstrap::getDbVendorName'),
-    array('reinitialize', 'Magento_Test_Bootstrap', 'Magento_Test_Helper_Bootstrap::reinitialize'),
-    array('runApp', 'Magento_Test_Bootstrap', 'Magento_Test_Helper_Bootstrap::runApp'),
-    array('getTestsDir', 'Magento_Test_Bootstrap'),
 );
diff --git a/dev/tests/static/testsuite/Php/_files/blacklist/common.txt b/dev/tests/static/testsuite/Php/_files/blacklist/common.txt
index 2bb6727ca99c455aabb7cc873f20d805cc681633..7f40f50ee039f048484d1261037c63c1ca22489e 100644
--- a/dev/tests/static/testsuite/Php/_files/blacklist/common.txt
+++ b/dev/tests/static/testsuite/Php/_files/blacklist/common.txt
@@ -7,6 +7,8 @@ app/code/core/Mage/Backend/Model/Config/Structure/Converter.php
 app/code/core/Mage/Backend/Model/Menu/Config.php
 app/code/core/Mage/Backend/Block/Widget/Grid
 app/code/core/Mage/Backend/view
+app/code/core/Mage/Core/Model/Config/Data
+app/code/core/Mage/Core/Model/Config/Element.php
 app/code/core/Mage/DesignEditor/view
 app/code/core/Mage/Webapi/view
 app/code/core/Mage/User/view
diff --git a/dev/tests/static/testsuite/Php/_files/phpcpd/blacklist/common.txt b/dev/tests/static/testsuite/Php/_files/phpcpd/blacklist/common.txt
index 2a4d791afd8f4cf48e634118bd7ef402f0163850..f198be89ef27a8144dd32abfe0fb821de5197a9c 100644
--- a/dev/tests/static/testsuite/Php/_files/phpcpd/blacklist/common.txt
+++ b/dev/tests/static/testsuite/Php/_files/phpcpd/blacklist/common.txt
@@ -37,6 +37,7 @@ Mage/Tag/Model/Resource
 Mage/Catalog/Model/Resource/Product
 Mage/Core/Model/Store
 Mage/Cron/Model/Config/Backend/Product
+Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code
 Mage/DesignEditor/Block/Adminhtml/Theme/Selector/Tab
 Mage/DesignEditor/Model/Url
 Mage/GiftMessage/Block/Adminhtml/Sales/Order
diff --git a/dev/tests/static/testsuite/Php/_files/whitelist/common.txt b/dev/tests/static/testsuite/Php/_files/whitelist/common.txt
index 4e57ef633d64a719cbc404c61acd7cd8e549760b..a642890bb799cf506f196c93b8250dcdd5c46a0f 100644
--- a/dev/tests/static/testsuite/Php/_files/whitelist/common.txt
+++ b/dev/tests/static/testsuite/Php/_files/whitelist/common.txt
@@ -20,7 +20,9 @@ app/code/core/Mage/Adminhtml/controllers/UrlrewriteController.php
 app/code/core/Mage/Backend
 app/code/core/Mage/Catalog/Block/Product/Configurable
 app/code/core/Mage/Catalog/Block/Product/Grouped
+app/code/core/Mage/Catalog/Block/Product/TemplateSelector.php
 app/code/core/Mage/Catalog/Model/Resource/Product/Collection
+app/code/core/Mage/Catalog/Model/Product/Type.php
 app/code/core/Mage/CatalogInventory/Block/Adminhtml/Form/Field/Stock.php
 app/code/core/Mage/Centinel/Model/State/Jcb.php
 app/code/core/Mage/Cms/Controller/Router.php
@@ -32,18 +34,20 @@ app/code/core/Mage/Core/Controller/Varien/Action/Forward.php
 app/code/core/Mage/Core/Controller/Varien/DispatchableInterface.php
 app/code/core/Mage/Core/Controller/Varien/Router/Abstract.php
 app/code/core/Mage/Core/data
-app/code/core/Mage/Core/Model/Config.php
-app/code/core/Mage/Core/Model/Config/Module.php
+app/code/core/Mage/Core/Model/Abstract.php
+app/code/core/Mage/Core/Model/Config
 app/code/core/Mage/Core/Model/Design.php
 app/code/core/Mage/Core/Model/Design/Fallback
 app/code/core/Mage/Core/Model/Design/Fallback.php
 app/code/core/Mage/Core/Model/Design/FallbackInterface.php
 app/code/core/Mage/Core/Model/Design/Source/Design.php
 app/code/core/Mage/Core/Model/Dir.php
+app/code/core/Mage/Core/Model/EntryPoint
 app/code/core/Mage/Core/Model/Layout.php
 app/code/core/Mage/Core/Model/Layout/Factory.php
 app/code/core/Mage/Core/Model/Layout/Update.php
 app/code/core/Mage/Core/Model/Layout/Argument
+app/code/core/Mage/Core/Model/ObjectManager
 app/code/core/Mage/Core/Model/Resource/Setup/Migration.php
 app/code/core/Mage/Core/Model/Resource/Theme/Collection.php
 app/code/core/Mage/Core/Model/Resource/Theme.php
diff --git a/dev/tests/unit/framework/bootstrap.php b/dev/tests/unit/framework/bootstrap.php
index 30be5acff37dca3492c3394a670579ebbc830319..849c877f430f3346d359461d7d53bae772e5ad19 100755
--- a/dev/tests/unit/framework/bootstrap.php
+++ b/dev/tests/unit/framework/bootstrap.php
@@ -35,6 +35,7 @@ Magento_Autoload_IncludePath::addIncludePath(array(
 ));
 
 define('TESTS_TEMP_DIR', dirname(__DIR__) . DIRECTORY_SEPARATOR . 'tmp');
+define('DS', DIRECTORY_SEPARATOR);
 if (is_dir(TESTS_TEMP_DIR)) {
     Varien_Io_File::rmdirRecursive(TESTS_TEMP_DIR);
 }
diff --git a/dev/tests/unit/testsuite/Mage/Adminhtml/Block/Catalog/Product/Edit/NewCategoryTest.php b/dev/tests/unit/testsuite/Mage/Adminhtml/Block/Catalog/Product/Edit/NewCategoryTest.php
deleted file mode 100644
index 1bf0abaf4306972419b0ef41defa4175f4cb9a8b..0000000000000000000000000000000000000000
--- a/dev/tests/unit/testsuite/Mage/Adminhtml/Block/Catalog/Product/Edit/NewCategoryTest.php
+++ /dev/null
@@ -1,79 +0,0 @@
-<?php
-/**
- * Magento
- *
- * NOTICE OF LICENSE
- *
- * This source file is subject to the Open Software License (OSL 3.0)
- * that is bundled with this package in the file LICENSE.txt.
- * It is also available through the world-wide-web at this URL:
- * http://opensource.org/licenses/osl-3.0.php
- * If you did not receive a copy of the license and are unable to
- * obtain it through the world-wide-web, please send an email
- * to license@magentocommerce.com so we can send you a copy immediately.
- *
- * DISCLAIMER
- *
- * Do not edit or add to this file if you wish to upgrade Magento to newer
- * versions in the future. If you wish to customize Magento for your
- * needs please refer to http://www.magentocommerce.com for more information.
- *
- * @category    Magento
- * @package     Mage_Adminhtml
- * @subpackage  unit_tests
- * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
- * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
- */
-
-class Mage_Adminhtml_Block_Catalog_Product_Edit_NewCategoryTest extends PHPUnit_Framework_TestCase
-{
-    /** @var Mage_Adminhtml_Block_Catalog_Product_Edit_NewCategory */
-    protected $_object;
-
-    /** @var Mage_Core_Model_Url|PHPUnit_Framework_MockObject_MockObject */
-    protected $_urlModel;
-
-    protected function setUp()
-    {
-        $objectManager = new Magento_Test_Helper_ObjectManager($this);
-
-        $this->_urlModel = $this->getMock('Mage_Backend_Model_Url', array('getUrl'), array(), '', false);
-        $this->_object = $objectManager->getBlock('Mage_Adminhtml_Block_Catalog_Product_Edit_NewCategory', array(
-            'urlBuilder' => $this->_urlModel,
-        ));
-    }
-
-    /**
-     * @covers Mage_Adminhtml_Block_Catalog_Product_Edit_NewCategory::getSaveCategoryUrl
-     * @covers Mage_Adminhtml_Block_Catalog_Product_Edit_NewCategory::getSuggestCategoryUrl
-     * @dataProvider urlMethodsDataProvider
-     * @param string $expectedUrl
-     * @param string $executedMethod
-     */
-    public function testGetUrlMethods($expectedUrl, $executedMethod)
-    {
-        $this->_urlModel->expects($this->once())
-            ->method('getUrl')
-            ->with($expectedUrl)
-            ->will($this->returnCallback(
-                function ($string) {
-                    return strrev($string);
-                }
-            ));
-        $this->assertEquals(
-            strrev($expectedUrl),
-            call_user_func_array(array($this->_object, $executedMethod), array($expectedUrl))
-        );
-    }
-
-    /**
-     * @return array
-     */
-    public static function urlMethodsDataProvider()
-    {
-        return array(
-            array('*/catalog_category/save', 'getSaveCategoryUrl'),
-            array('*/catalog_category/suggestCategories', 'getSuggestCategoryUrl'),
-        );
-    }
-}
diff --git a/dev/tests/unit/testsuite/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/BaseImageTest.php b/dev/tests/unit/testsuite/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/BaseImageTest.php
deleted file mode 100644
index d9428e4af9e6b078bc5cd5147b78d9d5dbc29fba..0000000000000000000000000000000000000000
--- a/dev/tests/unit/testsuite/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/BaseImageTest.php
+++ /dev/null
@@ -1,161 +0,0 @@
-<?php
-/**
- * Magento
- *
- * NOTICE OF LICENSE
- *
- * This source file is subject to the Open Software License (OSL 3.0)
- * that is bundled with this package in the file LICENSE.txt.
- * It is also available through the world-wide-web at this URL:
- * http://opensource.org/licenses/osl-3.0.php
- * If you did not receive a copy of the license and are unable to
- * obtain it through the world-wide-web, please send an email
- * to license@magentocommerce.com so we can send you a copy immediately.
- *
- * DISCLAIMER
- *
- * Do not edit or add to this file if you wish to upgrade Magento to newer
- * versions in the future. If you wish to customize Magento for your
- * needs please refer to http://www.magentocommerce.com for more information.
- *
- * @category    Magento
- * @package     Mage_Adminhtml
- * @subpackage  unit_tests
- * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
- * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
- */
-
-class Mage_Adminhtml_Block_Catalog_Product_Helper_Form_BaseImageTest extends PHPUnit_Framework_TestCase
-{
-    /**
-     * Object under test
-     *
-     * @var Mage_Adminhtml_Block_Catalog_Product_Helper_Form_BaseImage
-     */
-    protected $_block;
-
-    /**
-     * @var Mage_Backend_Model_Url|PHPUnit_Framework_MockObject_MockObject
-     */
-    protected $_url;
-
-    /**
-     * @var Mage_Core_Helper_Data|PHPUnit_Framework_MockObject_MockObject
-     */
-    protected $_coreHelper;
-
-    /**
-     * @var Mage_Catalog_Helper_Data|PHPUnit_Framework_MockObject_MockObject
-     */
-    protected $_catalogHelperData;
-
-    protected function setUp()
-    {
-        $mediaUploader = $this->getMockBuilder('Mage_Adminhtml_Block_Media_Uploader')->disableOriginalConstructor()
-            ->setMethods(array('getDataMaxSizeInBytes'))->getMock();
-        $mediaUploader->expects($this->once())->method('getDataMaxSizeInBytes')->will($this->returnValue('999'));
-        $this->_url = $this->getMock('Mage_Backend_Model_Url', array('getUrl'), array(), '', false);
-        $this->_url->expects($this->once())->method('getUrl')
-            ->will($this->returnValue('http://example.com/pub/images/catalog_product_gallery/upload/'));
-
-        $jsonEncode = function ($value) {
-            return json_encode($value);
-        };
-
-        $this->_coreHelper = $this->getMockBuilder('Mage_Core_Helper_Data')->disableOriginalConstructor()
-            ->setMethods(array('escapeHtml', 'jsonEncode'))->getMock();
-        $this->_coreHelper->expects($this->any())->method('jsonEncode')->will($this->returnCallback($jsonEncode));
-        $this->_catalogHelperData = $this->getMockBuilder('Mage_Catalog_Helper_Data')->disableOriginalConstructor()
-            ->setMethods(array('__'))->getMock();
-        $this->_catalogHelperData->expects($this->any())->method('__')->will($this->returnCallback('json_encode'));
-        $form = $this->getMockBuilder('Varien_Data_Form')->disableOriginalConstructor()
-            ->setMethods(null)->getMock();
-        $product = $this->getMockBuilder('Mage_Catalog_Model_Product')->disableOriginalConstructor()
-            ->setMethods(array('getMediaGalleryImages'))->getMock();
-        $form->setDataObject($product);
-
-        $this->_block = new Mage_Adminhtml_Block_Catalog_Product_Helper_Form_BaseImage(array(
-            'name' => 'image',
-            'label' => 'Base Image',
-            'mediaUploader' => $mediaUploader,
-            'url' => $this->_url,
-            'coreHelper' => $this->_coreHelper,
-            'catalogHelperData' => $this->_catalogHelperData,
-        ));
-        $this->_block->setForm($form);
-        $this->_block->setHtmlId('image');
-    }
-
-    /**
-     * Test to get valid html code for 'image' attribute
-     *
-     * @param mixed $imageValue
-     * @param string $urlPath
-     * @dataProvider validateImageUrlDataProvider
-     */
-    public function testGetElementHtml($imageValue, $urlPath)
-    {
-        $this->markTestIncomplete('Test should be rewritten as part of MAGETWO-4611');
-        $this->_block->setValue($imageValue);
-        $this->_coreHelper->expects($this->any())->method('escapeHtml')->will($this->returnArgument(0));
-        $html = $this->_createHtmlCode($imageValue, $urlPath);
-
-        $this->assertXmlStringEqualsXmlString(
-            str_replace('&times;', '&amp;times;', "<test>{$html}</test>"),
-            str_replace('&times;', '&amp;times;', "<test>{$this->_block->getElementHtml()}</test>"),
-            'Another BaseImage html code is expected'
-        );
-    }
-
-    /**
-     * @return array
-     */
-    public function validateImageUrlDataProvider()
-    {
-        return array(
-            array(
-                '/f/i/file_666.png',
-                'http://example.com/pub/media/tmp/catalog/product/f/i/file_78.png'
-            ),
-            array(
-                '/f/i/file_666.png.tmp',
-                'http://example.com/pub/images/image-placeholder.png'
-            )
-        );
-    }
-
-    /**
-     * Test to get valid html code for 'image' with placeholder
-     */
-    public function testImagePlaceholder()
-    {
-        $this->markTestIncomplete('Test should be rewritten as part of MAGETWO-4611');
-        $urlPath = 'http://example.com/pub/images/image-placeholder.png';
-        $this->_block->setValue(null);
-        $this->_coreHelper->expects($this->any())->method('escapeHtml')->will($this->returnArgument(0));
-        $html = $this->_createHtmlCode('', $urlPath);
-        $this->assertXmlStringEqualsXmlString(
-            str_replace('&times;', '&amp;times;', "<test>{$html}</test>"),
-            str_replace('&times;', '&amp;times;', "<test>{$this->_block->getElementHtml()}</test>"),
-            'Another BaseImage html code is expected'
-        );
-    }
-
-    /**
-     * Create html code for expected result
-     *
-     * @param string $imageValue
-     * @param string $urlPath
-     *
-     * @return string
-     */
-    protected function _createHtmlCode($imageValue, $urlPath)
-    {
-        $uploadImage = 'http://example.com/pub/images/catalog_product_gallery/upload/';
-        return str_replace(
-            array('%htmlId%', '%imageValue%', '%uploadImage%', '%imageUrl%'),
-            array($this->_block->getHtmlId(), $imageValue, $uploadImage, $urlPath),
-            file_get_contents(__DIR__ . '/_files/BaseImageHtml.txt')
-        );
-    }
-}
diff --git a/dev/tests/unit/testsuite/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Weight/RendererTest.php b/dev/tests/unit/testsuite/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Weight/RendererTest.php
index d8bd5b0114cd40e75e1d401169cf09e319d95d2c..3b69af28e7e7d59cc5dfa526b3864fc7d3958ecb 100644
--- a/dev/tests/unit/testsuite/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Weight/RendererTest.php
+++ b/dev/tests/unit/testsuite/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Weight/RendererTest.php
@@ -43,7 +43,9 @@ class Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Weight_RendererTest exten
     {
         $this->_virtual = new Varien_Object();
 
-        $helper = $this->getMock('Mage_Catalog_Helper_Product', array('getTypeSwitcherControlLabel'));
+        $helper = $this->getMock('Mage_Catalog_Helper_Product', array('getTypeSwitcherControlLabel'),
+            array(), '', false, false
+        );
         $helper->expects($this->any())->method('getTypeSwitcherControlLabel')
             ->will($this->returnValue('Virtual / Downloadable'));
 
diff --git a/dev/tests/unit/testsuite/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/_files/BaseImageHtml.txt b/dev/tests/unit/testsuite/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/_files/BaseImageHtml.txt
deleted file mode 100644
index 1264294877f7a504a57d2bf931f65628fcfa736b..0000000000000000000000000000000000000000
--- a/dev/tests/unit/testsuite/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/_files/BaseImageHtml.txt
+++ /dev/null
@@ -1,16 +0,0 @@
-<input id="%htmlId%-upload" type="file" name="image" data-url="%uploadImage%" style="display:none" />
-<input id="%htmlId%" type="hidden" name="%htmlId%" />
-<div id="%htmlId%-container" data-main="%imageValue%" data-images="[]">
-    <span id="%htmlId%-upload-placeholder"></span>
-    <script id="%htmlId%-template" type="text/x-jquery-tmpl">
-        <span class="container">
-            <span class="main-sticker">"Main"</span>
-            <span class="close">&amp;times;</span>
-            <img class="base-image-uploader" src="${url}" data-position="${position}" alt="${label}" />
-            <div class="drag-zone">
-                <button class="make-main" type="button">"Make Main"</button>
-            </div>
-        </span>
-    </script>
-</div>
-<script>/* <![CDATA[ */jQuery(function(){BaseImageUploader("%htmlId%", "999"); });/*]]>*/</script>
diff --git a/dev/tests/unit/testsuite/Mage/Adminhtml/Block/Page/System/Config/Robots/ResetTest.php b/dev/tests/unit/testsuite/Mage/Adminhtml/Block/Page/System/Config/Robots/ResetTest.php
index 3a80d1fa351d71608ab210e9bfdaef68fd9809d4..0864af404d6a990c75dab3fc7d25d1e1134524d8 100644
--- a/dev/tests/unit/testsuite/Mage/Adminhtml/Block/Page/System/Config/Robots/ResetTest.php
+++ b/dev/tests/unit/testsuite/Mage/Adminhtml/Block/Page/System/Config/Robots/ResetTest.php
@@ -50,9 +50,9 @@ class Mage_Adminhtml_Block_Page_System_Config_Robots_ResetTest extends PHPUnit_F
                 'urlBuilder' => $this->getMock('Mage_Backend_Model_Url', array(), array(), '', false)
             )
         );
-        $this->_mockRobotsHelper = $this->getMockBuilder('Mage_Page_Helper_Robots')
-            ->setMethods(array('getRobotsDefaultCustomInstructions'))
-            ->getMock();
+        $this->_mockRobotsHelper = $this->getMock('Mage_Page_Helper_Robots',
+            array('getRobotsDefaultCustomInstructions'), array(), '', false, false
+        );
         Mage::register('_helper/Mage_Page_Helper_Robots', $this->_mockRobotsHelper);
     }
 
diff --git a/dev/tests/unit/testsuite/Mage/Adminhtml/DashboardControllerTest.php b/dev/tests/unit/testsuite/Mage/Adminhtml/DashboardControllerTest.php
index 8d5e93da46edfe5029afc5812bdf7f62ad9b0fb9..bd52faef9db657caf46814a3705951d3ca75f6ec 100644
--- a/dev/tests/unit/testsuite/Mage/Adminhtml/DashboardControllerTest.php
+++ b/dev/tests/unit/testsuite/Mage/Adminhtml/DashboardControllerTest.php
@@ -35,7 +35,9 @@ class Mage_Adminhtml_DashboardControllerTest extends PHPUnit_Framework_TestCase
         $httpClient = $this->getMock('Varien_Http_Client', array('request'));
         $httpClient->expects($this->once())->method('request')->will($this->returnValue($tunnelResponse));
         /** @var $helper Mage_Adminhtml_Helper_Dashboard_Data|PHPUnit_Framework_MockObject_MockObject */
-        $helper = $this->getMock('Mage_Adminhtml_Helper_Dashboard_Data', array('getChartDataHash'));
+        $helper = $this->getMock('Mage_Adminhtml_Helper_Dashboard_Data',
+            array('getChartDataHash'), array(), '', false, false
+        );
         $helper->expects($this->any())->method('getChartDataHash')->will($this->returnValue($fixture));
 
         $objectManager = $this->getMock('Magento_ObjectManager_Zend', array('create', 'get'));
@@ -69,7 +71,9 @@ class Mage_Adminhtml_DashboardControllerTest extends PHPUnit_Framework_TestCase
         $request->setParam('h', $fixture);
 
         /** @var $helper Mage_Adminhtml_Helper_Dashboard_Data|PHPUnit_Framework_MockObject_MockObject */
-        $helper = $this->getMock('Mage_Adminhtml_Helper_Dashboard_Data', array('getChartDataHash'));
+        $helper = $this->getMock('Mage_Adminhtml_Helper_Dashboard_Data',
+            array('getChartDataHash'), array(), '', false, false
+        );
         $helper->expects($this->any())->method('getChartDataHash')->will($this->returnValue($fixture));
 
         $objectManager = $this->getMock('Magento_ObjectManager_Zend', array('create', 'get'));
@@ -119,8 +123,8 @@ class Mage_Adminhtml_DashboardControllerTest extends PHPUnit_Framework_TestCase
         $layoutFactory = $this->getMock('Mage_Core_Model_Layout_Factory', array(), array(), '', false);
 
         return $this->getMock('Mage_Adminhtml_DashboardController', array('__'), array(
-            $request, $response, null, $objectManager,
-            $varienFront, $layoutFactory,
+            $request, $response, $objectManager,
+            $varienFront, $layoutFactory, null,
             array('helper' => 1, 'session' => 1, 'translator' => 1)
         ));
     }
diff --git a/dev/tests/unit/testsuite/Mage/Backend/Block/Widget/ButtonTest.php b/dev/tests/unit/testsuite/Mage/Backend/Block/Widget/ButtonTest.php
index 2374325752e56f8a6430ace3cc9f72901119e56f..6fcb8caf1426bbb2b73cc6bfb55b18a8dd7422c2 100644
--- a/dev/tests/unit/testsuite/Mage/Backend/Block/Widget/ButtonTest.php
+++ b/dev/tests/unit/testsuite/Mage/Backend/Block/Widget/ButtonTest.php
@@ -45,33 +45,32 @@ class Mage_Backend_Block_Widget_ButtonTest extends PHPUnit_Framework_TestCase
      */
     protected $_factoryMock;
 
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_blockMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_buttonMock;
+
     protected function setUp()
     {
         $this->_helperMock =
-            $this->getMock('Mage_Backend_Helper_Data', array(), array(), '', false);
+            $this->getMock('Mage_Backend_Helper_Data', array('uniqHash'), array(), '', false, false);
 
         $this->_layoutMock =
-            $this->getMock('Mage_Core_Model_Layout', array(), array(), '', false);
+            $this->getMock('Mage_Core_Model_Layout', array(), array(), '', false, false);
         $this->_layoutMock
             ->expects($this->any())
             ->method('helper')
             ->will($this->returnValue($this->_helperMock));
 
-        $coreHelperMock = $this->getMockBuilder('Mage_Core_Helper_Data')->disableOriginalConstructor()->getMock();
-
-        $helperFactoryMock = $this->getMockBuilder('Mage_Core_Model_Factory_Helper')
-            ->disableOriginalConstructor()->getMock();
-
-        $helperFactoryMock->expects($this->any())
-            ->method('get')
-            ->with('Mage_Core_Helper_Data')
-            ->will($this->returnValue($coreHelperMock));
-
         $arguments = array(
             'urlBuilder' =>
-                $this->getMock('Mage_Backend_Model_Url', array(), array(), '', false),
-            'layout' => $this->_layoutMock,
-            'helperFactory' => $helperFactoryMock
+                $this->getMock('Mage_Backend_Model_Url', array(), array(), '', false, false),
+            'layout' => $this->_layoutMock
         );
 
         $objectManagerHelper = new Magento_Test_Helper_ObjectManager($this);
diff --git a/dev/tests/unit/testsuite/Mage/Backend/Helper/DataTest.php b/dev/tests/unit/testsuite/Mage/Backend/Helper/DataTest.php
index 30112fa7dd48d431871a4ed1996886b48a9c88cd..fccbc93f0353fc780555e7cc8c197090911d147a 100644
--- a/dev/tests/unit/testsuite/Mage/Backend/Helper/DataTest.php
+++ b/dev/tests/unit/testsuite/Mage/Backend/Helper/DataTest.php
@@ -39,8 +39,10 @@ class Mage_Backend_Helper_DataTest extends PHPUnit_Framework_TestCase
 
     public function setUp()
     {
-        $this->_configMock = $this->getMock('Mage_Core_Model_Config', array(), array(), '', false);
-        $this->_helper = new Mage_Backend_Helper_Data($this->_configMock);
+        $this->_configMock = $this->getMock('Mage_Core_Model_Config', array(), array(), '', false, false);
+        $this->_helper = new Mage_Backend_Helper_Data($this->_configMock,
+            $this->getMock('Mage_Core_Model_Translate', array(), array(), '', false, false)
+        );
     }
 
     public function testGetAreaFrontNameReturnsDefaultValueWhenCustomNotSet()
diff --git a/dev/tests/unit/testsuite/Mage/Backend/Model/Acl/ConfigTest.php b/dev/tests/unit/testsuite/Mage/Backend/Model/Acl/ConfigTest.php
index 7ecfddff6908ca1616aa4259041a0b3983b3959c..8317f58f9c75b0e288d4ba08117a1fac44bfff35 100644
--- a/dev/tests/unit/testsuite/Mage/Backend/Model/Acl/ConfigTest.php
+++ b/dev/tests/unit/testsuite/Mage/Backend/Model/Acl/ConfigTest.php
@@ -53,10 +53,9 @@ class Mage_Backend_Model_Acl_ConfigTest extends PHPUnit_Framework_TestCase
         $this->_configMock = $this->getMock('Mage_Core_Model_Config', array(), array(), '', false);
         $this->_cacheMock  = $this->getMock('Mage_Core_Model_Cache', array(), array(), '', false);
 
-        $this->_model = new Mage_Backend_Model_Acl_Config(array(
-            'config' => $this->_configMock,
-            'cache'  => $this->_cacheMock
-        ));
+        $this->_model = new Mage_Backend_Model_Acl_Config($this->_configMock, $this->_cacheMock,
+            $this->getMock('Mage_Core_Model_Config_Modules_Reader', array(), array(), '', false, false)
+        );
     }
 
     public function testGetAclResourcesWhenCacheLoadCorruptedValue()
diff --git a/dev/tests/unit/testsuite/Mage/Backend/Model/Config/Structure/ReaderTest.php b/dev/tests/unit/testsuite/Mage/Backend/Model/Config/Structure/ReaderTest.php
index fd5e3505f85ea305264b4aaae857df325520e6a4..b556a0e8b72a0e8b8cc48ff8dffab1d00abcc395 100644
--- a/dev/tests/unit/testsuite/Mage/Backend/Model/Config/Structure/ReaderTest.php
+++ b/dev/tests/unit/testsuite/Mage/Backend/Model/Config/Structure/ReaderTest.php
@@ -35,7 +35,7 @@ class Mage_Backend_Model_Config_Structure_ReaderTest extends PHPUnit_Framework_T
     /**
      * @var PHPUnit_Framework_MockObject_MockObject
      */
-    protected $_appConfigMock;
+    protected $_configMock;
 
     /**
      * @var PHPUnit_Framework_MockObject_MockObject
@@ -49,7 +49,7 @@ class Mage_Backend_Model_Config_Structure_ReaderTest extends PHPUnit_Framework_T
 
     public function setUp()
     {
-        $this->_appConfigMock = $this->getMock('Mage_Core_Model_Config', array(), array(), '', false);
+        $this->_configMock = $this->getMock('Mage_Core_Model_Config_Modules_Reader', array(), array(), '', false);
         $this->_cacheMock = $this->getMock('Mage_Core_Model_Cache', array(), array(), '', false);
         $this->_cacheMock->expects($this->any())->method('canUse')->will($this->returnValue(true));
         $this->_converterMock = $this->getMock(
@@ -68,7 +68,7 @@ class Mage_Backend_Model_Config_Structure_ReaderTest extends PHPUnit_Framework_T
             ->will($this->returnValue($cachedData));
 
         $model = new Mage_Backend_Model_Config_Structure_Reader(
-            $this->_appConfigMock, $this->_cacheMock, $this->_converterMock
+            $this->_cacheMock, $this->_configMock, $this->_converterMock
         );
         $this->assertEquals($cachedObject, $model->getData());
     }
@@ -82,7 +82,7 @@ class Mage_Backend_Model_Config_Structure_ReaderTest extends PHPUnit_Framework_T
             array('config' => array('system' => $expected))
         ));
         $filePath = dirname(dirname(__DIR__)) . '/_files';
-        $this->_appConfigMock->expects($this->once())
+        $this->_configMock->expects($this->once())
             ->method('getModuleConfigurationFiles')
             ->will($this->returnValue(array($filePath . '/system_2.xml')));
 
@@ -91,7 +91,7 @@ class Mage_Backend_Model_Config_Structure_ReaderTest extends PHPUnit_Framework_T
         );
 
         $model = new Mage_Backend_Model_Config_Structure_Reader(
-            $this->_appConfigMock, $this->_cacheMock, $this->_converterMock, false
+            $this->_cacheMock, $this->_configMock, $this->_converterMock, false
         );
         $this->assertEquals($expected, $model->getData());
     }
diff --git a/dev/tests/unit/testsuite/Mage/Backend/Model/Menu/ConfigTest.php b/dev/tests/unit/testsuite/Mage/Backend/Model/Menu/ConfigTest.php
index fedf0d08028f22ab59352e655cce4f312f921af6..bd86e1b0fa81949002736831828479a19bf48d7f 100644
--- a/dev/tests/unit/testsuite/Mage/Backend/Model/Menu/ConfigTest.php
+++ b/dev/tests/unit/testsuite/Mage/Backend/Model/Menu/ConfigTest.php
@@ -29,9 +29,9 @@
 class Mage_Backend_Model_Menu_ConfigTest extends PHPUnit_Framework_TestCase
 {
     /**
-     * @var Mage_Core_ModeL_Config
+     * @var Mage_Core_Model_Config_Modules_Reader
      */
-    protected $_appConfigMock;
+    protected $_configMock;
 
     /**
      * @var Mage_Core_Model_Cache
@@ -95,7 +95,9 @@ class Mage_Backend_Model_Menu_ConfigTest extends PHPUnit_Framework_TestCase
 
     public function setUp()
     {
-        $this->_appConfigMock = $this->getMock('Mage_Core_Model_Config', array(), array(), '', false);
+        $this->_configMock = $this->getMock('Mage_Core_Model_Config_Modules_Reader',
+            array(), array(), '', false, false
+        );
 
         $this->_objectManagerMock = $this->getMock(
             'Magento_ObjectManager_Zend', array('create', 'get'), array(), '', false
@@ -117,7 +119,7 @@ class Mage_Backend_Model_Menu_ConfigTest extends PHPUnit_Framework_TestCase
 
         $this->_domDocumentMock = $this->getMock('DOMDocument', array(), array(), '', false);
 
-        $this->_eventManagerMock = $this->getMock('Mage_Core_Model_Event_Manager');
+        $this->_eventManagerMock = $this->getMock('Mage_Core_Model_Event_Manager', array(), array(), '', false, false);
 
         $this->_logger = $this->getMock(
             'Mage_Core_Model_Logger', array('addStoreLog', 'log', 'logException'), array(), '', false
@@ -134,7 +136,7 @@ class Mage_Backend_Model_Menu_ConfigTest extends PHPUnit_Framework_TestCase
         $this->_model = new Mage_Backend_Model_Menu_Config(
             $this->_cacheInstanceMock,
             $this->_objectManagerMock,
-            $this->_appConfigMock,
+            $this->_configMock,
             $this->_eventManagerMock,
             $this->_logger,
             $this->_menuFactoryMock
@@ -143,7 +145,7 @@ class Mage_Backend_Model_Menu_ConfigTest extends PHPUnit_Framework_TestCase
 
     public function testGetMenuConfigurationFiles()
     {
-        $this->_appConfigMock->expects($this->any())
+        $this->_configMock->expects($this->any())
             ->method('getModuleConfigurationFiles')
             ->will($this->returnValue(array(
                 realpath(__DIR__) . '/../_files/menu_1.xml',
@@ -269,7 +271,7 @@ class Mage_Backend_Model_Menu_ConfigTest extends PHPUnit_Framework_TestCase
     {
         $xmlString = '<?xml version="1.0" encoding="utf-8"?><config><menu></menu></config>';
 
-        $this->_appConfigMock->expects($this->any())
+        $this->_configMock->expects($this->any())
             ->method('getModelInstance')
             ->will($this->returnCallback(array($this, 'getModelInstance')));
 
diff --git a/dev/tests/unit/testsuite/Mage/Backend/Model/Menu/Item/FactoryTest.php b/dev/tests/unit/testsuite/Mage/Backend/Model/Menu/Item/FactoryTest.php
index 202df95a9e0929f8283e3598f31abd0069d0b6b9..968fa189dc5acfd92d6cc73f1c8317d1345fadb2 100644
--- a/dev/tests/unit/testsuite/Mage/Backend/Model/Menu/Item/FactoryTest.php
+++ b/dev/tests/unit/testsuite/Mage/Backend/Model/Menu/Item/FactoryTest.php
@@ -86,7 +86,7 @@ class Mage_Backend_Model_Menu_Item_FactoryTest extends PHPUnit_Framework_TestCas
         $this->_factoryMock = $this->getMock('Mage_Backend_Model_Menu_Factory', array(), array(), '', false);
         $this->_helpers = array(
             'Mage_Backend_Helper_Data' => $this->getMock('Mage_Backend_Helper_Data', array(), array(), '', false),
-            'Mage_User_Helper_Data' => $this->getMock('Mage_User_Helper_Data')
+            'Mage_User_Helper_Data' => $this->getMock('Mage_User_Helper_Data', array(), array(), '', false)
         );
         $this->_urlModelMock = $this->getMock("Mage_Backend_Model_Url", array(), array(), '', false);
         $this->_appConfigMock = $this->getMock('Mage_Core_Model_Config', array(), array(), '', false);
diff --git a/dev/tests/unit/testsuite/Mage/Backend/controllers/Adminhtml/System/Config/SaveControllerTest.php b/dev/tests/unit/testsuite/Mage/Backend/controllers/Adminhtml/System/Config/SaveControllerTest.php
index 21420c2098b80e8cf1093c218041102108646840..41357bc575912d52bfca32aca6c4ff07e7d4797c 100644
--- a/dev/tests/unit/testsuite/Mage/Backend/controllers/Adminhtml/System/Config/SaveControllerTest.php
+++ b/dev/tests/unit/testsuite/Mage/Backend/controllers/Adminhtml/System/Config/SaveControllerTest.php
@@ -123,23 +123,27 @@ class Mage_Backend_Adminhtml_System_Config_SaveControllerTest extends PHPUnit_Fr
         $helperMock->expects($this->any())->method('getUrl')->will($this->returnArgument(0));
         $responseMock->expects($this->once())->method('setRedirect')->with('*/system_config/edit');
 
-        $this->_controller = new Mage_Backend_Adminhtml_System_Config_SaveController($this->_requestMock,
-            $responseMock,
-            null,
-            $objectManagerMock,
-            $frontControllerMock,
-            $authorizationMock,
-            $configStructureMock,
-            $this->_configMock,
-            $this->_configFactoryMock,
-            $this->_eventManagerMock,
-            $this->_appMock,
-            $this->_authMock,
-            $this->_layoutMock,
+        $this->_controller = $this->getMock(
+            'Mage_Backend_Adminhtml_System_Config_SaveController',
+            array('deniedAction'),
             array(
-                'helper' => $helperMock,
-                'session' => $this->_sessionMock,
-            )
+                $this->_requestMock,
+                $responseMock,
+                $objectManagerMock,
+                $frontControllerMock,
+                $authorizationMock,
+                $configStructureMock,
+                $this->_configMock,
+                $this->_configFactoryMock,
+                $this->_eventManagerMock,
+                $this->_appMock,
+                $this->_authMock,
+                $this->_layoutMock,
+                null,
+                array(
+                    'helper' => $helperMock,
+                    'session' => $this->_sessionMock,
+                ))
         );
     }
 
diff --git a/dev/tests/unit/testsuite/Mage/Captcha/Helper/DataTest.php b/dev/tests/unit/testsuite/Mage/Captcha/Helper/DataTest.php
index bce1e24d08fac168607e2fc8f0903da87c4a0749..4d8583282d0ea5b47e2abf9bac7b6a1864987894 100644
--- a/dev/tests/unit/testsuite/Mage/Captcha/Helper/DataTest.php
+++ b/dev/tests/unit/testsuite/Mage/Captcha/Helper/DataTest.php
@@ -33,26 +33,13 @@ class Mage_Captcha_Helper_DataTest extends PHPUnit_Framework_TestCase
     const FONT_FIXTURE = '<fonts><font_code><label>Label</label><path>path/to/fixture.ttf</path></font_code></fonts>';
 
     /**
-     * Temp dir to act as media dir for the test
-     *
-     * @var string
+     * @var PHPUnit_Framework_MockObject_MockObject
      */
-    protected $_mediaDir;
+    protected $_dirMock;
 
     protected function setUp()
     {
-        $this->_mediaDir = TESTS_TEMP_DIR . DIRECTORY_SEPARATOR . 'media';
-        if (!is_dir($this->_mediaDir)) {
-            mkdir($this->_mediaDir, 0777);
-        }
-    }
-
-    protected function tearDown()
-    {
-        if (is_dir($this->_mediaDir)) {
-            $filesystem = new Magento_Filesystem(new Magento_Filesystem_Adapter_Local);
-            $filesystem->delete($this->_mediaDir);
-        }
+        $this->_dirMock = $this->getMock('Mage_Core_Model_Dir', array(), array(), '', false, false);
     }
 
     /**
@@ -79,13 +66,12 @@ class Mage_Captcha_Helper_DataTest extends PHPUnit_Framework_TestCase
         $adapterMock->expects($this->any())
             ->method('isDirectory')
             ->will($this->returnValue(true));
-        $filesystem = new Magento_Filesystem(new Magento_Filesystem_Adapter_Local);
 
-        $customPaths = array(
-            Mage_Core_Model_Dir::MEDIA => $this->_mediaDir
-        );
-        $dirs = new Mage_Core_Model_Dir(TESTS_TEMP_DIR, array(), $customPaths);
-        return new Mage_Captcha_Helper_Data($dirs, $app, $config, $filesystem);
+        $filesystem = $this->getMock('Magento_Filesystem', array(), array(), '', false);
+
+        $translator = $this->getMock('Mage_Core_Model_Translate', array(), array(), '', false);
+
+        return new Mage_Captcha_Helper_Data($this->_dirMock, $app, $config, $filesystem, $translator);
     }
 
     /**
@@ -108,10 +94,11 @@ class Mage_Captcha_Helper_DataTest extends PHPUnit_Framework_TestCase
         $config->expects($this->once())
             ->method('getModelInstance')
             ->with('Mage_Captcha_Model_Zend')
-            ->will($this->returnValue(new Mage_Captcha_Model_Zend($objectManager, array('formId' => 'user_create'))));
+            ->will($this->returnValue(
+            new Mage_Captcha_Model_Default($objectManager, array('formId' => 'user_create'))));
 
         $helper = $this->_getHelper($store, $config);
-        $this->assertInstanceOf('Mage_Captcha_Model_Zend', $helper->getCaptcha('user_create'));
+        $this->assertInstanceOf('Mage_Captcha_Model_Default', $helper->getCaptcha('user_create'));
     }
 
     /**
@@ -134,6 +121,11 @@ class Mage_Captcha_Helper_DataTest extends PHPUnit_Framework_TestCase
 
     public function testGetFonts()
     {
+        $this->_dirMock->expects($this->once())
+            ->method('getDir')
+            ->with(Mage_Core_Model_Dir::LIB)
+            ->will($this->returnValue(TESTS_TEMP_DIR . '/lib'));
+
         $object = $this->_getHelper($this->_getStoreStub(), $this->_getConfigStub());
         $fonts = $object->getFonts();
         $this->assertArrayHasKey('font_code', $fonts); // fixture
@@ -145,22 +137,26 @@ class Mage_Captcha_Helper_DataTest extends PHPUnit_Framework_TestCase
     }
 
     /**
-     * @covers Mage_Captcha_Model_Zend::getImgDir
+     * @covers Mage_Captcha_Model_Default::getImgDir
      * @covers Mage_Captcha_Helper_Data::getImgDir
      */
     public function testGetImgDir()
     {
+        $this->_dirMock->expects($this->once())
+            ->method('getDir')
+            ->with(Mage_Core_Model_Dir::MEDIA)
+            ->will($this->returnValue(TESTS_TEMP_DIR . '/media'));
+
         $object = $this->_getHelper($this->_getStoreStub(), $this->_getConfigStub());
         $this->assertFileNotExists(TESTS_TEMP_DIR . '/captcha');
         $result = $object->getImgDir();
         $result = str_replace('/', DIRECTORY_SEPARATOR, $result);
-        $this->assertFileExists($result);
         $this->assertStringStartsWith(TESTS_TEMP_DIR, $result);
         $this->assertStringEndsWith('captcha' . DIRECTORY_SEPARATOR . 'base' . DIRECTORY_SEPARATOR, $result);
     }
 
     /**
-     * @covers Mage_Captcha_Model_Zend::getImgUrl
+     * @covers Mage_Captcha_Model_Default::getImgUrl
      * @covers Mage_Captcha_Helper_Data::getImgUrl
      */
     public function testGetImgUrl()
diff --git a/dev/tests/unit/testsuite/Mage/Captcha/Model/ZendTest.php b/dev/tests/unit/testsuite/Mage/Captcha/Model/DefaultTest.php
similarity index 88%
rename from dev/tests/unit/testsuite/Mage/Captcha/Model/ZendTest.php
rename to dev/tests/unit/testsuite/Mage/Captcha/Model/DefaultTest.php
index 7bf7e81c9de2e71680168a7ee1064960318fafd6..f390c8e44731b725b1dfc1077abbaf999b6d00ef 100644
--- a/dev/tests/unit/testsuite/Mage/Captcha/Model/ZendTest.php
+++ b/dev/tests/unit/testsuite/Mage/Captcha/Model/DefaultTest.php
@@ -25,14 +25,14 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-class Mage_Captcha_Model_ZendTest extends PHPUnit_Framework_TestCase
+class Mage_Captcha_Model_DefaultTest extends PHPUnit_Framework_TestCase
 {
     /**
      * Captcha default config data
      * @var array
      */
     protected static $_defaultConfig = array(
-        'type' => 'zend',
+        'type' => 'default',
         'enable' => '1',
         'font' => 'linlibertine',
         'mode' => 'after_fail',
@@ -51,6 +51,11 @@ class Mage_Captcha_Model_ZendTest extends PHPUnit_Framework_TestCase
         ),
     );
 
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_dirMock;
+
     /**
      * path to fonts
      * @var array
@@ -63,7 +68,7 @@ class Mage_Captcha_Model_ZendTest extends PHPUnit_Framework_TestCase
     );
 
     /**
-     * @var Mage_Captcha_Model_Zend
+     * @var Mage_Captcha_Model_Default
      */
     protected $_object;
 
@@ -84,7 +89,7 @@ class Mage_Captcha_Model_ZendTest extends PHPUnit_Framework_TestCase
             ->with('Mage_Captcha_Helper_Data')
             ->will($this->returnValue($this->_getHelperStub()));
 
-        $this->_object = new Mage_Captcha_Model_Zend(
+        $this->_object = new Mage_Captcha_Model_Default(
             $this->_objectManager,
             array(
                 'formId' => 'user_create',
@@ -94,15 +99,15 @@ class Mage_Captcha_Model_ZendTest extends PHPUnit_Framework_TestCase
     }
 
     /**
-     * @covers Mage_Captcha_Model_Zend::getBlockName
+     * @covers Mage_Captcha_Model_Default::getBlockName
      */
     public function testGetBlockName()
     {
-        $this->assertEquals($this->_object->getBlockName(), 'Mage_Captcha_Block_Captcha_Zend');
+        $this->assertEquals($this->_object->getBlockName(), 'Mage_Captcha_Block_Captcha_Default');
     }
 
     /**
-     * @covers Mage_Captcha_Model_Zend::isRequired
+     * @covers Mage_Captcha_Model_Default::isRequired
      */
     public function testIsRequired()
     {
@@ -110,7 +115,7 @@ class Mage_Captcha_Model_ZendTest extends PHPUnit_Framework_TestCase
     }
 
     /**
-     * @covers Mage_Captcha_Model_Zend::isCaseSensitive
+     * @covers Mage_Captcha_Model_Default::isCaseSensitive
      */
     public function testIsCaseSensitive()
     {
@@ -121,7 +126,7 @@ class Mage_Captcha_Model_ZendTest extends PHPUnit_Framework_TestCase
     }
 
     /**
-     * @covers Mage_Captcha_Model_Zend::getFont
+     * @covers Mage_Captcha_Model_Default::getFont
      */
     public function testGetFont()
     {
@@ -132,8 +137,8 @@ class Mage_Captcha_Model_ZendTest extends PHPUnit_Framework_TestCase
     }
 
     /**
-     * @covers Mage_Captcha_Model_Zend::getTimeout
-     * @covers Mage_Captcha_Model_Zend::getExpiration
+     * @covers Mage_Captcha_Model_Default::getTimeout
+     * @covers Mage_Captcha_Model_Default::getExpiration
      */
     public function testGetTimeout()
     {
@@ -144,7 +149,7 @@ class Mage_Captcha_Model_ZendTest extends PHPUnit_Framework_TestCase
     }
 
     /**
-     * @covers Mage_Captcha_Model_Zend::isCorrect
+     * @covers Mage_Captcha_Model_Default::isCorrect
      */
     public function testIsCorrect()
     {
@@ -162,7 +167,7 @@ class Mage_Captcha_Model_ZendTest extends PHPUnit_Framework_TestCase
     }
 
     /**
-     * @covers Mage_Captcha_Model_Zend::getImgSrc
+     * @covers Mage_Captcha_Model_Default::getImgSrc
      */
     public function testGetImgSrc()
     {
@@ -173,13 +178,13 @@ class Mage_Captcha_Model_ZendTest extends PHPUnit_Framework_TestCase
     }
 
     /**
-     * @covers Mage_Captcha_Model_Zend::logAttempt
+     * @covers Mage_Captcha_Model_Default::logAttempt
      */
     public function testLogAttempt()
     {
         $resourceModel = $this->_getResourceModelStub();
 
-        $captcha = new Mage_Captcha_Model_Zend(
+        $captcha = new Mage_Captcha_Model_Default(
             $this->_objectManager,
             array(
                 'formId' => 'user_create',
@@ -192,7 +197,7 @@ class Mage_Captcha_Model_ZendTest extends PHPUnit_Framework_TestCase
     }
 
     /**
-     * @covers Mage_Captcha_Model_Zend::getWord
+     * @covers Mage_Captcha_Model_Default::getWord
      */
     public function testGetWord()
     {
@@ -249,7 +254,7 @@ class Mage_Captcha_Model_ZendTest extends PHPUnit_Framework_TestCase
 
         $helper->expects($this->any())
             ->method('getConfigNode')
-            ->will($this->returnCallback('Mage_Captcha_Model_ZendTest::getConfigNodeStub'));
+            ->will($this->returnCallback('Mage_Captcha_Model_DefaultTest::getConfigNodeStub'));
 
         $helper->expects($this->any())
             ->method('getFonts')
diff --git a/dev/tests/unit/testsuite/Mage/Catalog/Model/Product/Indexer/FlatTest.php b/dev/tests/unit/testsuite/Mage/Catalog/Model/Product/Indexer/FlatTest.php
index 3f52441a832727f51766896c8b72efea3a8b5259..e32c072004380272c2f94c3f845860841556726c 100644
--- a/dev/tests/unit/testsuite/Mage/Catalog/Model/Product/Indexer/FlatTest.php
+++ b/dev/tests/unit/testsuite/Mage/Catalog/Model/Product/Indexer/FlatTest.php
@@ -51,7 +51,7 @@ class Mage_Catalog_Model_Product_Indexer_FlatTest extends PHPUnit_Framework_Test
 
     public function testMatchEventAvailability()
     {
-        $flatHelper = $this->getMock('Mage_Catalog_Helper_Product_Flat');
+        $flatHelper = $this->getMock('Mage_Catalog_Helper_Product_Flat', array(), array(), '', false, false);
         $flatHelper->expects($this->any())
             ->method('isAvailable')
             ->will($this->returnValue(false));
diff --git a/dev/tests/unit/testsuite/Mage/Checkout/Block/Cart/Item/RendererTest.php b/dev/tests/unit/testsuite/Mage/Checkout/Block/Cart/Item/RendererTest.php
index 8a26d8e5bd071c8af16213fc8ac7c2a7e107f1de..17e1c9d678368ef07b20e6b505838fdb3f5aff58 100644
--- a/dev/tests/unit/testsuite/Mage/Checkout/Block/Cart/Item/RendererTest.php
+++ b/dev/tests/unit/testsuite/Mage/Checkout/Block/Cart/Item/RendererTest.php
@@ -35,7 +35,9 @@ class Mage_Checkout_Block_Cart_Item_RendererTest extends PHPUnit_Framework_TestC
         $configView->expects($this->any())->method('getVarValue')->will($this->returnValue(75));
 
         $filesystem = $this->getMockBuilder('Magento_Filesystem')->disableOriginalConstructor()->getMock();
-        $designPackage = $this->getMock('Mage_Core_Model_Design_Package', array('getViewConfig'), array($filesystem));
+        $designPackage = $this->getMock(
+            'Mage_Core_Model_Design_Package', array('getViewConfig'), array($filesystem), '', false
+        );
         $designPackage->expects($this->any())->method('getViewConfig')->will($this->returnValue($configView));
 
         $configurable = $objectManagerHelper->getBlock('Mage_Checkout_Block_Cart_Item_Renderer_Configurable',
@@ -48,14 +50,19 @@ class Mage_Checkout_Block_Cart_Item_RendererTest extends PHPUnit_Framework_TestC
             $this->getMock('Mage_Catalog_Model_Product', array('getThumbnail', 'getDataByKey'), array(), '', false);
         $childProduct->expects($this->any())->method('getThumbnail')->will($this->returnValue('/_/_/__green.gif'));
 
-        $childItem = $objectManagerHelper->getModel('Mage_Sales_Model_Quote_Item');
+        $arguments = array(
+            'statusListFactory' => $this->getMock('Mage_Sales_Model_Status_ListFactory', array(), array(), '', false),
+        );
+        $childItem = $objectManagerHelper->getModel('Mage_Sales_Model_Quote_Item', $arguments);
         $childItem->setData('product', $childProduct);
 
-        $item = $objectManagerHelper->getModel('Mage_Sales_Model_Quote_Item');
+        $item = $objectManagerHelper->getModel('Mage_Sales_Model_Quote_Item', $arguments);
         $item->setData('product', $product);
         $item->addChild($childItem);
 
-        $helperImage = $this->getMock('Mage_Catalog_Helper_Image', array('init', 'resize', '__toString'));
+        $helperImage = $this->getMock('Mage_Catalog_Helper_Image',
+            array('init', 'resize', '__toString'), array(), '', false
+        );
         $helperImage->expects($this->any())->method('init')->will($this->returnValue($helperImage));
         $helperImage->expects($this->any())->method('resize')->will($this->returnValue($helperImage));
         $helperImage->expects($this->any())->method('__toString')->will($this->returnValue($url));
diff --git a/dev/tests/unit/testsuite/Mage/Core/Block/AbstractTest.php b/dev/tests/unit/testsuite/Mage/Core/Block/AbstractTest.php
index dd938996bf0e72a2322f0c0d824fbe3f8ae153ce..21139a1daa47913465471dff69e2df3393c3a953 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Block/AbstractTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Block/AbstractTest.php
@@ -72,21 +72,22 @@ class Mage_Core_Block_AbstractTest extends PHPUnit_Framework_TestCase
 
     public function testGetVar()
     {
-        $filesystemMock = $this->getMock('Magento_Filesystem', array(), array(), '', false);
-        $design = $this->getMock('Mage_Core_Model_Design_Package', array('getViewConfig'), array($filesystemMock));
+        $design = $this->getMock('Mage_Core_Model_Design_Package', array('getViewConfig'),
+            array(), '', false, false
+        );
         /** @var $block Mage_Core_Block_Abstract|PHPUnit_Framework_MockObject_MockObject */
         $block = $this->getMockForAbstractClass('Mage_Core_Block_Abstract', array(
             $this->getMock('Mage_Core_Controller_Request_Http'),
-            $this->getMock('Mage_Core_Model_Layout', array(), array(), '', false),
-            $this->getMock('Mage_Core_Model_Event_Manager'),
-            $this->getMock('Mage_Core_Model_Url'),
-            $this->getMock('Mage_Core_Model_Translate', array(), array($design)),
+            $this->getMock('Mage_Core_Model_Layout', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Event_Manager', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Url', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Translate', array(), array($design), '', false, false),
             $this->getMock('Mage_Core_Model_Cache', array(), array(), '', false),
             $design,
-            $this->getMock('Mage_Core_Model_Session'),
-            $this->getMock('Mage_Core_Model_Store_Config'),
-            $this->getMock('Mage_Core_Controller_Varien_Front', array(), array(), '', false),
-            $this->getMock('Mage_Core_Model_Factory_Helper'),
+            $this->getMock('Mage_Core_Model_Session', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Store_Config', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Controller_Varien_Front', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Factory_Helper', array(), array(), '', false, false),
         ), uniqid('Mage_Core_Block_Abstract_'));
         $config = $this->getMock('Magento_Config_View', array('getVarValue'), array(), '', false);
         $design->expects($this->exactly(2))->method('getViewConfig')->will($this->returnValue($config));
diff --git a/dev/tests/unit/testsuite/Mage/Core/Block/TemplateTest.php b/dev/tests/unit/testsuite/Mage/Core/Block/TemplateTest.php
index c247e195aa1494549732b0df6e426ca00ea71820..832854d0d04ef5a141f3a7e53315d7e60c66cf43 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Block/TemplateTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Block/TemplateTest.php
@@ -33,17 +33,17 @@ class Mage_Core_Block_TemplateTest extends PHPUnit_Framework_TestCase
         $template = 'fixture';
         $area = 'areaFixture';
         $block = new Mage_Core_Block_Template(
-            $this->getMock('Mage_Core_Controller_Request_Http'),
+            $this->getMock('Mage_Core_Controller_Request_Http', array(), array(), '', false, false),
             $this->getMock('Mage_Core_Model_Layout', array(), array(), '', false),
-            $this->getMock('Mage_Core_Model_Event_Manager'),
-            $this->getMock('Mage_Core_Model_Url'),
-            $this->getMock('Mage_Core_Model_Translate', array(), array($design)),
+            $this->getMock('Mage_Core_Model_Event_Manager', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Url', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Translate', array(), array($design), '', false, false),
             $this->getMock('Mage_Core_Model_Cache', array(), array(), '', false),
             $design,
-            $this->getMock('Mage_Core_Model_Session'),
-            $this->getMock('Mage_Core_Model_Store_Config'),
-            $this->getMock('Mage_Core_Controller_Varien_Front', array(), array(), '', false),
-            $this->getMock('Mage_Core_Model_Factory_Helper'),
+            $this->getMock('Mage_Core_Model_Session', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Store_Config', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Controller_Varien_Front', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Factory_Helper', array(), array(), '', false, false),
             $this->getMock('Mage_Core_Model_Dir', array(), array(), '', false),
             $this->getMock('Mage_Core_Model_Logger', array(), array(), '', false),
             $this->getMock('Magento_Filesystem', array(), array(), '', false),
@@ -62,26 +62,33 @@ class Mage_Core_Block_TemplateTest extends PHPUnit_Framework_TestCase
      */
     public function testFetchView($filename, $expectedOutput)
     {
+        $map = array(
+            array(Mage_Core_Model_Dir::APP, __DIR__),
+            array(Mage_Core_Model_Dir::THEMES, __DIR__ . 'design'),
+        );
+        $dirMock = $this->getMock('Mage_Core_Model_Dir', array(), array(), '', false, false);
+        $dirMock->expects($this->any())->method('getDir')->will($this->returnValueMap($map));
         $layout = $this->getMock('Mage_Core_Model_Layout', array('isDirectOutput'), array(), '', false);
         $filesystem = new Magento_Filesystem(new Magento_Filesystem_Adapter_Local);
-        $design = $this->getMock('Mage_Core_Model_Design_Package', array(), array($filesystem));
+        $design = $this->getMock('Mage_Core_Model_Design_Package', array(), array(), '', false);
         $block = $this->getMock('Mage_Core_Block_Template', array('getShowTemplateHints'), array(
             $this->getMock('Mage_Core_Controller_Request_Http'),
             $layout,
-            $this->getMock('Mage_Core_Model_Event_Manager'),
-            $this->getMock('Mage_Core_Model_Url'),
-            $this->getMock('Mage_Core_Model_Translate', array(), array($design)),
+            $this->getMock('Mage_Core_Model_Event_Manager', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Url', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Translate', array(),
+                array(
+                    $design,
+                    $this->getMock('Mage_Core_Model_Locale_Hierarchy_Loader', array(), array(), '', false, false)
+                )
+            ),
             $this->getMock('Mage_Core_Model_Cache', array(), array(), '', false),
             $this->getMock('Mage_Core_Model_Design_Package', array(), array(), '', false),
-            $this->getMock('Mage_Core_Model_Session'),
-            $this->getMock('Mage_Core_Model_Store_Config'),
-            $this->getMock('Mage_Core_Controller_Varien_Front', array(), array(), '', false),
-            $this->getMock('Mage_Core_Model_Factory_Helper'),
-            new Mage_Core_Model_Dir(
-                __DIR__ . '/_files',
-                array(Mage_Core_Model_Dir::APP => ''),
-                array(Mage_Core_Model_Dir::APP => __DIR__)
-            ),
+            $this->getMock('Mage_Core_Model_Session', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Store_Config', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Controller_Varien_Front', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Factory_Helper', array(), array(), '', false, false),
+            $dirMock,
             $this->getMock('Mage_Core_Model_Logger', array('log'), array(), '', false),
             $filesystem
         ));
diff --git a/dev/tests/unit/testsuite/Mage/Core/Helper/CookieTest.php b/dev/tests/unit/testsuite/Mage/Core/Helper/CookieTest.php
index 168cf284c5efd2f727754de33feec59d4063cc83..1b5d4b8ee9856755780130ef9f4b133f71ae977a 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Helper/CookieTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Helper/CookieTest.php
@@ -35,6 +35,7 @@ class Mage_Core_Helper_CookieTest extends PHPUnit_Framework_TestCase
     protected function setUp()
     {
         $this->_object = new Mage_Core_Helper_Cookie(
+            $this->getMock('Mage_Core_Model_Translate', array(), array(), '', false, false),
             array(
                 'current_store' => $this->_getStoreStub(),
                 'cookie_model' => $this->_getCookieStub(array(1 => 1)),
@@ -47,6 +48,7 @@ class Mage_Core_Helper_CookieTest extends PHPUnit_Framework_TestCase
     {
         $this->assertFalse($this->_object->isUserNotAllowSaveCookie());
         $this->_object = new Mage_Core_Helper_Cookie(
+            $this->getMock('Mage_Core_Model_Translate', array(), array(), '', false, false),
             array(
                 'current_store' => $this->_getStoreStub(),
                 'cookie_model' => $this->_getCookieStub(array()),
@@ -72,6 +74,7 @@ class Mage_Core_Helper_CookieTest extends PHPUnit_Framework_TestCase
             ->will($this->returnCallback('Mage_Core_Helper_CookieTest::getConfigMethodStub'))
             ->with($this->equalTo('web/cookie/cookie_restriction_lifetime'));
         $this->_object = new Mage_Core_Helper_Cookie(
+            $this->getMock('Mage_Core_Model_Translate', array(), array(), '', false, false),
             array(
                 'current_store' => $storeStub,
                 'cookie_model' => $this->_getCookieStub(array(1 => 1)),
diff --git a/dev/tests/unit/testsuite/Mage/Core/Helper/HttpTest.php b/dev/tests/unit/testsuite/Mage/Core/Helper/HttpTest.php
index d3a466f9c5abd8166062c5e61f13e23d67b48318..a2ef7276283478c82af710a3f937d9ce2b32dab3 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Helper/HttpTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Helper/HttpTest.php
@@ -34,7 +34,9 @@ class Mage_Core_Helper_HttpTest extends PHPUnit_Framework_TestCase
 
     protected function setUp()
     {
-        $this->_object = new Mage_Core_Helper_Http;
+        $this->_object = new Mage_Core_Helper_Http(
+            $this->getMock('Mage_Core_Model_Translate', array(), array(), '', false, false)
+        );
     }
 
     /**
diff --git a/dev/tests/unit/testsuite/Mage/Core/Helper/ThemeTest.php b/dev/tests/unit/testsuite/Mage/Core/Helper/ThemeTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..aa0f4227fd38a5679ea7748831e7f44e78a23b3c
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Helper/ThemeTest.php
@@ -0,0 +1,613 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_Core
+ * @subpackage  unit_tests
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Helper_ThemeTest extends PHPUnit_Framework_TestCase
+{
+    const ROOT = '/zzz';
+    const APP = '/zzz/qqq';
+    const MODULES = '/zzz/qqq/code00';
+    const THEMES = '/zzz/qqq/design00';
+    const PUB_LIB = '/zzz/qqq/js00';
+
+    /**
+     * @dataProvider getSafePathDataProvider
+     * @param string $filePath
+     * @param string $basePath
+     * @param string $expectedResult
+     */
+    public function testGetSafePath($filePath, $basePath, $expectedResult)
+    {
+        /** @var $design Mage_Core_Model_Design_Package */
+        $design = $this->getMock('Mage_Core_Model_Design_Package', null, array(), '', false);
+
+        /** @var $dirs Mage_Core_Model_Dir */
+        $dirs = $this->getMock('Mage_Core_Model_Dir', null, array(), '', false);
+
+        /** @var $layoutMergeFactory Mage_Core_Model_Layout_Merge_Factory */
+        $layoutMergeFactory = $this->getMock('Mage_Core_Model_Layout_Merge_Factory', null, array(), '', false);
+
+        /** @var $themeCollection Mage_Core_Model_Resource_Theme_Collection */
+        $themeCollection = $this->getMock('Mage_Core_Model_Resource_Theme_Collection', null, array(), '', false);
+
+        /** @var $translator Mage_Core_Model_Translate */
+        $translator = $this->getMock('Mage_Core_Model_Translate', null, array(), '', false);
+
+        $helper = new Mage_Core_Helper_Theme($design, $dirs, $layoutMergeFactory, $themeCollection, $translator);
+
+        $result = $helper->getSafePath($filePath, $basePath);
+
+        $this->assertEquals($expectedResult, $result);
+    }
+
+    public function getSafePathDataProvider()
+    {
+        return array(
+            array('/1/2/3/4/5/6.test', '/1/2/3/', '4/5/6.test'),
+            array('/1/2/3/4/5/6.test', '/1/2/3', '4/5/6.test'),
+        );
+    }
+
+    /**
+     * @dataProvider getCssFilesDataProvider
+     * @param string $layoutStr
+     * @param array $expectedResult
+     */
+    public function testGetCssFiles($layoutStr, $expectedResult)
+    {
+        // 1. Set data
+        $themeId = 123;
+        $themeArea = 'area123';
+
+        // 2. Get theme model
+        $theme = $this->_getTheme($themeId, $themeArea);
+
+        // 3. Get Design Package model
+        $params = array(
+            'area'       => $themeArea,
+            'themeModel' => $theme,
+            'skipProxy'  => true
+        );
+        $map = array(
+            array('test1.css', $params, '/zzz/qqq/test1.css'),
+            array('test2.css', $params, '/zzz/qqq/test2.css'),
+            array('Mage_Core::test3.css', $params, '/zzz/qqq/test3.css'),
+            array('test4.css', $params, '/zzz/qqq/test4.css'),
+            array('test21.css', $params, '/zzz/qqq/test21.css'),
+            array('test22.css', $params, '/zzz/qqq/test22.css'),
+            array('Mage_Core::test23.css', $params, '/zzz/qqq/test23.css'),
+            array('test24.css', $params, '/zzz/qqq/test24.css'),
+        );
+        $design = $this->_getDesign($map);
+
+        // 4. Get dirs model
+        $dirs = $this->_getDirs();
+
+        // 5. Get layout merge model and factory
+        $layoutMergeFactory = $this->_getLayoutMergeFactory($layoutStr);
+
+        /** @var $themeCollection Mage_Core_Model_Resource_Theme_Collection */
+        $themeCollection = $this->getMock('Mage_Core_Model_Resource_Theme_Collection', null, array(), '', false);
+
+        /** @var $translator Mage_Core_Model_Translate */
+        $translator = $this->getMock('Mage_Core_Model_Translate', null, array(), '', false);
+
+        // 6. Run tested method
+        $helper = new Mage_Core_Helper_Theme($design, $dirs, $layoutMergeFactory, $themeCollection, $translator);
+        $result = $helper->getCssFiles($theme);
+
+        $this->assertEquals($expectedResult, $result);
+    }
+
+    /**
+     * @return array
+     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
+     */
+    public function getCssFilesDataProvider()
+    {
+        return array(
+            array(
+                '<block type="Mage_Page_Block_Html_Head" name="head">
+                    <action method="addCss"><param>test1.css</param></action>
+                </block>',
+                array(
+                    'test1.css' => array(
+                        'id'       => 'test1.css',
+                        'path'     => '/zzz/qqq/test1.css',
+                        'safePath' => 'qqq/test1.css'
+                    )
+                )
+            ),
+            array(
+                '<block type="Mage_Page_Block_Html_Head" name="head">
+                    <action method="addCss"><file>test2.css</file></action>
+                </block>',
+                array(
+                    'test2.css' => array(
+                        'id'       => 'test2.css',
+                        'path'     => '/zzz/qqq/test2.css',
+                        'safePath' => 'qqq/test2.css'
+                    )
+                )
+            ),
+            array(
+                '<block type="Mage_Page_Block_Html_Head" name="head">
+                    <action method="addCss"><param>Mage_Core::test3.css</param></action>
+                </block>',
+                array(
+                    'Mage_Core::test3.css' => array(
+                        'id'       => 'Mage_Core::test3.css',
+                        'path'     => '/zzz/qqq/test3.css',
+                        'safePath' => 'qqq/test3.css'
+                    ),
+                )
+            ),
+            array(
+                '<block type="Mage_Page_Block_Html_Head" name="head">
+                    <action method="addCssIe"><param>test4.css</param></action>
+                </block>',
+                array(
+                    'test4.css' => array(
+                        'id'       => 'test4.css',
+                        'path'     => '/zzz/qqq/test4.css',
+                        'safePath' => 'qqq/test4.css'
+                    )
+                )
+            ),
+            array(
+                '<reference name="head"><action method="addCss"><param>test21.css</param></action></reference>',
+                array(
+                    'test21.css' => array(
+                        'id'       => 'test21.css',
+                        'path'     => '/zzz/qqq/test21.css',
+                        'safePath' => 'qqq/test21.css'
+                    ),
+                )
+            ),
+            array(
+                '<reference name="head"><action method="addCss"><file>test22.css</file></action></reference>',
+                array(
+                    'test22.css' => array(
+                        'id'       => 'test22.css',
+                        'path'     => '/zzz/qqq/test22.css',
+                        'safePath' => 'qqq/test22.css'
+                    ),
+                )
+            ),
+            array(
+                '<reference name="head">
+                    <action method="addCss"><param>Mage_Core::test23.css</param></action>
+                </reference>',
+                array(
+                    'Mage_Core::test23.css' => array(
+                        'id'       => 'Mage_Core::test23.css',
+                        'path'     => '/zzz/qqq/test23.css',
+                        'safePath' => 'qqq/test23.css'
+                    ),
+                )
+            ),
+            array(
+                '<reference name="head"><action method="addCssIe"><param>test24.css</param></action></reference>',
+                array(
+                    'test24.css' => array(
+                        'id'       => 'test24.css',
+                        'path'     => '/zzz/qqq/test24.css',
+                        'safePath' => 'qqq/test24.css'
+                    ),
+                )
+            ),
+            array(
+                '<block type="Some_Block_Class"><action method="addCss"><param>test31.css</param></action></block>',
+                array(),
+
+            ),
+            array(
+                '<block type="Some_Block_Class"><action method="addCss"><file>test32.css</file></action></block>',
+                array(),
+            ),
+            array(
+                '<block type="Some_Block_Class">
+                    <action method="addCss"><param>Mage_Core::test33.css</param></action>
+                </block>',
+                array(),
+            ),
+            array(
+                '<block type="Some_Block_Class"><action method="addCssIe"><param>test34.css</param></action></block>',
+                array(),
+            ),
+            array(
+                '<reference name="some_block_name">
+                    <action method="addCss"><param>test41.css</param></action>
+                </reference>',
+                array(),
+            ),
+            array(
+                '<reference name="some_block_name">
+                    <action method="addCss"><file>test42.css</file></action>
+                </reference>',
+                array(),
+            ),
+            array(
+                '<reference name="some_block_name">
+                    <action method="addCss"><param>Mage_Core::test43.css</param></action>
+                </reference>',
+                array(),
+            ),
+            array(
+                '<reference name="some_block_name">
+                    <action method="addCssIe"><param>test44.css</param></action>
+                </reference>',
+                array(),
+            ),
+            array(
+                '<block type="Mage_Page_Block_Html_Head" name="head">
+                    <action method="addCss"><param>test1.css</param></action>
+                    <action method="addCss"><file>test2.css</file></action>
+                    <action method="addCss"><param>Mage_Core::test3.css</param></action>
+                    <action method="addCssIe"><param>test4.css</param></action>
+                </block>
+                <reference name="head">
+                    <action method="addCss"><param>test21.css</param></action>
+                    <action method="addCss"><file>test22.css</file></action>
+                    <action method="addCss"><param>Mage_Core::test23.css</param></action>
+                    <action method="addCssIe"><param>test24.css</param></action>
+                </reference>
+                <block type="Some_Block_Class">
+                    <action method="addCss"><param>test31.css</param></action>
+                    <action method="addCss"><file>test32.css</file></action>
+                    <action method="addCss"><param>Mage_Core::test33.css</param></action>
+                    <action method="addCssIe"><param>test34.css</param></action>
+                </block>
+                <reference name="some_block_name">
+                    <action method="addCss"><param>test41.css</param></action>
+                    <action method="addCss"><file>test42.css</file></action>
+                    <action method="addCss"><param>Mage_Core::test43.css</param></action>
+                    <action method="addCssIe"><param>test44.css</param></action>
+                </reference>',
+                array(
+                    'test21.css' => array(
+                        'id'       => 'test21.css',
+                        'path'     => '/zzz/qqq/test21.css',
+                        'safePath' => 'qqq/test21.css'
+                    ),
+                    'test22.css' => array(
+                        'id'       => 'test22.css',
+                        'path'     => '/zzz/qqq/test22.css',
+                        'safePath' => 'qqq/test22.css'
+                    ),
+                    'Mage_Core::test23.css' => array(
+                        'id'       => 'Mage_Core::test23.css',
+                        'path'     => '/zzz/qqq/test23.css',
+                        'safePath' => 'qqq/test23.css'
+                    ),
+                    'test24.css' => array(
+                        'id'       => 'test24.css',
+                        'path'     => '/zzz/qqq/test24.css',
+                        'safePath' => 'qqq/test24.css'
+                    ),
+                    'test1.css' => array(
+                        'id'       => 'test1.css',
+                        'path'     => '/zzz/qqq/test1.css',
+                        'safePath' => 'qqq/test1.css'
+                    ),
+                    'test2.css' => array(
+                        'id'       => 'test2.css',
+                        'path'     => '/zzz/qqq/test2.css',
+                        'safePath' => 'qqq/test2.css'
+                    ),
+                    'Mage_Core::test3.css' => array(
+                        'id'       => 'Mage_Core::test3.css',
+                        'path'     => '/zzz/qqq/test3.css',
+                        'safePath' => 'qqq/test3.css'
+                    ),
+                    'test4.css' => array(
+                        'id'       => 'test4.css',
+                        'path'     => '/zzz/qqq/test4.css',
+                        'safePath' => 'qqq/test4.css'
+                    ),
+                ),
+            ),
+        );
+    }
+
+    /**
+     * depends testGetCssFiles
+     * @dataProvider getGroupedCssFilesDataProvider
+     * @param array $files
+     * @param array $expectedResult
+     */
+    public function testGetGroupedCssFiles($files, $expectedResult)
+    {
+        $helper = $this->_getHelper($files);
+
+        $theme = 'anything';
+        $result = $helper->getGroupedCssFiles($theme);
+
+        $this->assertEquals($expectedResult, $result);
+    }
+
+    public function getGroupedCssFilesDataProvider()
+    {
+        $item11 = array(
+            'path'     => '/zzz/qqq/design00/area11/package11/theme11/test11.test',
+            'safePath' => 'design00/area11/package11/theme11/test11.test'
+        );
+        $item12 = array(
+            'path'     => '/zzz/qqq/design00/area12/package12/theme12/test12.test',
+            'safePath' => 'design00/area12/package12/theme12/test12.test'
+        );
+        $item13 = array(
+            'path'     => '/zzz/qqq/design00/area13/package13/theme13/test13.test',
+            'safePath' => 'design00/area13/package13/theme13/test13.test'
+        );
+
+        $item21 = array(
+            'path'     => '/zzz/qqq/code00/Mage_Core00/test21.test',
+            'safePath' => 'code00/Mage_Core00/test21.test'
+        );
+        $item31 = array(
+            'path'     => '/zzz/qqq/js00/some_path/test31.test',
+            'safePath' => 'js00/some_path/test31.test'
+        );
+        $groups11 = array(
+            '"11" Theme files' => array(
+                array(
+                    'path'     => '/zzz/qqq/design00/area11/package11/theme11/test11.test',
+                    'safePath' => 'design00/area11/package11/theme11/test11.test'
+                ),
+            )
+        );
+        $groups12 = array(
+            '"12" Theme files' => array(
+                array(
+                    'path'     => '/zzz/qqq/design00/area12/package12/theme12/test12.test',
+                    'safePath' => 'design00/area12/package12/theme12/test12.test'
+                ),
+            )
+        );
+        $groups13 = array(
+            '"13" Theme files' => array(
+                array(
+                    'path'     => '/zzz/qqq/design00/area13/package13/theme13/test13.test',
+                    'safePath' => 'design00/area13/package13/theme13/test13.test'
+                ),
+            )
+        );
+        $groups1 = array(
+            '"11" Theme files' => array(
+                array(
+                    'path'     => '/zzz/qqq/design00/area11/package11/theme11/test11.test',
+                    'safePath' => 'design00/area11/package11/theme11/test11.test'
+                ),
+            ),
+            '"12" Theme files' => array(
+                array(
+                    'path'     => '/zzz/qqq/design00/area12/package12/theme12/test12.test',
+                    'safePath' => 'design00/area12/package12/theme12/test12.test'
+                ),
+            ),
+            '"13" Theme files' => array(
+                array(
+                    'path'     => '/zzz/qqq/design00/area13/package13/theme13/test13.test',
+                    'safePath' => 'design00/area13/package13/theme13/test13.test'
+                ),
+            )
+        );
+        $groups21 = array(
+            'Framework files' => array(
+                array(
+                    'path'     => '/zzz/qqq/code00/Mage_Core00/test21.test',
+                    'safePath' => 'code00/Mage_Core00/test21.test'
+                ),
+            )
+        );
+        $groups31 = array(
+            'Library files' => array(
+                array(
+                    'path'     => '/zzz/qqq/js00/some_path/test31.test',
+                    'safePath' => 'js00/some_path/test31.test'
+                ),
+            )
+        );
+        return array(
+            array(array($item11), $groups11),
+            array(array($item12), $groups12),
+            array(array($item13), $groups13),
+            array(array($item11, $item12, $item13), $groups1),
+            array(array($item21), $groups21),
+            array(array($item31), $groups31),
+            array(
+                array($item11, $item12, $item13, $item21, $item31),
+                array_merge($groups1, $groups21, $groups31)
+            ),
+        );
+    }
+
+    /**
+     * depends testGetCssFiles
+     * @expectedException Mage_Core_Exception
+     * @expectedExceptionMessage Invalid view file directory "some_path/test.test"
+     */
+    public function testGetGroupedCssFilesException()
+    {
+        $files = array(array(
+            'path'     => '/zzz/some_path/test.test',
+            'safePath' => 'some_path/test.test'
+        ));
+
+        $helper = $this->_getHelper($files);
+
+        $theme = 'anything';
+        $helper->getGroupedCssFiles($theme);
+    }
+
+    /**
+     * @param int $themeId
+     * @param string $themeArea
+     * @return Mage_Core_Model_Theme|PHPUnit_Framework_MockObject_MockObject
+     */
+    protected function _getTheme($themeId, $themeArea)
+    {
+        /** @var $theme Mage_Core_Model_Theme */
+        $theme = $this->getMock('Mage_Core_Model_Theme',
+            array('getThemeId', 'getArea', 'getThemeTitle'), array(), '', false
+        );
+        $theme->expects($this->any())
+            ->method('getThemeId')
+            ->will($this->returnValue($themeId));
+        $theme->expects($this->any())
+            ->method('getArea')
+            ->will($this->returnValue($themeArea));
+        $theme->expects($this->any())
+            ->method('getThemeTitle')
+            ->will($this->returnValue($themeId));
+
+        return $theme;
+    }
+
+    /**
+     * @param array $map
+     * @return Mage_Core_Model_Design_Package|\PHPUnit_Framework_MockObject_MockObject
+     */
+    protected function _getDesign($map)
+    {
+        /** @var $design Mage_Core_Model_Design_Package */
+        $design = $this->getMock('Mage_Core_Model_Design_Package', array('getViewFile'), array(), '', false);
+        $design->expects($this->any())
+            ->method('getViewFile')
+            ->will($this->returnValueMap($map));
+
+        return $design;
+    }
+
+    /**
+     * @param string $layoutStr
+     * @return Mage_Core_Model_Layout_Merge_Factory|PHPUnit_Framework_MockObject_MockObject
+     */
+    protected function _getLayoutMergeFactory($layoutStr)
+    {
+        /** @var $layoutMerge Mage_Core_Model_Layout_Merge */
+        $layoutMerge = $this->getMock('Mage_Core_Model_Layout_Merge',
+            array('getFileLayoutUpdatesXml'), array(), '', false
+        );
+        $xml = '<layouts>' . $layoutStr . '</layouts>';
+        $layoutElement = simplexml_load_string($xml);
+        $layoutMerge->expects($this->any())
+            ->method('getFileLayoutUpdatesXml')
+            ->will($this->returnValue($layoutElement));
+
+        /** @var $layoutMergeFactory Mage_Core_Model_Layout_Merge_Factory */
+        $layoutMergeFactory = $this->getMock('Mage_Core_Model_Layout_Merge_Factory',
+            array('create'), array(), '', false
+        );
+        $layoutMergeFactory->expects($this->any())
+            ->method('create')
+            ->will($this->returnValue($layoutMerge));
+
+        return $layoutMergeFactory;
+    }
+
+    /**
+     * @return Mage_Core_Model_Dir|PHPUnit_Framework_MockObject_MockObject
+     */
+    protected function _getDirs()
+    {
+        /** @var $dirs Mage_Core_Model_Dir */
+        $dirs = $this->getMock('Mage_Core_Model_Dir', array('getDir'), array(), '', false);
+        $dirs->expects($this->any())
+            ->method('getDir')
+            ->will($this->returnValueMap(array(
+                array(Mage_Core_Model_Dir::ROOT, self::ROOT),
+                array(Mage_Core_Model_Dir::APP, self::APP),
+                array(Mage_Core_Model_Dir::MODULES, self::MODULES),
+                array(Mage_Core_Model_Dir::THEMES, self::THEMES),
+                array(Mage_Core_Model_Dir::PUB_LIB, self::PUB_LIB),
+            )));
+
+        return $dirs;
+    }
+
+    /**
+     * @return Mage_Core_Model_Resource_Theme_Collection|PHPUnit_Framework_MockObject_MockObject
+     */
+    protected function _getThemeCollection()
+    {
+        $theme11 = $this->_getTheme('11', 'area11');
+        $theme12 = $this->_getTheme('12', 'area12');
+        $theme13 = $this->_getTheme('13', 'area13');
+
+        /** @var $themeCollection Mage_Core_Model_Resource_Theme_Collection */
+        $themeCollection = $this->getMock('Mage_Core_Model_Resource_Theme_Collection',
+            array('getThemeByFullPath'), array(), '', false
+        );
+        $themeCollection->expects($this->any())
+            ->method('getThemeByFullPath')
+            ->will($this->returnValueMap(array(
+                array('area11/package11/theme11', $theme11),
+                array('area12/package12/theme12', $theme12),
+                array('area13/package13/theme13', $theme13),
+        )));
+
+        return $themeCollection;
+    }
+
+    /**
+     * @param array $files
+     * @return Mage_Core_Helper_Theme|PHPUnit_Framework_MockObject_MockObject
+     */
+    protected function _getHelper($files)
+    {
+        // Get theme collection
+        $themeCollection = $this->_getThemeCollection();
+
+        // 3. Get Design Package model
+        /** @var $design Mage_Core_Model_Design_Package */
+        $design = $this->getMock('Mage_Core_Model_Design_Package', null, array(), '', false);
+
+        // 4. Get dirs model
+        $dirs = $this->_getDirs();
+
+        // 5. Get layout merge model and factory
+        /** @var $layoutMergeFactory Mage_Core_Model_Layout_Merge_Factory|PHPUnit_Framework_MockObject_MockObject */
+        $layoutMergeFactory = $this->getMock('Mage_Core_Model_Layout_Merge_Factory', null, array(), '', false);
+
+        /** @var $translator Mage_Core_Model_Translate */
+        $translator = $this->getMock('Mage_Core_Model_Translate', null, array(), '', false);
+
+        /** @var $helper Mage_Core_Helper_Theme */
+        $helper = $this->getMock('Mage_Core_Helper_Theme', array('getCssFiles', '__'), array(
+            $design, $dirs, $layoutMergeFactory, $themeCollection, $translator
+        ));
+        $helper->expects($this->once())
+            ->method('getCssFiles')
+            ->will($this->returnValue($files));
+        $helper->expects($this->any())
+            ->method('__')
+            ->will($this->returnCallback('sprintf'));
+
+        return $helper;
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Core/Helper/Url/RewriteTest.php b/dev/tests/unit/testsuite/Mage/Core/Helper/Url/RewriteTest.php
index 614bf67be33c606ab52678b161cd80477b411a7c..ecfcb35ffd6b90986b62028ca68c3dfaab877075 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Helper/Url/RewriteTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Helper/Url/RewriteTest.php
@@ -64,7 +64,9 @@ class Mage_Core_Helper_Url_RewriteTest extends PHPUnit_Framework_TestCase
      */
     public function testHasRedirectOptions($option, $expected)
     {
-        $helper = new Mage_Core_Helper_Url_Rewrite();
+        $helper = new Mage_Core_Helper_Url_Rewrite(
+            $this->getMock('Mage_Core_Model_Translate', array(), array(), '', false, false)
+        );
         $mockObject = new Varien_Object();
         $mockObject->setOptions($option);
         $this->assertEquals($expected, $helper->hasRedirectOptions($mockObject));
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/AppTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/AppTest.php
index 6119e5324adb85f14b2feb2ed4bd78c7a68d9239..db3c821f67e11a397be92288873040d6e96e11c2 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Model/AppTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/AppTest.php
@@ -18,9 +18,7 @@
  * versions in the future. If you wish to customize Magento for your
  * needs please refer to http://www.magentocommerce.com for more information.
  *
- * @category    Magento
- * @package     Mage_Core
- * @subpackage  unit_tests
+ *
  * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
@@ -31,73 +29,233 @@
 class Mage_Core_Model_AppTest extends PHPUnit_Framework_TestCase
 {
     /**
-     * @var Mage_Core_Model_App|PHPUnit_Framework_MockObject_MockObject
+     * @var Mage_Core_Model_App
      */
     protected $_model;
 
     /**
-     * @var Magento_ObjectManager
+     * @var PHPUnit_Framework_MockObject_MockObject
      */
-    protected $_objectManager;
+    protected $_configMock;
 
-    protected function setUp()
-    {
-        $frontController = $this->getMock('Mage_Core_Controller_Varien_Front', array(), array(), '', false);
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_frontControllerMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_cacheMock;
 
-        $this->_objectManager = new Magento_ObjectManager_Zend();
-        $dirs = new Mage_Core_Model_Dir(__DIR__, array(), array(Mage_Core_Model_Dir::CONFIG => __DIR__));
-        $this->_objectManager->addSharedInstance($dirs, 'Mage_Core_Model_Dir');
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_objectManagerMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_dbUpdaterMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_storeManagerMock;
 
-        $this->_model = $this->getMock(
-            'Mage_Core_Model_App',
-            array('_initEnvironment', '_initFilesystem', '_initLogger', '_initCache'),
-            array($frontController, $this->_objectManager)
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_eventManagerMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_appStateMock;
+
+    protected function setUp()
+    {
+        $this->_configMock = $this->getMock('Mage_Core_Model_Config', array(), array(), '', false, false);
+        $this->_frontControllerMock = $this->getMock('Mage_Core_Controller_Varien_Front',
+            array(), array(), '', false, false);
+        $this->_cacheMock = $this->getMock('Mage_Core_Model_Cache', array(), array(), '', false, false);
+        $this->_objectManagerMock = $this->getMock('Magento_ObjectManager', array(), array(), '', false, false);
+        $this->_dbUpdaterMock = $this->getMock('Mage_Core_Model_Db_UpdaterInterface',
+            array(), array(), '', false, false);
+        $this->_storeManagerMock = $this->getMock('Mage_Core_Model_StoreManager', array(), array(), '', false, false);
+        $this->_eventManagerMock = $this->getMock('Mage_Core_Model_Event_Manager', array(), array(), '', false, false);
+        $this->_appStateMock = $this->getMock('Mage_Core_Model_App_State', array(), array(), '', false, false);
+        $this->_model = new Mage_Core_Model_App(
+            $this->_configMock,
+            $this->_frontControllerMock,
+            $this->_cacheMock,
+            $this->_objectManagerMock,
+            $this->_dbUpdaterMock,
+            $this->_storeManagerMock,
+            $this->_eventManagerMock,
+            $this->_appStateMock
         );
-        $this->_objectManager->addSharedInstance($this->_model, 'Mage_Core_Model_App');
     }
 
     protected function tearDown()
     {
-        $this->_model = null;
-        $this->_objectManager = null;
+        unset($this->_configMock);
+        unset($this->_frontControllerMock);
+        unset($this->_cacheMock);
+        unset($this->_objectManagerMock);
+        unset($this->_dbUpdaterMock);
+        unset($this->_storeManagerMock);
+        unset($this->_eventManagerMock);
+        unset($this->_appStateMock);
+        unset($this->_model);
     }
 
-    public function testIsInstalledFalse()
+    public function testGetSafeStore()
     {
-        $this->_model->baseInit(array(
-            Mage_Core_Model_Config::INIT_OPTION_EXTRA_DATA
-                => sprintf(Mage_Core_Model_Config::CONFIG_TEMPLATE_INSTALL_DATE, 'invalid')
-        ));
-        $this->assertFalse($this->_model->isInstalled());
+        $storeId = 'test';
+        $this->_storeManagerMock->expects($this->once())
+            ->method('getSafeStore')
+            ->with($this->equalTo($storeId))
+            ->will($this->returnValue('proxy_result'));
+        $this->assertEquals('proxy_result', $this->_model->getSafeStore($storeId));
     }
 
-    public function testIsInstalledTrue()
+    public function testSetIsSingleStoreModeAllowed()
     {
-        $this->_model->baseInit(array(
-            Mage_Core_Model_Config::INIT_OPTION_EXTRA_DATA
-                => sprintf(Mage_Core_Model_Config::CONFIG_TEMPLATE_INSTALL_DATE, 'Fri, 28 Dec 2012 11:29:51 -0800')
-        ));
-        $this->assertTrue($this->_model->isInstalled());
+        $value = true;
+        $this->_storeManagerMock->expects($this->once())
+            ->method('setIsSingleStoreModeAllowed')
+            ->with($this->equalTo($value));
+        $this->_model->setIsSingleStoreModeAllowed($value);
     }
 
-    /**
-     * @expectedException Magento_Exception
-     * @expectedExceptionMessage Application is not installed yet, please complete the installation first.
-     */
-    public function testRequireInstalledInstance()
+    public function testHasSingleStore()
     {
-        $this->_model->baseInit(array(
-            Mage_Core_Model_Config::INIT_OPTION_EXTRA_DATA
-                => sprintf(Mage_Core_Model_Config::CONFIG_TEMPLATE_INSTALL_DATE, 'invalid')
-        ));
-        $this->_model->requireInstalledInstance();
+        $this->_storeManagerMock->expects($this->once())
+            ->method('hasSingleStore')
+            ->will($this->returnValue('proxy_result'));
+        $this->assertEquals('proxy_result', $this->_model->hasSingleStore());
     }
 
-    public function testGetLayout()
+    public function testIsSingleStoreMode()
     {
-        $layout = $this->getMock('Mage_Core_Model_Layout', array(), array(), '', false);
-        $this->_objectManager->addSharedInstance($layout, 'Mage_Core_Model_Layout');
+        $this->_storeManagerMock->expects($this->once())
+            ->method('isSingleStoreMode')
+            ->will($this->returnValue('proxy_result'));
+        $this->assertEquals('proxy_result', $this->_model->isSingleStoreMode());
+    }
 
-        $this->assertEquals($layout, $this->_model->getLayout());
+    public function testThrowStoreException()
+    {
+        $this->_storeManagerMock->expects($this->once())
+            ->method('throwStoreException');
+        $this->_model->throwStoreException();
+    }
+
+    public function testGetStore()
+    {
+        $storeId = 'some_value';
+        $this->_storeManagerMock->expects($this->once())
+            ->method('getStore')
+            ->with($this->equalTo($storeId))
+            ->will($this->returnValue('proxy_result'));
+        $this->assertEquals('proxy_result', $this->_model->getStore($storeId));
+    }
+
+    public function testGetStores()
+    {
+        $withDefault = true;
+        $codeKey = true;
+        $this->_storeManagerMock->expects($this->once())
+            ->method('getStores')
+            ->with($this->equalTo($withDefault),
+                   $this->equalTo($codeKey))
+            ->will($this->returnValue('proxy_result'));
+        $this->assertEquals('proxy_result', $this->_model->getStores($withDefault, $codeKey));
+    }
+
+    public function testGetWebsite()
+    {
+        $websiteId = 'some_value';
+        $this->_storeManagerMock->expects($this->once())
+            ->method('getWebsite')
+            ->with($this->equalTo($websiteId))
+            ->will($this->returnValue('proxy_result'));
+        $this->assertEquals('proxy_result', $this->_model->getWebsite($websiteId));
+    }
+
+    public function testGetWebsites()
+    {
+        $withDefault = true;
+        $codeKey = true;
+        $this->_storeManagerMock->expects($this->once())
+            ->method('getWebsites')
+            ->with($this->equalTo($withDefault),
+                   $this->equalTo($codeKey))
+            ->will($this->returnValue('proxy_result'));
+        $this->assertEquals('proxy_result', $this->_model->getWebsites($withDefault, $codeKey));
+    }
+
+    public function testReinitStores()
+    {
+        $this->_storeManagerMock->expects($this->once())
+            ->method('reinitStores');
+        $this->_model->reinitStores();
+    }
+
+    public function testSetCurrentStore()
+    {
+        $store = 'Test';
+        $this->_storeManagerMock->expects($this->once())
+            ->method('setCurrentStore')
+            ->with($this->equalTo($store));
+        $this->_model->setCurrentStore($store);
+    }
+
+    public function testGetDefaultStoreView()
+    {
+        $this->_storeManagerMock->expects($this->once())
+            ->method('getDefaultStoreView')
+            ->will($this->returnValue('proxy_result'));
+        $this->assertEquals('proxy_result', $this->_model->getDefaultStoreView());
+    }
+
+    public function testGetGroup()
+    {
+        $groupId = 'test';
+        $this->_storeManagerMock->expects($this->once())
+            ->method('getGroup')
+            ->will($this->returnValue('proxy_result'))
+            ->with($this->equalTo($groupId));
+        $this->assertEquals('proxy_result', $this->_model->getGroup($groupId));
+    }
+
+    public function testGetGroups()
+    {
+        $withDefault = true;
+        $codeKey = true;
+        $this->_storeManagerMock->expects($this->once())
+            ->method('getGroups')
+            ->with($this->equalTo($withDefault),
+            $this->equalTo($codeKey))
+            ->will($this->returnValue('proxy_result'));
+        $this->assertEquals('proxy_result', $this->_model->getGroups($withDefault, $codeKey));
+    }
+
+    public function testClearWebsiteCache()
+    {
+        $websiteId = 'Test';
+        $this->_storeManagerMock->expects($this->once())
+            ->method('clearWebsiteCache')
+            ->with($this->equalTo($websiteId));
+        $this->_model->clearWebsiteCache($websiteId);
+    }
+
+    public function testGetAnyStoreView()
+    {
+        $this->_storeManagerMock->expects($this->once())
+            ->method('getAnyStoreView')
+            ->will($this->returnValue('proxy_result'));
+        $this->assertEquals('proxy_result', $this->_model->getAnyStoreView());
     }
 }
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/CacheTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/CacheTest.php
index 60b4a3afb3c33496ffcfc17db36843bc64e1bf43..4fa1debd87ff120176999e7dc2f400ea5be311c4 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Model/CacheTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/CacheTest.php
@@ -24,147 +24,101 @@
  * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
-
 class Mage_Core_Model_CacheTest extends PHPUnit_Framework_TestCase
 {
-    /**
-     * @var Mage_Core_Model_Dir
-     */
-    protected static $_dirs;
-
     /**
      * @var Mage_Core_Model_Cache
      */
     protected $_model;
 
     /**
-     * @var Mage_Core_Model_App|PHPUnit_Framework_MockObject_MockObject
+     * @var Mage_Core_Model_Config_Primary
      */
-    protected $_app;
+    protected $_primaryConfigMock;
 
     /**
-     * @var Magento_ObjectManager_Zend|PHPUnit_Framework_MockObject_MockObject
+     * @var PHPUnit_Framework_MockObject_MockObject
      */
-    protected $_objectManager;
+    protected $_configMock;
 
     /**
-     * @var Mage_Core_Helper_Abstract
+     * @var PHPUnit_Framework_MockObject_MockObject
      */
-    protected $_helper;
+    protected $_dirsMock;
 
     /**
-     * @var Zend_Cache_Backend|PHPUnit_Framework_MockObject_MockObject
+     * @var PHPUnit_Framework_MockObject_MockObject
      */
-    protected $_cacheFrontend;
+    protected $_helperMock;
 
     /**
-     * @var stdClass|PHPUnit_Framework_MockObject_MockObject
+     * @var PHPUnit_Framework_MockObject_MockObject
      */
-    protected $_requestProcessor;
-
-    public static function setUpBeforeClass()
-    {
-        self::$_dirs = new Mage_Core_Model_Dir(TESTS_TEMP_DIR);
-        mkdir(self::$_dirs->getDir(Mage_Core_Model_Dir::CACHE), 0777, true);
-    }
+    protected $_helperFactoryMock;
 
-    public static function tearDownAfterClass()
-    {
-        self::$_dirs = null;
-    }
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject;
+     */
+    protected $_cacheFrontend;
 
     protected function setUp()
     {
-        $this->_prepareApp('global_ban_use_cache', false);
-        $this->_objectManager = $this->getMock(
-            'Magento_ObjectManager_Zend', array('create', 'get'), array(), '', false
-        );
-        $this->_objectManager->expects($this->any())
-            ->method('create')
-            ->will($this->returnCallback(array($this, 'getInstance')));
-        $this->_objectManager->expects($this->any())
-            ->method('get')
-            ->will($this->returnCallback(array($this, 'getObject')));
-
-        $this->_helper = $this->getMock('Mage_Core_Helper_Data', array('__'));
-        $this->_helper
+        $this->_helperFactoryMock = $this->getMock('Mage_Core_Model_Factory_Helper', array(), array(), '', false);
+        $this->_helperMock = $this->getMock('Mage_Core_Helper_Data', array('__'), array(), '', false);
+        $this->_helperMock
             ->expects($this->any())
             ->method('__')
-            ->will($this->returnArgument(0))
-        ;
+            ->will($this->returnArgument(0));
+        $this->_helperFactoryMock->expects($this->any())->method('get')->will($this->returnValue($this->_helperMock));
+
+        $this->_dirsMock = $this->getMock('Mage_Core_Model_Dir', array(), array(), '', false);
+
+        $this->_primaryConfigMock = $this->getMock('Mage_Core_Model_Config_Primary', array(), array(), '', false);
+
+        $this->_configMock = new Mage_Core_Model_Config_Base(<<<XML
+            <config>
+                <global>
+                    <cache>
+                        <types>
+                            <single_tag>
+                                <label>Tag One</label>
+                                <description>This is Tag One</description>
+                                <tags>tag_one</tags>
+                            </single_tag>
+                            <multiple_tags>
+                                <label>Tags One and Two</label>
+                                <description>These are Tags One and Two</description>
+                                <tags>tag_one,tag_two</tags>
+                            </multiple_tags>
+                        </types>
+                    </cache>
+                </global>
+            </config>
+XML
+        );
+
         $this->_cacheFrontend = $this->getMock(
             'Zend_Cache_Core', array('load', 'test', 'save', 'remove', 'clean', '_getHelper')
         );
-        $this->_requestProcessor = $this->getMock('stdClass', array('extractContent'));
         $this->_model = new Mage_Core_Model_Cache(
-            $this->_objectManager,
-            array(
-                'helper'   => $this->_helper,
+            $this->_configMock, $this->_primaryConfigMock, $this->_dirsMock, $this->_helperFactoryMock, false, array(
                 'frontend' => $this->_cacheFrontend,
                 'backend'  => 'BlackHole',
-                'request_processors' => array($this->_requestProcessor),
-        ));
+            )
+        );
     }
 
     protected function tearDown()
     {
-        $this->_objectManager = null;
+        $this->_primaryConfigMock = null;
+        $this->_configMock = null;
+        $this->_dirsMock = null;
+        $this->_helperFactoryMock = null;
+        $this->_helperMock = null;
         $this->_cacheFrontend = null;
         $this->_model = null;
     }
 
-    /**
-     * Create application mock
-     *
-     * @param string $initParam
-     * @param mixed $initValue
-     */
-    protected function _prepareApp($initParam, $initValue)
-    {
-        $this->_app = $this->getMock('Mage_Core_Model_App', array('getInitParam'), array(), '', false);
-        $this->_app->expects($this->any())
-            ->method('getInitParam')
-            ->with($initParam)
-            ->will($this->returnValue($initValue));
-    }
-
-    /**
-     * Callback for getter of the object manager
-     *
-     * @param string $className
-     * @return object|null|PHPUnit_Framework_MockObject_MockObject
-     */
-    public function getObject($className)
-    {
-        switch ($className) {
-            case 'Mage_Core_Model_Config':
-                return new Mage_Core_Model_Config($this->_objectManager, <<<XML
-                    <config>
-                        <global>
-                            <cache>
-                                <types>
-                                    <single_tag>
-                                        <label>Tag One</label>
-                                        <description>This is Tag One</description>
-                                        <tags>tag_one</tags>
-                                    </single_tag>
-                                    <multiple_tags>
-                                        <label>Tags One and Two</label>
-                                        <description>These are Tags One and Two</description>
-                                        <tags>tag_one,tag_two</tags>
-                                    </multiple_tags>
-                                </types>
-                            </cache>
-                        </global>
-                    </config>
-XML
-                );
-            case 'Mage_Core_Model_App': return $this->_app;
-            case 'Mage_Core_Model_Dir': return self::$_dirs;
-            default: return null;
-        }
-    }
-
     /**
      * Force to load desired cache type options
      *
@@ -187,8 +141,11 @@ XML
      */
     public function testConstructor(array $options, $expectedBackendClass)
     {
-        $options += array('helper' => $this->_helper);
-        $model = new Mage_Core_Model_Cache($this->_objectManager, $options);
+        $options += array('helper' => $this->_helperMock);
+        $model = new Mage_Core_Model_Cache(
+            $this->_configMock, $this->_primaryConfigMock, $this->_dirsMock,
+            $this->_helperFactoryMock, false, $options
+        );
 
         $backend = $model->getFrontend()->getBackend();
         $this->assertInstanceOf($expectedBackendClass, $backend);
@@ -245,7 +202,7 @@ XML
     public function saveDataProvider()
     {
         $configTag = Mage_Core_Model_Config::CACHE_TAG;
-        $appTag = Mage_Core_Model_App::CACHE_TAG;
+        $appTag = Mage_Core_Model_AppInterface::CACHE_TAG;
         return array(
             'default tags' => array(
                 'test_data', 'test_id', array(), 'test_data', 'TEST_ID', array($appTag)
@@ -257,15 +214,15 @@ XML
                 'test_data', 'test_id', array('test_tag'), 'test_data', 'TEST_ID', array('TEST_TAG', $appTag)
             ),
             'non-string data' => array(
-                1234567890, 'test_id', array(), '1234567890', 'TEST_ID', array(Mage_Core_Model_App::CACHE_TAG)
+                1234567890, 'test_id', array(), '1234567890', 'TEST_ID', array(Mage_Core_Model_AppInterface::CACHE_TAG)
             ),
         );
     }
 
     public function testSaveDisallowed()
     {
-        $model = new Mage_Core_Model_Cache($this->_objectManager, array(
-            'helper'   => $this->_helper,
+        $model = new Mage_Core_Model_Cache(
+            $this->_configMock, $this->_primaryConfigMock, $this->_dirsMock, $this->_helperFactoryMock, array(
             'frontend' => $this->_cacheFrontend,
             'backend'  => 'BlackHole',
             'disallow_save' => true
@@ -319,7 +276,7 @@ XML
     public function cleanDataProvider()
     {
         return array(
-            'default tags' => array(array(), array(Mage_Core_Model_App::CACHE_TAG)),
+            'default tags' => array(array(), array(Mage_Core_Model_AppInterface::CACHE_TAG)),
             'custom tags'  => array(array('test_tag'), array('TEST_TAG')),
         );
     }
@@ -329,7 +286,7 @@ XML
         $this->_cacheFrontend
             ->expects($this->at(0))
             ->method('clean')
-            ->with(Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, array(Mage_Core_Model_App::CACHE_TAG))
+            ->with(Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG, array(Mage_Core_Model_AppInterface::CACHE_TAG))
             ->will($this->returnValue(true))
         ;
         $this->_cacheFrontend
@@ -366,15 +323,6 @@ XML
         return $this->_model;
     }
 
-    public function testCanUseBanCache()
-    {
-        $this->_prepareApp('global_ban_use_cache', true);
-        $this->_emulateCacheTypeOptions();
-        $this->assertEquals(array('config' => false), $this->_model->canUse(''));
-        $this->assertFalse($this->_model->canUse('config'));
-        return $this->_model;
-    }
-
     /**
      * @depends testCanUse
      * @param Mage_Core_Model_Cache $model
@@ -495,40 +443,4 @@ XML
         ;
         $this->_model->cleanType('multiple_tags');
     }
-
-    public function testProcessRequestFalse()
-    {
-        $response = new Zend_Controller_Response_Http();
-        $this->_model = new Mage_Core_Model_Cache($this->_objectManager, array(
-            'helper'   => $this->_helper,
-            'frontend' => $this->_cacheFrontend,
-            'backend'  => 'BlackHole',
-        ));
-        $this->assertFalse($this->_model->processRequest($response));
-    }
-
-    public function testProcessRequestTrue()
-    {
-        $response = new Zend_Controller_Response_Http();
-        $response->setBody('Initial response body.');
-        $this->_requestProcessor
-            ->expects($this->any())
-            ->method('extractContent')
-            ->will($this->returnValue('Additional response text.'))
-        ;
-        $this->assertTrue($this->_model->processRequest($response));
-        $this->assertEquals('Initial response body.Additional response text.', $response->getBody());
-    }
-
-    /**
-     * Callback to use instead Magento_ObjectManager_Zend::create
-     *
-     * @param string $className
-     * @param array $params
-     * @return string
-     */
-    public function getInstance($className, $params = array())
-    {
-        return new $className($params);
-    }
 }
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/CacheTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Config/CacheTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..886f14b328723b1a558a224d65e7928474289231
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/CacheTest.php
@@ -0,0 +1,112 @@
+<?php
+/**
+ * Test class for Mage_Core_Model_Config_Cache
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_Config_CacheTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Config_Cache
+     */
+    protected $_model;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_contFactoryMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_baseFactoryMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_cacheMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_configSectionsMock;
+
+    protected function setUp()
+    {
+        $this->_cacheMock = $this->getMock('Mage_Core_Model_Cache', array(), array(), '', false, false);
+        $this->_configSectionsMock = $this->getMock('Mage_Core_Model_Config_Sections',
+            array(), array(), '', false, false);
+        $this->_contFactoryMock = $this->getMock('Mage_Core_Model_Config_ContainerFactory',
+            array(), array(), '', false, false);
+        $this->_baseFactoryMock = $this->getMock('Mage_Core_Model_Config_BaseFactory',
+            array(), array(), '', false, false);
+        $this->_model = new Mage_Core_Model_Config_Cache(
+            $this->_cacheMock,
+            $this->_configSectionsMock,
+            $this->_contFactoryMock,
+            $this->_baseFactoryMock
+        );
+    }
+
+    protected function tearDown()
+    {
+        unset($this->_cacheMock);
+        unset($this->_configSectionsMock);
+        unset($this->_contFactoryMock);
+        unset($this->_baseFactoryMock);
+        unset($this->_model);
+    }
+
+
+    public function testCacheLifetime()
+    {
+        $lifetime = 10;
+        $this->_model->setCacheLifetime($lifetime);
+        $this->assertEquals($lifetime, $this->_model->getCacheLifeTime());
+    }
+
+    public function testLoadWithoutConfig()
+    {
+        $this->assertFalse($this->_model->load());
+    }
+
+    public function testLoadWithConfig()
+    {
+        $this->_cacheMock->expects($this->once())
+            ->method('canUse')
+            ->with('config')
+            ->will($this->returnValue(true));
+        $this->_cacheMock->expects($this->at(1))
+            ->method('load')
+            ->will($this->returnValue(false));
+        $this->_cacheMock->expects($this->at(2))
+            ->method('load')
+            ->will($this->returnValue('test_config'));
+        $this->_contFactoryMock->expects($this->once())
+            ->method('create')
+            ->with($this->equalTo(array('sourceData' => 'test_config')))
+            ->will($this->returnValue('some_instance'));
+
+        $this->assertEquals('some_instance', $this->_model->load());
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/InvalidatorTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Config/InvalidatorTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..19d64964c1cc1412348f07432958b7f52dd0aad4
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/InvalidatorTest.php
@@ -0,0 +1,42 @@
+<?php
+/**
+ * Test class for Mage_Core_Model_Config_Invalidator
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_Config_InvalidatorTest extends PHPUnit_Framework_TestCase
+{
+    public function testInvalidate()
+    {
+        $primaryMock = $this->getMock('Mage_Core_Model_ConfigInterface', array(), array(), '', false, false);
+        $modulesMock = $this->getMock('Mage_Core_Model_ConfigInterface', array(), array(), '', false, false);
+        $localesMock = $this->getMock('Mage_Core_Model_ConfigInterface', array(), array(), '', false, false);
+        $model = new Mage_Core_Model_Config_Invalidator($primaryMock, $modulesMock, $localesMock);
+
+        $primaryMock->expects($this->once())->method('reinit');
+        $modulesMock->expects($this->once())->method('reinit');
+        $localesMock->expects($this->once())->method('reinit');
+        $model->invalidate();
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/Loader/DbTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Config/Loader/DbTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..c1d967c629039b6577def5e8ad7510216a8da844
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/Loader/DbTest.php
@@ -0,0 +1,114 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Test class for Mage_Core_Model_Config_Loader_Db
+ */
+class Mage_Core_Model_Config_Loader_DbTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Config_Loader_Db
+     */
+    protected $_model;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_dbUpdaterMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_modulesConfigMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_resourceMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_factoryMock;
+
+    protected function setUp()
+    {
+        $this->_modulesConfigMock = $this->getMock('Mage_Core_Model_Config_Modules',
+            array(), array(), '', false, false
+        );
+        $this->_dbUpdaterMock = $this->getMock('Mage_Core_Model_Db_UpdaterInterface',
+            array(), array(), '', false, false
+        );
+        $this->_resourceMock = $this->getMock('Mage_Core_Model_Resource_Config', array(), array(), '', false, false);
+        $this->_factoryMock = $this->getMock('Mage_Core_Model_Config_BaseFactory', array(), array(), '', false, false);
+
+        $this->_model = new Mage_Core_Model_Config_Loader_Db(
+            $this->_modulesConfigMock,
+            $this->_resourceMock,
+            $this->_dbUpdaterMock,
+            $this->_factoryMock
+        );
+    }
+
+    protected function tearDown()
+    {
+        unset($this->_dbUpdaterMock);
+        unset($this->_modulesConfigMock);
+        unset($this->_resourceMock);
+        unset($this->_factoryMock);
+        unset($this->_model);
+    }
+
+    public function testLoadWithReadConnection()
+    {
+        $this->_resourceMock->expects($this->once())->method('getReadConnection')->will($this->returnValue(true));
+        $this->_dbUpdaterMock->expects($this->once())->method('updateScheme');
+
+        $configData = new Varien_Simplexml_Config();
+        $configMock = $this->getMock('Mage_Core_Model_Config_Base', array(), array(), '', false, false);
+        $this->_modulesConfigMock->expects($this->once())->method('getNode')->will($this->returnValue('config_node'));
+        $this->_factoryMock->expects($this->once())->method('create')
+            ->with('config_node')
+            ->will($this->returnValue($configData));
+
+        $configMock->expects($this->once())->method('extend')->with($configData);
+
+        $this->_resourceMock->expects($this->once())->method('loadToXml')->with($configMock);
+
+        $this->_model->load($configMock);
+    }
+
+    public function testLoadWithoutReadConnection()
+    {
+        $this->_resourceMock->expects($this->once())->method('getReadConnection')->will($this->returnValue(false));
+        $this->_dbUpdaterMock->expects($this->never())->method('updateScheme');
+
+        $configMock = $this->getMock('Mage_Core_Model_Config_Base', array(), array(), '', false, false);
+        $configMock->expects($this->never())->method('extend');
+        $this->_resourceMock->expects($this->never())->method('loadToXml');
+
+        $this->_model->load($configMock);
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/Loader/LocalTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Config/Loader/LocalTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..7c9029aa86aa86f135acbe4af7d1026b0d8665b2
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/Loader/LocalTest.php
@@ -0,0 +1,185 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Test class for Mage_Core_Model_Config_Loader_Local
+ */
+class Mage_Core_Model_Config_Loader_LocalTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Config_Loader_Local
+     */
+    protected $_model;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_dirsMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_protFactoryMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_baseConfigMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_customConfig;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_customFile;
+
+    protected function setUp()
+    {
+        $this->_customConfig = null;
+        $this->_customFile = null;
+        $this->_dirsMock = $this->getMock('Mage_Core_Model_Dir', array(), array(), '', false, false);
+        $this->_protFactoryMock = $this->getMock('Mage_Core_Model_Config_BaseFactory',
+            array(), array(), '', false, false);
+        $this->_baseConfigMock = $this->getMock('Mage_Core_Model_Config_Base', array(), array(), '', false, false);
+    }
+
+    protected function createModel()
+    {
+        return new Mage_Core_Model_Config_Loader_Local(
+            $this->_protFactoryMock,
+            $this->_dirsMock,
+            $this->_customConfig,
+            $this->_customFile
+        );
+    }
+
+    protected function tearDown()
+    {
+        unset($this->_protFactoryMock);
+        unset($this->_dirsMock);
+        unset($this->_baseConfigMock);
+        unset($this->_model);
+    }
+
+    public function testLoadWithoutData()
+    {
+        $this->_dirsMock->expects($this->once())
+            ->method('getDir')
+            ->with($this->equalTo(Mage_Core_Model_Dir::CONFIG))
+            ->will($this->returnValue('testdir\etc'));
+        $this->_protFactoryMock->expects($this->never())
+            ->method('create');
+        $this->_baseConfigMock->expects($this->never())
+            ->method('loadFile');
+        $this->_baseConfigMock->expects($this->never())
+            ->method('loadString');
+        $this->_baseConfigMock->expects($this->never())
+            ->method('extend');
+        $this->createModel()->load($this->_baseConfigMock);
+    }
+
+    public function testLoadWithLocalConfig()
+    {
+        $localConfigFile = realpath(__DIR__. '/../_files/testdir/etc/local.xml');
+        $this->_dirsMock->expects($this->once())
+            ->method('getDir')
+            ->with($this->equalTo(Mage_Core_Model_Dir::CONFIG))
+            ->will($this->returnValue(realpath(__DIR__. '/../_files/testdir/etc')));
+        $this->_protFactoryMock->expects($this->exactly(1))
+            ->method('create')
+            ->with('<config/>')
+            ->will($this->returnValue($this->_baseConfigMock));
+        $this->_baseConfigMock->expects($this->once())
+            ->method('loadFile')
+            ->with($this->equalTo($localConfigFile))
+            ->will($this->returnValue(true));
+        $this->_baseConfigMock->expects($this->exactly(1))
+            ->method('extend')
+            ->with($this->equalTo($this->_baseConfigMock))
+            ->will($this->returnValue($this->getMockBuilder('Varien_Simplexml_Config')
+            ->disableOriginalConstructor()->getMock())
+        );
+        $this->createModel()->load($this->_baseConfigMock);
+    }
+
+    public function testLoadWithCustomConfig()
+    {
+        $localConfigFile = realpath(__DIR__. '/../_files/testdir/etc/local.xml');
+        $this->_customFile = 'directorytest' . DS . 'testconfig.xml';
+        $localConfigExtraFile = realpath(__DIR__. '/../_files/testdir/etc/directorytest/testconfig.xml');
+        $this->_dirsMock->expects($this->once())
+            ->method('getDir')
+            ->with($this->equalTo(Mage_Core_Model_Dir::CONFIG))
+            ->will($this->returnValue(realpath(__DIR__. '/../_files/testdir/etc/')));
+        $this->_protFactoryMock->expects($this->exactly(2))
+            ->method('create')
+            ->with('<config/>')
+            ->will($this->returnValue($this->_baseConfigMock));
+        $this->_baseConfigMock->expects($this->at(0))
+            ->method('loadFile')
+            ->with($this->equalTo($localConfigFile))
+            ->will($this->returnValue(true));
+        $this->_baseConfigMock->expects($this->at(1))
+            ->method('loadFile')
+            ->with($this->equalTo($localConfigExtraFile))
+            ->will($this->returnValue(true));
+        $this->_baseConfigMock->expects($this->exactly(2))
+            ->method('extend')
+            ->with($this->equalTo($this->_baseConfigMock))
+            ->will($this->returnValue($this->getMockBuilder('Varien_Simplexml_Config')
+                ->disableOriginalConstructor()->getMock())
+        );
+        $this->createModel()->load($this->_baseConfigMock);
+    }
+
+    public function testLoadWithExtraLocalConfig()
+    {
+        $this->_customConfig = realpath(__DIR__. '/../_files/testdir/etc/testdirectory/customconfig.xml');
+        $this->_dirsMock->expects($this->once())
+            ->method('getDir')
+            ->with($this->equalTo(Mage_Core_Model_Dir::CONFIG))
+            ->will($this->returnValue(realpath(__DIR__. '/../_files/testdir/etc/testdirectory')));
+        $this->_protFactoryMock->expects($this->exactly(1))
+            ->method('create')
+            ->with('<config/>')
+            ->will($this->returnValue($this->_baseConfigMock));
+        $this->_baseConfigMock->expects($this->never())
+            ->method('loadFile');
+        $this->_baseConfigMock->expects($this->exactly(1))
+            ->method('loadString')
+            ->with($this->equalTo($this->_customConfig))
+            ->will($this->returnValue(true));
+        $this->_baseConfigMock->expects($this->exactly(1))
+            ->method('extend')
+            ->with($this->equalTo($this->_baseConfigMock))
+            ->will($this->returnValue($this->getMockBuilder('Varien_Simplexml_Config')
+                ->disableOriginalConstructor()->getMock())
+        );
+        $this->createModel()->load($this->_baseConfigMock);
+    }
+}
\ No newline at end of file
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/Loader/LocalesTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Config/Loader/LocalesTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..e30dac06eaed21faecdd84b71a181b90df3432fe
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/Loader/LocalesTest.php
@@ -0,0 +1,88 @@
+<?php
+/**
+ * Test class for Mage_Core_Model_Config_Loader_Locales
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_Config_Loader_LocalesTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Config_Loader_Locales
+     */
+    protected $_model;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_baseConfigMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_dirsMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_factoryMock;
+
+    protected function setUp()
+    {
+        $this->_dirsMock = $this->getMock('Mage_Core_Model_Dir', array(), array(), '', false, false);
+        $this->_baseConfigMock = $this->getMock('Mage_Core_Model_Config_Base', array(), array(), '', false, false);
+        $this->_factoryMock = $this->getMock('Mage_Core_Model_Config_BaseFactory', array(), array(), '', false, false);
+        $this->_model = new Mage_Core_Model_Config_Loader_Locales(
+            $this->_dirsMock,
+            $this->_factoryMock
+        );
+    }
+
+    protected function tearDown()
+    {
+        unset($this->_dirsMock);
+        unset($this->_factoryMock);
+        unset($this->_baseConfigMock);
+        unset($this->_model);
+    }
+
+    public function testLoad()
+    {
+        $this->_dirsMock->expects(
+            $this->once())->method('getDir')->will($this->returnValue( __DIR__ . '/../_files/locale')
+        );
+        $mergeMock = $this->getMock('Mage_Core_Model_Config_Base', array(), array(), '', false, false);
+        $mergeMock->expects($this->exactly(4))->method('loadFile')->with($this->stringEndsWith('config.xml'));
+        $this->_factoryMock->expects($this->exactly(4))->method('create')->will($this->returnValue($mergeMock));
+        $this->_model->load($this->_baseConfigMock);
+    }
+
+    public function testLoadConditions()
+    {
+        $this->_dirsMock->expects($this->once())
+            ->method('getDir')
+            ->will($this->returnValue(__DIR__ . '/_files/locale/etc/etc/'));
+        $this->_factoryMock->expects($this->never())->method('create');
+        $this->_baseConfigMock->expects($this->never())->method('extend');
+        $this->_model->load($this->_baseConfigMock);
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/Loader/Modules/FileTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Config/Loader/Modules/FileTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..d74480d07f7de628f6330e6b6491a097b1e62864
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/Loader/Modules/FileTest.php
@@ -0,0 +1,126 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Test class for Mage_Core_Model_Config_Loader_Modules_File
+ */
+class Mage_Core_Model_Config_Loader_Modules_FileTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Config_Loader_Modules_File
+     */
+    protected $_model;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_modulesConfigMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_protFactoryMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_dirsMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_baseConfigMock;
+
+    protected function setUp()
+    {
+        $this->_modulesConfigMock = $this->getMock('Mage_Core_Model_Config_Modules',
+            array(), array(), '', false, false);
+        $this->_protFactoryMock = $this->getMock('Mage_Core_Model_Config_BaseFactory',
+            array(), array(), '', false, false);
+        $this->_dirsMock = $this->getMock('Mage_Core_Model_Dir', array(), array(), '', false, false);
+        $this->_baseConfigMock = $this->getMock('Mage_Core_Model_Config_Base', array(), array(), '', false, false);
+        $this->_model = new Mage_Core_Model_Config_Loader_Modules_File(
+            $this->_dirsMock,
+            $this->_protFactoryMock
+        );
+    }
+
+    protected function tearDown()
+    {
+        unset($this->_modulesConfigMock);
+        unset($this->_protFactoryMock);
+        unset($this->_dirsMock);
+        unset($this->_baseConfigMock);
+        unset($this->_model);
+    }
+
+    public function testLoadConfigurationFromFile()
+    {
+        $nodes = new Mage_Core_Model_Config_Element('<modules><mod1><active>1</active></mod1></modules>');
+        $fileName = 'acl.xml';
+        $this->_protFactoryMock->expects($this->exactly(2))
+            ->method('create')
+            ->with($this->equalTo('<config/>'))
+            ->will($this->returnValue($this->_baseConfigMock));
+        $this->_modulesConfigMock->expects($this->exactly(2))
+            ->method('getNode')
+            ->will($this->returnValueMap(array(
+                array('modules', $nodes),
+                array('modules/mod1/codePool', 'core')
+            )));
+        $result = $this->_model->loadConfigurationFromFile($this->_modulesConfigMock, $fileName, null, null, array());
+        $this->assertInstanceOf('Mage_Core_Model_Config_Base', $result);
+    }
+
+    public function testLoadConfigurationFromFileMergeToObject()
+    {
+        $nodes = new Mage_Core_Model_Config_Element('<config><mod1><active>1</active></mod1></config>');
+        $modulesConfigMock = $this->getMock('Mage_Core_Model_ConfigInterface', array(), array(), '', false, false);
+        $fileName = 'acl.xml';
+        $mergeToObject = $this->getMock('Mage_Core_Model_Config_Base', array(), array(), '', false, false);
+        $mergeModel = null;
+        $configCache = array();
+        $modulesConfigMock->expects($this->exactly(2))
+            ->method('getNode')
+            ->will($this->returnValue($nodes)
+        );
+        $this->_protFactoryMock->expects($this->exactly(1))
+            ->method('create')
+            ->with($this->equalTo('<config/>'))
+            ->will($this->returnValue($mergeToObject)
+        );
+        $this->_model->loadConfigurationFromFile($modulesConfigMock, $fileName, $mergeToObject, $mergeModel,
+            $configCache);
+    }
+
+    public function testGetModuleDirWithData()
+    {
+        $moduleName = 'test';
+        $type = 'etc';
+        $path = realpath(__DIR__. '/../../_files/testdir/etc');
+        $this->_model->setModuleDir($moduleName, $type, $path);
+        $this->assertEquals($path, $this->_model->getModuleDir($this->_modulesConfigMock, $type, $moduleName));
+    }
+}
\ No newline at end of file
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/Loader/PrimaryTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Config/Loader/PrimaryTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..169df956534859c72c9100a57c391059740803a8
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/Loader/PrimaryTest.php
@@ -0,0 +1,134 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Test class for Mage_Core_Model_Config_Loader_Primary
+ */
+class Mage_Core_Model_Config_Loader_PrimaryTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Config_Loader_Primary
+     */
+    protected $_model;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_dirsMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_protFactoryMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_localLoaderMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_baseConfigMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_simpleXmlConfig;
+
+    protected function setUp()
+    {
+        $this->_simpleXmlConfig = $this->getMock('Varien_Simplexml_Config',
+            array('getNode'), array(), '', false, false);
+        $this->_protFactoryMock = $this->getMock('Mage_Core_Model_Config_BaseFactory',
+            array(), array(), '', false, false);
+        $this->_dirsMock = $this->getMock('Mage_Core_Model_Dir', array(), array(), '', false, false);
+        $this->_localLoaderMock = $this->getMock('Mage_Core_Model_Config_Loader_Local',
+            array(), array(), '', false, false);
+        $this->_baseConfigMock = $this->getMock('Mage_Core_Model_Config_Base', array(), array(), '', false, false);
+        $this->_model = new Mage_Core_Model_Config_Loader_Primary(
+            $this->_protFactoryMock,
+            $this->_dirsMock,
+            $this->_localLoaderMock
+        );
+    }
+
+    protected function tearDown()
+    {
+        unset($this->_protFactoryMock);
+        unset($this->_dirsMock);
+        unset($this->_localLoaderMock);
+        unset($this->_baseConfigMock);
+        unset($this->_model);
+    }
+
+    public function testLoadWithData()
+    {
+        $this->_dirsMock->expects($this->once())
+            ->method('getDir')
+            ->with($this->equalTo(Mage_Core_Model_Dir::CONFIG))
+            ->will($this->returnValue(realpath(__DIR__. '/../_files/testdir/etc')));
+        $this->_baseConfigMock->expects($this->once())
+            ->method('getNode')
+            ->will($this->returnValue($this->getMockBuilder('Varien_Simplexml_Config')));
+        $this->_protFactoryMock->expects($this->once())
+            ->method('create')
+            ->with('<config/>')
+            ->will($this->returnValue($this->_baseConfigMock));
+        $this->_baseConfigMock->expects($this->once())
+            ->method('loadFile')
+            ->with($this->equalTo(realpath(__DIR__. '/../_files/testdir/etc/testconfig.xml')))
+            ->will($this->returnValue(true));
+        $this->_baseConfigMock->expects($this->once())
+            ->method('extend')
+            ->with($this->equalTo($this->_baseConfigMock))
+            ->will($this->returnValue($this->_simpleXmlConfig));
+        $this->_localLoaderMock->expects($this->once())
+            ->method('load')
+            ->with($this->equalTo($this->_baseConfigMock));
+        $this->_model->load($this->_baseConfigMock);
+    }
+
+    public function testLoadWithoutData()
+    {
+        $this->_dirsMock->expects($this->once())
+            ->method('getDir')
+            ->with($this->equalTo(Mage_Core_Model_Dir::CONFIG))
+            ->will($this->returnValue(realpath(__DIR__. '/../_files/dirtest/etc')));
+        $this->_baseConfigMock->expects($this->any())
+            ->method('getNode')
+            ->will($this->returnValue($this->getMockBuilder('Varien_Simplexml_Config')));
+        $this->_protFactoryMock->expects($this->never())
+            ->method('create');
+        $this->_baseConfigMock->expects($this->never())
+            ->method('loadFile');
+        $this->_baseConfigMock->expects($this->never())
+            ->method('extend');
+        $this->_localLoaderMock->expects($this->once())
+            ->method('load')
+            ->with($this->equalTo($this->_baseConfigMock));
+        $this->_model->load($this->_baseConfigMock);
+    }
+}
\ No newline at end of file
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/LoaderTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Config/LoaderTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..56f78fff4ad86bef8299b4d1bceb830d313c6c41
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/LoaderTest.php
@@ -0,0 +1,108 @@
+<?php
+/**
+ * Test class for Mage_Core_Model_Config_Loader
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_Config_LoaderTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Config_Loader
+     */
+    protected $_model;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_modulesConfigMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_baseConfigMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_localesConfigMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_dbLoaderMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_baseFactoryMock;
+
+    protected function setUp()
+    {
+        $this->_modulesConfigMock = $this->getMock('Mage_Core_Model_Config_Modules',
+            array('getNode'), array(), '', false, false);
+        $this->_localesConfigMock = $this->getMock('Mage_Core_Model_Config_Locales',
+            array(), array(), '', false, false);
+        $this->_baseConfigMock = $this->getMock('Mage_Core_Model_Config_Base',
+            array('extend'), array(), '', false, false);
+        $this->_dbLoaderMock = $this->getMock('Mage_Core_Model_Config_Loader_Db', array(), array(), '', false, false);
+        $this->_baseFactoryMock = $this->getMock('Mage_Core_Model_Config_BaseFactory',
+            array('create'), array(), '', false, false);
+        $this->_model = new Mage_Core_Model_Config_Loader(
+            $this->_modulesConfigMock,
+            $this->_localesConfigMock,
+            $this->_dbLoaderMock,
+            $this->_baseFactoryMock
+        );
+    }
+
+    protected function tearDown()
+    {
+        unset($this->_modulesConfigMock);
+        unset($this->_localesConfigMock);
+        unset($this->_dbLoaderMock);
+        unset($this->_baseConfigMock);
+        unset($this->_baseFactoryMock);
+        unset($this->_model);
+    }
+
+    public function testLoad()
+    {
+        $element = new Varien_Simplexml_Element('<config>test_data</config>');
+        $elementConfig = new Varien_Simplexml_Config();
+        $this->_modulesConfigMock->expects($this->once())
+            ->method('getNode')
+            ->will($this->returnValue($element));
+        $this->_localesConfigMock->expects($this->once())
+            ->method('getNode')
+            ->will($this->returnValue($element));
+        $this->_baseFactoryMock->expects($this->exactly(2))
+            ->method('create')
+            ->with($element)
+            ->will($this->returnValue($elementConfig));
+        $this->_baseConfigMock->expects($this->exactly(2))
+            ->method('extend')
+            ->with($this->equalTo($elementConfig))
+            ->will($this->returnValue($element));
+        $this->_model->load($this->_baseConfigMock);
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/ModuleTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Config/ModuleTest.php
deleted file mode 100644
index 3f625ab3381d7f0f1e8ede68692654be0dd47096..0000000000000000000000000000000000000000
--- a/dev/tests/unit/testsuite/Mage/Core/Model/Config/ModuleTest.php
+++ /dev/null
@@ -1,105 +0,0 @@
-<?php
-/**
- * Magento
- *
- * NOTICE OF LICENSE
- *
- * This source file is subject to the Open Software License (OSL 3.0)
- * that is bundled with this package in the file LICENSE.txt.
- * It is also available through the world-wide-web at this URL:
- * http://opensource.org/licenses/osl-3.0.php
- * If you did not receive a copy of the license and are unable to
- * obtain it through the world-wide-web, please send an email
- * to license@magentocommerce.com so we can send you a copy immediately.
- *
- * DISCLAIMER
- *
- * Do not edit or add to this file if you wish to upgrade Magento to newer
- * versions in the future. If you wish to customize Magento for your
- * needs please refer to http://www.magentocommerce.com for more information.
- *
- * @category    Magento
- * @package     Mage_Core
- * @subpackage  unit_tests
- * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
- * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
- */
-
-/**
- * Test class for Mage_Core_Model_Config_Module.
- */
-class Mage_Core_Model_Config_ModuleTest extends PHPUnit_Framework_TestCase
-{
-    /**
-     * @param string $inputConfigFile
-     * @param string $expectedConfigFile
-     * @param array $allowedModules
-     * @dataProvider constructorDataProvider
-     */
-    public function testConstructor($inputConfigFile, $expectedConfigFile, $allowedModules = array())
-    {
-        $model = new Mage_Core_Model_Config_Module(new Mage_Core_Model_Config_Base($inputConfigFile), $allowedModules);
-        $this->assertXmlStringEqualsXmlFile($expectedConfigFile, $model->getXmlString());
-    }
-
-    public function constructorDataProvider()
-    {
-        return array(
-            'sorting dependencies' => array(
-                __DIR__ . '/_files/module_input.xml',
-                __DIR__ . '/_files/module_sorted.xml',
-            ),
-            'disallowed modules' => array(
-                __DIR__ . '/_files/module_input.xml',
-                __DIR__ . '/_files/module_filtered.xml',
-                array('Fixture_ModuleOne', 'Fixture_ModuleTwo'),
-            ),
-        );
-    }
-
-    /**
-     * @param string $inputConfigFile
-     * @param string $expectedException
-     * @param string $expectedExceptionMsg
-     * @param array $allowedModules
-     * @dataProvider constructorExceptionDataProvider
-     */
-    public function testConstructorException(
-        $inputConfigFile, $expectedException, $expectedExceptionMsg, $allowedModules = array()
-    ) {
-        $this->setExpectedException($expectedException, $expectedExceptionMsg);
-        new Mage_Core_Model_Config_Module(new Mage_Core_Model_Config_Base($inputConfigFile), $allowedModules);
-    }
-
-    public function constructorExceptionDataProvider()
-    {
-        return array(
-            'linear dependency' => array(
-                __DIR__ . '/_files/module_dependency_linear_input.xml',
-                'Magento_Exception',
-                "Module 'Fixture_Module' requires module 'Fixture_NonExistingModule'.",
-            ),
-            'circular dependency' => array(
-                __DIR__ . '/_files/module_dependency_circular_input.xml',
-                'Magento_Exception',
-                "Module 'Fixture_ModuleTwo' cannot depend on 'Fixture_ModuleOne' since it creates circular dependency.",
-            ),
-            'soft circular dependency' => array(
-                __DIR__ . '/_files/module_dependency_circular_soft_input.xml',
-                'Magento_Exception',
-                "Module 'Fixture_ModuleTwo' cannot depend on 'Fixture_ModuleOne' since it creates circular dependency.",
-            ),
-            'wrong dependency type' => array(
-                __DIR__ . '/_files/module_dependency_wrong_input.xml',
-                'UnexpectedValueException',
-                'Unknown module dependency type \'wrong\' in declaration \'<Fixture_ModuleTwo type="wrong"/>\'.',
-            ),
-            'dependency on disallowed module' => array(
-                __DIR__ . '/_files/module_input.xml',
-                'Magento_Exception',
-                "Module 'Fixture_ModuleTwo' requires module 'Fixture_ModuleOne'.",
-                array('Fixture_ModuleTwo')
-            )
-        );
-    }
-}
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/Modules/ReaderTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Config/Modules/ReaderTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..0b2f11cefd10f007d57501ee92fe405f5f69f8db
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/Modules/ReaderTest.php
@@ -0,0 +1,108 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Test class for Mage_Core_Model_Config_Modules_Reader
+ */
+class Mage_Core_Model_Config_Modules_ReaderTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Config_Modules_Reader
+     */
+    protected $_model;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_configMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_fileReaderMock;
+
+    protected function setUp()
+    {
+        $this->_configMock = $this->getMock('Mage_Core_Model_Config_Modules', array(), array(), '', false, false);
+        $this->_fileReaderMock = $this->getMock('Mage_Core_Model_Config_Loader_Modules_File',
+            array(), array(), '', false, false);
+        $this->_model = new Mage_Core_Model_Config_Modules_Reader(
+            $this->_configMock,
+            $this->_fileReaderMock
+        );
+    }
+
+    protected function tearDown()
+    {
+        unset($this->_configMock);
+        unset($this->_fileReaderMock);
+        unset($this->_model);
+    }
+
+    public function testLoadModulesConfiguration()
+    {
+        $fileName = 'acl.xml';
+        $mergeToObjectMock = $this->getMock('Mage_Core_Model_Config_Base', array(), array(), '', false, false);
+        $mergeModelMock = $this->getMock('Mage_Core_Model_Config_Base', array(), array(), '', false, false);
+        $this->_fileReaderMock->expects($this->once())
+            ->method('loadConfigurationFromFile')
+            ->with($this->equalTo($this->_configMock),
+                   $this->equalTo($fileName),
+                   $this->equalTo($mergeToObjectMock),
+                   $this->equalTo($mergeModelMock))
+            ->will($this->returnValue('test_data')
+        );
+        $result = $this->_model->loadModulesConfiguration($fileName, $mergeToObjectMock, $mergeModelMock);
+        $this->assertEquals('test_data', $result);
+    }
+
+    public function testGetModuleConfigurationFiles()
+    {
+        $fileName = 'acl.xml';
+        $this->_fileReaderMock->expects($this->once())
+            ->method('getConfigurationFiles')
+            ->with($this->equalTo($this->_configMock),
+                   $this->equalTo($fileName))
+            ->will($this->returnValue('test_data')
+        );
+        $result = $this->_model->getModuleConfigurationFiles($fileName);
+        $this->assertEquals('test_data', $result);
+    }
+
+    public function testGetModuleDir()
+    {
+        $type = 'some_type';
+        $moduleName = 'some_module';
+        $this->_fileReaderMock->expects($this->once())
+            ->method('getModuleDir')
+            ->with($this->equalTo($this->_configMock),
+                   $this->equalTo($type),
+                   $this->equalTo($moduleName))
+            ->will($this->returnValue('test_data')
+        );
+        $result = $this->_model->getModuleDir($type, $moduleName);
+        $this->assertEquals('test_data', $result);
+    }
+}
\ No newline at end of file
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/ModulesTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Config/ModulesTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..e07933e63e623ffbc12dd3f25f0e7c8674168f6d
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/ModulesTest.php
@@ -0,0 +1,103 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_ModulesTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Config_Modules
+     */
+    protected $_model;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_configMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_storageMock;
+
+    protected function setUp()
+    {
+        $this->_configMock = $this->getMock('Mage_Core_Model_ConfigInterface');
+        $this->_storageMock = $this->getMock('Mage_Core_Model_Config_StorageInterface');
+        $this->_storageMock->expects($this->any())->method('getConfiguration')
+            ->will($this->returnValue($this->_configMock));
+        $this->_model = new Mage_Core_Model_Config_Modules($this->_storageMock);
+    }
+
+    protected function tearDown()
+    {
+        unset($this->_configMock);
+        unset($this->_storageMock);
+        unset($this->_model);
+    }
+
+    public function testGetNode()
+    {
+        $path = 'some_path';
+        $result = 'some_result';
+        $this->_configMock->expects($this->once())->method('getNode')->with($path)->will($this->returnValue($result));
+        $this->assertEquals($result, $this->_model->getNode($path));
+    }
+
+    public function testSetNode()
+    {
+        $path = 'some_path';
+        $value = 'some_value';
+        $this->_configMock->expects($this->once())->method('setNode')
+            ->with($path, $value, true);
+        $this->_model->setNode($path, $value);
+    }
+
+    public function testGetXpath()
+    {
+        $path = 'some_path';
+        $result = 'some_result';
+        $this->_configMock->expects($this->once())->method('getXpath')->with($path)->will($this->returnValue($result));
+        $this->assertEquals($result, $this->_model->getXpath($path));
+    }
+
+    public function testGetModuleConfigReturnsRequestedModuleConfig()
+    {
+        $this->_prepareModulesConfig();
+        $this->assertEquals('backend', $this->_model->getModuleConfig('backend'));
+    }
+
+    public function testGetModuleConfigReturnsAllModulesConfigIfNoModuleIsSpecified()
+    {
+        $modulesConfig = $this->_prepareModulesConfig();
+        $this->assertEquals($modulesConfig, $this->_model->getModuleConfig());
+    }
+
+    public function _prepareModulesConfig()
+    {
+        $modulesConfig = new stdClass();
+        $modulesConfig->core = 'core';
+        $modulesConfig->backend = 'backend';
+        $this->_configMock->expects($this->once())->method('getNode')->with('modules')
+            ->will($this->returnValue($modulesConfig));
+        return $modulesConfig;
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/ResourceTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Config/ResourceTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..6382758b7cd00531ca09191373e1382547e28ec2
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/ResourceTest.php
@@ -0,0 +1,115 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_ResourceTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Config_Resource
+     */
+    protected $_model;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_configMock;
+
+    protected function setUp()
+    {
+        $this->_configMock = new Mage_Core_Model_Config_Base('
+        <config>
+            <global>
+                <resources>
+                    <default_setup>
+                        <connection>
+                            <type>pdo_mysql</type>
+                            <model>mysql4</model>
+                        </connection>
+                    </default_setup>
+                    <default_read>
+                        <connection>
+                            <use>default_setup</use>
+                        </connection>
+                    </default_read>
+                    <core_setup>
+                        <connection>
+                            <use>default_setup</use>
+                        </connection>
+                    </core_setup>
+                    <db>
+                        <table_prefix>some_prefix_</table_prefix>
+                    </db>
+                </resources>
+                <resource>
+                    <connection>
+                        <types>
+                            <pdo_mysql>Mysql_Config</pdo_mysql>
+                        </types>
+                    </connection>
+                </resource>
+            </global>
+        </config>
+        ');
+        $this->_model = new Mage_Core_Model_Config_Resource($this->_configMock);
+    }
+
+    protected function tearDown()
+    {
+        unset($this->_model);
+        unset($this->_configMock);
+    }
+
+    public function testGetResourceConfig()
+    {
+        $resourceConfig = $this->_model->getResourceConfig('default_read');
+        $this->assertEquals('default_setup', (string) $resourceConfig->connection->use);
+    }
+
+    public function testGetResourceConnectionConfig()
+    {
+        $resourceConfig = $this->_model->getResourceConnectionConfig('default_setup');
+        $this->assertEquals('pdo_mysql', (string) $resourceConfig->type);
+        $this->assertEquals('mysql4', (string) $resourceConfig->model);
+    }
+
+    public function testGetResourceConnectionConfigUsesInheritance()
+    {
+        $resourceConfig = $this->_model->getResourceConnectionConfig('default_read');
+        $this->assertEquals('pdo_mysql', (string) $resourceConfig->type);
+        $this->assertEquals('mysql4', (string) $resourceConfig->model);
+    }
+
+    public function testGetTablePrefix()
+    {
+        $this->assertEquals('some_prefix_', $this->_model->getTablePrefix());
+    }
+
+    public function testGetResourceTypeConfig()
+    {
+        $this->assertEquals('Mysql_Config', $this->_model->getResourceTypeConfig('pdo_mysql'));
+    }
+
+    public function testGetResourceConnectionModel()
+    {
+        $this->assertEquals('mysql4', $this->_model->getResourceConnectionModel('core'));
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/SectionsTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Config/SectionsTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..df104a14aa40170b13ae9d3e4c77a3cf91f90525
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/SectionsTest.php
@@ -0,0 +1,65 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_Config_SectionsTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Config_Sections
+     */
+    protected $_model;
+
+    protected function setUp()
+    {
+        $this->_model = new Mage_Core_Model_Config_Sections();
+    }
+
+    protected function tearDown()
+    {
+        unset($this->_model);
+    }
+
+    /**
+     * @param string $path
+     * @param string|bool $expectedResult
+     * @dataProvider getKeyDataProvider
+     */
+    public function testGetKey($path, $expectedResult)
+    {
+        $this->assertEquals($expectedResult, $this->_model->getKey($path));
+    }
+
+    public function getKeyDataProvider()
+    {
+        return array(
+            array('admin/user/active', 'admin'),
+            array('adminhtml/routers/default', 'adminhtml'),
+            array('crontab/routers/default', 'crontab'),
+            array('install/routers/default', 'install'),
+            array('stores/admin/routers/default', 'stores_admin'),
+            array('stores/default/routers/default', 'stores_default'),
+            array('stores/custom/routers/default', 'stores_custom'),
+            array('websites/custom/routers/default', 'websites'),
+            array('global/custom/routers/default', false),
+        );
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/Storage/Writer/DbTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Config/Storage/Writer/DbTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..0b2c390f3a08dd5caf66b468bb095cded66614c2
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/Storage/Writer/DbTest.php
@@ -0,0 +1,85 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Test class for Mage_Core_Model_Config_Storage_Writer_Db
+ */
+class Mage_Core_Model_Config_Storage_Writer_DbTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Config_Storage_Writer_Db
+     */
+    protected $_model;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_resourceMock;
+
+
+    protected function setUp()
+    {
+        $this->_resourceMock = $this->getMock('Mage_Core_Model_Resource_Config', array(), array(), '', false, false);
+        $this->_model = new Mage_Core_Model_Config_Storage_Writer_Db($this->_resourceMock);
+    }
+
+    protected function tearDown()
+    {
+        unset($this->_resourceMock);
+        unset($this->_model);
+    }
+
+    public function testDelete()
+    {
+        $this->_resourceMock->expects($this->once())
+            ->method('deleteConfig')
+            ->with('test/path', 'store', 1);
+        $this->_model->delete('test/path/', 'store', 1);
+    }
+
+    public function testDeleteWithDefaultParams()
+    {
+        $this->_resourceMock->expects($this->once())
+            ->method('deleteConfig')
+            ->with('test/path', Mage_Core_Model_Store::DEFAULT_CODE, 0);
+        $this->_model->delete('test/path');
+    }
+
+    public function testSave()
+    {
+        $this->_resourceMock->expects($this->once())
+            ->method('saveConfig')
+            ->with('test/path', 'test_value', 'store', 1);
+        $this->_model->save('test/path/', 'test_value', 'store', 1);
+    }
+
+    public function testSaveWithDefaultParams()
+    {
+        $this->_resourceMock->expects($this->once())
+            ->method('saveConfig')
+            ->with('test/path', 'test_value', Mage_Core_Model_Store::DEFAULT_CODE, 0);
+        $this->_model->save('test/path', 'test_value');
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/StorageTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Config/StorageTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..1e8ca9b295442573d85837f001870b07a7010099
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/StorageTest.php
@@ -0,0 +1,117 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Test class for Mage_Core_Model_Config_Storage
+ */
+class Mage_Core_Model_Config_StorageTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Config_Storage
+     */
+    protected $_model;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_configMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_resourcesConfigMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_cacheMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_loaderMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_factoryMock;
+
+    protected function setUp()
+    {
+        $this->_configMock = $this->getMock('Mage_Core_Model_ConfigInterface',
+            array(), array(), '', false, false);
+        $this->_resourcesConfigMock = $this->getMock('Mage_Core_Model_Config_Resource',
+            array(), array(), '', false, false);
+        $this->_cacheMock = $this->getMock('Mage_Core_Model_Config_Cache',
+            array(), array(), '', false, false);
+        $this->_loaderMock = $this->getMock('Mage_Core_Model_Config_LoaderInterface',
+            array(), array(), '', false, false);
+        $this->_factoryMock = $this->getMock('Mage_Core_Model_Config_BaseFactory',
+            array(), array(), '', false, false);
+        $this->_model = new Mage_Core_Model_Config_Storage($this->_cacheMock, $this->_loaderMock, $this->_factoryMock,
+            $this->_resourcesConfigMock);
+    }
+
+    protected function tearDown()
+    {
+        unset($this->_resourcesConfigMock);
+        unset($this->_cacheMock);
+        unset($this->_loaderMock);
+        unset($this->_factoryMock);
+        unset($this->_model);
+    }
+
+    public function testGetConfigurationWithData()
+    {
+        $this->_cacheMock->expects($this->once())->method('load')->will($this->returnValue($this->_configMock));
+        $this->_factoryMock->expects($this->never())->method('create');
+        $this->_loaderMock->expects($this->never())->method('load');
+        $this->_cacheMock->expects($this->never())->method('save');
+        $this->_resourcesConfigMock->expects($this->once())
+            ->method('setConfig')
+            ->with($this->equalTo($this->_configMock));
+        $this->_model->getConfiguration();
+    }
+
+    public function testGetConfigurationWithoutData()
+    {
+        $mockConfigBase = $this->getMockBuilder('Mage_Core_Model_Config_Base')->disableOriginalConstructor()->getMock();
+        $this->_cacheMock->expects($this->once())->method('load')->will($this->returnValue(false));
+        $this->_factoryMock->expects($this->once())->method('create')->will($this->returnValue($mockConfigBase));
+        $this->_loaderMock->expects($this->once())->method('load');
+        $this->_cacheMock->expects($this->once())->method('save');
+        $this->_resourcesConfigMock->expects($this->once())
+            ->method('setConfig')
+            ->with($this->equalTo($mockConfigBase));
+        $this->_model->getConfiguration();
+    }
+
+    public function testRemoveCache()
+    {
+        $this->_cacheMock->expects($this->once())->method('clean');
+        $this->_model->removeCache();
+    }
+
+}
\ No newline at end of file
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/dirtest/etc/test.php b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/dirtest/etc/test.php
new file mode 100644
index 0000000000000000000000000000000000000000..afbaa66b5b929c5e40ea18ca8eba190721a92d9d
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/dirtest/etc/test.php
@@ -0,0 +1,26 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Magento
+ * @package     Mage_Core
+ * @subpackage  unit_tests
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/locale/de_DE/config.xml b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/locale/de_DE/config.xml
new file mode 100644
index 0000000000000000000000000000000000000000..80bed350306242e789b04625ff3052e803b73379
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/locale/de_DE/config.xml
@@ -0,0 +1,50 @@
+<?xml version="1.0"?>
+<!--
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Magento
+ * @package     unit_tests
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<config>
+    <modules>
+        <Fixture_ModuleOne>
+            <active>true</active>
+            <depends>
+                <Fixture_NonExistingModule type="soft"/>
+            </depends>
+        </Fixture_ModuleOne>
+        <Fixture_ModuleTwo>
+            <active>true</active>
+            <depends>
+                <Fixture_InactiveModule type="soft"/>
+                <Fixture_ModuleOne type="hard"/>
+            </depends>
+        </Fixture_ModuleTwo>
+        <Fixture_ModuleThree>
+            <active>true</active>
+            <depends>
+                <Fixture_ModuleTwo/>
+            </depends>
+        </Fixture_ModuleThree>
+    </modules>
+</config>
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/locale/en_US/config.xml b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/locale/en_US/config.xml
new file mode 100644
index 0000000000000000000000000000000000000000..80bed350306242e789b04625ff3052e803b73379
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/locale/en_US/config.xml
@@ -0,0 +1,50 @@
+<?xml version="1.0"?>
+<!--
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Magento
+ * @package     unit_tests
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<config>
+    <modules>
+        <Fixture_ModuleOne>
+            <active>true</active>
+            <depends>
+                <Fixture_NonExistingModule type="soft"/>
+            </depends>
+        </Fixture_ModuleOne>
+        <Fixture_ModuleTwo>
+            <active>true</active>
+            <depends>
+                <Fixture_InactiveModule type="soft"/>
+                <Fixture_ModuleOne type="hard"/>
+            </depends>
+        </Fixture_ModuleTwo>
+        <Fixture_ModuleThree>
+            <active>true</active>
+            <depends>
+                <Fixture_ModuleTwo/>
+            </depends>
+        </Fixture_ModuleThree>
+    </modules>
+</config>
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/locale/es_ES/config.xml b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/locale/es_ES/config.xml
new file mode 100644
index 0000000000000000000000000000000000000000..80bed350306242e789b04625ff3052e803b73379
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/locale/es_ES/config.xml
@@ -0,0 +1,50 @@
+<?xml version="1.0"?>
+<!--
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Magento
+ * @package     unit_tests
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<config>
+    <modules>
+        <Fixture_ModuleOne>
+            <active>true</active>
+            <depends>
+                <Fixture_NonExistingModule type="soft"/>
+            </depends>
+        </Fixture_ModuleOne>
+        <Fixture_ModuleTwo>
+            <active>true</active>
+            <depends>
+                <Fixture_InactiveModule type="soft"/>
+                <Fixture_ModuleOne type="hard"/>
+            </depends>
+        </Fixture_ModuleTwo>
+        <Fixture_ModuleThree>
+            <active>true</active>
+            <depends>
+                <Fixture_ModuleTwo/>
+            </depends>
+        </Fixture_ModuleThree>
+    </modules>
+</config>
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/locale/fr_FR/config.xml b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/locale/fr_FR/config.xml
new file mode 100644
index 0000000000000000000000000000000000000000..80bed350306242e789b04625ff3052e803b73379
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/locale/fr_FR/config.xml
@@ -0,0 +1,50 @@
+<?xml version="1.0"?>
+<!--
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Magento
+ * @package     unit_tests
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<config>
+    <modules>
+        <Fixture_ModuleOne>
+            <active>true</active>
+            <depends>
+                <Fixture_NonExistingModule type="soft"/>
+            </depends>
+        </Fixture_ModuleOne>
+        <Fixture_ModuleTwo>
+            <active>true</active>
+            <depends>
+                <Fixture_InactiveModule type="soft"/>
+                <Fixture_ModuleOne type="hard"/>
+            </depends>
+        </Fixture_ModuleTwo>
+        <Fixture_ModuleThree>
+            <active>true</active>
+            <depends>
+                <Fixture_ModuleTwo/>
+            </depends>
+        </Fixture_ModuleThree>
+    </modules>
+</config>
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/testdir/etc/directorytest/local.xml b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/testdir/etc/directorytest/local.xml
new file mode 100644
index 0000000000000000000000000000000000000000..17522391cc9db06ba09482a4cf87bef04d9273c1
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/testdir/etc/directorytest/local.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0"?>
+<!--
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Magento
+ * @package     unit_tests
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<config>
+    <modules>
+        <Fixture_ModuleOne>
+            <active>true</active>
+            <depends>
+                <Fixture_ModuleTwo/>
+            </depends>
+        </Fixture_ModuleOne>
+        <Fixture_ModuleTwo>
+            <active>true</active>
+            <depends>
+                <Fixture_ModuleOne/>
+            </depends>
+        </Fixture_ModuleTwo>
+    </modules>
+</config>
\ No newline at end of file
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/testdir/etc/directorytest/testconfig.xml b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/testdir/etc/directorytest/testconfig.xml
new file mode 100644
index 0000000000000000000000000000000000000000..17522391cc9db06ba09482a4cf87bef04d9273c1
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/testdir/etc/directorytest/testconfig.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0"?>
+<!--
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Magento
+ * @package     unit_tests
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<config>
+    <modules>
+        <Fixture_ModuleOne>
+            <active>true</active>
+            <depends>
+                <Fixture_ModuleTwo/>
+            </depends>
+        </Fixture_ModuleOne>
+        <Fixture_ModuleTwo>
+            <active>true</active>
+            <depends>
+                <Fixture_ModuleOne/>
+            </depends>
+        </Fixture_ModuleTwo>
+    </modules>
+</config>
\ No newline at end of file
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/testdir/etc/local.xml b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/testdir/etc/local.xml
new file mode 100644
index 0000000000000000000000000000000000000000..17522391cc9db06ba09482a4cf87bef04d9273c1
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/testdir/etc/local.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0"?>
+<!--
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Magento
+ * @package     unit_tests
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<config>
+    <modules>
+        <Fixture_ModuleOne>
+            <active>true</active>
+            <depends>
+                <Fixture_ModuleTwo/>
+            </depends>
+        </Fixture_ModuleOne>
+        <Fixture_ModuleTwo>
+            <active>true</active>
+            <depends>
+                <Fixture_ModuleOne/>
+            </depends>
+        </Fixture_ModuleTwo>
+    </modules>
+</config>
\ No newline at end of file
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/testdir/etc/testconfig.xml b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/testdir/etc/testconfig.xml
new file mode 100644
index 0000000000000000000000000000000000000000..17522391cc9db06ba09482a4cf87bef04d9273c1
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/testdir/etc/testconfig.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0"?>
+<!--
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Magento
+ * @package     unit_tests
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<config>
+    <modules>
+        <Fixture_ModuleOne>
+            <active>true</active>
+            <depends>
+                <Fixture_ModuleTwo/>
+            </depends>
+        </Fixture_ModuleOne>
+        <Fixture_ModuleTwo>
+            <active>true</active>
+            <depends>
+                <Fixture_ModuleOne/>
+            </depends>
+        </Fixture_ModuleTwo>
+    </modules>
+</config>
\ No newline at end of file
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/testdir/etc/testdirectory/customconfig.xml b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/testdir/etc/testdirectory/customconfig.xml
new file mode 100644
index 0000000000000000000000000000000000000000..17522391cc9db06ba09482a4cf87bef04d9273c1
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Config/_files/testdir/etc/testdirectory/customconfig.xml
@@ -0,0 +1,43 @@
+<?xml version="1.0"?>
+<!--
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Magento
+ * @package     unit_tests
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<config>
+    <modules>
+        <Fixture_ModuleOne>
+            <active>true</active>
+            <depends>
+                <Fixture_ModuleTwo/>
+            </depends>
+        </Fixture_ModuleOne>
+        <Fixture_ModuleTwo>
+            <active>true</active>
+            <depends>
+                <Fixture_ModuleOne/>
+            </depends>
+        </Fixture_ModuleTwo>
+    </modules>
+</config>
\ No newline at end of file
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/ConfigTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/ConfigTest.php
index cd899c38aaffeacbd05c54dee3002106786c5f1d..26671b65287365731b4f390ac781210633878f26 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Model/ConfigTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/ConfigTest.php
@@ -32,47 +32,170 @@ class Mage_Core_Model_ConfigTest extends PHPUnit_Framework_TestCase
      */
     protected $_model;
 
-    /**
-     * @param mixed $data
-     * @dataProvider constructorDataProvider
-     */
-    public function testConstructor($data)
+    public function setUp()
+    {
+        $xml = '<config>
+                    <modules>
+                        <Module>
+                            <version>1.6.0.0</version>
+                            <active>false</active>
+                            <codePool>community</codePool>
+                        </Module>
+                    </modules>
+                    <global>
+                        <areas>
+                            <adminhtml>
+                                <base_controller>base_controller</base_controller>
+                                <routers>
+                                    <admin>
+                                        <class>class</class>
+                                    </admin>
+                                </routers>
+                                <frontName>backend</frontName>
+                                <acl>
+                                    <resourceLoader>resourceLoader</resourceLoader>
+                                    <roleLocator>roleLocator</roleLocator>
+                                    <policy>policy</policy>
+                                </acl>
+                            </adminhtml>
+                        </areas>
+                        <resources>
+                            <module_setup>
+                                <setup>
+                                    <module>Module</module>
+                                    <class>Module_Model_Resource_Setup</class>
+                                </setup>
+                            </module_setup>
+                        </resources>
+                        <di>
+                            <Mage_Core_Model_Cache>
+                                <parameters><one>two</one></parameters>
+                            </Mage_Core_Model_Cache>
+                        </di>
+                    </global>
+                </config>';
+
+        $configBase = new Mage_Core_Model_Config_Base($xml);
+        $objectManagerMock = $this->getMock('Magento_ObjectManager');
+        $objectManagerMock->expects($this->once())->method('setConfiguration')->with(array(
+            'Mage_Core_Model_Cache' => array(
+                'parameters' => array('one' => 'two')
+            )
+        ));
+        $appMock = $this->getMock('Mage_Core_Model_AppInterface');
+        $configStorageMock = $this->getMock('Mage_Core_Model_Config_StorageInterface');
+        $configStorageMock->expects($this->any())->method('getConfiguration')->will($this->returnValue($configBase));
+        $modulesReaderMock = $this->getMock('Mage_Core_Model_Config_Modules_Reader', array(), array(), '', false);
+        $invalidatorMock = $this->getMock('Mage_Core_Model_Config_InvalidatorInterface');
+
+        $this->_model = new Mage_Core_Model_Config(
+            $objectManagerMock, $configStorageMock, $appMock, $modulesReaderMock, $invalidatorMock
+        );
+    }
+
+    public function tearDown()
     {
-        //TODO: We should not use mocks in integration tests
-        /** @var Magento_ObjectManager_Zend|PHPUnit_Framework_MockObject_MockObject $objectManagerMock */
-        $objectManagerMock = $this->getMock('Magento_ObjectManager_Zend', array('create', 'get'), array(), '', false);
-        $objectManagerMock->expects($this->any())
-            ->method('create')
-            ->will($this->returnValueMap(
-                array(
-                    array(
-                        'Mage_Core_Model_Config_Base',
-                        array(),
-                        true,
-                        new Mage_Core_Model_Config_Base()
-                    )
-                )
-            ));
-
-        $this->_model = new Mage_Core_Model_Config($objectManagerMock, $data);
+        unset($this->_model);
     }
 
-    /**
-     * @return array
-     */
-    public function constructorDataProvider()
+    public function testGetXpathMissingXpath()
+    {
+        $xpath = $this->_model->getXpath('global/resources/module_setup/setup/module1');
+        $this->assertEquals(false, $xpath);
+    }
+
+    public function testGetXpath()
+    {
+        /** @var Mage_Core_Model_Config_Element $tmp */
+        $node = 'Module';
+        $expected = array( 0 => $node );
+
+        $xpath = $this->_model->getXpath('global/resources/module_setup/setup/module');
+        $this->assertEquals($expected, $xpath);
+    }
+
+    public function testSetNodeData()
+    {
+        $this->_model->setNode('modules/Module/active', 'true');
+
+        /** @var Mage_Core_Model_Config_Element $tmp */
+        $node = 'true';
+        $expected = array( 0 => $node );
+
+        $actual = $this->_model->getXpath('modules/Module/active');
+        $this->assertEquals($expected, $actual);
+    }
+
+    public function testGetNode()
     {
-        $simpleXml = new Varien_Simplexml_Element('<body></body>');
-        return array(
-            array(
-                'data' => null
+        $this->assertInstanceOf('Mage_Core_Model_Config_Element', $this->_model->getNode(
+            'global/resources/module_setup/setup/module'));
+    }
+
+    public function testSetCurrentAreaCode()
+    {
+        $this->assertInstanceOf('Mage_Core_Model_Config', $this->_model->setCurrentAreaCode('adminhtml'));
+    }
+
+    public function testGetCurrentAreaCode()
+    {
+        $areaCode = 'adminhtml';
+        $this->_model->setCurrentAreaCode($areaCode);
+        $actual = $this->_model->getCurrentAreaCode();
+        $this->assertEquals($areaCode, $actual);
+    }
+
+    public function testGetAreas()
+    {
+        $expected = array(
+            'adminhtml' => array(
+                'base_controller' => 'base_controller',
+                'routers' => array(
+                    'admin' => array(
+                        'class' => 'class'
+                    ),
+                ),
+                'frontName' => 'backend',
+                'acl' => array(
+                    'resourceLoader' => 'resourceLoader',
+                    'roleLocator' => 'roleLocator',
+                    'policy' => 'policy',
+                ),
             ),
-            array(
-                'data' => array()
+        );
+
+        $areaCode = 'adminhtml';
+        $this->_model->setCurrentAreaCode($areaCode);
+        $this->assertEquals($expected, $this->_model->getAreas());
+    }
+
+    public function testGetRouters()
+    {
+        $expected = array(
+            'admin' => array(
+                'class' => 'class',
+                'base_controller' => 'base_controller',
+                'frontName' => 'backend',
+                'acl' => array(
+                    'resourceLoader' => 'resourceLoader',
+                    'roleLocator' => 'roleLocator',
+                    'policy' => 'policy',
+                ),
+                'area' => 'adminhtml',
             ),
-            array(
-                'data' => $simpleXml
-            )
         );
+
+        $this->assertEquals($expected, $this->_model->getRouters());
+    }
+
+    public function testGetModuleConfig()
+    {
+        $this->assertInstanceOf('Mage_Core_Model_Config_Element', $this->_model->getModuleConfig('Module'));
+    }
+
+    public function testIsModuleEnabled()
+    {
+        $this->_model->setNode('modules/Module/active', 'true');
+        $this->assertEquals(true, $this->_model->isModuleEnabled('Module'));
     }
 }
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/DirTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/DirTest.php
index 8e90493146b3c27aee91e043ad6b0fdee36c93ad..2cd99b87b4675f4f252a6d433a6df02157526be7 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Model/DirTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/DirTest.php
@@ -23,12 +23,24 @@
  */
 class Mage_Core_Model_DirTest extends PHPUnit_Framework_TestCase
 {
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_fileSystemMock;
+
+    public function setUp()
+    {
+        $this->_fileSystemMock = $this->getMock('Varien_Io_File',
+            array('checkAndCreateFolder'), array(), '', false, false
+        );
+    }
+
     public function testGetWritableDirCodes()
     {
         $codes = Mage_Core_Model_Dir::getWritableDirCodes();
         $this->assertInternalType('array', $codes);
         $this->assertNotEmpty($codes);
-        $dir = new Mage_Core_Model_Dir(__DIR__);
+        $dir = new Mage_Core_Model_Dir(__DIR__, $this->_fileSystemMock);
         foreach ($codes as $code) {
             $this->assertNotEmpty($dir->getDir($code));
         }
@@ -42,7 +54,7 @@ class Mage_Core_Model_DirTest extends PHPUnit_Framework_TestCase
      */
     public function testInvalidUri($code, $value)
     {
-        new Mage_Core_Model_Dir(__DIR__, array($code => $value));
+        new Mage_Core_Model_Dir(__DIR__, $this->_fileSystemMock, array($code => $value));
     }
 
     /**
@@ -65,11 +77,14 @@ class Mage_Core_Model_DirTest extends PHPUnit_Framework_TestCase
 
     public function testGetUri()
     {
-        $dir = new Mage_Core_Model_Dir(__DIR__, array(
-            Mage_Core_Model_Dir::PUB   => '',
-            Mage_Core_Model_Dir::MEDIA => 'test',
-            'custom' => 'test2'
-        ));
+        $dir = new Mage_Core_Model_Dir(__DIR__,
+            $this->_fileSystemMock,
+            array(
+                Mage_Core_Model_Dir::PUB   => '',
+                Mage_Core_Model_Dir::MEDIA => 'test',
+                'custom' => 'test2'
+            )
+        );
 
         // arbitrary custom value
         $this->assertEquals('test2', $dir->getUri('custom'));
@@ -83,7 +98,7 @@ class Mage_Core_Model_DirTest extends PHPUnit_Framework_TestCase
         $this->assertEquals('test/upload', $dir->getUri(Mage_Core_Model_Dir::UPLOAD));
 
         // dirs should not be affected (there is no getter for all directories, so use whatever getter is available)
-        $default = new Mage_Core_Model_Dir(__DIR__);
+        $default = new Mage_Core_Model_Dir(__DIR__, $this->_fileSystemMock);
         foreach (Mage_Core_Model_Dir::getWritableDirCodes() as $code) {
             $this->assertEquals($default->getDir($code), $dir->getDir($code));
         }
@@ -93,7 +108,7 @@ class Mage_Core_Model_DirTest extends PHPUnit_Framework_TestCase
     {
         $newRoot = __DIR__ . DIRECTORY_SEPARATOR . 'root';
         $newMedia = __DIR__ . DIRECTORY_SEPARATOR . 'media';
-        $dir = new Mage_Core_Model_Dir(__DIR__, array(), array(
+        $dir = new Mage_Core_Model_Dir(__DIR__, $this->_fileSystemMock, array(), array(
             Mage_Core_Model_Dir::ROOT => $newRoot,
             Mage_Core_Model_Dir::MEDIA => $newMedia,
             'custom' => 'test2'
@@ -111,7 +126,7 @@ class Mage_Core_Model_DirTest extends PHPUnit_Framework_TestCase
         $this->assertStringStartsWith($newMedia, $dir->getDir(Mage_Core_Model_Dir::UPLOAD));
 
         // uris should not be affected
-        $default = new Mage_Core_Model_Dir(__DIR__);
+        $default = new Mage_Core_Model_Dir(__DIR__, $this->_fileSystemMock);
         foreach (array(
             Mage_Core_Model_Dir::PUB,
             Mage_Core_Model_Dir::PUB_LIB,
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/EncryptionTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/EncryptionTest.php
index cf39cb6648a26cf2ddba17eb1d2de140ed6e71fc..cbf80642b90bfb29022e3716a9c2cd323a08db05 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Model/EncryptionTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/EncryptionTest.php
@@ -32,8 +32,8 @@ class Mage_Core_Model_EncryptionTest extends PHPUnit_Framework_TestCase
         $objectManager = $this->getMock('Magento_ObjectManager_Zend', array('get'), array(), '', false);
         $objectManager->expects($this->once())
             ->method('get')
-            ->with('Mage_Core_Helper_Data')
-            ->will($this->returnValue(new Mage_Core_Helper_Data()));
+            ->with($this->stringContains('Mage_Core_Helper_Data'))
+            ->will($this->returnValue($this->getMock('Mage_Core_Helper_Data', array(), array(), '', false, false)));
 
         /**
          * @var Mage_Core_Model_Encryption
@@ -50,7 +50,7 @@ class Mage_Core_Model_EncryptionTest extends PHPUnit_Framework_TestCase
     {
         return array(
             'string' => array('Mage_Core_Helper_Data'),
-            'object' => array(new Mage_Core_Helper_Data()),
+            'object' => array($this->getMock('Mage_Core_Helper_Data', array(), array(), '', false, false)),
         );
     }
 
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/EntryPoint/HttpTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/EntryPoint/HttpTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..d9adc42643740ea32ad36db43ab469d3cb354fb6
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/EntryPoint/HttpTest.php
@@ -0,0 +1,55 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_EntryPoint_HttpTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_objectManagerMock;
+
+    /**
+     * @var Mage_Core_Model_EntryPoint_Http
+     */
+    protected $_model;
+
+    protected function setUp()
+    {
+        $this->_objectManagerMock = $this->getMock('Magento_ObjectManager');
+        $this->_model = new Mage_Core_Model_EntryPoint_Http(__DIR__, array(), $this->_objectManagerMock);
+    }
+
+    public function testHttpHandlerProcessesRequest()
+    {
+        $request = $this->getMock('Mage_Core_Controller_Request_Http', array(), array(), '', false);
+        $response = $this->getMock('Mage_Core_Controller_Response_Http', array(), array(), '', false);
+        $requestHandlerMock = $this->getMock('Magento_Http_HandlerInterface');
+        $requestHandlerMock->expects($this->once())->method('handle')->with($request, $response);
+        $this->_objectManagerMock->expects($this->any())->method('get')->will($this->returnValueMap(array(
+            array('Mage_Core_Controller_Request_Http', array(), $request),
+            array('Mage_Core_Controller_Response_Http', array(), $response),
+            array('Magento_Http_Handler_Composite', array(), $requestHandlerMock),
+        )));
+        $this->_model->processRequest();
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Core/Helper/TranslateTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Locale/Hierarchy/LoaderTest.php
similarity index 57%
rename from dev/tests/unit/testsuite/Mage/Core/Helper/TranslateTest.php
rename to dev/tests/unit/testsuite/Mage/Core/Model/Locale/Hierarchy/LoaderTest.php
index 5825a549f1fdb87b17958e96b25648999aeb7456..aaed2bc1cee6841f5ce71977ae73699c6c17f281 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Helper/TranslateTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Locale/Hierarchy/LoaderTest.php
@@ -25,64 +25,62 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-class Mage_Core_Helper_TranslateTest extends PHPUnit_Framework_TestCase
+class Mage_Core_Model_Locale_Hierarchy_LoaderTest extends PHPUnit_Framework_TestCase
 {
     /**
-     * Template helper mock
-     *
-     * @var Mage_Core_Helper_Translate
+     * @var Mage_Core_Model_Locale_Hierarchy_Loader
      */
-    protected $_helper;
+    protected $_model;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_configMock;
 
     protected function setUp()
     {
-        parent::setUp();
-        $this->_helper = new Mage_Core_Helper_Translate();
+        $this->_configMock = $this->getMock('Mage_Core_Model_Config_Locales', array(), array(), '', false, false);
+        $this->_model = new Mage_Core_Model_Locale_Hierarchy_Loader($this->_configMock);
     }
 
     /**
-     * @dataProvider testComposeLocaleHierarchyDataProvider
+     * @dataProvider composeLocaleHierarchyDataProvider
      */
     public function testComposeLocaleHierarchy($localeConfig, $localeHierarchy)
     {
-        $this->assertEquals($localeHierarchy, $this->_helper->composeLocaleHierarchy($localeConfig));
+        $node = new Varien_Simplexml_Element($localeConfig);
+        $this->_configMock->expects($this->once())->method('getNode')
+            ->with(Mage_Core_Model_Locale_Hierarchy_Loader::XML_PATH_LOCALE_INHERITANCE)
+            ->will($this->returnValue($node));
+        $this->assertEquals($localeHierarchy, $this->_model->load());
     }
 
-    public function testComposeLocaleHierarchyDataProvider()
+    public function composeLocaleHierarchyDataProvider()
     {
         return array(
             array(
-                array(
-                    'en_US' => 'en_UK',
-                    'en_UK' => 'pt_BR',
-                ),
+                'xml' => '<config><en_US>en_UK</en_US><en_UK>pt_BR</en_UK></config>',
                 array(
                     'en_US' => array('pt_BR', 'en_UK'),
                     'en_UK' => array('pt_BR'),
                 )
             ),
             array(
-                array(
-                    'en_US' => 'en_UK',
-                    'en_UK' => 'en_US',
-                ),
+                'xml' => '<config><en_US>en_UK</en_US><en_UK>en_US</en_UK></config>',
                 array(
                     'en_US' => array('en_UK'),
                     'en_UK' => array('en_US'),
                 )
             ),
             array(
-                array(
-                    'en_US' => '',
-                    'en_UK' => 'wrong_locale'
-                ),
+                'xml' => '<config><en_US/><en_UK>wrong_locale</en_UK></config>',
                 array(
                     'en_US' => array(''),
-                    'en_UK' => array('wrong_locale')
+                    'en_UK' => array('wrong_locale'),
                 )
             ),
             array(
-                array(),
+                'xml' => '<config></config>',
                 array()
             ),
         );
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/LoggerTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/LoggerTest.php
index d0c6e4a987b4e1def1fd049e1173c913f7e30cf0..72725d206e2b70645f595453dcd00ca392806be1 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Model/LoggerTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/LoggerTest.php
@@ -33,16 +33,28 @@ class Mage_Core_Model_LoggerTest extends PHPUnit_Framework_TestCase
      */
     protected $_loggersProperty = null;
 
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_dirMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_filesystemMock;
+
     protected function setUp()
     {
-        $dirs = new Mage_Core_Model_Dir(TESTS_TEMP_DIR);
-        $this->_model = new Mage_Core_Model_Logger($dirs);
-        $this->_loggersProperty = new ReflectionProperty($this->_model, '_loggers');
-        $this->_loggersProperty->setAccessible(true);
+        $this->_filesystemMock = $this->getMock('Varien_Io_File', array(), array(), '', false, false);
+        $dirs = new Mage_Core_Model_Dir(TESTS_TEMP_DIR, $this->_filesystemMock);
         $logDir = $dirs->getDir(Mage_Core_Model_Dir::LOG);
         if (!is_dir($logDir)) {
             mkdir($logDir, 0777, true);
         }
+
+        $this->_model = new Mage_Core_Model_Logger($dirs, $this->_filesystemMock);
+        $this->_loggersProperty = new ReflectionProperty($this->_model, '_loggers');
+        $this->_loggersProperty->setAccessible(true);
     }
 
     /**
@@ -114,6 +126,7 @@ class Mage_Core_Model_LoggerTest extends PHPUnit_Framework_TestCase
      */
     public function testAddStoreLog()
     {
+        $this->_filesystemMock->expects($this->once())->method('checkAndCreateFolder');
         $store = $this->getMock('Mage_Core_Model_Store', array('getConfig'), array(), '', false);
         $store->expects($this->at(0))->method('getConfig')->with('dev/log/active')->will($this->returnValue(false));
         $store->expects($this->at(1))->method('getConfig')->with('dev/log/active')->will($this->returnValue(true));
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/ObjectManager/ConfigTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/ObjectManager/ConfigTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..a618bb872e8edcf6b8839352568c28ea0217925a
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/ObjectManager/ConfigTest.php
@@ -0,0 +1,55 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_ObjectManager_ConfigTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_ObjectManager_Config
+     */
+    protected $_model;
+
+    protected function setUp()
+    {
+        $params = array(
+        );
+        $this->_model = new Mage_Core_Model_ObjectManager_Config($params);
+    }
+
+    public function testConfigureInitializedObjectManager()
+    {
+        $configuration = $this->getMock('stdClass', array('asArray'));
+        $configuration->expects($this->any())->method('asArray')->will($this->returnValue(array('configuratorClass')));
+        $configMock = $this->getMock('Mage_Core_Model_Config_Primary', array(), array(), '', false);
+        $configMock->expects($this->any())->method('getNode')->with($this->stringStartsWith('global'))
+            ->will($this->returnValue($configuration));
+        $objectManagerMock = $this->getMock('Magento_ObjectManager');
+        $objectManagerMock->expects($this->exactly(2))->method('setConfiguration');
+        $objectManagerMock->expects($this->once())->method('get')->with('Mage_Core_Model_Config_Primary')
+            -> will($this->returnValue($configMock));
+        $configuratorMock = $this->getMock('Magento_ObjectManager_Configuration');
+        $configuratorMock->expects($this->once())->method('configure')->with($objectManagerMock);
+        $objectManagerMock->expects($this->once())->method('create')->with('configuratorClass')
+            ->will($this->returnValue($configuratorMock));
+        $this->_model->configure($objectManagerMock);
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/ObjectManagerTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/ObjectManagerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..a8676fc2c1aa3c4fbc5d1d0b3b179d2bd9542884
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/ObjectManagerTest.php
@@ -0,0 +1,39 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Core_Model_ObjectManagerTest extends PHPUnit_Framework_TestCase
+{
+    public function testConstructConfiguresObjectManager()
+    {
+        $this->assertNull(Mage::getObjectManager());
+        $configMock = $this->getMock('Magento_ObjectManager_Configuration');
+        $configMock->expects($this->once())
+            ->method('configure')
+            ->with($this->isInstanceOf('Mage_Core_Model_ObjectManager'));
+        $diMock = $this->getMock('Magento_Di');
+        $imMock = $this->getMock('Magento_Di_InstanceManager');
+        $diMock->expects($this->any())->method('instanceManager')->will($this->returnValue($imMock));
+        $objectManager = new Mage_Core_Model_ObjectManager($configMock, __DIR__, $diMock);
+        $this->assertEquals($objectManager, Mage::getObjectManager());
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Resource/Db/AbstractTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Resource/Db/AbstractTest.php
index bdf2e944e2975022565e0eb26304883eac76298c..e9add072b8ff3fe073dd4e14504b6a6d17b69b9e 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Model/Resource/Db/AbstractTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Resource/Db/AbstractTest.php
@@ -42,7 +42,9 @@ class Mage_Core_Model_Resource_Db_AbstractTest extends PHPUnit_Framework_TestCas
 
     public function setUp()
     {
-        $this->_resource = $this->getMock('Mage_Core_Model_Resource', array('getConnection'));
+        $this->_resource = $this->getMock('Mage_Core_Model_Resource',
+            array('getConnection'), array(), '', false, false
+        );
         $this->_model = $this->getMock(
             'Mage_Core_Model_Resource_Db_Abstract',
             array('_construct', '_getWriteAdapter'),
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Resource/SessionTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Resource/SessionTest.php
index 900c55739f945111eccd5dbaf1d1358572176e40..0d91743377edcba4847bd13354091cc7c7bd1a9b 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Model/Resource/SessionTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Resource/SessionTest.php
@@ -96,7 +96,8 @@ class Mage_Core_Model_Resource_SessionTest extends PHPUnit_Framework_TestCase
      */
     protected function _prepareResourceMock($connection)
     {
-        $resource = $this->getMock('Mage_Core_Model_Resource', array('getTableName', 'getConnection'));
+        $resource = $this->getMock('Mage_Core_Model_Resource', array('getTableName', 'getConnection'),
+            array(), '', false, false);
         $resource->expects($this->once())
             ->method('getTableName')
             ->will($this->returnValue(self::SESSION_TABLE));
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Resource/Setup/MigrationTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Resource/Setup/MigrationTest.php
index 2f04e129bc5cd0f41e4aef551bea14a19f6ce045..2268b6bbc92a5a73fa7a2bb41b2c0551e61323a8 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Model/Resource/Setup/MigrationTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Resource/Setup/MigrationTest.php
@@ -100,7 +100,7 @@ class Mage_Core_Model_Resource_Setup_MigrationTest extends PHPUnit_Framework_Tes
             'base_dir'          => 'not_used',
             'path_to_map_file'  => 'not_used',
             'connection'        => $adapterMock,
-            'core_helper'       => new Mage_Core_Helper_Data(),
+            'core_helper'       => $this->getMock('Mage_Core_Helper_Data', array(), array(), '', false, false),
             'aliases_map'       => $aliasesMap
         );
     }
@@ -150,7 +150,14 @@ class Mage_Core_Model_Resource_Setup_MigrationTest extends PHPUnit_Framework_Tes
     public function testAppendClassAliasReplace()
     {
         $setupModel = new Mage_Core_Model_Resource_Setup_Migration(
-            'core_setup', $this->_getFilesystemMock(), $this->_getModelDependencies());
+            $this->getMock('Mage_Core_Model_Config_Resource', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Config_Modules', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Resource', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Config_Modules_Reader', array(), array(), '', false, false),
+            $this->getMock('Magento_Filesystem', array(), array(), '', false),
+            'core_setup',
+            $this->_getModelDependencies()
+        );
 
         $setupModel->appendClassAliasReplace('tableName', 'fieldName', 'entityType', 'fieldContentType',
             array('pk_field1', 'pk_field2'), 'additionalWhere'
@@ -199,10 +206,15 @@ class Mage_Core_Model_Resource_Setup_MigrationTest extends PHPUnit_Framework_Tes
         $tableRowsCount = count($tableData);
 
         $setupModel = new Mage_Core_Model_Resource_Setup_Migration(
+            $this->getMock('Mage_Core_Model_Config_Resource', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Config_Modules', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Resource', array(), array(), '', false, false),
+            $this->getMock('Mage_Core_Model_Config_Modules_Reader', array(), array(), '', false, false),
+            $this->getMock('Magento_Filesystem', array(), array(), '', false),
             'core_setup',
-            $this->_getFilesystemMock(),
             $this->_getModelDependencies($tableRowsCount, $tableData, $aliasesMap)
         );
+
         $setupModel->setTable('table', 'table');
 
         foreach ($replaceRules as $replaceRule) {
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Store/Storage/DefaultTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Store/Storage/DefaultTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..a020be17fd241f083ae0a64eed50a646123a9641
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Store/Storage/DefaultTest.php
@@ -0,0 +1,190 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Test class for Mage_Core_Model_Store_Storage_Default
+ */
+class Mage_Core_Model_Store_Storage_DefaultTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Store_Storage_Default
+     */
+    protected $_model;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_storeFactoryMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_websiteFactoryMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_groupFactoryMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_storeMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_websiteMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_groupMock;
+
+    protected function setUp()
+    {
+        $this->_websiteMock = $this->getMock('Mage_Core_Model_Website',
+            array('getCode', 'getId'), array(), '', false, false);
+        $this->_groupMock = $this->getMock('Mage_Core_Model_Store_Group',
+            array('getCode', 'getId'), array(), '', false, false);
+        $this->_storeFactoryMock = $this->getMock('Mage_Core_Model_StoreFactory',
+            array('create'), array(), '', false, false);
+        $this->_websiteFactoryMock = $this->getMock('Mage_Core_Model_Website_Factory',
+            array('create'), array(), '', false, false);
+        $this->_websiteFactoryMock
+            ->expects($this->once())
+            ->method('create')
+            ->will($this->returnValue($this->_websiteMock));
+        $this->_groupFactoryMock = $this->getMock('Mage_Core_Model_Store_Group_Factory',
+            array('createFromArray'), array(), '', false, false);
+        $this->_groupFactoryMock
+            ->expects($this->once())
+            ->method('createFromArray')
+            ->will($this->returnValue($this->_groupMock));
+        $this->_storeMock = $this->getMock('Mage_Core_Model_Store', array('setId', 'setCode', 'getCode'),
+            array(), '', false, false);
+        $this->_storeFactoryMock->expects($this->once())
+            ->method('create')
+            ->will($this->returnValue($this->_storeMock));
+        $this->_model = new Mage_Core_Model_Store_Storage_Default(
+            $this->_storeFactoryMock,
+            $this->_websiteFactoryMock,
+            $this->_groupFactoryMock
+        );
+    }
+
+    protected function tearDown()
+    {
+        unset($this->_storeFactoryMock);
+        unset($this->_websiteFactoryMock);
+        unset($this->_groupFactoryMock);
+        unset($this->_storeMock);
+        unset($this->_model);
+    }
+
+    public function testHasSingleStore()
+    {
+        $this->assertEquals(false, $this->_model->hasSingleStore());
+    }
+
+    public function testGetStore()
+    {
+        $storeId = 'testStore';
+        $this->assertInstanceOf('Mage_Core_Model_Store', $this->_model->getStore($storeId));
+    }
+
+    public function testGetStores()
+    {
+        $withDefault = true;
+        $codeKey = true;
+        $this->assertEquals(array(), $this->_model->getStores($withDefault, $codeKey));
+    }
+
+    public function testGetWebsite()
+    {
+        $websiteId = 'testWebsite';
+        $this->assertInstanceOf('Mage_Core_Model_Website', $this->_model->getWebsite($websiteId));
+    }
+
+    public function testGetWebsitesWithDefault()
+    {
+        $withDefault = true;
+        $codeKey = 'someKey';
+        $this->_websiteMock->expects($this->once())->method('getCode')->will($this->returnValue(0));
+        $this->_websiteMock->expects($this->never())->method('getId');
+        $result = $this->_model->getWebsites($withDefault, $codeKey);
+        $this->assertInstanceOf('Mage_Core_Model_Website', $result[0]);
+    }
+
+    public function testGetWebsitesWithoutDefault()
+    {
+        $withDefault = false;
+        $codeKey = 'someKey';
+        $this->_websiteMock->expects($this->never())->method('getCode');
+        $this->_websiteMock->expects($this->never())->method('getId');
+        $result = $this->_model->getWebsites($withDefault, $codeKey);
+        $this->assertEquals(array(), $result);
+    }
+
+    public function testGetGroup()
+    {
+        $groupId = 'testGroup';
+        $this->assertInstanceOf('Mage_Core_Model_Store_Group', $this->_model->getGroup($groupId));
+    }
+
+    public function testGetGroupsWithDefault()
+    {
+        $withDefault = true;
+        $codeKey = 'someKey';
+        $this->_groupMock->expects($this->once())->method('getCode')->will($this->returnValue(0));
+        $this->_groupMock->expects($this->never())->method('getId');
+        $result = $this->_model->getGroups($withDefault, $codeKey);
+        $this->assertInstanceOf('Mage_Core_Model_Store_Group', $result[0]);
+    }
+
+    public function testGetGroupsWithoutDefault()
+    {
+        $withDefault = false;
+        $codeKey = 'someKey';
+        $this->_groupMock->expects($this->never())->method('getCode');
+        $this->_groupMock->expects($this->never())->method('getId');
+        $result = $this->_model->getGroups($withDefault, $codeKey);
+        $this->assertEquals(array(), $result);
+    }
+
+    public function testGetDefaultStoreView()
+    {
+        $this->assertNull($this->_model->getDefaultStoreView());
+    }
+
+    public function testGetCurrentStore()
+    {
+        $this->_storeMock->expects($this->once())
+            ->method('getCode')
+            ->will($this->returnValue('result'));
+        $result = $this->_model->getCurrentStore();
+        $this->assertEquals('result', $result);
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Store/StorageFactoryTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Store/StorageFactoryTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..568889d0e9dc1f81adf02e5e123130b38c7db864
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Store/StorageFactoryTest.php
@@ -0,0 +1,194 @@
+<?php
+/**
+ * Test class for Mage_Core_Model_Store_StorageFactory
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Magento
+ * @package     Mage_Core
+ * @subpackage  unit_tests
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_Store_StorageFactoryTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Store_StorageFactory
+     */
+    protected $_model;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_objectManagerMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_eventManagerMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_logMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_configMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_appMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_appStateMock;
+
+    /**
+     * @var string
+     */
+    protected $_defaultStorage = 'Default_Storage_Class_Name';
+
+    /**
+     * @var string
+     */
+    protected $_dbStorage = 'Db_Storage_Class_Name';
+
+    /**
+     * @var array
+     */
+    protected $_arguments = array();
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_storage;
+
+    protected function setUp()
+    {
+        $this->_arguments = array('test' => 'argument');
+        $this->_objectManagerMock = $this->getMock('Magento_ObjectManager');
+        $this->_eventManagerMock = $this->getMock('Mage_Core_Model_Event_Manager', array(), array(), '', false);
+        $this->_logMock = $this->getMock('Mage_Core_Model_Logger', array(), array(), '', false);
+        $this->_configMock = $this->getMock('Mage_Core_Model_ConfigInterface', array(), array(), '', false);
+        $this->_appMock = $this->getMock('Mage_Core_Model_App_Proxy', array(), array(), '', false);
+        $this->_appStateMock = $this->getMock('Mage_Core_Model_App_State', array(), array(), '', false);
+        $this->_storage = $this->getMock('Mage_Core_Model_Store_StorageInterface');
+
+        $this->_model = new Mage_Core_Model_Store_StorageFactory(
+            $this->_objectManagerMock,
+            $this->_eventManagerMock,
+            $this->_logMock,
+            $this->_configMock,
+            $this->_appMock,
+            $this->_appStateMock,
+            $this->_defaultStorage,
+            $this->_dbStorage
+        );
+    }
+
+    public function testGetInNotInstalledModeWithInternalCache()
+    {
+        $this->_appStateMock->expects($this->exactly(2))->method('isInstalled')->will($this->returnValue(false));
+
+        $this->_objectManagerMock
+            ->expects($this->once())
+            ->method('get')
+            ->with($this->_defaultStorage)
+            ->will($this->returnValue($this->_storage));
+
+        $this->_eventManagerMock->expects($this->never())->method('dispatch');
+        $this->_logMock->expects($this->never())->method('initForStore');
+        $this->_appMock->expects($this->never())->method('setUseSessionInUrl');
+
+        /** test create instance */
+        $this->assertEquals($this->_storage, $this->_model->get($this->_arguments));
+
+        /** test read instance from internal cache */
+        $this->assertEquals($this->_storage, $this->_model->get($this->_arguments));
+    }
+
+    public function testGetInstalledModeWithInternalCache()
+    {
+        $this->_appStateMock->expects($this->exactly(2))->method('isInstalled')->will($this->returnValue(true));
+
+        $store = $this->getMock('Mage_Core_Model_Store', array(), array(), '', false);
+
+        $this->_storage
+            ->expects($this->exactly(2))
+            ->method('getStore')
+            ->will($this->returnValue($store));
+
+        $store->expects($this->once())
+            ->method('getConfig')
+            ->with(Mage_Core_Model_Session_Abstract::XML_PATH_USE_FRONTEND_SID)
+            ->will($this->returnValue(true));
+
+
+        $this->_objectManagerMock
+            ->expects($this->once())
+            ->method('get')
+            ->with($this->_dbStorage)
+            ->will($this->returnValue($this->_storage));
+
+        $this->_eventManagerMock->expects($this->once())->method('dispatch')->with('core_app_init_current_store_after');
+        $this->_logMock
+            ->expects($this->once())
+            ->method('initForStore')
+            ->with($store, $this->_configMock);
+
+        $this->_appMock->expects($this->once())->method('setUseSessionInUrl')->with(true);
+
+        /** test create instance */
+        $this->assertEquals($this->_storage, $this->_model->get($this->_arguments));
+
+        /** test read instance from internal cache */
+        $this->assertEquals($this->_storage, $this->_model->get($this->_arguments));
+    }
+
+    /**
+     * @expectedException InvalidArgumentException
+     */
+    public function testGetWithInvalidStorageClassName()
+    {
+        $this->_appStateMock->expects($this->once())->method('isInstalled')->will($this->returnValue(true));
+
+        $invalidObject = $this->getMock('Mage_Core_Model_Store', array(), array(), '', false);
+
+        $this->_objectManagerMock
+            ->expects($this->once())
+            ->method('get')
+            ->with($this->_dbStorage)
+            ->will($this->returnValue($invalidObject));
+
+        $this->_eventManagerMock->expects($this->never())->method('dispatch');
+        $this->_logMock->expects($this->never())->method('initForStore');
+        $this->_appMock->expects($this->never())->method('setUseSessionInUrl');
+
+        /** test create instance */
+        $this->assertEquals($this->_storage, $this->_model->get($this->_arguments));
+
+        /** test read instance from internal cache */
+        $this->assertEquals($this->_storage, $this->_model->get($this->_arguments));
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/StoreManagerTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/StoreManagerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..88396eed747caa411625f30a925c7582b89780ab
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/StoreManagerTest.php
@@ -0,0 +1,243 @@
+<?php
+/**
+ * Test class for Mage_Core_Model_StoreManagerTest
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Magento
+ * @package     Mage_Core
+ * @subpackage  unit_tests
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Core_Model_StoreManagerTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_StoreManager
+     */
+    protected $_model;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_factoryMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_requestMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_helperFactoryMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_storage;
+
+    protected function setUp()
+    {
+        $this->_factoryMock = $this->getMock('Mage_Core_Model_Store_StorageFactory', array(), array(), '', false);
+        $this->_requestMock = $this->getMock('Mage_Core_Controller_Request_Http', array(), array(), '', false);
+        $this->_helperFactoryMock = $this->getMock('Mage_Core_Model_Factory_Helper', array(), array(), '', false);
+        $this->_storage = $this->getMock('Mage_Core_Model_Store_StorageInterface');
+
+        $this->_model = new Mage_Core_Model_StoreManager(
+            $this->_factoryMock,
+            $this->_requestMock,
+            $this->_helperFactoryMock,
+            'scope_code',
+            'scope_type'
+        );
+    }
+
+    /**
+     * @param $method
+     * @param $arguments
+     * @param $expectedResult
+     * @dataProvider proxyMethodDataProvider
+     */
+    public function testProxyMethods($method, $arguments, $expectedResult)
+    {
+        $this->_factoryMock->expects($this->any())->method('get')->will($this->returnValue($this->_storage));
+
+        $map = array_values($arguments);
+        $map[] = $expectedResult;
+        $this->_storage->expects($this->once())
+            ->method($method)
+            ->will($this->returnValueMap(array($map)));
+
+        $actualResult = call_user_func_array(array($this->_model, $method), $arguments);
+        $this->assertEquals($expectedResult, $actualResult);
+    }
+
+    public function proxyMethodDataProvider()
+    {
+        return array(
+            'getCurrentStore' => array('getCurrentStore', array(), 'currentStoreObject'),
+            'getAnyStoreView' => array('getAnyStoreView', array(), 'anyStoreObject'),
+            'clearWebsiteCache' => array('clearWebsiteCache', array('id' => 101), null),
+            'getGroups' => array('getGroups', array('withDefault' => true, 'codeKey' => true), 'groupsArray'),
+            'getGroup' => array('getGroup', array('id' => 102), 'groupObject'),
+            'getDefaultStoreView' => array('getDefaultStoreView', array(), 'defaultStoreObject'),
+            'reinitStores' => array('reinitStores', array(), null),
+            'getWebsites' => array('getWebsites', array('withDefault' => true, 'codeKey' => true), 'websitesArray'),
+            'getWebsite' => array('getWebsite', array('id' => 103), 'websiteObject'),
+            'getStores' => array('getStores', array('withDefault' => true, 'codeKey' => true), 'storesArray'),
+            'getStore' => array('getStore', array('id' => 104), 'storeObject'),
+            'hasSingleStore' => array('hasSingleStore', array(), 'singleStoreResult'),
+            'throwStoreException' => array('throwStoreException', array(), null),
+        );
+    }
+
+    public function testGetStorageWithCurrentStore()
+    {
+        $arguments = array(
+            'isSingleStoreAllowed' => true,
+            'currentStore' => 'current_store_code',
+            'scopeCode' => 'scope_code',
+            'scopeType' => 'scope_type',
+        );
+
+        $this->_factoryMock->expects($this->any())
+            ->method('get')
+            ->with($arguments)
+            ->will($this->returnValue($this->_storage));
+
+        $this->_storage->expects($this->once())->method('setCurrentStore')->with('current_store_code');
+
+        $this->_model->setCurrentStore('current_store_code');
+    }
+
+    public function testGetStorageWithSingleStoreMode()
+    {
+        $arguments = array(
+            'isSingleStoreAllowed' => false,
+            'currentStore' => null,
+            'scopeCode' => 'scope_code',
+            'scopeType' => 'scope_type',
+        );
+
+        $this->_factoryMock->expects($this->any())
+            ->method('get')
+            ->with($arguments)
+            ->will($this->returnValue($this->_storage));
+
+        $this->_storage->expects($this->once())->method('setIsSingleStoreModeAllowed')->with(false);
+
+        $this->_model->setIsSingleStoreModeAllowed(false);
+    }
+
+    public function testIsSingleStoreModeWhenSingleStoreModeEnabledAndHasSingleStore()
+    {
+        $helperMock = $this->getMock('Mage_Core_Helper_Data', array(), array(), '', false);
+        $helperMock->expects($this->once())->method('isSingleStoreModeEnabled')->will($this->returnValue(true));
+
+        $this->_helperFactoryMock
+            ->expects($this->any())
+            ->method('get')
+            ->with('Mage_Core_Helper_Data')
+            ->will($this->returnValue($helperMock));
+
+        $this->_storage->expects($this->once())->method('hasSingleStore')->will($this->returnValue(true));
+
+        $this->_factoryMock->expects($this->any())->method('get')->will($this->returnValue($this->_storage));
+
+        $this->assertTrue($this->_model->isSingleStoreMode());
+    }
+
+    public function testIsSingleStoreModeWhenSingleStoreModeDisabledAndHasSingleStore()
+    {
+        $helperMock = $this->getMock('Mage_Core_Helper_Data', array(), array(), '', false);
+        $helperMock->expects($this->once())->method('isSingleStoreModeEnabled')->will($this->returnValue(false));
+
+        $this->_helperFactoryMock
+            ->expects($this->any())
+            ->method('get')
+            ->with('Mage_Core_Helper_Data')
+            ->will($this->returnValue($helperMock));
+
+        $this->_storage->expects($this->once())->method('hasSingleStore')->will($this->returnValue(true));
+
+        $this->_factoryMock->expects($this->any())->method('get')->will($this->returnValue($this->_storage));
+
+        $this->assertFalse($this->_model->isSingleStoreMode());
+    }
+
+    public function testGetSafeStoreWithoutException()
+    {
+        $this->_factoryMock->expects($this->any())->method('get')->will($this->returnValue($this->_storage));
+        $this->_storage->expects($this->once())->method('getStore')->with(10)->will($this->returnValue('storeObject'));
+        $this->_requestMock->expects($this->never())->method('setActionName');
+        $this->_model->getSafeStore(10);
+    }
+
+    public function testGetSafeStoreWithExceptionWithCurrentStore()
+    {
+        $this->_factoryMock->expects($this->any())->method('get')->will($this->returnValue($this->_storage));
+        $this->_storage->expects($this->once())
+            ->method('getStore')
+            ->with(10)
+            ->will($this->returnCallback(
+                function(){
+                    throw new Exception('test');
+                }
+            )
+        );
+
+        $this->_storage->expects($this->once())->method('getCurrentStore')->will($this->returnValue('current'));
+        $this->_requestMock->expects($this->once())->method('setActionName')->with('noRoute');
+
+        $this->assertInstanceOf('Varien_Object', $this->_model->getSafeStore(10));
+    }
+
+    /**
+     * @expectedException Mage_Core_Exception
+     */
+    public function testGetSafeStoreWithExceptionAndWithoutCurrentStore()
+    {
+        $this->_factoryMock->expects($this->any())->method('get')->will($this->returnValue($this->_storage));
+        $this->_storage->expects($this->once())
+            ->method('getStore')
+            ->with(10)
+            ->will($this->returnCallback(
+                function(){
+                    throw new Exception('test');
+                }
+            )
+        );
+
+        $this->_storage->expects($this->once())->method('getCurrentStore')->will($this->returnValue(false));
+        $this->_requestMock->expects($this->never())->method('setActionName');
+        $helperMock = $this->getMock('Mage_Core_Helper_Data', array(), array(), '', false);
+        $helperMock->expects($this->once())->method('__')->with($this->stringStartsWith('Requested invalid store'))
+            ->will($this->returnArgument(0));
+
+        $this->_helperFactoryMock
+            ->expects($this->any())
+            ->method('get')
+            ->with('Mage_Core_Helper_Data')
+            ->will($this->returnValue($helperMock));
+
+        $this->_model->getSafeStore(10);
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Theme/Customization/Files/JsTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Theme/Customization/Files/JsTest.php
index 7bec23913d0b257fb507a1b56bacdf4c03341857..e54ad5bd586cc645c30bc824ac36db3f52204ef2 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Model/Theme/Customization/Files/JsTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Theme/Customization/Files/JsTest.php
@@ -194,25 +194,25 @@ class Mage_Core_Model_Theme_Customization_Files_JsTest extends PHPUnit_Framework
             // case 1
             array(
                 array(
-                    array('file_name' => '1.js', 'sort_order' => '123'),
-                    array('file_name' => '2.js', 'sort_order' => '0'),
-                    array('file_name' => '3.js', 'sort_order' => '456')
+                    array('id' => '1', 'sort_order' => '123'),
+                    array('id' => '2', 'sort_order' => '0'),
+                    array('id' => '3', 'sort_order' => '456')
                 ),
-                array('1.js', '2.js', '3.js'),
+                array('2', '1', '3'),
                 array(
                     'totalRecords' => null,
                     'items'        => array(
                         array(
-                         'file_name' => '1.js',
-                         'sort_order'     => 1
+                         'id'         => 1,
+                         'sort_order' => 2
                         ),
                         array(
-                         'file_name' => '2.js',
-                         'sort_order'     => 2
+                         'id'         => 2,
+                         'sort_order' => 1
                         ),
                         array(
-                         'file_name' => '3.js',
-                         'sort_order'     => 3
+                         'id'         => 3,
+                         'sort_order' => 3
                         ),
                     )
                 )
@@ -220,25 +220,25 @@ class Mage_Core_Model_Theme_Customization_Files_JsTest extends PHPUnit_Framework
             // case 2
             array(
                 array(
-                    array('file_name' => '3.js', 'sort_order' => '0'),
-                    array('file_name' => '2.js', 'sort_order' => '0'),
-                    array('file_name' => '1.js', 'sort_order' => '0')
+                    array('id' => '3', 'sort_order' => '0'),
+                    array('id' => '2', 'sort_order' => '0'),
+                    array('id' => '1', 'sort_order' => '0')
                 ),
-                array('1.js', '2.js', '3.js'),
+                array('1', '2', '3'),
                 array(
                     'totalRecords' => null,
                     'items'        => array(
                         array(
-                         'file_name' => '1.js',
-                         'sort_order'     => 1
+                         'id'         => 1,
+                         'sort_order' => 1
                         ),
                         array(
-                         'file_name' => '2.js',
-                         'sort_order'     => 2
+                         'id'         => 2,
+                         'sort_order' => 2
                         ),
                         array(
-                         'file_name' => '3.js',
-                         'sort_order'     => 3
+                         'id'         => 3,
+                         'sort_order' => 3
                         ),
                     )
                 )
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Theme/ImageTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Theme/ImageTest.php
index 568d068f669e28b7e2c272787ad84e8394a1c987..8031a5ec0e1d1369fd8f4d6d0ccded9c35ab7241 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Model/Theme/ImageTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Theme/ImageTest.php
@@ -77,6 +77,23 @@ class Mage_Core_Model_Theme_ImageTest extends PHPUnit_Framework_TestCase
         return $designMock;
     }
 
+    /**
+     * @return PHPUnit_Framework_MockObject_MockObject|Mage_Core_Model_Dir
+     */
+    protected function _getDirMock()
+    {
+        $dirMock = $this->getMock('Mage_Core_Model_Dir', array('getDir'), array(), '', false);
+        $dirMock->expects($this->any())
+            ->method('getDir')
+            ->with($this->equalTo(Mage_Core_Model_Dir::THEME))
+            ->will($this->returnValue('pub/media/theme'));
+        $this->_objectManager->expects($this->any())
+            ->method('get')
+            ->with($this->equalTo('Mage_Core_Model_Dir'))
+            ->will($this->returnValue($dirMock));
+        return $dirMock;
+    }
+
     public function testSavePreviewImage()
     {
         $this->_model->setTheme($this->getMock('Mage_Core_Model_Theme', array(), array(), '', false));
@@ -85,9 +102,8 @@ class Mage_Core_Model_Theme_ImageTest extends PHPUnit_Framework_TestCase
 
     public function testGetImagePathOrigin()
     {
-        $designMock = $this->_getDesignMock();
-
-        $expectedResult = $designMock->getPublicDir() . DIRECTORY_SEPARATOR
+        $dirMock = $this->_getDirMock();
+        $expectedResult = $dirMock->getDir(Mage_Core_Model_Dir::THEME) . DIRECTORY_SEPARATOR
             . Mage_Core_Model_Theme_Image::IMAGE_DIR_ORIGIN;
 
         $this->assertEquals($expectedResult, $this->_model->getImagePathOrigin());
@@ -95,8 +111,9 @@ class Mage_Core_Model_Theme_ImageTest extends PHPUnit_Framework_TestCase
 
     public function testCreatePreviewImageCopy()
     {
-        $designMock = $this->_getDesignMock();
-        $filePath = $designMock->getPublicDir() . DIRECTORY_SEPARATOR . Mage_Core_Model_Theme_Image::IMAGE_DIR_PREVIEW;
+        $dirMock = $this->_getDirMock();
+        $filePath = $dirMock->getDir(Mage_Core_Model_Dir::THEME) . DIRECTORY_SEPARATOR
+            . Mage_Core_Model_Theme_Image::IMAGE_DIR_PREVIEW;
         $fileName = $filePath . DIRECTORY_SEPARATOR . 'image.jpg';
 
         $this->_filesystem->expects($this->any())
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Theme/ServiceTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Theme/ServiceTest.php
index 312b1c7d3f098d0af45dd036e8061350bd626328..a3b030ab0890e7ddda520c6169a7b0607ac0c2c5 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Model/Theme/ServiceTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Theme/ServiceTest.php
@@ -64,7 +64,8 @@ class Mage_Core_Model_Theme_ServiceTest extends PHPUnit_Framework_TestCase
             $this->getMock('Mage_Core_Model_App', array(), array(), '', false),
             $this->getMock('Mage_Core_Helper_Data', array(), array(), '', false),
             $this->getMock('Mage_DesignEditor_Model_Resource_Layout_Update', array(), array(), '', false),
-            $this->getMock('Mage_Core_Model_Event_Manager', array(), array(), '', false)
+            $this->getMock('Mage_Core_Model_Event_Manager', array(), array(), '', false),
+            $this->getMock('Mage_Core_Model_Config_Storage_WriterInterface', array(), array(), '', false)
         );
         $this->assertEquals($expectedResult, $themeService->isCustomizationsExist());
     }
@@ -107,7 +108,8 @@ class Mage_Core_Model_Theme_ServiceTest extends PHPUnit_Framework_TestCase
             $this->getMock('Mage_Core_Model_App', array(), array(), '', false),
             $this->getMock('Mage_Core_Helper_Data', array(), array(), '', false),
             $this->getMock('Mage_DesignEditor_Model_Resource_Layout_Update', array(), array(), '', false),
-            $this->getMock('Mage_Core_Model_Event_Manager', array(), array(), '', false)
+            $this->getMock('Mage_Core_Model_Event_Manager', array(), array(), '', false),
+            $this->getMock('Mage_Core_Model_Config_Storage_WriterInterface', array(), array(), '', false)
         );
         $themeService->assignThemeToStores(-1);
     }
@@ -175,9 +177,12 @@ class Mage_Core_Model_Theme_ServiceTest extends PHPUnit_Framework_TestCase
             ->method('create')
             ->will($this->returnValue($this->getMock('Mage_Core_Model_Theme', array(), array(), '', false)));
 
+        $writerMock = $this->getMock('Mage_Core_Model_Config_Storage_WriterInterface', array(), array(), '', false);
         /** @var $themeService Mage_Core_Model_Theme_Service */
         $themeService = $this->getMock('Mage_Core_Model_Theme_Service', array('_getThemeCustomizations'),
-            array($themeFactoryMock, $designMock, $appMock, $helperMock, $layoutUpdateMock, $eventManagerMock));
+            array($themeFactoryMock, $designMock, $appMock, $helperMock,
+                $layoutUpdateMock, $eventManagerMock, $writerMock)
+        );
         $themeService->expects($this->once())
             ->method('_getThemeCustomizations')
             ->will($this->returnValue($themesMock));
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/ThemeTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/ThemeTest.php
index ab9170bd0d5d6f6a79d7ff82ed00284bb3ca5193..8265f055268f772f81d0a66e55b7ba1119d49dec 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Model/ThemeTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/ThemeTest.php
@@ -102,6 +102,7 @@ class Mage_Core_Model_ThemeTest extends PHPUnit_Framework_TestCase
      */
     public function testLoadFromConfiguration()
     {
+        $this->markTestIncomplete('MAGETWO-5625');
         $targetPath = implode(DIRECTORY_SEPARATOR, array('frontend', 'default', 'iphone', 'theme.xml'));
         $designDir = implode(DIRECTORY_SEPARATOR, array(__DIR__, '_files'));
 
@@ -119,6 +120,7 @@ class Mage_Core_Model_ThemeTest extends PHPUnit_Framework_TestCase
      */
     public function testLoadInvalidConfiguration()
     {
+        $this->markTestIncomplete('MAGETWO-5625');
         $targetPath = implode(DIRECTORY_SEPARATOR, array('frontend', 'default', 'iphone', 'theme_invalid.xml'));
         $designDir = implode(DIRECTORY_SEPARATOR, array(__DIR__, '_files'));
 
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Validator/FactoryTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Validator/FactoryTest.php
index a91d18ec3853c150966de0e1149874d6f4c9a328..cf00b7b130291a26481d565cfbcfaf9ab45ff110 100644
--- a/dev/tests/unit/testsuite/Mage/Core/Model/Validator/FactoryTest.php
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Validator/FactoryTest.php
@@ -31,7 +31,7 @@ class Mage_Core_Model_Validator_FactoryTest extends PHPUnit_Framework_TestCase
     protected $_objectManager;
 
     /**
-     * @var Mage_Core_Model_Config
+     * @var Mage_Core_Model_Config_Modules_Reader
      */
     protected $_config;
 
@@ -74,7 +74,7 @@ class Mage_Core_Model_Validator_FactoryTest extends PHPUnit_Framework_TestCase
             ->will($this->returnValue(new Magento_Translate_Adapter()));
 
         // Config mock
-        $this->_config = $this->getMockBuilder('Mage_Core_Model_Config')
+        $this->_config = $this->getMockBuilder('Mage_Core_Model_Config_Modules_Reader')
             ->setMethods(array('getModuleConfigurationFiles'))
             ->disableOriginalConstructor()
             ->getMock();
@@ -86,7 +86,9 @@ class Mage_Core_Model_Validator_FactoryTest extends PHPUnit_Framework_TestCase
         // Translate adapter mock
         $designMock = $this->getMock('Mage_Core_Model_Design_Package', array(), array(), '', false);
         $this->_translateAdapter = $this->getMockBuilder('Mage_Core_Model_Translate')
-            ->setConstructorArgs(array($designMock))
+            ->setConstructorArgs(array($designMock,
+                $this->getMock('Mage_Core_Model_Locale_Hierarchy_Loader', array(), array(), '', false, false))
+            )
             ->setMethods(array('_getTranslatedString'))
             ->getMock();
         $this->_translateAdapter->expects($this->any())
@@ -113,8 +115,11 @@ class Mage_Core_Model_Validator_FactoryTest extends PHPUnit_Framework_TestCase
             ->with('Mage_Core_Model_Translate_Expr')
             ->will($this->returnValue(new Mage_Core_Model_Translate_Expr()));
 
-        $factory = new Mage_Core_Model_Validator_Factory($this->_objectManager, $this->_config,
-            $this->_translateAdapter);
+        $factory = new Mage_Core_Model_Validator_Factory(
+            $this->_objectManager,
+            $this->_config,
+            $this->_translateAdapter
+        );
         $actualConfig = $factory->getValidatorConfig();
         $this->assertInstanceOf('Magento_Validator_Config', $actualConfig,
             'Object of incorrect type was created');
diff --git a/dev/tests/unit/testsuite/Mage/Customer/Service/CustomerTest.php b/dev/tests/unit/testsuite/Mage/Customer/Service/CustomerTest.php
index 3e313bf95b7c6487613eee933df8063411e8336c..bbe338b994211548cb53f8311201f5492b396775 100644
--- a/dev/tests/unit/testsuite/Mage/Customer/Service/CustomerTest.php
+++ b/dev/tests/unit/testsuite/Mage/Customer/Service/CustomerTest.php
@@ -53,7 +53,9 @@ class Mage_Customer_Service_CustomerTest extends PHPUnit_Framework_TestCase
     protected function setUp()
     {
         $helper = $this->getMockBuilder('Mage_Customer_Helper_Data')
+            ->disableOriginalConstructor()
             ->getMock();
+
         $helper->expects($this->any())
             ->method('__')
             ->will($this->returnArgument(0));
@@ -69,7 +71,9 @@ class Mage_Customer_Service_CustomerTest extends PHPUnit_Framework_TestCase
         $this->_customer = $this->getMockBuilder('Mage_Customer_Model_Customer')
             ->setMethods(array('save', 'generatePassword', 'getOrigData', 'sendNewAccountEmail', 'getConfirmation',
                 'getPrimaryAddress', 'getAddresses', 'getAdditionalAddresses', 'load', 'getId', 'changePassword',
-                'sendPasswordReminderEmail', 'addAddress', 'getAddressItemById', 'getAddressesCollection'))
+                'sendPasswordReminderEmail', 'addAddress', 'getAddressItemById', 'getAddressesCollection',
+                'hashPassword')
+            )
             ->disableOriginalConstructor()
             ->getMock();
         $this->_customerFactory->expects($this->any())
@@ -220,6 +224,7 @@ class Mage_Customer_Service_CustomerTest extends PHPUnit_Framework_TestCase
                 ->method('generatePassword')
                 ->will($this->returnValue('generated_password'));
         }
+        
         $this->_customer->expects($this->once())
             ->method('save');
 
diff --git a/dev/tests/unit/testsuite/Mage/DesignEditor/Block/Adminhtml/Editor/ContainerTest.php b/dev/tests/unit/testsuite/Mage/DesignEditor/Block/Adminhtml/Editor/ContainerTest.php
index c839025f94e185d61222021fb8e81830b39f82f9..a6a031ccce10661c681bd42fbb0ed0aded2a6072 100644
--- a/dev/tests/unit/testsuite/Mage/DesignEditor/Block/Adminhtml/Editor/ContainerTest.php
+++ b/dev/tests/unit/testsuite/Mage/DesignEditor/Block/Adminhtml/Editor/ContainerTest.php
@@ -102,7 +102,7 @@ class Mage_DesignEditor_Block_Adminhtml_Editor_ContainerTest extends PHPUnit_Fra
     public function testPrepareLayout()
     {
         $buttonTitle = 'Back';
-        $eventManager = $this->getMock('Mage_Core_Model_Event_Manager', array('dispatch'));
+        $eventManager = $this->getMock('Mage_Core_Model_Event_Manager', array(), array(), '', false);
         $arguments = $this->_getBlockArguments(array('expectedTranslation' => $buttonTitle));
         $arguments['eventManager'] = $eventManager;
 
diff --git a/dev/tests/unit/testsuite/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code/CustomTest.php b/dev/tests/unit/testsuite/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code/CustomTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..fe6058176a88c0ea226814f4414ece003cd3e759
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code/CustomTest.php
@@ -0,0 +1,128 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_DesignEditor
+ * @subpackage  unit_tests
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_CustomTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Backend_Model_Url|PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_urlBuilder;
+
+    /**
+     * @var Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Custom|PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_model;
+
+    public function setUp()
+    {
+        $this->_urlBuilder = $this->getMock('Mage_Backend_Model_Url', array(), array(), '', false);
+
+        $objectManagerHelper = new Magento_Test_Helper_ObjectManager($this);
+        $this->_model = $objectManagerHelper->getBlock(
+            'Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Custom',
+            array(
+                'config' => $this->getMock('Mage_Core_Model_Config', array(), array(), '', false),
+                'urlBuilder' => $this->_urlBuilder
+        ));
+    }
+
+    public function tearDown()
+    {
+        $this->_model = null;
+        $this->_urlBuilder = null;
+    }
+
+    /**
+     * @dataProvider prepareTheme
+     * @covers Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Custom::getDownloadCustomCssUrl
+     */
+    public function testGetDownloadCustomCssUrl($theme)
+    {
+        $expectedUrl = 'some_url';
+
+        $this->_urlBuilder->expects($this->once())
+            ->method('getUrl')
+            ->with('*/system_design_theme/downloadCustomCss', array('theme_id' => $theme->getThemeId()))
+            ->will($this->returnValue($expectedUrl));
+
+        $this->assertEquals($expectedUrl, $this->_model->getDownloadCustomCssUrl($theme));
+    }
+
+    /**
+     * @dataProvider prepareTheme
+     */
+    public function testGetSaveCustomCssUrl($theme)
+    {
+        $expectedUrl = 'some_url';
+
+        $this->_urlBuilder->expects($this->once())
+            ->method('getUrl')
+            ->with('*/system_design_editor_tools/saveCssContent', array('theme_id' => $theme->getThemeId()))
+            ->will($this->returnValue($expectedUrl));
+
+        $this->assertEquals($expectedUrl, $this->_model->getSaveCustomCssUrl($theme));
+    }
+
+    public function testGetCustomCssContent()
+    {
+        $expectedContent = 'New file content';
+
+        /** @var $theme Mage_Core_Model_Theme */
+        $theme = $this->getMock(
+            'Mage_Core_Model_Theme', array('getCustomizationData', 'getFirstItem'), array(), '', false
+        );
+
+        /** @var $cssFile Mage_Core_Model_Theme_Customization_Files_Css */
+        $cssFile = $this->getMock(
+            'Mage_Core_Model_Theme_Customization_Files_Css', array('getContent'), array(), '', false
+        );
+
+        $theme->expects($this->once())
+            ->method('getCustomizationData')
+            ->with(Mage_Core_Model_Theme_Customization_Files_Css::TYPE)
+            ->will($this->returnValue($theme));
+
+        $theme->expects($this->once())
+            ->method('getFirstItem')
+            ->will($this->returnValue($cssFile));
+
+        $cssFile->expects($this->once())
+            ->method('getContent')
+            ->will($this->returnValue('New file content'));
+
+        $this->assertEquals($expectedContent, $this->_model->getCustomCssContent($theme));
+    }
+
+    public function prepareTheme()
+    {
+        $themeId = 15;
+        $theme = $this->getMock('Mage_Core_Model_Theme', null, array(), '', false);
+        $theme->setThemeId($themeId);
+
+        return array(array($theme));
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code/JsTest.php b/dev/tests/unit/testsuite/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code/JsTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..4edd946b4d468eacaa360d1f02266fda5f5a788d
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/DesignEditor/Block/Adminhtml/Editor/Tools/Code/JsTest.php
@@ -0,0 +1,138 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_DesignEditor
+ * @subpackage  unit_tests
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_JsTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Backend_Model_Url|PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_urlBuilder;
+
+    /**
+     * @var Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Js|PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_model;
+
+    public function setUp()
+    {
+        $this->_urlBuilder = $this->getMock('Mage_Backend_Model_Url', array(), array(), '', false);
+
+        $objectManagerHelper = new Magento_Test_Helper_ObjectManager($this);
+        $constructArguments = $objectManagerHelper->getConstructArguments(
+            Magento_Test_Helper_ObjectManager::BLOCK_ENTITY,
+            'Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Js',
+            array(
+                 'config'     => $this->getMock('Mage_Core_Model_Config', array(), array(), '', false),
+                 'service'    => $this->getMock('Mage_Core_Model_Theme_Service', array(), array(), '', false),
+                 'urlBuilder' => $this->_urlBuilder
+        ));
+        $this->_model = $this->getMock(
+            'Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Js',
+            array('__'),
+            $constructArguments
+        );
+    }
+
+    public function tearDown()
+    {
+        $this->_model = null;
+        $this->_urlBuilder = null;
+    }
+
+    /**
+     * @covers Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Js::getJsUploadUrl
+     */
+    public function testGetDownloadCustomCssUrl()
+    {
+        $themeId = 15;
+        $theme = $this->getMockBuilder('Mage_Core_Model_Theme')->disableOriginalConstructor()->getMock();
+        $theme->expects($this->once())->method('getId')->will($this->returnValue($themeId));
+
+        $this->_model->setTheme($theme);
+        $expectedUrl = 'some_url';
+
+        $this->_urlBuilder->expects($this->once())
+            ->method('getUrl')
+            ->with('*/system_design_editor_tools/uploadjs', array('id' => $themeId))
+            ->will($this->returnValue($expectedUrl));
+
+        $this->assertEquals($expectedUrl, $this->_model->getJsUploadUrl());
+    }
+
+    /**
+     * @covers Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Js::getJsReorderUrl
+     */
+    public function testGetJsReorderUrl()
+    {
+        $themeId = 8;
+        $theme = $this->getMockBuilder('Mage_Core_Model_Theme')->disableOriginalConstructor()->getMock();
+        $theme->expects($this->once())->method('getId')->will($this->returnValue($themeId));
+        $this->_model->setTheme($theme);
+
+        $expectedUrl = 'some_url';
+        $this->_urlBuilder->expects($this->once())
+            ->method('getUrl')
+            ->with('*/system_design_editor_tools/reorderjs', array('id' => $themeId))
+            ->will($this->returnValue($expectedUrl));
+
+        $this->assertEquals($expectedUrl, $this->_model->getJsReorderUrl());
+    }
+
+    /**
+     * @covers Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Js::getTitle
+     */
+    public function testGetTitle()
+    {
+        $this->_model->expects($this->atLeastOnce())
+            ->method('__')
+            ->will($this->returnArgument(0));
+        $this->assertEquals('Custom javascript files', $this->_model->getTitle());
+    }
+
+    /**
+     * @covers Mage_DesignEditor_Block_Adminhtml_Editor_Tools_Code_Js::getJsFiles
+     */
+    public function testGetJsFiles()
+    {
+        $filesCollection = $this->getMockBuilder('Mage_Core_Model_Resource_Theme_Files_Collection')
+            ->disableOriginalConstructor()
+            ->getMock();
+
+        $theme = $this->getMockBuilder('Mage_Core_Model_Theme')
+            ->disableOriginalConstructor()
+            ->setMethods(array('getCustomizationData'))
+            ->getMock();
+
+        $theme->expects($this->once())
+            ->method('getCustomizationData')
+            ->with(Mage_Core_Model_Theme_Customization_Files_Js::TYPE)
+            ->will($this->returnValue($filesCollection));
+
+        $this->_model->setTheme($theme);
+        $this->assertEquals($filesCollection, $this->_model->getJsFiles());
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/DesignEditor/Controller/Varien/Router/StandardTest.php b/dev/tests/unit/testsuite/Mage/DesignEditor/Controller/Varien/Router/StandardTest.php
index 9a1e08100d0b01f732b209b4f6c54f6d865f5313..9c60fb4e13339489847f0f5c5f933cca0a372eaf 100644
--- a/dev/tests/unit/testsuite/Mage/DesignEditor/Controller/Varien/Router/StandardTest.php
+++ b/dev/tests/unit/testsuite/Mage/DesignEditor/Controller/Varien/Router/StandardTest.php
@@ -190,6 +190,7 @@ class Mage_DesignEditor_Controller_Varien_Router_StandardTest extends PHPUnit_Fr
         $backendSession = $this->_getBackendSessionMock($isVde, $isLoggedIn);
         $stateModel     = $this->_getStateModelMock($routers);
         $configuration  = $this->_getConfigurationMock($isVde, $isLoggedIn, $isConfiguration);
+        $app            = $this->getMock('Mage_Core_Model_App', array(), array(), '', false);
         $callback = function ($name) use ($helper, $backendSession, $stateModel, $configuration) {
             switch ($name) {
                 case 'Mage_DesignEditor_Helper_Data': return $helper;
@@ -219,6 +220,7 @@ class Mage_DesignEditor_Controller_Varien_Router_StandardTest extends PHPUnit_Fr
             $controllerFactory,
             $objectManager,
             $filesystem,
+            $app,
             'frontend',
             'Mage_Core_Controller_Varien_Action'
         );
diff --git a/dev/tests/unit/testsuite/Mage/DesignEditor/Helper/DataTest.php b/dev/tests/unit/testsuite/Mage/DesignEditor/Helper/DataTest.php
index 11a491fdca7f27db17e1d2b27f6453a457e6ae27..70edd00f0b3c5624d1d6633b315cd87cd67cafa8 100644
--- a/dev/tests/unit/testsuite/Mage/DesignEditor/Helper/DataTest.php
+++ b/dev/tests/unit/testsuite/Mage/DesignEditor/Helper/DataTest.php
@@ -67,6 +67,16 @@ class Mage_DesignEditor_Helper_DataTest extends PHPUnit_Framework_TestCase
      */
     protected $_model;
 
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_translatorMock;
+
+    protected function setUp()
+    {
+        $this->_translatorMock = $this->getMock('Mage_Core_Model_Translate', array(), array(), '', false);
+    }
+
     protected function tearDown()
     {
         unset($this->_model);
@@ -82,7 +92,7 @@ class Mage_DesignEditor_Helper_DataTest extends PHPUnit_Framework_TestCase
             ->with(Mage_DesignEditor_Helper_Data::XML_PATH_FRONT_NAME)
             ->will($this->returnValue($frontNameNode));
 
-        $this->_model = new Mage_DesignEditor_Helper_Data($configurationMock);
+        $this->_model = new Mage_DesignEditor_Helper_Data($this->_translatorMock, $configurationMock);
         $this->assertEquals(self::TEST_FRONT_NAME, $this->_model->getFrontName());
     }
 
@@ -96,7 +106,7 @@ class Mage_DesignEditor_Helper_DataTest extends PHPUnit_Framework_TestCase
             ->with(Mage_DesignEditor_Helper_Data::XML_PATH_DEFAULT_HANDLE)
             ->will($this->returnValue($defaultHandleNode));
 
-        $this->_model = new Mage_DesignEditor_Helper_Data($configurationMock);
+        $this->_model = new Mage_DesignEditor_Helper_Data($this->_translatorMock, $configurationMock);
         $this->assertEquals(self::TEST_DEFAULT_HANDLE, $this->_model->getDefaultHandle());
     }
 
@@ -110,7 +120,7 @@ class Mage_DesignEditor_Helper_DataTest extends PHPUnit_Framework_TestCase
             ->with(Mage_DesignEditor_Helper_Data::XML_PATH_DISABLED_CACHE_TYPES)
             ->will($this->returnValue($cacheTypesNode));
 
-        $this->_model = new Mage_DesignEditor_Helper_Data($configurationMock);
+        $this->_model = new Mage_DesignEditor_Helper_Data($this->_translatorMock, $configurationMock);
         $this->assertEquals($this->_disabledCacheTypes, $this->_model->getDisabledCacheTypes());
     }
 
@@ -135,7 +145,7 @@ class Mage_DesignEditor_Helper_DataTest extends PHPUnit_Framework_TestCase
             ->with($xmlPath)
             ->will($this->returnValue($blockDataNode));
 
-        $this->_model = new Mage_DesignEditor_Helper_Data($configurationMock);
+        $this->_model = new Mage_DesignEditor_Helper_Data($this->_translatorMock, $configurationMock);
         $this->assertEquals($this->_elementData, $this->_model->$method());
     }
 
@@ -172,7 +182,7 @@ class Mage_DesignEditor_Helper_DataTest extends PHPUnit_Framework_TestCase
             ->with(Mage_DesignEditor_Helper_Data::XML_PATH_DAYS_TO_EXPIRE)
             ->will($this->returnValue($frontNameNode));
 
-        $this->_model = new Mage_DesignEditor_Helper_Data($configurationMock);
+        $this->_model = new Mage_DesignEditor_Helper_Data($this->_translatorMock, $configurationMock);
         $this->assertEquals(self::TEST_DATE_TO_EXPIRE, $this->_model->getDaysToExpire());
     }
 }
diff --git a/dev/tests/unit/testsuite/Mage/DesignEditor/Model/Url/NavigationModeTest.php b/dev/tests/unit/testsuite/Mage/DesignEditor/Model/Url/NavigationModeTest.php
index 38c5781043380c8a1fe0ecc2102be5a02bf4f811..3f0f83673e68bfe7f603fe5866b1ff29426ddf0f 100644
--- a/dev/tests/unit/testsuite/Mage/DesignEditor/Model/Url/NavigationModeTest.php
+++ b/dev/tests/unit/testsuite/Mage/DesignEditor/Model/Url/NavigationModeTest.php
@@ -53,7 +53,9 @@ class Mage_DesignEditor_Model_Url_NavigationModeTest extends PHPUnit_Framework_T
     public function setUp()
     {
         $this->_helper = $this->getMock('Mage_DesignEditor_Helper_Data', array('getFrontName'), array(), '', false);
+        $requestMock = $this->getMock('Mage_Core_Controller_Request_Http', array(), array(), '', false);
         $this->_model = new Mage_DesignEditor_Model_Url_NavigationMode($this->_helper, $this->_testData);
+        $this->_model->setRequest($requestMock);
     }
 
     public function testConstruct()
@@ -68,13 +70,29 @@ class Mage_DesignEditor_Model_Url_NavigationModeTest extends PHPUnit_Framework_T
             ->method('getFrontName')
             ->will($this->returnValue(self::FRONT_NAME));
 
-        $store = $this->getMock('Mage_Core_Model_Store', array('getBaseUrl'), array(), '', false);
+        $store = $this->getMock('Mage_Core_Model_Store',
+            array('getBaseUrl', 'isAdmin', 'isAdminUrlSecure', 'isFrontUrlSecure'),
+            array(), '', false
+        );
         $store->expects($this->any())
             ->method('getBaseUrl')
             ->will($this->returnValue(self::BASE_URL));
 
+        $store->expects($this->any())
+            ->method('isAdmin')
+            ->will($this->returnValue(false));
+
+        $store->expects($this->any())
+            ->method('isAdminUrlSecure')
+            ->will($this->returnValue(false));
+
+        $store->expects($this->any())
+            ->method('isFrontUrlSecure')
+            ->will($this->returnValue(false));
+
         $this->_model->setData('store', $store);
         $this->_model->setData('type', null);
+        $this->_model->setData('route_front_name', self::FRONT_NAME);
 
         $sourceUrl   = self::BASE_URL . '/' . self::ROUTE_PATH;
         $expectedUrl = self::BASE_URL . '/' . self::FRONT_NAME . '/' . self::ROUTE_PATH;
diff --git a/dev/tests/unit/testsuite/Mage/DesignEditor/controllers/Adminhtml/System/Design/EditorControllerTest.php b/dev/tests/unit/testsuite/Mage/DesignEditor/controllers/Adminhtml/System/Design/EditorControllerTest.php
index a3b35f3bb80e82d008bec9f969df7f3b11a67827..4dd303360541c51f4d47402fe7ad18f3ddc6f82b 100644
--- a/dev/tests/unit/testsuite/Mage/DesignEditor/controllers/Adminhtml/System/Design/EditorControllerTest.php
+++ b/dev/tests/unit/testsuite/Mage/DesignEditor/controllers/Adminhtml/System/Design/EditorControllerTest.php
@@ -51,10 +51,10 @@ class Mage_DesignEditor_Controller_Adminhtml_System_Design_EditorControllerTest
             array(
                 $this->getMock('Mage_Core_Controller_Request_Http', array(), array(), '', false),
                 $this->getMock('Mage_Core_Controller_Response_Http', array(), array(), '', false),
-                null,
                 $this->_objectManagerMock,
                 $this->getMock('Mage_Core_Controller_Varien_Front', array(), array(), '', false),
                 $this->getMock('Mage_Core_Model_Layout_Factory', array(), array(), '', false),
+                null,
                 array(
                     'translator' => 'translator',
                     'helper'     => 'helper',
diff --git a/dev/tests/unit/testsuite/Mage/Downloadable/Model/Sales/Order/Pdf/Items/CreditmemoTest.php b/dev/tests/unit/testsuite/Mage/Downloadable/Model/Sales/Order/Pdf/Items/CreditmemoTest.php
index 0cc22b0eb2e56726158da69f36d9f9e78b33cab5..bd47b188d69bf4d6139be75a21cfd2d871685d24 100644
--- a/dev/tests/unit/testsuite/Mage/Downloadable/Model/Sales/Order/Pdf/Items/CreditmemoTest.php
+++ b/dev/tests/unit/testsuite/Mage/Downloadable/Model/Sales/Order/Pdf/Items/CreditmemoTest.php
@@ -64,7 +64,8 @@ class Mage_Downloadable_Model_Sales_Order_Pdf_Items_CreditmemoTest extends PHPUn
             array('getLinks', 'getLinksTitle'),
             $modelConstructorArgs
         );
-        $this->_model->setStringHelper(new Mage_Core_Helper_String());
+        $translator = $this->getMock('Mage_Core_Model_Translate', array(), array(), '', false, false);
+        $this->_model->setStringHelper(new Mage_Core_Helper_String($translator));
         $this->_model->setOrder($this->_order);
         $this->_model->setPdf($this->_pdf);
         $this->_model->setPage(new Zend_Pdf_Page('a4'));
diff --git a/dev/tests/unit/testsuite/Mage/Eav/Model/Attribute/Data/TextTest.php b/dev/tests/unit/testsuite/Mage/Eav/Model/Attribute/Data/TextTest.php
index 4e259059676bc5c3d6468b530a38d8fc73b1a9b5..691f2c8c27f562756181209f1e3ddc3fd2630ecf 100644
--- a/dev/tests/unit/testsuite/Mage/Eav/Model/Attribute/Data/TextTest.php
+++ b/dev/tests/unit/testsuite/Mage/Eav/Model/Attribute/Data/TextTest.php
@@ -34,7 +34,7 @@ class Mage_Eav_Model_Attribute_Data_TextTest extends PHPUnit_Framework_TestCase
 
     protected function setUp()
     {
-        $helper = $this->getMock('Mage_Core_Helper_String', array('__'));
+        $helper = $this->getMock('Mage_Core_Helper_String', array('__'), array(), '', false, false);
         $helper->expects($this->any())
             ->method('__')
             ->will($this->returnArgument(0))
diff --git a/dev/tests/unit/testsuite/Mage/Eav/Model/Entity/AbstractTest.php b/dev/tests/unit/testsuite/Mage/Eav/Model/Entity/AbstractTest.php
index 42fb589e7ab53e9cba29401c4d2ed8f6a19b5caa..62a8a47017aa2c2f4edbd836ab48b8a5bd0f3bfc 100644
--- a/dev/tests/unit/testsuite/Mage/Eav/Model/Entity/AbstractTest.php
+++ b/dev/tests/unit/testsuite/Mage/Eav/Model/Entity/AbstractTest.php
@@ -44,9 +44,10 @@ class Mage_Eav_Model_Entity_AbstractTest extends PHPUnit_Framework_TestCase
     }
 
     /**
-     * @param array $attribute1SetInfo
-     * @param array $attribute2SetInfo
+     * @param array $attribute1Sort
+     * @param array $attribute2Sort
      * @param float $expected
+     *
      * @dataProvider compareAttributesDataProvider
      */
     public function testCompareAttributes($attribute1Sort, $attribute2Sort, $expected)
@@ -240,12 +241,24 @@ class Mage_Eav_Model_Entity_AbstractTest extends PHPUnit_Framework_TestCase
         $attributes[$code] = $attribute;
 
 
-        /** @var $model Mage_Eav_Model_Entity_Abstract */
-        $model = $this->getMock('Mage_Eav_Model_Entity_Abstract', null, array(array(
+        $data = array(
             'type' => $entityType,
             'entityTable' => 'entityTable',
             'attributesByCode' => $attributes,
-        )));
+        );
+        /** @var $model PHPUnit_Framework_MockObject_MockObject */
+        $model = $this->getMockForAbstractClass(
+            'Mage_Eav_Model_Entity_Abstract',
+            array($data),
+            '',
+            true,
+            true,
+            true,
+            array('_getConfig')
+        );
+
+        $configMock = $this->getMock('Mage_Eav_Model_Config', array(), array(), '', false);
+        $model->expects($this->any())->method('_getConfig')->will($this->returnValue($configMock));
 
         $model->setConnection($this->_getAdapterMock());
         $model->isPartialSave(true);
diff --git a/dev/tests/unit/testsuite/Mage/Eav/Model/Entity/Attribute/SetTest.php b/dev/tests/unit/testsuite/Mage/Eav/Model/Entity/Attribute/SetTest.php
index e599f5a2efeacc4b48d17027694c13f25d4cbbaf..b295937d993ef96e6d7c20fe9cbda04c4a4752e6 100644
--- a/dev/tests/unit/testsuite/Mage/Eav/Model/Entity/Attribute/SetTest.php
+++ b/dev/tests/unit/testsuite/Mage/Eav/Model/Entity/Attribute/SetTest.php
@@ -39,7 +39,7 @@ class Mage_Eav_Model_Entity_Attribute_SetTest extends PHPUnit_Framework_TestCase
     {
         $resource = $this->getMock('Mage_Eav_Model_Resource_Entity_Attribute_Set', array(), array(), '', false);
 
-        $helper = $this->getMock('Mage_Eav_Helper_Data', array('__'));
+        $helper = $this->getMock('Mage_Eav_Helper_Data', array('__'), array(), '', false, false);
         $helper->expects($this->any())
             ->method('__')
             ->will($this->returnArgument(0));
diff --git a/dev/tests/unit/testsuite/Mage/Eav/Model/Resource/Entity/AttributeTest.php b/dev/tests/unit/testsuite/Mage/Eav/Model/Resource/Entity/AttributeTest.php
index ab00121421598a4a38e42f40d5c20a9d60ed3047..44abfcea38a85a021c0e5b715b476eb4a8dca3c0 100644
--- a/dev/tests/unit/testsuite/Mage/Eav/Model/Resource/Entity/AttributeTest.php
+++ b/dev/tests/unit/testsuite/Mage/Eav/Model/Resource/Entity/AttributeTest.php
@@ -222,7 +222,9 @@ class Mage_Eav_Model_Resource_Entity_AttributeTest extends PHPUnit_Framework_Tes
             )));
 
         /** @var $resource Mage_Core_Model_Resource */
-        $resource = $this->getMock('Mage_Core_Model_Resource', array('getTableName', 'getConnection'));
+        $resource = $this->getMock('Mage_Core_Model_Resource',
+            array('getTableName', 'getConnection'), array(), '', false, false
+        );
         $resource->expects($this->any())
             ->method('getTableName')
             ->will($this->returnArgument(0));
@@ -235,7 +237,7 @@ class Mage_Eav_Model_Resource_Entity_AttributeTest extends PHPUnit_Framework_Tes
             'resource'  => $resource,
             'arguments' => array(
                 'application' => $application,
-                'helper'      => $this->getMock('Mage_Eav_Helper_Data'),
+                'helper'      => $this->getMock('Mage_Eav_Helper_Data', array(), array(), '', false, false),
             )
         );
         $resourceModel = $this->getMock(
diff --git a/dev/tests/unit/testsuite/Mage/ImportExport/Block/Adminhtml/Import/Edit/BeforeTest.php b/dev/tests/unit/testsuite/Mage/ImportExport/Block/Adminhtml/Import/Edit/BeforeTest.php
index c4bbdd32a31d34919a10168781bb23a8cf88ca4e..e6ff97bb96eae0dbc5dddbc6dd65f47d752313f3 100644
--- a/dev/tests/unit/testsuite/Mage/ImportExport/Block/Adminhtml/Import/Edit/BeforeTest.php
+++ b/dev/tests/unit/testsuite/Mage/ImportExport/Block/Adminhtml/Import/Edit/BeforeTest.php
@@ -82,7 +82,7 @@ class Mage_ImportExport_Block_Adminhtml_Import_Edit_BeforeTest extends PHPUnit_F
 
     public function setUp()
     {
-        $coreHelper = $this->getMock('Mage_Core_Helper_Data', array('jsonEncode'));
+        $coreHelper = $this->getMock('Mage_Core_Helper_Data', array('jsonEncode'), array(), '', false, false);
         $coreHelper->expects($this->any())
             ->method('jsonEncode')
             ->will($this->returnCallback(array($this, 'jsonEncodeCallback')));
diff --git a/dev/tests/unit/testsuite/Mage/ImportExport/Model/Export/Entity/Eav/Customer/AddressTest.php b/dev/tests/unit/testsuite/Mage/ImportExport/Model/Export/Entity/Eav/Customer/AddressTest.php
index 85b3099073715acc9fbdfaf9271644cad8fe515c..58193639407208963656e1e3876b51802731b08c 100644
--- a/dev/tests/unit/testsuite/Mage/ImportExport/Model/Export/Entity/Eav/Customer/AddressTest.php
+++ b/dev/tests/unit/testsuite/Mage/ImportExport/Model/Export/Entity/Eav/Customer/AddressTest.php
@@ -38,8 +38,8 @@ class Mage_ImportExport_Model_Export_Entity_Eav_Customer_AddressTest extends PHP
      * @var array
      */
     protected $_websites = array(
-        Mage_Core_Model_App::ADMIN_STORE_ID => 'admin',
-        1                                   => 'website1',
+        Mage_Core_Model_AppInterface::ADMIN_STORE_ID => 'admin',
+        1                                            => 'website1',
     );
 
     /**
@@ -186,7 +186,7 @@ class Mage_ImportExport_Model_Export_Entity_Eav_Customer_AddressTest extends PHP
             unset($websites[0]);
         }
         foreach ($this->_websites as $id => $code) {
-            if (!$withDefault && $id == Mage_Core_Model_App::ADMIN_STORE_ID) {
+            if (!$withDefault && $id == Mage_Core_Model_AppInterface::ADMIN_STORE_ID) {
                 continue;
             }
             $websiteData = array(
diff --git a/dev/tests/unit/testsuite/Mage/ImportExport/Model/Export/Entity/Eav/CustomerTest.php b/dev/tests/unit/testsuite/Mage/ImportExport/Model/Export/Entity/Eav/CustomerTest.php
index dbb72b7d72a8b1e70f19442d971779cc79e9d1b8..2cde59f85cd659f3d2cc1f02c1f506e4209dda45 100644
--- a/dev/tests/unit/testsuite/Mage/ImportExport/Model/Export/Entity/Eav/CustomerTest.php
+++ b/dev/tests/unit/testsuite/Mage/ImportExport/Model/Export/Entity/Eav/CustomerTest.php
@@ -39,8 +39,8 @@ class Mage_ImportExport_Model_Export_Entity_Eav_CustomerTest extends PHPUnit_Fra
      * @var array
      */
     protected $_websites = array(
-        Mage_Core_Model_App::ADMIN_STORE_ID => 'admin',
-        1                                   => 'website1',
+        Mage_Core_Model_AppInterface::ADMIN_STORE_ID => 'admin',
+        1                                            => 'website1',
     );
 
     /**
@@ -156,7 +156,7 @@ class Mage_ImportExport_Model_Export_Entity_Eav_CustomerTest extends PHPUnit_Fra
             unset($websites[0]);
         }
         foreach ($this->_websites as $id => $code) {
-            if (!$withDefault && $id == Mage_Core_Model_App::ADMIN_STORE_ID) {
+            if (!$withDefault && $id == Mage_Core_Model_AppInterface::ADMIN_STORE_ID) {
                 continue;
             }
             $websiteData = array(
diff --git a/dev/tests/unit/testsuite/Mage/ImportExport/Model/Import/Entity/CustomerCompositeTest.php b/dev/tests/unit/testsuite/Mage/ImportExport/Model/Import/Entity/CustomerCompositeTest.php
index e976db932ba13dfc37f45ce0ee19ffd1bef1dd10..4c964309f4d852480b9f73aee55df3573392e598 100644
--- a/dev/tests/unit/testsuite/Mage/ImportExport/Model/Import/Entity/CustomerCompositeTest.php
+++ b/dev/tests/unit/testsuite/Mage/ImportExport/Model/Import/Entity/CustomerCompositeTest.php
@@ -234,7 +234,7 @@ class Mage_ImportExport_Model_Import_Entity_CustomerCompositeTest extends PHPUni
      */
     protected function _getModelDependencies()
     {
-        $mageHelper = $this->getMock('Mage_ImportExport_Helper_Data', array('__'));
+        $mageHelper = $this->getMock('Mage_ImportExport_Helper_Data', array('__'), array(), '', false, false);
         $mageHelper->expects($this->any())
             ->method('__')
             ->will($this->returnArgument(0));
@@ -246,7 +246,9 @@ class Mage_ImportExport_Model_Import_Entity_CustomerCompositeTest extends PHPUni
             'connection'                   => 'not_used',
             'helpers'                      => array('Mage_ImportExport_Helper_Data' => $mageHelper),
             'json_helper'                  => 'not_used',
-            'string_helper'                => new Mage_Core_Helper_String(),
+            'string_helper'                => new Mage_Core_Helper_String(
+                $this->getMock('Mage_Core_Model_Translate', array(), array(), '', false, false)
+            ),
             'page_size'                    => 1,
             'max_data_size'                => 1,
             'bunch_size'                   => 1,
diff --git a/dev/tests/unit/testsuite/Mage/ImportExport/Model/Import/Entity/Eav/Customer/AddressTest.php b/dev/tests/unit/testsuite/Mage/ImportExport/Model/Import/Entity/Eav/Customer/AddressTest.php
index 224cde800c33790b5c680a9afff4f056e2d7f331..902bd363c4f830e3eb753d4bce7ca1259486570a 100644
--- a/dev/tests/unit/testsuite/Mage/ImportExport/Model/Import/Entity/Eav/Customer/AddressTest.php
+++ b/dev/tests/unit/testsuite/Mage/ImportExport/Model/Import/Entity/Eav/Customer/AddressTest.php
@@ -191,7 +191,7 @@ class Mage_ImportExport_Model_Import_Entity_Eav_Customer_AddressTest extends PHP
             $regionCollection->addItem(new Varien_Object($region));
         }
 
-        $mageHelper = $this->getMock('Mage_ImportExport_Helper_Data', array('__'));
+        $mageHelper = $this->getMock('Mage_ImportExport_Helper_Data', array('__'), array(), '', false, false);
         $mageHelper->expects($this->any())
             ->method('__')
             ->will($this->returnArgument(0));
@@ -200,7 +200,9 @@ class Mage_ImportExport_Model_Import_Entity_Eav_Customer_AddressTest extends PHP
             'data_source_model'            => $dataSourceModel,
             'connection'                   => $connection,
             'json_helper'                  => 'not_used',
-            'string_helper'                => new Mage_Core_Helper_String(),
+            'string_helper'                => new Mage_Core_Helper_String(
+                $this->getMock('Mage_Core_Model_Translate', array(), array(), '', false, false)
+            ),
             'page_size'                    => 1,
             'max_data_size'                => 1,
             'bunch_size'                   => 1,
@@ -304,7 +306,7 @@ class Mage_ImportExport_Model_Import_Entity_Eav_Customer_AddressTest extends PHP
             unset($websites[0]);
         }
         foreach ($this->_websites as $id => $code) {
-            if (!$withDefault && $id == Mage_Core_Model_App::ADMIN_STORE_ID) {
+            if (!$withDefault && $id == Mage_Core_Model_AppInterface::ADMIN_STORE_ID) {
                 continue;
             }
             $websiteData = array(
diff --git a/dev/tests/unit/testsuite/Mage/ImportExport/Model/Import/Entity/EavAbstractTest.php b/dev/tests/unit/testsuite/Mage/ImportExport/Model/Import/Entity/EavAbstractTest.php
index ce69895e99d71ead12e63605378517a8e0cc6e8a..23290dbaf0039fa3b4a42a7ecc66e2a1a6bac650 100644
--- a/dev/tests/unit/testsuite/Mage/ImportExport/Model/Import/Entity/EavAbstractTest.php
+++ b/dev/tests/unit/testsuite/Mage/ImportExport/Model/Import/Entity/EavAbstractTest.php
@@ -71,7 +71,9 @@ class Mage_ImportExport_Model_Import_Entity_EavAbstractTest extends PHPUnit_Fram
             'connection'                   => 'not_used',
             'translator'                   => $translator,
             'json_helper'                  => 'not_used',
-            'string_helper'                => new Mage_Core_Helper_String(),
+            'string_helper'                => new Mage_Core_Helper_String(
+                $this->getMock('Mage_Core_Model_Translate', array(), array(), '', false, false)
+            ),
             'page_size'                    => 1,
             'max_data_size'                => 1,
             'bunch_size'                   => 1,
diff --git a/dev/tests/unit/testsuite/Mage/ImportExport/Model/Import/EntityAbstractTest.php b/dev/tests/unit/testsuite/Mage/ImportExport/Model/Import/EntityAbstractTest.php
index 5622b45876dfccc42bbb1bc8ba6096e02c3304fe..44d9b988ba8738206cbc88ca46ec7bf3530f1d7e 100644
--- a/dev/tests/unit/testsuite/Mage/ImportExport/Model/Import/EntityAbstractTest.php
+++ b/dev/tests/unit/testsuite/Mage/ImportExport/Model/Import/EntityAbstractTest.php
@@ -69,7 +69,7 @@ class Mage_ImportExport_Model_Import_EntityAbstractTest extends PHPUnit_Framewor
      */
     protected function _getModelDependencies()
     {
-        $mageHelper = $this->getMock('Mage_ImportExport_Helper_Data', array('__'));
+        $mageHelper = $this->getMock('Mage_ImportExport_Helper_Data', array('__'), array(), '', false, false);
         $mageHelper->expects($this->any())
             ->method('__')
             ->will($this->returnArgument(0));
@@ -79,7 +79,9 @@ class Mage_ImportExport_Model_Import_EntityAbstractTest extends PHPUnit_Framewor
             'connection'                   => 'not_used',
             'helpers'                      => array('Mage_ImportExport_Helper_Data' => $mageHelper),
             'json_helper'                  => 'not_used',
-            'string_helper'                => new Mage_Core_Helper_String(),
+            'string_helper'                => new Mage_Core_Helper_String(
+                $this->getMock('Mage_Core_Model_Translate', array(), array(), '', false, false)
+            ),
             'page_size'                    => 1,
             'max_data_size'                => 1,
             'bunch_size'                   => 1,
@@ -443,7 +445,9 @@ class Mage_ImportExport_Model_Import_EntityAbstractTest extends PHPUnit_Framewor
     {
         $registryKey = '_helper/Mage_Core_Helper_String';
         if (!Mage::registry($registryKey)) {
-            $helper = new Mage_Core_Helper_String();
+            $helper = new Mage_Core_Helper_String(
+                $this->getMock('Mage_Core_Model_Translate', array(), array(), '', false, false)
+            );
             Mage::register($registryKey, $helper);
         }
 
diff --git a/dev/tests/unit/testsuite/Mage/ImportExport/Model/Resource/Import/CustomerComposite/DataTest.php b/dev/tests/unit/testsuite/Mage/ImportExport/Model/Resource/Import/CustomerComposite/DataTest.php
index ec5340dba8fc28f67bf78b1afb1a4f0f4b6e8231..95c423744b8bb32f7f1b65ceabf198ffcfe08931 100644
--- a/dev/tests/unit/testsuite/Mage/ImportExport/Model/Resource/Import/CustomerComposite/DataTest.php
+++ b/dev/tests/unit/testsuite/Mage/ImportExport/Model/Resource/Import/CustomerComposite/DataTest.php
@@ -86,7 +86,10 @@ class Mage_ImportExport_Model_Resource_Import_CustomerComposite_DataTest extends
         $resourceModelMock->createConnection('core_write', '', array());
 
         $data = array(
-            'json_helper' => new Mage_Core_Helper_Data(),
+            'json_helper' => new Mage_Core_Helper_Data(
+                $this->getMock('Mage_Core_Model_Translate', array(), array(), '', false, false),
+                $this->getMock('Mage_Core_Model_Config_Modules', array(), array(), '', false, false)
+            ),
             'resource'    => $resourceModelMock,
             'entity_type' => $entityType
         );
diff --git a/dev/tests/unit/testsuite/Mage/ImportExport/Model/Source/Import/EntityTest.php b/dev/tests/unit/testsuite/Mage/ImportExport/Model/Source/Import/EntityTest.php
index 018a68875f9489a71ec8cf30794beda2efc57c2c..bdc2ff9eece3a94fa190c1af046c2b7e9094e642 100644
--- a/dev/tests/unit/testsuite/Mage/ImportExport/Model/Source/Import/EntityTest.php
+++ b/dev/tests/unit/testsuite/Mage/ImportExport/Model/Source/Import/EntityTest.php
@@ -82,7 +82,11 @@ class Mage_ImportExport_Model_Source_Import_EntityTest extends PHPUnit_Framework
         if (!self::$_helper) {
             self::$_helper = $this->getMock(
                 'Mage_ImportExport_Helper_Data',
-                array('__')
+                array('__'),
+                array(),
+                '',
+                false,
+                false
             );
             self::$_helper->expects($this->any())
                 ->method('__')
diff --git a/dev/tests/unit/testsuite/Mage/Index/Model/Lock/StorageTest.php b/dev/tests/unit/testsuite/Mage/Index/Model/Lock/StorageTest.php
index 136cf2d14f0211fd7c42cf6ffb6414b5744694c9..cf8ab3e17e4743470a2c627e6d3540cbf13811d4 100644
--- a/dev/tests/unit/testsuite/Mage/Index/Model/Lock/StorageTest.php
+++ b/dev/tests/unit/testsuite/Mage/Index/Model/Lock/StorageTest.php
@@ -33,9 +33,19 @@ class Mage_Index_Model_Lock_StorageTest extends PHPUnit_Framework_TestCase
      */
     protected $_callbackProcessId;
 
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_dirsMock;
+
     public function testGetFile()
     {
-        $dirs = new Mage_Core_Model_Dir(__DIR__);
+        $this->_dirsMock = $this->getMock('Mage_Core_Model_Dir', array(), array(), '', false, false);
+        $this->_dirsMock->expects($this->any())
+            ->method('getDir')
+            ->with(Mage_Core_Model_Dir::VAR_DIR)
+            ->will($this->returnValue(__DIR__ . DIRECTORY_SEPARATOR. 'var'));
+
         $fileModel = $this->getMock('Mage_Index_Model_Process_File',
             array(
                 'setAllowCreateFolders',
@@ -65,7 +75,7 @@ class Mage_Index_Model_Lock_StorageTest extends PHPUnit_Framework_TestCase
             ->method('createFromArray')
             ->will($this->returnValue($fileModel));
 
-        $storage = new Mage_Index_Model_Lock_Storage($dirs, $fileFactory);
+        $storage = new Mage_Index_Model_Lock_Storage($this->_dirsMock, $fileFactory);
 
         /**
          * List if test process IDs.
diff --git a/dev/tests/unit/testsuite/Mage/Index/Model/ProcessTest.php b/dev/tests/unit/testsuite/Mage/Index/Model/ProcessTest.php
index f0c9ca5333de2cf8351c9be32634c753a6e0fdfe..9f67333bace0e668e94734375a7e88b40b4567e6 100644
--- a/dev/tests/unit/testsuite/Mage/Index/Model/ProcessTest.php
+++ b/dev/tests/unit/testsuite/Mage/Index/Model/ProcessTest.php
@@ -69,7 +69,7 @@ class Mage_Index_Model_ProcessTest extends PHPUnit_Framework_TestCase
 
     public function testGetProcessFile()
     {
-        $this->_processFile = $this->getMock('Mage_Index_Model_Process_File');
+        $this->_processFile = $this->getMock('Mage_Index_Model_Process_File', array(), array(), '', false, false);
         $this->_prepareIndexProcess();
 
         // assert that process file is stored in process entity instance and isn't changed after several invocations
@@ -87,7 +87,9 @@ class Mage_Index_Model_ProcessTest extends PHPUnit_Framework_TestCase
      */
     protected function _prepareMocksForTestLock($nonBlocking)
     {
-        $this->_processFile = $this->getMock('Mage_Index_Model_Process_File', array('processLock'));
+        $this->_processFile = $this->getMock('Mage_Index_Model_Process_File', array('processLock'), array(), '',
+            false, false
+        );
         $this->_processFile->expects($this->once())
             ->method('processLock')
             ->with($nonBlocking);
@@ -111,11 +113,16 @@ class Mage_Index_Model_ProcessTest extends PHPUnit_Framework_TestCase
             ->with(self::PROCESS_ID)
             ->will($this->returnValue($this->_processFile));
 
+        $resource = $this->getMockForAbstractClass(
+            'Mage_Core_Model_Resource_Db_Abstract',
+            array(), '', false, false, true, array('getIdFieldName')
+        );
+        $resource->expects($this->any())->method('getIdFieldName')->will($this->returnValue('process_id'));
         $this->_indexProcess = new Mage_Index_Model_Process(
             $eventDispatcher,
             $cacheManager,
             $lockStorage,
-            null,
+            $resource,
             null,
             array('process_id' => self::PROCESS_ID)
         );
diff --git a/dev/tests/unit/testsuite/Mage/Install/Model/Installer/ConfigTest.php b/dev/tests/unit/testsuite/Mage/Install/Model/Installer/ConfigTest.php
index edd88ae24db3ff26cdfc83ac15f953472a0dbf6d..cb998bf3137feff105d9c3cb80248ebe56bb70de 100644
--- a/dev/tests/unit/testsuite/Mage/Install/Model/Installer/ConfigTest.php
+++ b/dev/tests/unit/testsuite/Mage/Install/Model/Installer/ConfigTest.php
@@ -53,7 +53,10 @@ class Mage_Install_Model_Installer_ConfigTest extends PHPUnit_Framework_TestCase
     {
         $this->_model = new Mage_Install_Model_Installer_Config(
             $this->getMock('Mage_Core_Model_Config', array(), array(), '', false),
-            new Mage_Core_Model_Dir(__DIR__, array(), array(Mage_Core_Model_Dir::CONFIG => TESTS_TEMP_DIR)),
+            new Mage_Core_Model_Dir(
+                __DIR__, new Varien_Io_File(), array(), array(Mage_Core_Model_Dir::CONFIG => TESTS_TEMP_DIR)
+            ),
+            $this->getMock('Mage_Core_Model_Config_Resource', array(), array(), '', false),
             new Magento_Filesystem(new Magento_Filesystem_Adapter_Local())
         );
     }
diff --git a/dev/tests/unit/testsuite/Mage/Page/Block/Html/HeaderTest.php b/dev/tests/unit/testsuite/Mage/Page/Block/Html/HeaderTest.php
index 251b67fb5b18e1eb36bf474a49f18a132d08ba10..a9284f645bfd3f7a1f9aade97144ee856e9947fe 100644
--- a/dev/tests/unit/testsuite/Mage/Page/Block/Html/HeaderTest.php
+++ b/dev/tests/unit/testsuite/Mage/Page/Block/Html/HeaderTest.php
@@ -42,10 +42,9 @@ class Mage_Page_Block_Html_HeaderTest extends PHPUnit_Framework_TestCase
             ->method('getBaseUrl')
             ->will($this->returnValue('http://localhost/pub/media/'));
 
-        $helper = $this->getMockBuilder('Mage_Core_Helper_File_Storage_Database')
-            ->setMethods(array('checkDbUsage'))
-            ->disableOriginalConstructor()
-            ->getMock();
+        $helper = $this->getMock('Mage_Core_Helper_File_Storage_Database',
+            array('checkDbUsage'), array(), '', false, false
+        );
         $helper->expects($this->once())
             ->method('checkDbUsage')
             ->will($this->returnValue(false));
diff --git a/dev/tests/unit/testsuite/Mage/Review/Helper/Action/PagerTest.php b/dev/tests/unit/testsuite/Mage/Review/Helper/Action/PagerTest.php
index ab2c8d089db6ad6c3c323ebc3ad7bd014f916d88..4d576c89e1cbe57bb7dcfc65b12576939b622072 100644
--- a/dev/tests/unit/testsuite/Mage/Review/Helper/Action/PagerTest.php
+++ b/dev/tests/unit/testsuite/Mage/Review/Helper/Action/PagerTest.php
@@ -49,6 +49,7 @@ class Mage_Review_Helper_Action_PagerTest extends PHPUnit_Framework_TestCase
 
         $this->_helper = $this->getMockBuilder('Mage_Review_Helper_Action_Pager')
             ->setMethods(array('_getSession'))
+            ->disableOriginalConstructor()
             ->getMock();
         $this->_helper->expects($this->any())
             ->method('_getSession')
diff --git a/dev/tests/unit/testsuite/Mage/Sales/Model/Config/OrderTest.php b/dev/tests/unit/testsuite/Mage/Sales/Model/Config/OrderTest.php
index a2356101d7dfbbf3d3be33c3ab570616868914e7..c502a7255b158021fd84f6f9eb2544e6262548f1 100644
--- a/dev/tests/unit/testsuite/Mage/Sales/Model/Config/OrderTest.php
+++ b/dev/tests/unit/testsuite/Mage/Sales/Model/Config/OrderTest.php
@@ -40,6 +40,9 @@ class Mage_Sales_Model_Config_OrderedTest extends PHPUnit_Framework_TestCase
         $this->assertEquals($expectedResult, $actualResult);
     }
 
+    /**
+     * @return array
+     */
     public function getSortedCollectorCodesDataProvider()
     {
         $ambiguousCases = self::ambiguousTotalsDataProvider();
@@ -71,6 +74,9 @@ class Mage_Sales_Model_Config_OrderedTest extends PHPUnit_Framework_TestCase
         Mage_Sales_Model_Config_Ordered::validateCollectorDeclarations($config);
     }
 
+    /**
+     * @return array
+     */
     public function ambiguousTotalsDataProvider()
     {
         return array(
diff --git a/dev/tests/unit/testsuite/Mage/Sitemap/Model/SitemapTest.php b/dev/tests/unit/testsuite/Mage/Sitemap/Model/SitemapTest.php
index b866fd0bbd061b31fa48a0e142f923a97e5b9498..26e1d0b150fa56175a3dc5e17fac013e69e5cd37 100644
--- a/dev/tests/unit/testsuite/Mage/Sitemap/Model/SitemapTest.php
+++ b/dev/tests/unit/testsuite/Mage/Sitemap/Model/SitemapTest.php
@@ -37,7 +37,7 @@ class Mage_Sitemap_Model_SitemapTest extends PHPUnit_Framework_TestCase
      */
     protected function setUp()
     {
-        $helperMockCore = $this->getMock('Mage_Core_Helper_Data', array('__'));
+        $helperMockCore = $this->getMock('Mage_Core_Helper_Data', array('__'), array(), '', false, false);
         $helperMockCore->expects($this->any())
             ->method('__')
             ->will($this->returnArgument(0));
@@ -54,7 +54,8 @@ class Mage_Sitemap_Model_SitemapTest extends PHPUnit_Framework_TestCase
             'getMaximumLinesNumber',
             'getMaximumFileSize',
             'getEnableSubmissionRobots'
-        ));
+         ), array(), '', false, false
+        );
         $helperMockSitemap->expects($this->any())
             ->method('__')
             ->will($this->returnArgument(0));
diff --git a/dev/tests/unit/testsuite/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Form/Element/FileTest.php b/dev/tests/unit/testsuite/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Form/Element/FileTest.php
index ed3d303e9e10166914c9ea7b0864d5fae45f907b..642c3206a779263a0df29a002f1da389908685ab 100644
--- a/dev/tests/unit/testsuite/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Form/Element/FileTest.php
+++ b/dev/tests/unit/testsuite/Mage/Theme/Block/Adminhtml/System/Design/Theme/Edit/Form/Element/FileTest.php
@@ -30,9 +30,8 @@ class Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_From_Element_FileTest
     public function testGetHtmlAttributes()
     {
         /** @var $fileBlock Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Form_Element_File */
-        $fileBlock = Mage::getObjectManager()->create(
-            'Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Form_Element_File'
-        );
+        $helper = new Magento_Test_Helper_ObjectManager($this);
+        $fileBlock = $helper->getBlock('Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Form_Element_File');
         $this->assertContains('accept', $fileBlock->getHtmlAttributes());
         $this->assertContains('multiple', $fileBlock->getHtmlAttributes());
     }
diff --git a/dev/tests/unit/testsuite/Mage/Theme/Block/Adminhtml/System/Design/Theme/Tab/CssTest.php b/dev/tests/unit/testsuite/Mage/Theme/Block/Adminhtml/System/Design/Theme/Tab/CssTest.php
index ac42c61ed9b8a7f21fbfe776524f92890075ff03..ca9113526340faaf8068b20614f03d6efbee6322 100644
--- a/dev/tests/unit/testsuite/Mage/Theme/Block/Adminhtml/System/Design/Theme/Tab/CssTest.php
+++ b/dev/tests/unit/testsuite/Mage/Theme/Block/Adminhtml/System/Design/Theme/Tab/CssTest.php
@@ -57,7 +57,7 @@ class Mage_Theme_Block_Adminhtml_System_Design_Theme_Tab_CssTest extends PHPUnit
 
         $this->_objectManager = $this->getMock('Magento_ObjectManager_Zend', array('get'), array(), '', false);
         /** @var $dirs Mage_Core_Model_Dir */
-        $dirs = new Mage_Core_Model_Dir(__DIR__);
+        $dirs = new Mage_Core_Model_Dir(__DIR__, new Varien_Io_File());
 
         $constructArguments = $objectManagerHelper->getConstructArguments(
             Magento_Test_Helper_ObjectManager::BLOCK_ENTITY,
@@ -118,470 +118,6 @@ class Mage_Theme_Block_Adminhtml_System_Design_Theme_Tab_CssTest extends PHPUnit
         $this->assertEquals($expectedResult, $result);
     }
 
-    /**
-     * @param array $files
-     * @param array $expectedResult
-     * @dataProvider getGroupedFilesProvider
-     */
-    public function testGetGroupedFiles($files, $expectedResult)
-    {
-        $themeMock = $this->getMock('Mage_Core_Model_Theme', array('getThemeTitle', 'getId'), array(), '', false);
-        $themeMock->expects($this->any())->method('getId')->will($this->returnValue(1));
-        $themeMock->expects($this->any())->method('getThemeTitle')->will($this->returnValue('test title'));
-
-        $helperFactoryMock = $this->getMock(
-            'Mage_Core_Model_Factory_Helper', array('get', 'urlEncode'), array(), '', false
-        );
-        $helperFactoryMock->expects($this->any())->method('get')->with($this->equalTo('Mage_Theme_Helper_Data'))
-            ->will($this->returnSelf());
-
-        $helperFactoryMock->expects($this->any())->method('urlEncode')->will($this->returnArgument(0));
-
-        $constructArguments = $this->_prepareModelArguments();
-        $constructArguments['helperFactory'] = $helperFactoryMock;
-        $constructArguments['objectManager'] = $objectManagerMock = $this->getMockBuilder('Magento_ObjectManager')
-            ->setMethods(array('create', 'get'))
-            ->disableOriginalConstructor()
-            ->getMockForAbstractClass();
-
-        $collectionMock = $this->getMock(
-            'Mage_Core_Model_Resource_Theme_Collection',
-            get_class_methods('Mage_Core_Model_Resource_Theme_Collection'),
-            array(),
-            '',
-            false
-        );
-
-        $collectionMock->expects($this->any())->method('getThemeByFullPath')->will($this->returnValue($themeMock));
-
-        $configMock = $this->getMock('Mage_Core_Model_Config', get_class_methods('Mage_Core_Model_Config'),
-            array(), '', false);
-
-        $objectManagerMock->expects($this->any())->method('create')
-            ->with($this->equalTo('Mage_Core_Model_Resource_Theme_Collection'))
-            ->will($this->returnValue($collectionMock));
-
-        $objectManagerMock->expects($this->any())->method('get')->with($this->equalTo('Mage_Core_Model_Config'))
-            ->will($this->returnValue($configMock));
-
-        $this->_model = $this->getMock('Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Tab_Css',
-            array('getUrl', '_getCurrentTheme'), $constructArguments, '', true);
-
-        $this->_model->setFiles($files);
-        $this->_model->expects($this->any())->method('_getCurrentTheme')->will($this->returnValue($themeMock));
-        $this->_model->expects($this->any())->method('getUrl')->will($this->returnArgument(1));
-
-        $method = self::getMethod('_getGroupedFiles');
-        $result = $method->invokeArgs($this->_model, array());
-        $this->assertEquals($expectedResult, $result);
-    }
-
-    /**
-     * @return array
-     */
-    public function getGroupedFilesProvider()
-    {
-        /** @var $dirs Mage_Core_Model_Dir */
-        $dirs = new Mage_Core_Model_Dir(__DIR__);
-
-        $designDir = str_replace(
-            $dirs->getDir(Mage_Core_Model_Dir::APP), '', $dirs->getDir(Mage_Core_Model_Dir::THEMES)
-        );
-        $jsDir = str_replace($dirs->getDir(Mage_Core_Model_Dir::APP), '', $dirs->getDir(Mage_Core_Model_Dir::PUB_LIB));
-        $codeDir = str_replace(
-            $dirs->getDir(Mage_Core_Model_Dir::APP), '', $dirs->getDir(Mage_Core_Model_Dir::MODULES)
-        );
-        return array(
-            array(array(), array()),
-            array(
-                array('mage/calendar.css' => str_replace('/', DIRECTORY_SEPARATOR,
-                    $dirs->getDir(Mage_Core_Model_Dir::MODULES) . '/pub/lib/mage/calendar.css')),
-                array('Framework files' => array(
-                    array(
-                        'href' => array('theme_id' => 1, 'file' => 'mage/calendar.css'),
-                        'label' => 'mage/calendar.css',
-                        'title' => str_replace('/', DIRECTORY_SEPARATOR, $codeDir . '/pub/lib/mage/calendar.css'),
-                        'delimiter' => '<br />'
-            )))),
-            array(
-                array('Mage_Page::css/tabs.css' => str_replace('/', DIRECTORY_SEPARATOR,
-                    $dirs->getDir(Mage_Core_Model_Dir::MODULES) . '/core/Mage/Page/view/frontend/css/tabs.css')),
-                array('Framework files' => array(
-                    array(
-                        'href' => array('theme_id' => 1, 'file' => 'Mage_Page::css/tabs.css'),
-                        'label' => 'Mage_Page::css/tabs.css',
-                        'title' => str_replace('/', DIRECTORY_SEPARATOR,
-                            $codeDir . '/core/Mage/Page/view/frontend/css/tabs.css'),
-                        'delimiter' => '<br />'
-            )))),
-            array(
-                array('mage/calendar.css' => str_replace('/', DIRECTORY_SEPARATOR,
-                    $dirs->getDir(Mage_Core_Model_Dir::PUB_LIB) . '/mage/calendar.css')),
-                array('Library files' => array(
-                    array(
-                        'href' => array('theme_id' => 1, 'file' => 'mage/calendar.css'),
-                        'label' => 'mage/calendar.css',
-                        'title' => str_replace('/', DIRECTORY_SEPARATOR, $jsDir . '/mage/calendar.css'),
-                        'delimiter' => '<br />'
-            )))),
-            array(
-                array('mage/calendar.css' => str_replace('/', DIRECTORY_SEPARATOR,
-                    $dirs->getDir(Mage_Core_Model_Dir::THEMES) . '/frontend/default/demo/css/styles.css'),
-                ),
-                array('"test title" Theme files' => array(
-                    array(
-                        'href' => array('theme_id' => 1, 'file' => 'mage/calendar.css'),
-                        'label' => 'mage/calendar.css',
-                        'title' => str_replace('/', DIRECTORY_SEPARATOR,
-                            $designDir . '/frontend/default/demo/css/styles.css'),
-                        'delimiter' => '<br />'
-            )))),
-        );
-    }
-
-    /**
-     * @dataProvider sortGroupFilesCallbackProvider
-     */
-    public function testSortGroupFilesCallback($firstGroup, $secondGroup, $expectedResult)
-    {
-        $method = self::getMethod('_sortGroupFilesCallback');
-        $result = $method->invokeArgs($this->_model, array($firstGroup, $secondGroup));
-        $this->assertEquals($expectedResult, $result);
-    }
-
-    /**
-     * @return array
-     */
-    public function sortGroupFilesCallbackProvider()
-    {
-        return array(
-            array(
-                array('label' => 'abcd'),
-                array('label' => 'abc'),
-                1
-            ),
-            array(
-                array('label' => 'abc'),
-                array('label' => 'abcd'),
-                -1
-            ),
-            array(
-                array('label' => 'abc'),
-                array('label' => 'abc'),
-                0
-            ),
-            array(
-                array('label' => 'Mage_Core::abc'),
-                array('label' => 'abc'),
-                1
-            ),
-            array(
-                array('label' => 'abc'),
-                array('label' => 'Mage_Core::abc'),
-                -1
-            ),
-            array(
-                array('label' => 'Mage_Core::abc'),
-                array('label' => 'Mage_Core::abcd'),
-                -1
-            ),
-            array(
-                array('label' => 'Mage_Core::abcd'),
-                array('label' => 'Mage_Core::abc'),
-                1
-            ),
-            array(
-                array('label' => 'Mage_Core::abc'),
-                array('label' => 'Mage_Core::abc'),
-                0
-            ),
-        );
-    }
-
-    /**
-     * @expectedException Mage_Core_Exception
-     * @expectedExceptionMessage Invalid view file directory "xyz"
-     */
-    public function testGetGroupException()
-    {
-        $method = self::getMethod('_getGroup');
-        $method->invokeArgs($this->_model, array('xyz'));
-    }
-
-    /**
-     * @param string $filename
-     * @param string $filePathForSearch
-     * @param int|string $themeId
-     * @dataProvider getGroupProvider
-     */
-    public function testGetGroup($filename, $filePathForSearch, $themeId)
-    {
-        $constructArguments = $this->_prepareModelArguments();
-        $constructArguments['objectManager'] = $objectManagerMock = $this->getMockBuilder('Magento_ObjectManager')
-            ->setMethods(array('get'))
-            ->disableOriginalConstructor()
-            ->getMockForAbstractClass();
-
-        $configMock = $this->getMock('Mage_Core_Model_Config', get_class_methods('Mage_Core_Model_Config'),
-            array(), '', false);
-
-        $objectManagerMock->expects($this->any())->method('get')->with($this->equalTo('Mage_Core_Model_Config'))
-            ->will($this->returnValue($configMock));
-
-        $this->_model = $this->getMock(
-            'Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Tab_Css',
-            array('_getThemeByFilename'),
-            $constructArguments,
-            '',
-            true
-        );
-
-        $themeMock = $this->getMock('Mage_Core_Model_Theme', array('getThemeId'), array(), '', false);
-        $themeMock->expects($this->any())
-            ->method('getThemeId')
-            ->will($this->returnValue($themeId));
-
-        $this->_model->expects($this->any())
-            ->method('_getThemeByFilename')
-            ->with($filePathForSearch)
-            ->will($this->returnValue($themeMock));
-
-        $method = self::getMethod('_getGroup');
-        $result = $method->invokeArgs($this->_model, array($filename));
-
-        $this->assertCount(2, $result);
-
-        if ($filePathForSearch) {
-            $this->assertSame($themeMock, $result[1]);
-            $this->assertEquals(array($themeId, $themeMock), $result);
-        } else {
-            $this->assertEquals(array($themeId, null), $result);
-        }
-    }
-
-    /**
-     * @return array
-     */
-    public function getGroupProvider()
-    {
-        /** @var $dirs Mage_Core_Model_Dir */
-        $dirs = new Mage_Core_Model_Dir(__DIR__);
-
-        $designDir = $dirs->getDir(Mage_Core_Model_Dir::THEMES);
-        $jsDir = $dirs->getDir(Mage_Core_Model_Dir::PUB_LIB);
-        $codeDir = $dirs->getDir(Mage_Core_Model_Dir::MODULES);
-
-        return array(
-            array(
-                $designDir . str_replace('/', DIRECTORY_SEPARATOR, '/a/b/c/f/file.xml'),
-                str_replace('/', DIRECTORY_SEPARATOR, '/a/b/c/f/file.xml'),
-                1
-            ),
-            array(
-                $jsDir . str_replace('/', DIRECTORY_SEPARATOR, '/a/b/c/f/file.xml'),
-                null,
-                $jsDir
-            ),
-            array(
-                $codeDir . str_replace('/', DIRECTORY_SEPARATOR, '/a/b/c/f/file.xml'),
-                null,
-                $codeDir
-            ),
-        );
-    }
-
-    /**
-     * @dataProvider sortThemesByHierarchyCallbackProvider
-     */
-    public function testSortThemesByHierarchyCallback($firstThemeParentId, $parentOfParentTheme,
-        $secondThemeId, $expectedResult
-    ) {
-        list($firstTheme, $secondTheme) = $this->_prepareThemesForHierarchyCallback(
-            $firstThemeParentId, $parentOfParentTheme, $secondThemeId
-        );
-
-        $method = self::getMethod('_sortThemesByHierarchyCallback');
-        $result = $method->invokeArgs($this->_model, array($firstTheme, $secondTheme));
-        $this->assertEquals($expectedResult, $result);
-    }
-
-    /**
-     * @return array
-     */
-    public function sortThemesByHierarchyCallbackProvider()
-    {
-        return array(
-            array(1, null, 1, -1),
-            array(1, $this->_getThemeMockFroHierarchyCallback(), 2, -1),
-            array(1, null, 2, 1),
-        );
-    }
-
-    /**
-     * @param int $firstThemeParentId
-     * @param Mage_Core_Model_Theme|null $parentOfParentTheme
-     * @param int $secondThemeId
-     * @return array
-     */
-    protected function _prepareThemesForHierarchyCallback($firstThemeParentId, $parentOfParentTheme, $secondThemeId)
-    {
-        $parentTheme = $this->getMock('Mage_Core_Model_Theme', array('getParentTheme', 'getId'), array(), '', false);
-
-        $firstTheme = $this->getMock('Mage_Core_Model_Theme', array('getParentTheme', 'getId'), array(), '', false);
-        $firstTheme->expects($this->any())
-            ->method('getParentTheme')
-            ->will($this->returnValue($parentTheme));
-
-        $firstTheme->expects($this->any())
-            ->method('getId')
-            ->will($this->returnValue(999));
-
-        $parentTheme->expects($this->any())
-            ->method('getId')
-            ->will($this->returnValue($firstThemeParentId));
-
-        $parentTheme->expects($this->any())
-            ->method('getParentTheme')
-            ->will($this->returnValue($parentOfParentTheme));
-
-        $secondTheme = $this->getMock('Mage_Core_Model_Theme', array('getId'), array(), '', false);
-        $secondTheme->expects($this->any())
-            ->method('getId')
-            ->will($this->returnValue($secondThemeId));
-        return array($firstTheme, $secondTheme);
-    }
-
-    /**
-     * @return PHPUnit_Framework_MockObject_MockObject
-     */
-    protected function _getThemeMockFroHierarchyCallback()
-    {
-        $parentOfParentTheme = $this->getMock('Mage_Core_Model_Theme', array('getId', 'getParentTheme'),
-            array(), '', false);
-        $parentOfParentTheme->expects($this->any())
-            ->method('getId')
-            ->will($this->returnValue(2));
-        $parentOfParentTheme->expects($this->any())
-            ->method('getParentTheme')
-            ->will($this->returnValue(false));
-
-        $parentTheme = $this->getMock('Mage_Core_Model_Theme', array('getParentTheme'), array(), '', false);
-        $parentTheme->expects($this->any())
-            ->method('getParentTheme')
-            ->will($this->returnValue($parentOfParentTheme));
-        return $parentTheme;
-    }
-
-    /**
-     * @param string $fileName
-     * @param string $expectedResult
-     * @dataProvider getThemeByFilenameProvider
-     */
-    public function testGetThemeByFilename($fileName, $expectedResult)
-    {
-        $constructArguments = $this->_prepareModelArguments();
-
-        $constructArguments['objectManager'] = $objectManagerMock = $this->getMockBuilder('Magento_ObjectManager')
-            ->setMethods(array('create'))
-            ->disableOriginalConstructor()
-            ->getMockForAbstractClass();
-
-        $collectionMock = $this->getMock('Mage_Core_Model_Resource_Theme_Collection',
-            get_class_methods('Mage_Core_Model_Resource_Theme_Collection'), array(), '', false);
-
-        $collectionMock->expects($this->atLeastOnce())
-            ->method('getThemeByFullPath')
-            ->will($this->returnArgument(0));
-
-        $objectManagerMock->expects($this->atLeastOnce())
-            ->method('create')
-            ->with($this->equalTo('Mage_Core_Model_Resource_Theme_Collection'))
-            ->will($this->returnValue($collectionMock));
-
-        $this->_model = $this->getMock(
-            'Mage_Theme_Block_Adminhtml_System_Design_Theme_Edit_Tab_Css', array(), $constructArguments, '', true
-        );
-
-        $method = self::getMethod('_getThemeByFilename');
-        $result = $method->invokeArgs($this->_model, array(str_replace('/', DIRECTORY_SEPARATOR, $fileName)));
-        $this->assertEquals($expectedResult, $result);
-    }
-
-    /**
-     * @return array
-     */
-    public function getThemeByFilenameProvider()
-    {
-        return array(array('a/b/c/d/e.xml', 'a/b/c'));
-    }
-
-    /**
-     * @expectedException InvalidArgumentException
-     * @expectedExceptionMessage Theme path does not recognized
-     */
-    public function testGetThemeByFilenameException()
-    {
-        $method = self::getMethod('_getThemeByFilename');
-        $method->invokeArgs($this->_model, array('a'));
-    }
-
-    public function testGetGroupLabels()
-    {
-        $themeModel = $this->getMock('Mage_Core_Model_Theme', array('getThemeId', 'getThemeTitle'), array(), '', false);
-        $themeModel->expects($this->any())
-            ->method('getThemeId')
-            ->will($this->returnValue(1));
-
-        $themeModel->expects($this->any())
-            ->method('getThemeTitle')
-            ->will($this->returnValue('title'));
-
-        $method = self::getMethod('_getGroupLabels');
-        $result = $method->invokeArgs($this->_model, array(array($themeModel)));
-
-        $this->assertContains('Library files', $result);
-        $this->assertContains('Framework files', $result);
-        $this->assertContains('"title" Theme files', $result);
-        $this->assertArrayHasKey(1, $result);
-    }
-
-    /**
-     * @param array $groups
-     * @param array $order
-     * @param array $expectedResult
-     * @dataProvider sortArrayByArrayProvider
-     */
-    public function testSortArrayByArray($groups, $order, $expectedResult)
-    {
-        $method = self::getMethod('_sortArrayByArray');
-        $result = $method->invokeArgs($this->_model, array($groups, $order));
-        $this->assertEquals($expectedResult, $result);
-    }
-
-    /**
-     * @return array
-     */
-    public function sortArrayByArrayProvider()
-    {
-        return array(
-            array(
-                array('b' => 'item2', 'a' => 'item1', 'c' => 'item3'),
-                array('a', 'b', 'c'),
-                array('a' => 'item1', 'b' => 'item2', 'c' => 'item3')
-            ),
-            array(
-                array('x' => 'itemX'),
-                array('a', 'b', 'c'),
-                array('x' => 'itemX')
-            ),
-            array(
-                array('b' => 'item2', 'a' => 'item1', 'c' => 'item3', 'd' => 'item4', 'e' => 'item5'),
-                array('d', 'e'),
-                array('d' => 'item4', 'e' => 'item5', 'b' => 'item2', 'a' => 'item1', 'c' => 'item3'),
-            ),
-        );
-    }
-
     public function testGetTabLabel()
     {
         $this->assertEquals('CSS Editor', $this->_model->getTabLabel());
diff --git a/dev/tests/unit/testsuite/Mage/Theme/Block/Adminhtml/Wysiwyg/Files/ContentTest.php b/dev/tests/unit/testsuite/Mage/Theme/Block/Adminhtml/Wysiwyg/Files/ContentTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..2a3dfeca7ba4e9d00092512b5c0e0bda0946f11a
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Theme/Block/Adminhtml/Wysiwyg/Files/ContentTest.php
@@ -0,0 +1,189 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_Theme
+ * @subpackage  unit_tests
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Mage_Theme_Block_Adminhtml_Wysiwyg_Files_ContentTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Backend_Model_Url|PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_urlBuilder;
+
+    /**
+     * @var Mage_Theme_Helper_Storage|PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_helperStorage;
+
+    /**
+     * @var Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Content|PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_filesContent;
+
+    /**
+     * @var Mage_Core_Controller_Request_Http|PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_request;
+
+    public function setUp()
+    {
+        $this->_helperStorage = $this->getMock('Mage_Theme_Helper_Storage', array(), array(), '', false);
+        $this->_urlBuilder = $this->getMock('Mage_Backend_Model_Url', array(), array(), '', false);
+        $this->_request = $this->getMock('Mage_Core_Controller_Request_Http', array(), array(), '', false);
+
+        $objectManagerHelper = new Magento_Test_Helper_ObjectManager($this);
+        $constructArguments =  $objectManagerHelper->getConstructArguments(
+            Magento_Test_Helper_ObjectManager::BLOCK_ENTITY,
+            'Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Content',
+            array(
+                'urlBuilder'    => $this->_urlBuilder,
+                'request'       => $this->_request
+            )
+        );
+        $this->_filesContent = $this->getMock(
+            'Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Content', array('helper'), $constructArguments
+        );
+
+        $this->_filesContent->expects($this->any())
+            ->method('helper')
+            ->with('Mage_Theme_Helper_Storage')
+            ->will($this->returnValue($this->_helperStorage));
+    }
+
+    /**
+     * @dataProvider requestParamsProvider
+     * @param array $requestParams
+     */
+    public function testGetNewFolderUrl($requestParams)
+    {
+        $expectedUrl = 'some_url';
+
+        $this->_helperStorage->expects($this->once())
+            ->method('getRequestParams')
+            ->will($this->returnValue($requestParams));
+
+        $this->_urlBuilder->expects($this->once())
+            ->method('getUrl')
+            ->with('*/*/newFolder', $requestParams)
+            ->will($this->returnValue($expectedUrl));
+
+        $this->assertEquals($expectedUrl, $this->_filesContent->getNewfolderUrl());
+    }
+
+    /**
+     * @dataProvider requestParamsProvider
+     * @param array $requestParams
+     */
+    public function testGetDeleteFilesUrl($requestParams)
+    {
+        $expectedUrl = 'some_url';
+
+        $this->_helperStorage->expects($this->once())
+            ->method('getRequestParams')
+            ->will($this->returnValue($requestParams));
+
+        $this->_urlBuilder->expects($this->once())
+            ->method('getUrl')
+            ->with('*/*/deleteFiles', $requestParams)
+            ->will($this->returnValue($expectedUrl));
+
+        $this->assertEquals($expectedUrl, $this->_filesContent->getDeleteFilesUrl());
+    }
+
+    /**
+     * @dataProvider requestParamsProvider
+     * @param array $requestParams
+     */
+    public function testGetOnInsertUrl($requestParams)
+    {
+        $expectedUrl = 'some_url';
+
+        $this->_helperStorage->expects($this->once())
+            ->method('getRequestParams')
+            ->will($this->returnValue($requestParams));
+
+        $this->_urlBuilder->expects($this->once())
+            ->method('getUrl')
+            ->with('*/*/onInsert', $requestParams)
+            ->will($this->returnValue($expectedUrl));
+
+        $this->assertEquals($expectedUrl, $this->_filesContent->getOnInsertUrl());
+    }
+
+    /**
+     * Data provider for requestParams
+     * @return array
+     */
+    public function requestParamsProvider()
+    {
+        return array(
+            'requestParams' => array(
+                Mage_Theme_Helper_Storage::PARAM_THEME_ID     => 1,
+                Mage_Theme_Helper_Storage::PARAM_CONTENT_TYPE => Mage_Theme_Model_Wysiwyg_Storage::TYPE_IMAGE,
+                Mage_Theme_Helper_Storage::PARAM_NODE         => 'root'
+            )
+        );
+    }
+
+    public function testGetTargetElementId()
+    {
+        $expectedRequest = 'some_request';
+
+        $this->_request->expects($this->once())
+            ->method('getParam')
+            ->with('target_element_id')
+            ->will($this->returnValue($expectedRequest));
+
+        $this->assertEquals($expectedRequest, $this->_filesContent->getTargetElementId());
+    }
+
+    public function testGetContentsUrl()
+    {
+        $expectedUrl = 'some_url';
+
+        $expectedRequest = 'some_request';
+
+        $requestParams = array(
+            Mage_Theme_Helper_Storage::PARAM_THEME_ID     => 1,
+            Mage_Theme_Helper_Storage::PARAM_CONTENT_TYPE => Mage_Theme_Model_Wysiwyg_Storage::TYPE_IMAGE,
+            Mage_Theme_Helper_Storage::PARAM_NODE         => 'root'
+        );
+
+        $this->_urlBuilder->expects($this->once())
+            ->method('getUrl')
+            ->with('*/*/contents', array('type' => $expectedRequest) + $requestParams)
+            ->will($this->returnValue($expectedUrl));
+
+        $this->_request->expects($this->once())
+            ->method('getParam')
+            ->with('type')
+            ->will($this->returnValue($expectedRequest));
+
+        $this->_helperStorage->expects($this->once())
+            ->method('getRequestParams')
+            ->will($this->returnValue($requestParams));
+
+        $this->assertEquals($expectedUrl, $this->_filesContent->getContentsUrl());
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Theme/Block/Adminhtml/Wysiwyg/Files/TreeTest.php b/dev/tests/unit/testsuite/Mage/Theme/Block/Adminhtml/Wysiwyg/Files/TreeTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..c695d510f7f2f38ef89959f15525cc6de3489e8c
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Theme/Block/Adminhtml/Wysiwyg/Files/TreeTest.php
@@ -0,0 +1,86 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Mage
+ * @package     Mage_Theme
+ * @subpackage  unit_tests
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Theme_Block_Adminhtml_Wysiwyg_Files_TreeTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Backend_Model_Url|PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_urlBuilder;
+
+    /**
+     * @var Mage_Theme_Helper_Storage|PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_helperStorage;
+
+    /**
+     * @var Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Tree|PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_filesTree;
+
+    public function setUp()
+    {
+        $this->_helperStorage = $this->getMock('Mage_Theme_Helper_Storage', array(), array(), '', false);
+        $this->_urlBuilder = $this->getMock('Mage_Backend_Model_Url', array(), array(), '', false);
+
+        $objectManagerHelper = new Magento_Test_Helper_ObjectManager($this);
+        $constructArguments =  $objectManagerHelper->getConstructArguments(
+            Magento_Test_Helper_ObjectManager::BLOCK_ENTITY,
+            'Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Content',
+            array('urlBuilder'    => $this->_urlBuilder)
+        );
+        $this->_filesTree = $this->getMock(
+            'Mage_Theme_Block_Adminhtml_Wysiwyg_Files_Tree', array('helper'), $constructArguments
+        );
+
+        $this->_filesTree->expects($this->any())
+            ->method('helper')
+            ->with('Mage_Theme_Helper_Storage')
+            ->will($this->returnValue($this->_helperStorage));
+    }
+
+    public function testGetTreeLoaderUrl()
+    {
+        $requestParams = array(
+            Mage_Theme_Helper_Storage::PARAM_THEME_ID     => 1,
+            Mage_Theme_Helper_Storage::PARAM_CONTENT_TYPE => Mage_Theme_Model_Wysiwyg_Storage::TYPE_IMAGE,
+            Mage_Theme_Helper_Storage::PARAM_NODE         => 'root'
+        );
+        $expectedUrl = 'some_url';
+
+        $this->_helperStorage->expects($this->once())
+            ->method('getRequestParams')
+            ->will($this->returnValue($requestParams));
+
+        $this->_urlBuilder->expects($this->once())
+            ->method('getUrl')
+            ->with('*/*/treeJson', $requestParams)
+            ->will($this->returnValue($expectedUrl));
+
+        $this->assertEquals($expectedUrl, $this->_filesTree->getTreeLoaderUrl());
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Theme/Helper/StorageTest.php b/dev/tests/unit/testsuite/Mage/Theme/Helper/StorageTest.php
index 32cd9c2957c4a252838e5c970f1648eae145ba28..8151776b7c44f50d2cd3a9547eb370d1d863870d 100644
--- a/dev/tests/unit/testsuite/Mage/Theme/Helper/StorageTest.php
+++ b/dev/tests/unit/testsuite/Mage/Theme/Helper/StorageTest.php
@@ -123,6 +123,7 @@ class Mage_Theme_Helper_StorageTest extends PHPUnit_Framework_TestCase
      */
     public function testConvertPathToId()
     {
+        $this->markTestIncomplete('MAGETWO-6406');
         $storageRoot = $this->_customizationPath . Magento_Filesystem::DIRECTORY_SEPARATOR
             . Mage_Theme_Model_Wysiwyg_Storage::TYPE_IMAGE;
         $this->_mockStorageRoot($storageRoot);
@@ -187,6 +188,7 @@ class Mage_Theme_Helper_StorageTest extends PHPUnit_Framework_TestCase
      */
     public function testGetRelativeUrl()
     {
+        $this->markTestIncomplete('MAGETWO-6406');
         $imageName = 'imageName.jpg';
         $dirOne = 'some_dir';
         $dirTwo = 'test_der';
@@ -218,6 +220,7 @@ class Mage_Theme_Helper_StorageTest extends PHPUnit_Framework_TestCase
      */
     public function testGetCurrentPath()
     {
+        $this->markTestIncomplete('MAGETWO-6406');
         $subPath = Magento_Filesystem::DIRECTORY_SEPARATOR . 'some_dir';
         $encodedSubPath = $this->_storageHelper->urlEncode($subPath);
         $storageRoot = $this->_customizationPath . Magento_Filesystem::DIRECTORY_SEPARATOR
diff --git a/dev/tests/unit/testsuite/Mage/Theme/controller/Adminhtml/System/Design/ThemeControllerTest.php b/dev/tests/unit/testsuite/Mage/Theme/controller/Adminhtml/System/Design/ThemeControllerTest.php
index 1a5b01d9c8c3be9319e0b63161962982f86092cb..8cb58bcc21a9c8fe061c467c2505674e49a926b2 100644
--- a/dev/tests/unit/testsuite/Mage/Theme/controller/Adminhtml/System/Design/ThemeControllerTest.php
+++ b/dev/tests/unit/testsuite/Mage/Theme/controller/Adminhtml/System/Design/ThemeControllerTest.php
@@ -58,17 +58,17 @@ class Mage_Theme_Controller_Adminhtml_System_Design_ThemeControllerTest extends
         $this->_model = $this->getMock('Mage_Theme_Adminhtml_System_Design_ThemeController',
             array('_forward', '_title', '__', 'loadLayout', 'renderLayout', '_redirect', '_getSession'),
             array(
-                 $this->_request,
-                 $this->getMock('Mage_Core_Controller_Response_Http', array(), array(), '', false),
-                 null,
-                 $this->_objectManagerMock,
-                 $this->getMock('Mage_Core_Controller_Varien_Front', array(), array(), '', false),
-                 $this->getMock('Mage_Core_Model_Layout_Factory', array(), array(), '', false),
-                 array(
-                     'translator' => 'translator',
-                     'helper'     => 'helper',
-                     'session'    => 'session'
-                 )
+                $this->_request,
+                $this->getMock('Mage_Core_Controller_Response_Http', array(), array(), '', false),
+                $this->_objectManagerMock,
+                $this->getMock('Mage_Core_Controller_Varien_Front', array(), array(), '', false),
+                $this->getMock('Mage_Core_Model_Layout_Factory', array(), array(), '', false),
+                null,
+                array(
+                    'translator' => 'translator',
+                    'helper'     => 'helper',
+                    'session'    => 'session'
+                ),
             ));
         $this->_model->expects($this->any())->method('_title')->will($this->returnValue($this->_model));
         $this->_model->expects($this->any())->method('loadLayout');
@@ -92,17 +92,18 @@ class Mage_Theme_Controller_Adminhtml_System_Design_ThemeControllerTest extends
 
         $this->_request->expects($this->at(0))->method('getParam')->with('back', false)
             ->will($this->returnValue(true));
-        $this->_request->expects($this->once(1))->method('getPost')->will($this->returnValue(true));
-        $this->_request->expects($this->at(2))->method('getParam')->with('theme')
+
+        $this->_request->expects($this->at(1))->method('getParam')->with('theme')
             ->will($this->returnValue($themeData));
-        $this->_request->expects($this->at(3))->method('getParam')->with('custom_css_content')
+        $this->_request->expects($this->at(2))->method('getParam')->with('custom_css_content')
             ->will($this->returnValue($customCssContent));
-        $this->_request->expects($this->at(4))->method('getParam')->with('js_uploaded_files')
+        $this->_request->expects($this->at(3))->method('getParam')->with('js_uploaded_files')
             ->will($this->returnValue($jsUploadedFiles));
-        $this->_request->expects($this->at(5))->method('getParam')->with('js_removed_files')
+        $this->_request->expects($this->at(4))->method('getParam')->with('js_removed_files')
             ->will($this->returnValue($jsRemovedFiles));
-        $this->_request->expects($this->at(6))->method('getParam')->with('js_order')
+        $this->_request->expects($this->at(5))->method('getParam')->with('js_order')
             ->will($this->returnValue($jsOrder));
+        $this->_request->expects($this->once(6))->method('getPost')->will($this->returnValue(true));
 
         $filesCssMock = $this->getMock(
             'Mage_Core_Model_Theme_Customization_Files_Css', array('setDataForSave'), array(), '', false
diff --git a/dev/tests/unit/testsuite/Mage/User/Model/Acl/Loader/RoleTest.php b/dev/tests/unit/testsuite/Mage/User/Model/Acl/Loader/RoleTest.php
index 5261f1af31f05e60224f0533346f918d6b1b6f2e..446d1d282f6fd962c64c65394abc07c033c273ed 100644
--- a/dev/tests/unit/testsuite/Mage/User/Model/Acl/Loader/RoleTest.php
+++ b/dev/tests/unit/testsuite/Mage/User/Model/Acl/Loader/RoleTest.php
@@ -49,7 +49,7 @@ class Mage_User_Model_Acl_Loader_RoleTest extends PHPUnit_Framework_TestCase
 
     public function setUp()
     {
-        $this->_resourceMock = $this->getMock('Mage_Core_Model_Resource');
+        $this->_resourceMock = $this->getMock('Mage_Core_Model_Resource', array(), array(), '', false, false);
         $this->_objectFactoryMock = $this->getMock('Mage_Core_Model_Config', array(), array(), '', false);
 
         $this->_resourceMock->expects($this->once())
diff --git a/dev/tests/unit/testsuite/Mage/User/Model/Acl/Loader/RuleTest.php b/dev/tests/unit/testsuite/Mage/User/Model/Acl/Loader/RuleTest.php
index 72fd741d21171325b8e8897bae51df72c179e14f..fdb146928e8d0d3d76a28c1692a035d9657b20c6 100644
--- a/dev/tests/unit/testsuite/Mage/User/Model/Acl/Loader/RuleTest.php
+++ b/dev/tests/unit/testsuite/Mage/User/Model/Acl/Loader/RuleTest.php
@@ -39,7 +39,7 @@ class Mage_User_Model_Acl_Loader_RuleTest extends PHPUnit_Framework_TestCase
 
     public function setUp()
     {
-        $this->_resourceMock = $this->getMock('Mage_Core_Model_Resource');
+        $this->_resourceMock = $this->getMock('Mage_Core_Model_Resource', array(), array(), '', false, false);
         $this->_model = new Mage_User_Model_Acl_Loader_Rule(array(
             'resource' => $this->_resourceMock
         ));
diff --git a/dev/tests/unit/testsuite/Mage/Webapi/Controller/Dispatcher/ErrorProcessorTest.php b/dev/tests/unit/testsuite/Mage/Webapi/Controller/Dispatcher/ErrorProcessorTest.php
index bc713579956a81692ca531f4d2acaa0625adab3e..07c33d81c87b3927a1bbcb014496c2a1d6966d88 100644
--- a/dev/tests/unit/testsuite/Mage/Webapi/Controller/Dispatcher/ErrorProcessorTest.php
+++ b/dev/tests/unit/testsuite/Mage/Webapi/Controller/Dispatcher/ErrorProcessorTest.php
@@ -40,7 +40,7 @@ class Mage_Webapi_Controller_Dispatcher_ErrorProcessorTest extends PHPUnit_Frame
     protected function setUp()
     {
         /** Set up mocks for SUT. */
-        $this->_helperMock = $this->getMockBuilder('Mage_Core_Helper_Data')->getMock();
+        $this->_helperMock = $this->getMockBuilder('Mage_Core_Helper_Data')->disableOriginalConstructor()->getMock();
         $this->_helperMock->expects($this->any())->method('__')->will($this->returnArgument(0));
         $helperFactoryMock = $this->getMockBuilder('Mage_Core_Model_Factory_Helper')->getMock();
         $helperFactoryMock->expects($this->any())->method('get')->will($this->returnValue($this->_helperMock));
diff --git a/dev/tests/unit/testsuite/Mage/Webapi/Controller/Request/Rest/Interpreter/JsonTest.php b/dev/tests/unit/testsuite/Mage/Webapi/Controller/Request/Rest/Interpreter/JsonTest.php
index 8f444ef4b0ec1afd90a33dec2fe9d60949ecfd4f..638b3cdb3ad899c161c9d62e2e2dc35927fc02d5 100644
--- a/dev/tests/unit/testsuite/Mage/Webapi/Controller/Request/Rest/Interpreter/JsonTest.php
+++ b/dev/tests/unit/testsuite/Mage/Webapi/Controller/Request/Rest/Interpreter/JsonTest.php
@@ -41,7 +41,9 @@ class Mage_Webapi_Controller_Request_Rest_Interpreter_JsonTest extends PHPUnit_F
     {
         /** Prepare mocks for SUT constructor. */
         $this->_helperFactoryMock = $this->getMock('Mage_Core_Model_Factory_Helper');
-        $this->_coreHelperMock = $this->getMock('Mage_Core_Helper_Data', array('__', 'jsonDecode'));
+        $this->_coreHelperMock = $this->getMock('Mage_Core_Helper_Data',
+            array('__', 'jsonDecode'), array(), '', false, false
+        );
         $this->_helperFactoryMock->expects($this->any())
             ->method('get')
             ->will($this->returnValue($this->_coreHelperMock));
diff --git a/dev/tests/unit/testsuite/Mage/Webapi/Controller/Request/Rest/Interpreter/XmlTest.php b/dev/tests/unit/testsuite/Mage/Webapi/Controller/Request/Rest/Interpreter/XmlTest.php
index 2d34455a7e38221e1cab429dbd2a18e30940b9ac..0ec1813c22f85929ab2cda301c52758056bfc7af 100644
--- a/dev/tests/unit/testsuite/Mage/Webapi/Controller/Request/Rest/Interpreter/XmlTest.php
+++ b/dev/tests/unit/testsuite/Mage/Webapi/Controller/Request/Rest/Interpreter/XmlTest.php
@@ -1,7 +1,5 @@
 <?php
 /**
- *
- *
  * Magento
  *
  * NOTICE OF LICENSE
diff --git a/dev/tests/unit/testsuite/Mage/Webapi/Controller/Response/Rest/Renderer/JsonTest.php b/dev/tests/unit/testsuite/Mage/Webapi/Controller/Response/Rest/Renderer/JsonTest.php
index ce67726aea4d1d8480b5e83d92cd85d9cc3269d7..85c00c5cf7111c8bfb16cb3071d9b418dcd59979 100644
--- a/dev/tests/unit/testsuite/Mage/Webapi/Controller/Response/Rest/Renderer/JsonTest.php
+++ b/dev/tests/unit/testsuite/Mage/Webapi/Controller/Response/Rest/Renderer/JsonTest.php
@@ -34,7 +34,7 @@ class Mage_Webapi_Controller_Response_Rest_Renderer_JsonTest extends PHPUnit_Fra
     protected function setUp()
     {
         /** Prepare mocks and objects for SUT constructor. */
-        $this->_helperMock = $this->getMockBuilder('Mage_Core_Helper_Data')->getMock();
+        $this->_helperMock = $this->getMockBuilder('Mage_Core_Helper_Data')->disableOriginalConstructor()->getMock();
         $helperFactoryMock = $this->getMock('Mage_Core_Model_Factory_Helper');
         $helperFactoryMock->expects($this->any())->method('get')->will($this->returnValue($this->_helperMock));
         /** Initialize SUT. */
diff --git a/dev/tests/unit/testsuite/Mage/Webapi/Model/Acl/RoleTest.php b/dev/tests/unit/testsuite/Mage/Webapi/Model/Acl/RoleTest.php
index d3040ea4200973ec3e97a4e5c4d2d114a8244f05..2876e7621ab87370c2a38b944b0e38ee60bac93e 100644
--- a/dev/tests/unit/testsuite/Mage/Webapi/Model/Acl/RoleTest.php
+++ b/dev/tests/unit/testsuite/Mage/Webapi/Model/Acl/RoleTest.php
@@ -98,21 +98,20 @@ class Mage_Webapi_Model_Acl_RoleTest extends PHPUnit_Framework_TestCase
      */
     public function testGetCollection()
     {
-        /** @var Mage_Webapi_Model_Resource_Acl_Role_Collection $collection */
-        $collection = $this->getMockBuilder('Mage_Webapi_Model_Resource_Acl_Role_Collection')
-            ->setConstructorArgs(array('resource' => $this->_roleResource))
-            ->setMethods(array('_initSelect'))
-            ->getMock();
+        /** @var PHPUnit_Framework_MockObject_MockObject $collection */
+        $collection = $this->getMock(
+            'Mage_Webapi_Model_Resource_Acl_Role_Collection',
+            array('_initSelect', 'setModel'),
+            array('resource' => $this->_roleResource),
+            '',
+            true
+        );
 
-        $collection->expects($this->any())
-            ->method('_initSelect')
-            ->withAnyParameters()
-            ->will($this->returnValue(null));
+        $collection->expects($this->any())->method('setModel')->with('Mage_Webapi_Model_Resource_Acl_Role');
 
         $model = $this->_createModel($this->_roleResource, $collection);
         $result = $model->getCollection();
 
-        $this->assertAttributeEquals('Mage_Webapi_Model_Acl_Role', '_model', $result);
         $this->assertAttributeEquals('Mage_Webapi_Model_Resource_Acl_Role', '_resourceModel', $result);
     }
 }
diff --git a/dev/tests/unit/testsuite/Mage/Webapi/Model/Acl/RuleTest.php b/dev/tests/unit/testsuite/Mage/Webapi/Model/Acl/RuleTest.php
index 742016a500c1e7927b4a4c721738f1daaedfbafc..998376fd6aeedd9daa5d0f4e624725ef731f11a5 100644
--- a/dev/tests/unit/testsuite/Mage/Webapi/Model/Acl/RuleTest.php
+++ b/dev/tests/unit/testsuite/Mage/Webapi/Model/Acl/RuleTest.php
@@ -113,17 +113,15 @@ class Mage_Webapi_Model_Acl_RuleTest extends PHPUnit_Framework_TestCase
      */
     public function testGetCollection()
     {
-        /** @var Mage_Webapi_Model_Resource_Acl_Rule_Collection $collection */
-        $collection = $this->getMockBuilder('Mage_Webapi_Model_Resource_Acl_Rule_Collection')
-            ->setConstructorArgs(array('resource' => $this->_ruleResource))
-            ->setMethods(array('_initSelect', 'getSelect'))
-            ->getMock();
-
-        $collection->expects($this->any())
-            ->method('_initSelect')
-            ->withAnyParameters()
-            ->will($this->returnValue(null));
-
+        /** @var PHPUnit_Framework_MockObject_MockObject $collection */
+        $collection = $this->getMock(
+            'Mage_Webapi_Model_Resource_Acl_Rule_Collection',
+            array('_initSelect', 'setModel', 'getSelect'),
+            array('resource' => $this->_ruleResource),
+            '',
+            true
+        );
+        $collection->expects($this->any())->method('setModel')->with('Mage_Webapi_Model_Resource_Acl_Role');
         $collection->expects($this->any())
             ->method('getSelect')
             ->withAnyParameters()
@@ -134,7 +132,6 @@ class Mage_Webapi_Model_Acl_RuleTest extends PHPUnit_Framework_TestCase
         // Test _construct
         $result = $model->getCollection();
 
-        $this->assertAttributeEquals('Mage_Webapi_Model_Acl_Rule', '_model', $result);
         $this->assertAttributeEquals('Mage_Webapi_Model_Resource_Acl_Rule', '_resourceModel', $result);
 
         // Test getByRole
diff --git a/dev/tests/unit/testsuite/Mage/Webapi/Model/Acl/UserTest.php b/dev/tests/unit/testsuite/Mage/Webapi/Model/Acl/UserTest.php
index b3e97f539642ff0c15d73e1776f0803b8cf87a98..20eab86c4d3556f1bf5adaa355ccd838f7de969c 100644
--- a/dev/tests/unit/testsuite/Mage/Webapi/Model/Acl/UserTest.php
+++ b/dev/tests/unit/testsuite/Mage/Webapi/Model/Acl/UserTest.php
@@ -144,21 +144,20 @@ class Mage_Webapi_Model_Acl_UserTest extends PHPUnit_Framework_TestCase
      */
     public function testGetCollection()
     {
-        /** @var Mage_Webapi_Model_Resource_Acl_User_Collection $collection */
-        $collection = $this->getMockBuilder('Mage_Webapi_Model_Resource_Acl_User_Collection')
-            ->setConstructorArgs(array('resource' => $this->_userResource))
-            ->setMethods(array('_initSelect'))
-            ->getMock();
+        /** @var PHPUnit_Framework_MockObject_MockObject $collection */
+        $collection = $this->getMock(
+            'Mage_Webapi_Model_Resource_Acl_User_Collection',
+            array('_initSelect', 'setModel'),
+            array('resource' => $this->_userResource),
+            '',
+            true
+        );
 
-        $collection->expects($this->any())
-            ->method('_initSelect')
-            ->withAnyParameters()
-            ->will($this->returnValue(null));
+        $collection->expects($this->any())->method('setModel')->with('Mage_Webapi_Model_Acl_User');
 
         $model = $this->_createModel($this->_userResource, $collection);
         $result = $model->getCollection();
 
-        $this->assertAttributeEquals('Mage_Webapi_Model_Acl_User', '_model', $result);
         $this->assertAttributeEquals('Mage_Webapi_Model_Resource_Acl_User', '_resourceModel', $result);
     }
 }
diff --git a/dev/tests/unit/testsuite/Mage/Webapi/Model/Authorization/ConfigTest.php b/dev/tests/unit/testsuite/Mage/Webapi/Model/Authorization/ConfigTest.php
index c85263a87b2b06d6d23a9b0800d6fb2388a05282..5636ea6da549f9dac83b9d7afa36d7e852c0cd8d 100644
--- a/dev/tests/unit/testsuite/Mage/Webapi/Model/Authorization/ConfigTest.php
+++ b/dev/tests/unit/testsuite/Mage/Webapi/Model/Authorization/ConfigTest.php
@@ -52,7 +52,7 @@ class Mage_Webapi_Model_Authorization_ConfigTest extends PHPUnit_Framework_TestC
     {
         $helper = new Magento_Test_Helper_ObjectManager($this);
 
-        $this->_config = $this->getMockBuilder('Mage_Core_Model_Config')
+        $this->_config = $this->getMockBuilder('Mage_Core_Model_Config_Modules_Reader')
             ->disableOriginalConstructor()
             ->setMethods(array('getModuleConfigurationFiles'))
             ->getMock();
@@ -68,7 +68,7 @@ class Mage_Webapi_Model_Authorization_ConfigTest extends PHPUnit_Framework_TestC
             ->getMock();
 
         $this->_model = $helper->getModel('Mage_Webapi_Model_Authorization_Config', array(
-            'config' => $this->_config,
+            'moduleReader' => $this->_config,
             'readerFactory' => $this->_readerFactory
         ));
 
diff --git a/dev/tests/unit/testsuite/Mage/Webapi/Model/Soap/AutoDiscoverTest.php b/dev/tests/unit/testsuite/Mage/Webapi/Model/Soap/AutoDiscoverTest.php
index cb0e50207102495e515a58787c86986b9e4022cb..06b20912deb87dc8fc79d5c5097a77fedff66c3a 100644
--- a/dev/tests/unit/testsuite/Mage/Webapi/Model/Soap/AutoDiscoverTest.php
+++ b/dev/tests/unit/testsuite/Mage/Webapi/Model/Soap/AutoDiscoverTest.php
@@ -70,7 +70,7 @@ class Mage_Webapi_Model_Soap_AutoDiscoverTest extends PHPUnit_Framework_TestCase
             array(new Magento_ObjectManager_Zend())
         );
         $wsdlFactory->expects($this->any())->method('create')->will($this->returnValue($this->_wsdlMock));
-        $helper = $this->getMock('Mage_Webapi_Helper_Config', array('__'));
+        $helper = $this->getMock('Mage_Webapi_Helper_Config', array('__'), array(), '', false, false);
         $helper->expects($this->any())->method('__')->will($this->returnArgument(0));
         $this->_cacheMock = $this->getMockBuilder('Mage_Core_Model_Cache')->disableOriginalConstructor()->getMock();
         /** Initialize SUT. */
diff --git a/dev/tests/unit/testsuite/Mage/Webapi/Model/Soap/Wsdl/ComplexTypeStrategy/ConfigBasedTest.php b/dev/tests/unit/testsuite/Mage/Webapi/Model/Soap/Wsdl/ComplexTypeStrategy/ConfigBasedTest.php
index 0525cfa307cc604ca3cd5d8d7812bac4a2bfffd4..a27dad4b8217ed76dbfff88394b614254b247950 100644
--- a/dev/tests/unit/testsuite/Mage/Webapi/Model/Soap/Wsdl/ComplexTypeStrategy/ConfigBasedTest.php
+++ b/dev/tests/unit/testsuite/Mage/Webapi/Model/Soap/Wsdl/ComplexTypeStrategy/ConfigBasedTest.php
@@ -49,7 +49,7 @@ class Mage_Webapi_Model_Soap_Wsdl_ComplexTypeStrategy_ConfigBasedTest extends PH
             ->setMethods(array('toDomDocument', 'getTypes', 'getSchema'))
             ->disableOriginalConstructor()
             ->getMock();
-        $helper = $this->getMock('Mage_Webapi_Helper_Config', array('__'));
+        $helper = $this->getMock('Mage_Webapi_Helper_Config', array('__'), array(), '', false, false);
         $helper->expects($this->any())->method('__')->will($this->returnArgument(0));
 
         $this->_strategy = new Mage_Webapi_Model_Soap_Wsdl_ComplexTypeStrategy_ConfigBased(
diff --git a/dev/tests/unit/testsuite/Magento/Http/Handler/CompositeTest.php b/dev/tests/unit/testsuite/Magento/Http/Handler/CompositeTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..45f62a620c7846324266bb5f6bffa546bab4ecac
--- /dev/null
+++ b/dev/tests/unit/testsuite/Magento/Http/Handler/CompositeTest.php
@@ -0,0 +1,114 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Magento_Http_Handler_CompositeTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Magento_Http_Handler_Composite
+     */
+    protected $_model;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_requestMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_responseMock;
+
+    /**
+     * @var PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_handlerFactoryMock;
+
+    public function setUp()
+    {
+        $handlers = array(
+            'app' => array(
+                'sortOrder' => 50,
+                'class' => 'Class_App_Handler',
+            ),
+            'fpc' => array(
+                'sortOrder' => 20,
+                'class' => 'Class_Fpc_Handler',
+            ),
+        );
+        $this->_requestMock = $this->getMock('Zend_Controller_Request_Http', array(), array(), '', false);
+        $this->_responseMock = $this->getMock('Zend_Controller_Response_Http', array(), array(), '', false);
+        $this->_handlerFactoryMock = $this->getMock('Magento_Http_HandlerFactory', array(), array(), '', false, false);
+        $this->_handlerMock = $this->getMock('Magento_Http_HandlerInterface', array(), array(), '', false, false);
+        $this->_model = new Magento_Http_Handler_Composite($this->_handlerFactoryMock, $handlers);
+    }
+
+    public function tearDown()
+    {
+        unset($this->_requestMock);
+        unset($this->_responseMock);
+        unset($this->_handlerFactoryMock);
+        unset($this->_model);
+    }
+
+    public function testHandleBreaksCycleIfRequestIsDispatched()
+    {
+        $this->_handlerFactoryMock->expects($this->once())
+            ->method('create')->with('Class_Fpc_Handler')->will($this->returnValue($this->_handlerMock));
+        $this->_handlerMock->expects($this->once())
+            ->method('handle')->with($this->_requestMock, $this->_responseMock);
+        $this->_requestMock->expects($this->once())->method('isDispatched')->will($this->returnValue(true));
+
+        $this->_model->handle($this->_requestMock, $this->_responseMock);
+    }
+
+    public function testSorting()
+    {
+        $handlers = array(
+            'app' => array(
+                'sortOrder' => 50,
+                'class' => 'Class_App_Handler',
+            ),
+            'fpc' => array(
+                'sortOrder' => 20,
+                'class' => 'Class_Fpc_Handler',
+            ),
+        );
+
+        $model = new Magento_Http_Handler_Composite($this->_handlerFactoryMock, $handlers);
+
+        $this->_handlerMock->expects($this->exactly(2))->method('handle')
+            ->with($this->_requestMock, $this->_responseMock);
+
+        $this->_handlerFactoryMock->expects($this->at(0))
+            ->method('create')
+            ->with('Class_Fpc_Handler')
+            ->will($this->returnValue($this->_handlerMock));
+
+        $this->_handlerFactoryMock->expects($this->at(1))
+            ->method('create')
+            ->with('Class_App_Handler')
+            ->will($this->returnValue($this->_handlerMock));
+
+        $model->handle($this->_requestMock, $this->_responseMock);
+    }
+}
diff --git a/dev/tests/unit/testsuite/tools/migration/Acl/Db/Adapter/FactoryTest.php b/dev/tests/unit/testsuite/tools/migration/Acl/Db/Adapter/FactoryTest.php
index f7b022fec3696c5ee61570f0eef7498b0e6a4503..7530f0206b65e00c6f45bb75ec412ff0cd45e234 100644
--- a/dev/tests/unit/testsuite/tools/migration/Acl/Db/Adapter/FactoryTest.php
+++ b/dev/tests/unit/testsuite/tools/migration/Acl/Db/Adapter/FactoryTest.php
@@ -82,6 +82,6 @@ class Tools_Migration_Acl_Db_Adapter_FactoryTest extends PHPUnit_Framework_TestC
      */
     public function testGetAdapterWithInvalidType()
     {
-        $this->_model->getAdapter($this->_config, 'Mage_Core_Helper_Data');
+        $this->_model->getAdapter($this->_config, 'Varien_Object');
     }
 }
diff --git a/dev/tools/di/compiler.php b/dev/tools/di/compiler.php
index 861d1f046d835ed0ad4d24c86b252bfb5f881a14..009a1628f1d7915833ea0b7ad49b762c17501a8b 100644
--- a/dev/tools/di/compiler.php
+++ b/dev/tools/di/compiler.php
@@ -61,9 +61,11 @@ class ArrayDefinitionCompiler
      */
     public function __construct()
     {
-        $this->_config = new Mage_Core_Model_Config(new Magento_ObjectManager_Zend());
-        $this->_config->loadBase();
-        $this->_config->loadModules();
+        $objectManager = new Mage_Core_Model_ObjectManager(new Mage_Core_Model_ObjectManager_Config(array(
+            Mage::PARAM_BASEDIR => BP,
+            Mage::PARAM_BAN_CACHE => true
+        )), BP);
+        $this->_config = $objectManager->get('Mage_Core_Model_Config');
 
         $this->_initCommonDependencies();
     }
@@ -272,9 +274,10 @@ echo "Compiling Magento\n";
 $definitions = array_merge_recursive($definitions, $compiler->compileModule(BP . '/lib/Magento'));
 echo "Compiling Mage\n";
 $definitions = array_merge_recursive($definitions, $compiler->compileModule(BP . '/lib/Mage'));
-echo "Compiling generated entities\n";
-$definitions = array_merge_recursive($definitions, $compiler->compileModule(BP . '/var/generation'));
-
+if (is_readable(BP . '/var/generation')) {
+    echo "Compiling generated entities\n";
+    $definitions = array_merge_recursive($definitions, $compiler->compileModule(BP . '/var/generation'));
+}
 foreach ($definitions as $key => $definition) {
     $definitions[$key] = json_encode($definition);
 }
diff --git a/downloader/Maged/Controller.php b/downloader/Maged/Controller.php
index e4ca50a09e6a7500dc01e154f2b280529c6a9352..7527e4b072e17f99033d3951c15a32fe3aeb8e7f 100755
--- a/downloader/Maged/Controller.php
+++ b/downloader/Maged/Controller.php
@@ -504,9 +504,18 @@ final class Maged_Controller
         if (!self::$_instance) {
             self::$_instance = new self;
 
-            if (self::$_instance->isDownloaded() && self::$_instance->isInstalled()) {
-                Mage::app('', 'store', array('global_ban_use_cache'=>true));
-                Mage::getSingleton('Mage_Backend_Model_Url')->turnOffSecretKey();
+            if (self::$_instance->isDownloaded()) {
+                if (!class_exists('Mage', false)) {
+                    if (!file_exists(self::getBootstrapPath())) {
+                        return false;
+                    }
+                    include_once self::getBootstrapPath();
+                    Mage::setIsDownloader();
+                }
+                Mage::getObjectManager()->get('Mage_Core_Model_App');
+                if (self::isInstalled()) {
+                    Mage::getSingleton('Mage_Backend_Model_Url')->turnOffSecretKey();
+                }
             }
         }
         return self::$_instance;
@@ -826,13 +835,6 @@ final class Maged_Controller
         if (!$this->isDownloaded()) {
             return false;
         }
-        if (!class_exists('Mage', false)) {
-            if (!file_exists($this->getBootstrapPath())) {
-                return false;
-            }
-            include_once $this->getBootstrapPath();
-            Mage::setIsDownloader();
-        }
         return Mage::isInstalled();
     }
 
@@ -936,8 +938,11 @@ final class Maged_Controller
 
                 // reinit config and apply all updates
                 Mage::app()->getConfig()->reinit();
-                Mage_Core_Model_Resource_Setup::applyAllUpdates();
-                Mage_Core_Model_Resource_Setup::applyAllDataUpdates();
+
+                /** @var $updater Mage_Core_Model_Db_UpdaterInterface*/
+                $updater = Mage::getObjectManager()->get('Mage_Core_Model_Db_UpdaterInterface');
+                $updater->updateScheme();
+                $updater->updateData();
                 $message .= 'Cache cleaned successfully';
             } else {
                 $result = true;
diff --git a/downloader/Maged/Model/Session.php b/downloader/Maged/Model/Session.php
index dfb85442279001f2c16f6421d2d81a62d29bc1f6..a166dfe5f144259d7b3f0499d0fda0459266c8b6 100644
--- a/downloader/Maged/Model/Session.php
+++ b/downloader/Maged/Model/Session.php
@@ -48,8 +48,6 @@ class Maged_Model_Session extends Maged_Model
     public function start()
     {
         if (class_exists('Mage') && Mage::isInstalled()) {
-            // initialize Magento Config
-            Mage::app();
             $this->_session = Mage::getSingleton('Mage_Backend_Model_Auth_Session');
         } else {
             session_start();
diff --git a/index.php b/index.php
index ced5562a0566b075a748943854d79092130ee7f3..22e76f708b7019a4dafff733b409cc9fa7325de8 100644
--- a/index.php
+++ b/index.php
@@ -2,6 +2,15 @@
 /**
  * Application entry point
  *
+ * Example - run a particular store or website:
+ * --------------------------------------------
+ * $params = $_SERVER;
+ * $params['MAGE_RUN_CODE'] = 'website2';
+ * $params['MAGE_RUN_TYPE'] = 'website';
+ * ...
+ * new Mage_Core_Model_EntryPoint_Http(BP, $params)
+ * --------------------------------------------
+ *
  * Magento
  *
  * NOTICE OF LICENSE
@@ -20,20 +29,9 @@
  * versions in the future. If you wish to customize Magento for your
  * needs please refer to http://www.magentocommerce.com for more information.
  *
- * @category   Mage
- * @package    Mage
  * @copyright  Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
-
 require __DIR__ . '/app/bootstrap.php';
-Mage::run($_SERVER);
-
-/**
- * Example - run a particular store or website:
- *
- * $params = $_SERVER;
- * $params['MAGE_RUN_CODE'] = 'website2';
- * $params['MAGE_RUN_TYPE'] = 'website';
- * Mage::run($params)
- */
+$entryPoint = new Mage_Core_Model_EntryPoint_Http(BP, $_SERVER);
+$entryPoint->processRequest();
diff --git a/lib/Magento/Http/Handler/Composite.php b/lib/Magento/Http/Handler/Composite.php
new file mode 100644
index 0000000000000000000000000000000000000000..d92300e86f86114a977fac94e94bf3e69baf6452
--- /dev/null
+++ b/lib/Magento/Http/Handler/Composite.php
@@ -0,0 +1,86 @@
+<?php
+/**
+ * Composite http request handler. Used to apply multiple request handlers
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Magento_Http_Handler_Composite implements Magento_Http_HandlerInterface
+{
+    /**
+     * Leaf request handlers
+     *
+     * @var Magento_Http_HandlerInterface[]
+     */
+    protected $_children;
+
+    /**
+     * Handler factory
+     *
+     * @var Magento_Http_HandlerFactory
+     */
+    protected $_handlerFactory;
+
+    /**
+     * @param Magento_Http_HandlerFactory $factory
+     * @param array $handlers
+     */
+    public function __construct(Magento_Http_HandlerFactory $factory, array $handlers)
+    {
+        usort($handlers, array($this, '_cmp'));
+        $this->_children = $handlers;
+        $this->_handlerFactory = $factory;
+    }
+
+    /**
+     * Sort handlers
+     *
+     * @param $handlerA
+     * @param $handlerB
+     * @return int
+     */
+    protected function _cmp($handlerA, $handlerB)
+    {
+        $sortOrderA = intval($handlerA['sortOrder']);
+        $sortOrderB = intval($handlerB['sortOrder']);
+        if ($sortOrderA == $sortOrderB) {
+            return 0;
+        }
+        return ($sortOrderA < $sortOrderB) ? -1 : 1;
+    }
+
+    /**
+     * Handle http request
+     *
+     * @param Zend_Controller_Request_Http $request
+     * @param Zend_Controller_Response_Http $response
+     */
+    public function handle(Zend_Controller_Request_Http $request, Zend_Controller_Response_Http $response)
+    {
+        foreach ($this->_children as $handlerConfig) {
+            $this->_handlerFactory->create($handlerConfig['class'])->handle($request, $response);
+            if ($request->isDispatched()) {
+                break;
+            }
+        }
+    }
+}
+
diff --git a/lib/Magento/Http/HandlerFactory.php b/lib/Magento/Http/HandlerFactory.php
new file mode 100644
index 0000000000000000000000000000000000000000..c572206111f42d9d24b1d456c04a9a59c91287a3
--- /dev/null
+++ b/lib/Magento/Http/HandlerFactory.php
@@ -0,0 +1,54 @@
+<?php
+/**
+ * Request Handler factory
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */ 
+class Magento_Http_HandlerFactory
+{
+
+    /**
+     * Application object manager
+     *
+     * @var Magento_ObjectManager
+     */
+    protected $_objectManager;
+
+    /**
+     * @param Magento_ObjectManager $objectManager
+     */
+    public function __construct(Magento_ObjectManager $objectManager)
+    {
+        $this->_objectManager = $objectManager;
+    }
+
+    /**
+     * Create new http request handler
+     *
+     * @param string $name
+     * @return Magento_Http_HandlerInterface
+     */
+    public function create($name)
+    {
+        return $this->_objectManager->create($name);
+    }
+}
diff --git a/lib/Magento/Http/HandlerInterface.php b/lib/Magento/Http/HandlerInterface.php
new file mode 100644
index 0000000000000000000000000000000000000000..eac07a683de411a3051e020705693dc2bee157a8
--- /dev/null
+++ b/lib/Magento/Http/HandlerInterface.php
@@ -0,0 +1,35 @@
+<?php
+/**
+ * Http request handler interface
+ *
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+interface Magento_Http_HandlerInterface
+{
+    /**
+     * Handle http request
+     *
+     * @param Zend_Controller_Request_Http $request
+     * @param Zend_Controller_Response_Http $response
+     */
+    public function handle(Zend_Controller_Request_Http $request, Zend_Controller_Response_Http $response);
+}
diff --git a/lib/Magento/ObjectManager/Configuration.php b/lib/Magento/ObjectManager/Configuration.php
new file mode 100644
index 0000000000000000000000000000000000000000..d9867c8ee91898e653a898ea1ec75399f53136eb
--- /dev/null
+++ b/lib/Magento/ObjectManager/Configuration.php
@@ -0,0 +1,35 @@
+<?php
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Open Software License (OSL 3.0)
+ * that is bundled with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/osl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    Magento
+ * @package     Magento_ObjectManager
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+interface Magento_ObjectManager_Configuration
+{
+    /**
+     * Configure di instance
+     *
+     * @param Magento_ObjectManager $objectManager
+     */
+    public function configure(Magento_ObjectManager $objectManager);
+}
diff --git a/lib/Magento/ObjectManager/Zend.php b/lib/Magento/ObjectManager/Zend.php
index 130fc7bda041077df53433891f0a8f06f0ed3222..af6b896c4715feddf0627b1d3386a6713a5972ac 100644
--- a/lib/Magento/ObjectManager/Zend.php
+++ b/lib/Magento/ObjectManager/Zend.php
@@ -50,12 +50,8 @@ class Magento_ObjectManager_Zend implements Magento_ObjectManager
         Magento_Di $diInstance = null,
         Magento_Di_InstanceManager $instanceManager = null
     ) {
-        Magento_Profiler::start('di');
-
         $this->_di = $diInstance ?: new Magento_Di_Zend(null, $instanceManager, null, $definitionsFile);
         $this->_di->instanceManager()->addSharedInstance($this, 'Magento_ObjectManager');
-
-        Magento_Profiler::stop('di');
     }
 
     /**
diff --git a/lib/Varien/Data/Collection.php b/lib/Varien/Data/Collection.php
index 68ce10f37f957cc64cf58d1c06f4203ef4d92eb9..832f6240b1d616bee40331e8e75cdeea53c39fcb 100644
--- a/lib/Varien/Data/Collection.php
+++ b/lib/Varien/Data/Collection.php
@@ -552,7 +552,6 @@ class Varien_Data_Collection implements IteratorAggregate, Countable
      */
     function setItemObjectClass($className)
     {
-        $className = Mage::getConfig()->getModelClassName($className);
         /**
          * is_subclass_of($className, 'Varien_Object') - Segmentation fault in php 5.2.3
          */
diff --git a/lib/Varien/Data/Form/Element/Date.php b/lib/Varien/Data/Form/Element/Date.php
index da00b74644fd993b64644c631afd2aecf7991663..757727abc0d3aca542f7fbf57633560cc014b50a 100644
--- a/lib/Varien/Data/Form/Element/Date.php
+++ b/lib/Varien/Data/Form/Element/Date.php
@@ -155,7 +155,7 @@ class Varien_Data_Form_Element_Date extends Varien_Data_Form_Element_Abstract
         $this->addClass('input-text');
 
         $html = sprintf(
-            '<input name="%s" id="%s" value="%s" %s style="width:110px !important;" />',
+            '<input name="%s" id="%s" value="%s" %s />',
             $this->getName(),
             $this->getHtmlId(),
             $this->_escape($this->getValue()),
diff --git a/lib/Varien/Data/Form/Element/Label.php b/lib/Varien/Data/Form/Element/Label.php
index a3805be73e9a7e07ae7aeeece06ea28869528b4f..e3b13be73ecdc5dc9202c166ba94baf216e6ea69 100644
--- a/lib/Varien/Data/Form/Element/Label.php
+++ b/lib/Varien/Data/Form/Element/Label.php
@@ -51,9 +51,9 @@ class Varien_Data_Form_Element_Label extends Varien_Data_Form_Element_Abstract
      */
     public function getElementHtml()
     {
-        $html = $this->getBold() ? '<strong class="control-value">' : '<span class="control-value">';
+        $html = $this->getBold() ? '<div class="control-value special">' : '<div class="control-value">';
         $html.= $this->getEscapedValue();
-        $html.= $this->getBold() ? '</strong>' : '</span>';
+        $html.= $this->getBold() ? '</div>' : '</div>';
         $html.= $this->getAfterElementHtml();
         return $html;
     }
diff --git a/lib/Varien/Data/Form/Element/Note.php b/lib/Varien/Data/Form/Element/Note.php
index 095398c2b6d836b36492a2746188b80e81df110c..31f3e87bf2304a1ff509e71dda92679ed1183f4a 100644
--- a/lib/Varien/Data/Form/Element/Note.php
+++ b/lib/Varien/Data/Form/Element/Note.php
@@ -42,7 +42,7 @@ class Varien_Data_Form_Element_Note extends Varien_Data_Form_Element_Abstract
 
     public function getElementHtml()
     {
-        $html = '<span id="' . $this->getHtmlId() . '" class="control-value">' . $this->getText() . '</span>';
+        $html = '<div id="' . $this->getHtmlId() . '" class="control-value">' . $this->getText() . '</div>';
         $html.= $this->getAfterElementHtml();
         return $html;
     }
diff --git a/pub/cron.php b/pub/cron.php
index 104b7fdd88ea681d8615f099a8266d34cf7ca92c..31ee3d466da999499dccee301d834c1cd6aea974 100644
--- a/pub/cron.php
+++ b/pub/cron.php
@@ -32,11 +32,9 @@ Mage::register('custom_entry_point', true);
 umask(0);
 
 try {
-    Mage::app('admin')->setUseSessionInUrl(false);
-    Mage::app()->requireInstalledInstance();
-    Mage::getConfig()->init()->loadEventObservers('crontab');
-    Mage::app()->addEventArea('crontab');
-    Mage::dispatchEvent('default');
+    $params = array(Mage::PARAM_RUN_CODE => 'admin');
+    $entryPoint = new Mage_Core_Model_EntryPoint_Cron(BP, $params);
+    $entryPoint->processRequest();
 } catch (Exception $e) {
     Mage::printException($e);
 }
diff --git a/pub/get.php b/pub/get.php
index 050d2eb26d22d0cfe76ed1aaa8dedd833ac8c641..2c52e4067c953adba8fed13fc2c86a8e9bc78947 100644
--- a/pub/get.php
+++ b/pub/get.php
@@ -56,17 +56,17 @@ if ($mediaDirectory) {
     checkResource($relativeFilename, $allowedResources);
     sendFile($filePath);
 }
-
-if (empty($mediaDirectory)) {
-    Mage::init($_SERVER);
-} else {
-    $params = array_merge(
-        $_SERVER,
-        array(Mage_Core_Model_Cache::APP_INIT_PARAM => array('disallow_save' => true))
-    );
-    Mage::init($params, array('Mage_Core'));
+try {
+    $entryPoint = new Mage_Core_Model_EntryPoint_Media(dirname(__DIR__), $mediaDirectory, $_SERVER);
+    $entryPoint->processRequest();
+    if (!Mage::isInstalled()) {
+        sendNotFoundPage();
+    }
+} catch (Mage_Core_Model_Store_Exception $e) {
+    sendNotFoundPage();
+} catch (Exception $e) {
+    Mage::printException($e);
 }
-Mage::app()->requireInstalledInstance();
 
 if (!$mediaDirectory) {
     $config = Mage_Core_Model_File_Storage::getScriptConfig();
diff --git a/pub/index.php b/pub/index.php
index 15c5b4a46740faadbace24b8417317ef92fa6f1f..79a4ffa2d1289543b72013fc034b3af234774ef4 100644
--- a/pub/index.php
+++ b/pub/index.php
@@ -20,13 +20,11 @@
  * versions in the future. If you wish to customize Magento for your
  * needs please refer to http://www.magentocommerce.com for more information.
  *
- * @category   Mage
- * @package    Mage
  * @copyright  Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
  * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
-
 require __DIR__ . '/../app/bootstrap.php';
 $params = $_SERVER;
-$params[Mage_Core_Model_App::INIT_OPTION_URIS][Mage_Core_Model_Dir::PUB] = '';
-Mage::run($params);
+$params[Mage::PARAM_APP_URIS][Mage_Core_Model_Dir::PUB] = '';
+$entryPoint = new Mage_Core_Model_EntryPoint_Http(BP, $params);
+$entryPoint->processRequest();
diff --git a/pub/lib/head.load.min.js b/pub/lib/head.load.min.js
index 1d0be6f673dee560892f23173adf09080a7ffff1..2478478f023ca3383a992813aaf0e101e4deab6b 100644
--- a/pub/lib/head.load.min.js
+++ b/pub/lib/head.load.min.js
@@ -1 +1 @@
-(function(e,t){"use strict";function y(e){if(e._done)return;e(),e._done=1}function b(e){var t=e.split("/"),n=t[t.length-1],r=n.indexOf("?");return r!=-1?n.substring(0,r):n}function w(e){var t;if(typeof e=="object")for(var n in e)e[n]&&(t={name:n,url:e[n]});else t={name:b(e),url:e};var r=l[t.name];return r&&r.url===t.url?r:(l[t.name]=t,t)}function E(e,t){if(!e)return;typeof e=="object"&&(e=[].slice.call(e));for(var n=0;n<e.length;n++)t.call(e,e[n],n)}function S(e){return Object.prototype.toString.call(e)=="[object Function]"}function x(e){e=e||l;var t;for(var n in e){if(e.hasOwnProperty(n)&&e[n].state!=g)return!1;t=!0}return t}function T(e){e.state=d,E(e.onpreload,function(e){e.call()})}function N(e,n){e.state===t&&(e.state=v,e.onpreload=[],k({src:e.url,type:"cache"},function(){T(e)}))}function C(e,t){if(e.state==g)return t&&t();if(e.state==m)return p.ready(e.name,t);if(e.state==v)return e.onpreload.push(function(){C(e,t)});e.state=m,k(e.url,function(){e.state=g,t&&t(),E(f[e.name],function(e){y(e)}),x()&&o&&E(f.ALL,function(e){y(e)})})}function k(e,t){var r=n.createElement("script");r.type="text/"+(e.type||"javascript"),r.src=e.src||e,r.async=!1,r.onreadystatechange=r.onload=function(){var e=r.readyState;!t.done&&(!e||/loaded|complete/.test(e))&&(t.done=!0,t())},(n.body||i).appendChild(r)}function L(){o||(o=!0,E(u,function(e){y(e)}))}var n=e.document,r=e.navigator,i=n.documentElement,s,o,u=[],a=[],f={},l={},c=n.createElement("script").async===!0||"MozAppearance"in n.documentElement.style||e.opera,h=e.head_conf&&e.head_conf.head||"head",p=e[h]=e[h]||function(){p.ready.apply(null,arguments)},d=1,v=2,m=3,g=4;c?p.js=function(){var e=arguments,t=e[e.length-1],n={};return S(t)||(t=null),E(e,function(r,i){r!=t&&(r=w(r),n[r.name]=r,C(r,t&&i==e.length-2?function(){x(n)&&y(t)}:null))}),p}:p.js=function(){var e=arguments,t=[].slice.call(e,1),n=t[0];return s?(n?(E(t,function(e){S(e)||N(w(e))}),C(w(e[0]),S(n)?n:function(){p.js.apply(null,t)})):C(w(e[0])),p):(a.push(function(){p.js.apply(null,e)}),p)},p.ready=function(e,t){if(e==n)return o?y(t):u.push(t),p;S(e)&&(t=e,e="ALL");if(typeof e!="string"||!S(t))return p;var r=l[e];if(r&&r.state==g||e=="ALL"&&x()&&o)return y(t),p;var i=f[e];return i?i.push(t):i=f[e]=[t],p},p.ready(n,function(){x()&&E(f.ALL,function(e){y(e)}),p.feature&&p.feature("domloaded",!0)});if(e.addEventListener)n.addEventListener("DOMContentLoaded",L,!1),e.addEventListener("load",L,!1);else if(e.attachEvent){n.attachEvent("onreadystatechange",function(){n.readyState==="complete"&&L()});var A=1;try{A=e.frameElement}catch(O){}!A&&i.doScroll&&function(){try{i.doScroll("left"),L()}catch(e){setTimeout(arguments.callee,1);return}}(),e.attachEvent("onload",L)}!n.readyState&&n.addEventListener&&(n.readyState="loading",n.addEventListener("DOMContentLoaded",handler=function(){n.removeEventListener("DOMContentLoaded",handler,!1),n.readyState="complete"},!1)),setTimeout(function(){s=!0,E(a,function(e){e()})},300)})(window)
\ No newline at end of file
+(function(e,t){"use strict";function y(e){if(e._done)return;e(),e._done=1}function b(e){var t=e.split("/"),n=t[t.length-1],r=n.indexOf("?");return r!=-1?n.substring(0,r):n}function w(e){var t;if(typeof e=="object")for(var n in e)e[n]&&(t={name:n,url:e[n]});else t={name:b(e),url:e};var r=l[t.name];return r&&r.url===t.url?r:(l[t.name]=t,t)}function E(e,t){if(!e)return;typeof e=="object"&&(e=[].slice.call(e));for(var n=0;n<e.length;n++)t.call(e,e[n],n)}function S(e){return Object.prototype.toString.call(e)=="[object Function]"}function x(e){e=e||l;var t;for(var n in e){if(e.hasOwnProperty(n)&&e[n].state!=g)return!1;t=!0}return t}function T(e){e.state=d,E(e.onpreload,function(e){e.call()})}function N(e,n){e.state===t&&(e.state=v,e.onpreload=[],k({src:e.url,type:"cache"},function(){T(e)}))}function C(e,t){if(e.state==g)return t&&t();if(e.state==m)return p.ready(e.name,t);if(e.state==v)return e.onpreload.push(function(){C(e,t)});e.state=m,k(e.url,function(){e.state=g,t&&t(),E(f[e.name],function(e){y(e)}),x()&&o&&E(f.ALL,function(e){y(e)})})}function k(e,t){var r=n.createElement("script");r.type="text/"+(e.type||"javascript"),r.src=e.src||e,r.async=!1,r.onreadystatechange=r.onload=function(){var e=r.readyState;!t.done&&(!e||/loaded|complete/.test(e))&&(t.done=!0,t())},(n.body||i).appendChild(r)}function L(){o||(o=!0,E(u,function(e){y(e)}))}var n=e.document,r=e.navigator,i=n.documentElement,s,o,u=[],a=[],f={},l={},c=n.createElement("script").async===!0||"MozAppearance"in n.documentElement.style||e.opera,h=e.head_conf&&e.head_conf.head||"head",p=e[h]=e[h]||function(){p.ready.apply(null,arguments)},d=1,v=2,m=3,g=4;c?p.js=function(){var e=arguments,t=e[e.length-1],n={};return S(t)||(t=null),E(e,function(r,i){r!=t&&(r=w(r),n[r.name]=r,C(r,t&&i==e.length-2?function(){x(n)&&y(t)}:null))}),p}:p.js=function(){var e=arguments,t=[].slice.call(e,1),n=t[0];return s?(n?(E(t,function(e){S(e)||N(w(e))}),C(w(e[0]),S(n)?n:function(){p.js.apply(null,t)})):C(w(e[0])),p):(a.push(function(){p.js.apply(null,e)}),p)},p.ready=function(e,t){if(e==n)return o?y(t):u.push(t),p;S(e)&&(t=e,e="ALL");if(typeof e!="string"||!S(t))return p;var r=l[e];if(r&&r.state==g||e=="ALL"&&x()&&o)return y(t),p;var i=f[e];return i?i.push(t):i=f[e]=[t],p},p.ready(n,function(){x()&&E(f.ALL,function(e){y(e)}),p.feature&&p.feature("domloaded",!0)});if(e.addEventListener)n.addEventListener("DOMContentLoaded",L,!1),e.addEventListener("load",L,!1);else if(e.attachEvent){n.attachEvent("onreadystatechange",function(){n.readyState==="complete"&&L()});var A=1;try{A=e.frameElement}catch(O){}!A&&i.doScroll&&function(){try{i.doScroll("left"),L()}catch(e){setTimeout(arguments.callee,1);return}}(),e.attachEvent("onload",L)}!n.readyState&&n.addEventListener&&(n.readyState="loading",n.addEventListener("DOMContentLoaded",handler=function(){n.removeEventListener("DOMContentLoaded",handler,!1),n.readyState="complete"},!1)),setTimeout(function(){s=!0,E(a,function(e){e()})},300)})(window);
\ No newline at end of file
diff --git a/pub/lib/jquery/jquery-ui.custom.min.js b/pub/lib/jquery/jquery-ui.custom.min.js
deleted file mode 100644
index f97100ba3f7b3af11c0fbf56945605f7db483831..0000000000000000000000000000000000000000
--- a/pub/lib/jquery/jquery-ui.custom.min.js
+++ /dev/null
@@ -1,6 +0,0 @@
-/*! jQuery UI - v1.9.2 - 2013-01-08
-* http://jqueryui.com
-* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.sortable.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.menu.js, jquery.ui.slider.js, jquery.ui.tabs.js, jquery.ui.effect.js
-* Copyright (c) 2013 jQuery Foundation and other contributors Licensed MIT */
-
-(function(e,t){function i(t,n){var r,i,o,u=t.nodeName.toLowerCase();return"area"===u?(r=t.parentNode,i=r.name,!t.href||!i||r.nodeName.toLowerCase()!=="map"?!1:(o=e("img[usemap=#"+i+"]")[0],!!o&&s(o))):(/input|select|textarea|button|object/.test(u)?!t.disabled:"a"===u?t.href||n:n)&&s(t)}function s(t){return e.expr.filters.visible(t)&&!e(t).parents().andSelf().filter(function(){return e.css(this,"visibility")==="hidden"}).length}var n=0,r=/^ui-id-\d+$/;e.ui=e.ui||{};if(e.ui.version)return;e.extend(e.ui,{version:"1.9.2",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({_focus:e.fn.focus,focus:function(t,n){return typeof t=="number"?this.each(function(){var r=this;setTimeout(function(){e(r).focus(),n&&n.call(r)},t)}):this._focus.apply(this,arguments)},scrollParent:function(){var t;return e.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?t=this.parents().filter(function(){return/(relative|absolute|fixed)/.test(e.css(this,"position"))&&/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0):t=this.parents().filter(function(){return/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!t.length?e(document):t},zIndex:function(n){if(n!==t)return this.css("zIndex",n);if(this.length){var r=e(this[0]),i,s;while(r.length&&r[0]!==document){i=r.css("position");if(i==="absolute"||i==="relative"||i==="fixed"){s=parseInt(r.css("zIndex"),10);if(!isNaN(s)&&s!==0)return s}r=r.parent()}}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++n)})},removeUniqueId:function(){return this.each(function(){r.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(n){return!!e.data(n,t)}}):function(t,n,r){return!!e.data(t,r[3])},focusable:function(t){return i(t,!isNaN(e.attr(t,"tabindex")))},tabbable:function(t){var n=e.attr(t,"tabindex"),r=isNaN(n);return(r||n>=0)&&i(t,!r)}}),e(function(){var t=document.body,n=t.appendChild(n=document.createElement("div"));n.offsetHeight,e.extend(n.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0}),e.support.minHeight=n.offsetHeight===100,e.support.selectstart="onselectstart"in n,t.removeChild(n).style.display="none"}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(n,r){function u(t,n,r,s){return e.each(i,function(){n-=parseFloat(e.css(t,"padding"+this))||0,r&&(n-=parseFloat(e.css(t,"border"+this+"Width"))||0),s&&(n-=parseFloat(e.css(t,"margin"+this))||0)}),n}var i=r==="Width"?["Left","Right"]:["Top","Bottom"],s=r.toLowerCase(),o={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+r]=function(n){return n===t?o["inner"+r].call(this):this.each(function(){e(this).css(s,u(this,n)+"px")})},e.fn["outer"+r]=function(t,n){return typeof t!="number"?o["outer"+r].call(this,t):this.each(function(){e(this).css(s,u(this,t,!0,n)+"px")})}}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(n){return arguments.length?t.call(this,e.camelCase(n)):t.call(this)}}(e.fn.removeData)),function(){var t=/msie ([\w.]+)/.exec(navigator.userAgent.toLowerCase())||[];e.ui.ie=t.length?!0:!1,e.ui.ie6=parseFloat(t[1],10)===6}(),e.fn.extend({disableSelection:function(){return this.bind((e.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),e.extend(e.ui,{plugin:{add:function(t,n,r){var i,s=e.ui[t].prototype;for(i in r)s.plugins[i]=s.plugins[i]||[],s.plugins[i].push([n,r[i]])},call:function(e,t,n){var r,i=e.plugins[t];if(!i||!e.element[0].parentNode||e.element[0].parentNode.nodeType===11)return;for(r=0;r<i.length;r++)e.options[i[r][0]]&&i[r][1].apply(e.element,n)}},contains:e.contains,hasScroll:function(t,n){if(e(t).css("overflow")==="hidden")return!1;var r=n&&n==="left"?"scrollLeft":"scrollTop",i=!1;return t[r]>0?!0:(t[r]=1,i=t[r]>0,t[r]=0,i)},isOverAxis:function(e,t,n){return e>t&&e<t+n},isOver:function(t,n,r,i,s,o){return e.ui.isOverAxis(t,r,s)&&e.ui.isOverAxis(n,i,o)}})})(jQuery);(function(e,t){var n=0,r=Array.prototype.slice,i=e.cleanData;e.cleanData=function(t){for(var n=0,r;(r=t[n])!=null;n++)try{e(r).triggerHandler("remove")}catch(s){}i(t)},e.widget=function(t,n,r){var i,s,o,u,a=t.split(".")[0];t=t.split(".")[1],i=a+"-"+t,r||(r=n,n=e.Widget),e.expr[":"][i.toLowerCase()]=function(t){return!!e.data(t,i)},e[a]=e[a]||{},s=e[a][t],o=e[a][t]=function(e,t){if(!this._createWidget)return new o(e,t);arguments.length&&this._createWidget(e,t)},e.extend(o,s,{version:r.version,_proto:e.extend({},r),_childConstructors:[]}),u=new n,u.options=e.widget.extend({},u.options),e.each(r,function(t,i){e.isFunction(i)&&(r[t]=function(){var e=function(){return n.prototype[t].apply(this,arguments)},r=function(e){return n.prototype[t].apply(this,e)};return function(){var t=this._super,n=this._superApply,s;return this._super=e,this._superApply=r,s=i.apply(this,arguments),this._super=t,this._superApply=n,s}}())}),o.prototype=e.widget.extend(u,{widgetEventPrefix:s?u.widgetEventPrefix:t},r,{constructor:o,namespace:a,widgetName:t,widgetBaseClass:i,widgetFullName:i}),s?(e.each(s._childConstructors,function(t,n){var r=n.prototype;e.widget(r.namespace+"."+r.widgetName,o,n._proto)}),delete s._childConstructors):n._childConstructors.push(o),e.widget.bridge(t,o)},e.widget.extend=function(n){var i=r.call(arguments,1),s=0,o=i.length,u,a;for(;s<o;s++)for(u in i[s])a=i[s][u],i[s].hasOwnProperty(u)&&a!==t&&(e.isPlainObject(a)?n[u]=e.isPlainObject(n[u])?e.widget.extend({},n[u],a):e.widget.extend({},a):n[u]=a);return n},e.widget.bridge=function(n,i){var s=i.prototype.widgetFullName||n;e.fn[n]=function(o){var u=typeof o=="string",a=r.call(arguments,1),f=this;return o=!u&&a.length?e.widget.extend.apply(null,[o].concat(a)):o,u?this.each(function(){var r,i=e.data(this,s);if(!i)return e.error("cannot call methods on "+n+" prior to initialization; "+"attempted to call method '"+o+"'");if(!e.isFunction(i[o])||o.charAt(0)==="_")return e.error("no such method '"+o+"' for "+n+" widget instance");r=i[o].apply(i,a);if(r!==i&&r!==t)return f=r&&r.jquery?f.pushStack(r.get()):r,!1}):this.each(function(){var t=e.data(this,s);t?t.option(o||{})._init():e.data(this,s,new i(o,this))}),f}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(t,r){r=e(r||this.defaultElement||this)[0],this.element=e(r),this.uuid=n++,this.eventNamespace="."+this.widgetName+this.uuid,this.options=e.widget.extend({},this.options,this._getCreateOptions(),t),this.bindings=e(),this.hoverable=e(),this.focusable=e(),r!==this&&(e.data(r,this.widgetName,this),e.data(r,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===r&&this.destroy()}}),this.document=e(r.style?r.ownerDocument:r.document||r),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(n,r){var i=n,s,o,u;if(arguments.length===0)return e.widget.extend({},this.options);if(typeof n=="string"){i={},s=n.split("."),n=s.shift();if(s.length){o=i[n]=e.widget.extend({},this.options[n]);for(u=0;u<s.length-1;u++)o[s[u]]=o[s[u]]||{},o=o[s[u]];n=s.pop();if(r===t)return o[n]===t?null:o[n];o[n]=r}else{if(r===t)return this.options[n]===t?null:this.options[n];i[n]=r}}return this._setOptions(i),this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){return this.options[e]=t,e==="disabled"&&(this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!t).attr("aria-disabled",t),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(t,n,r){var i,s=this;typeof t!="boolean"&&(r=n,n=t,t=!1),r?(n=i=e(n),this.bindings=this.bindings.add(n)):(r=n,n=this.element,i=this.widget()),e.each(r,function(r,o){function u(){if(!t&&(s.options.disabled===!0||e(this).hasClass("ui-state-disabled")))return;return(typeof o=="string"?s[o]:o).apply(s,arguments)}typeof o!="string"&&(u.guid=o.guid=o.guid||u.guid||e.guid++);var a=r.match(/^(\w+)\s*(.*)$/),f=a[1]+s.eventNamespace,l=a[2];l?i.delegate(l,f,u):n.bind(f,u)})},_off:function(e,t){t=(t||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.unbind(t).undelegate(t)},_delay:function(e,t){function n(){return(typeof e=="string"?r[e]:e).apply(r,arguments)}var r=this;return setTimeout(n,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,n,r){var i,s,o=this.options[t];r=r||{},n=e.Event(n),n.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),n.target=this.element[0],s=n.originalEvent;if(s)for(i in s)i in n||(n[i]=s[i]);return this.element.trigger(n,r),!(e.isFunction(o)&&o.apply(this.element[0],[n].concat(r))===!1||n.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,n){e.Widget.prototype["_"+t]=function(r,i,s){typeof i=="string"&&(i={effect:i});var o,u=i?i===!0||typeof i=="number"?n:i.effect||n:t;i=i||{},typeof i=="number"&&(i={duration:i}),o=!e.isEmptyObject(i),i.complete=s,i.delay&&r.delay(i.delay),o&&e.effects&&(e.effects.effect[u]||e.uiBackCompat!==!1&&e.effects[u])?r[t](i):u!==t&&r[u]?r[u](i.duration,i.easing,s):r.queue(function(n){e(this)[t](),s&&s.call(r[0]),n()})}}),e.uiBackCompat!==!1&&(e.Widget.prototype._getCreateOptions=function(){return e.metadata&&e.metadata.get(this.element[0])[this.widgetName]})})(jQuery);(function(e,t){var n=!1;e(document).mouseup(function(e){n=!1}),e.widget("ui.mouse",{version:"1.9.2",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var t=this;this.element.bind("mousedown."+this.widgetName,function(e){return t._mouseDown(e)}).bind("click."+this.widgetName,function(n){if(!0===e.data(n.target,t.widgetName+".preventClickEvent"))return e.removeData(n.target,t.widgetName+".preventClickEvent"),n.stopImmediatePropagation(),!1}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(t){if(n)return;this._mouseStarted&&this._mouseUp(t),this._mouseDownEvent=t;var r=this,i=t.which===1,s=typeof this.options.cancel=="string"&&t.target.nodeName?e(t.target).closest(this.options.cancel).length:!1;if(!i||s||!this._mouseCapture(t))return!0;this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){r.mouseDelayMet=!0},this.options.delay));if(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)){this._mouseStarted=this._mouseStart(t)!==!1;if(!this._mouseStarted)return t.preventDefault(),!0}return!0===e.data(t.target,this.widgetName+".preventClickEvent")&&e.removeData(t.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(e){return r._mouseMove(e)},this._mouseUpDelegate=function(e){return r._mouseUp(e)},e(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),t.preventDefault(),n=!0,!0},_mouseMove:function(t){return!e.ui.ie||document.documentMode>=9||!!t.button?this._mouseStarted?(this._mouseDrag(t),t.preventDefault()):(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,t)!==!1,this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)),!this._mouseStarted):this._mouseUp(t)},_mouseUp:function(t){return e(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,t.target===this._mouseDownEvent.target&&e.data(t.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(t)),!1},_mouseDistanceMet:function(e){return Math.max(Math.abs(this._mouseDownEvent.pageX-e.pageX),Math.abs(this._mouseDownEvent.pageY-e.pageY))>=this.options.distance},_mouseDelayMet:function(e){return this.mouseDelayMet},_mouseStart:function(e){},_mouseDrag:function(e){},_mouseStop:function(e){},_mouseCapture:function(e){return!0}})})(jQuery);(function(e,t){function h(e,t,n){return[parseInt(e[0],10)*(l.test(e[0])?t/100:1),parseInt(e[1],10)*(l.test(e[1])?n/100:1)]}function p(t,n){return parseInt(e.css(t,n),10)||0}e.ui=e.ui||{};var n,r=Math.max,i=Math.abs,s=Math.round,o=/left|center|right/,u=/top|center|bottom/,a=/[\+\-]\d+%?/,f=/^\w+/,l=/%$/,c=e.fn.position;e.position={scrollbarWidth:function(){if(n!==t)return n;var r,i,s=e("<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),o=s.children()[0];return e("body").append(s),r=o.offsetWidth,s.css("overflow","scroll"),i=o.offsetWidth,r===i&&(i=s[0].clientWidth),s.remove(),n=r-i},getScrollInfo:function(t){var n=t.isWindow?"":t.element.css("overflow-x"),r=t.isWindow?"":t.element.css("overflow-y"),i=n==="scroll"||n==="auto"&&t.width<t.element[0].scrollWidth,s=r==="scroll"||r==="auto"&&t.height<t.element[0].scrollHeight;return{width:i?e.position.scrollbarWidth():0,height:s?e.position.scrollbarWidth():0}},getWithinInfo:function(t){var n=e(t||window),r=e.isWindow(n[0]);return{element:n,isWindow:r,offset:n.offset()||{left:0,top:0},scrollLeft:n.scrollLeft(),scrollTop:n.scrollTop(),width:r?n.width():n.outerWidth(),height:r?n.height():n.outerHeight()}}},e.fn.position=function(t){if(!t||!t.of)return c.apply(this,arguments);t=e.extend({},t);var n,l,d,v,m,g=e(t.of),y=e.position.getWithinInfo(t.within),b=e.position.getScrollInfo(y),w=g[0],E=(t.collision||"flip").split(" "),S={};return w.nodeType===9?(l=g.width(),d=g.height(),v={top:0,left:0}):e.isWindow(w)?(l=g.width(),d=g.height(),v={top:g.scrollTop(),left:g.scrollLeft()}):w.preventDefault?(t.at="left top",l=d=0,v={top:w.pageY,left:w.pageX}):(l=g.outerWidth(),d=g.outerHeight(),v=g.offset()),m=e.extend({},v),e.each(["my","at"],function(){var e=(t[this]||"").split(" "),n,r;e.length===1&&(e=o.test(e[0])?e.concat(["center"]):u.test(e[0])?["center"].concat(e):["center","center"]),e[0]=o.test(e[0])?e[0]:"center",e[1]=u.test(e[1])?e[1]:"center",n=a.exec(e[0]),r=a.exec(e[1]),S[this]=[n?n[0]:0,r?r[0]:0],t[this]=[f.exec(e[0])[0],f.exec(e[1])[0]]}),E.length===1&&(E[1]=E[0]),t.at[0]==="right"?m.left+=l:t.at[0]==="center"&&(m.left+=l/2),t.at[1]==="bottom"?m.top+=d:t.at[1]==="center"&&(m.top+=d/2),n=h(S.at,l,d),m.left+=n[0],m.top+=n[1],this.each(function(){var o,u,a=e(this),f=a.outerWidth(),c=a.outerHeight(),w=p(this,"marginLeft"),x=p(this,"marginTop"),T=f+w+p(this,"marginRight")+b.width,N=c+x+p(this,"marginBottom")+b.height,C=e.extend({},m),k=h(S.my,a.outerWidth(),a.outerHeight());t.my[0]==="right"?C.left-=f:t.my[0]==="center"&&(C.left-=f/2),t.my[1]==="bottom"?C.top-=c:t.my[1]==="center"&&(C.top-=c/2),C.left+=k[0],C.top+=k[1],e.support.offsetFractions||(C.left=s(C.left),C.top=s(C.top)),o={marginLeft:w,marginTop:x},e.each(["left","top"],function(r,i){e.ui.position[E[r]]&&e.ui.position[E[r]][i](C,{targetWidth:l,targetHeight:d,elemWidth:f,elemHeight:c,collisionPosition:o,collisionWidth:T,collisionHeight:N,offset:[n[0]+k[0],n[1]+k[1]],my:t.my,at:t.at,within:y,elem:a})}),e.fn.bgiframe&&a.bgiframe(),t.using&&(u=function(e){var n=v.left-C.left,s=n+l-f,o=v.top-C.top,u=o+d-c,h={target:{element:g,left:v.left,top:v.top,width:l,height:d},element:{element:a,left:C.left,top:C.top,width:f,height:c},horizontal:s<0?"left":n>0?"right":"center",vertical:u<0?"top":o>0?"bottom":"middle"};l<f&&i(n+s)<l&&(h.horizontal="center"),d<c&&i(o+u)<d&&(h.vertical="middle"),r(i(n),i(s))>r(i(o),i(u))?h.important="horizontal":h.important="vertical",t.using.call(this,e,h)}),a.offset(e.extend(C,{using:u}))})},e.ui.position={fit:{left:function(e,t){var n=t.within,i=n.isWindow?n.scrollLeft:n.offset.left,s=n.width,o=e.left-t.collisionPosition.marginLeft,u=i-o,a=o+t.collisionWidth-s-i,f;t.collisionWidth>s?u>0&&a<=0?(f=e.left+u+t.collisionWidth-s-i,e.left+=u-f):a>0&&u<=0?e.left=i:u>a?e.left=i+s-t.collisionWidth:e.left=i:u>0?e.left+=u:a>0?e.left-=a:e.left=r(e.left-o,e.left)},top:function(e,t){var n=t.within,i=n.isWindow?n.scrollTop:n.offset.top,s=t.within.height,o=e.top-t.collisionPosition.marginTop,u=i-o,a=o+t.collisionHeight-s-i,f;t.collisionHeight>s?u>0&&a<=0?(f=e.top+u+t.collisionHeight-s-i,e.top+=u-f):a>0&&u<=0?e.top=i:u>a?e.top=i+s-t.collisionHeight:e.top=i:u>0?e.top+=u:a>0?e.top-=a:e.top=r(e.top-o,e.top)}},flip:{left:function(e,t){var n=t.within,r=n.offset.left+n.scrollLeft,s=n.width,o=n.isWindow?n.scrollLeft:n.offset.left,u=e.left-t.collisionPosition.marginLeft,a=u-o,f=u+t.collisionWidth-s-o,l=t.my[0]==="left"?-t.elemWidth:t.my[0]==="right"?t.elemWidth:0,c=t.at[0]==="left"?t.targetWidth:t.at[0]==="right"?-t.targetWidth:0,h=-2*t.offset[0],p,d;if(a<0){p=e.left+l+c+h+t.collisionWidth-s-r;if(p<0||p<i(a))e.left+=l+c+h}else if(f>0){d=e.left-t.collisionPosition.marginLeft+l+c+h-o;if(d>0||i(d)<f)e.left+=l+c+h}},top:function(e,t){var n=t.within,r=n.offset.top+n.scrollTop,s=n.height,o=n.isWindow?n.scrollTop:n.offset.top,u=e.top-t.collisionPosition.marginTop,a=u-o,f=u+t.collisionHeight-s-o,l=t.my[1]==="top",c=l?-t.elemHeight:t.my[1]==="bottom"?t.elemHeight:0,h=t.at[1]==="top"?t.targetHeight:t.at[1]==="bottom"?-t.targetHeight:0,p=-2*t.offset[1],d,v;a<0?(v=e.top+c+h+p+t.collisionHeight-s-r,e.top+c+h+p>a&&(v<0||v<i(a))&&(e.top+=c+h+p)):f>0&&(d=e.top-t.collisionPosition.marginTop+c+h+p-o,e.top+c+h+p>f&&(d>0||i(d)<f)&&(e.top+=c+h+p))}},flipfit:{left:function(){e.ui.position.flip.left.apply(this,arguments),e.ui.position.fit.left.apply(this,arguments)},top:function(){e.ui.position.flip.top.apply(this,arguments),e.ui.position.fit.top.apply(this,arguments)}}},function(){var t,n,r,i,s,o=document.getElementsByTagName("body")[0],u=document.createElement("div");t=document.createElement(o?"div":"body"),r={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},o&&e.extend(r,{position:"absolute",left:"-1000px",top:"-1000px"});for(s in r)t.style[s]=r[s];t.appendChild(u),n=o||document.documentElement,n.insertBefore(t,n.firstChild),u.style.cssText="position: absolute; left: 10.7432222px;",i=e(u).offset().left,e.support.offsetFractions=i>10&&i<11,t.innerHTML="",n.removeChild(t)}(),e.uiBackCompat!==!1&&function(e){var n=e.fn.position;e.fn.position=function(r){if(!r||!r.offset)return n.call(this,r);var i=r.offset.split(" "),s=r.at.split(" ");return i.length===1&&(i[1]=i[0]),/^\d/.test(i[0])&&(i[0]="+"+i[0]),/^\d/.test(i[1])&&(i[1]="+"+i[1]),s.length===1&&(/left|center|right/.test(s[0])?s[1]="center":(s[1]=s[0],s[0]="center")),n.call(this,e.extend(r,{at:s[0]+i[0]+" "+s[1]+i[1],offset:t}))}}(jQuery)})(jQuery);(function(e,t){e.widget("ui.draggable",e.ui.mouse,{version:"1.9.2",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1},_create:function(){this.options.helper=="original"&&!/^(?:r|a|f)/.test(this.element.css("position"))&&(this.element[0].style.position="relative"),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._mouseInit()},_destroy:function(){this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy()},_mouseCapture:function(t){var n=this.options;return this.helper||n.disabled||e(t.target).is(".ui-resizable-handle")?!1:(this.handle=this._getHandle(t),this.handle?(e(n.iframeFix===!0?"iframe":n.iframeFix).each(function(){e('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1e3}).css(e(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(t){var n=this.options;return this.helper=this._createHelper(t),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),e.ui.ddmanager&&(e.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,n.cursorAt&&this._adjustOffsetFromHelper(n.cursorAt),n.containment&&this._setContainment(),this._trigger("start",t)===!1?(this._clear(),!1):(this._cacheHelperProportions(),e.ui.ddmanager&&!n.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this._mouseDrag(t,!0),e.ui.ddmanager&&e.ui.ddmanager.dragStart(this,t),!0)},_mouseDrag:function(t,n){this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute");if(!n){var r=this._uiHash();if(this._trigger("drag",t,r)===!1)return this._mouseUp({}),!1;this.position=r.position}if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";return e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),!1},_mouseStop:function(t){var n=!1;e.ui.ddmanager&&!this.options.dropBehaviour&&(n=e.ui.ddmanager.drop(this,t)),this.dropped&&(n=this.dropped,this.dropped=!1);var r=this.element[0],i=!1;while(r&&(r=r.parentNode))r==document&&(i=!0);if(!i&&this.options.helper==="original")return!1;if(this.options.revert=="invalid"&&!n||this.options.revert=="valid"&&n||this.options.revert===!0||e.isFunction(this.options.revert)&&this.options.revert.call(this.element,n)){var s=this;e(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){s._trigger("stop",t)!==!1&&s._clear()})}else this._trigger("stop",t)!==!1&&this._clear();return!1},_mouseUp:function(t){return e("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),e.ui.ddmanager&&e.ui.ddmanager.dragStop(this,t),e.ui.mouse.prototype._mouseUp.call(this,t)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(t){var n=!this.options.handle||!e(this.options.handle,this.element).length?!0:!1;return e(this.options.handle,this.element).find("*").andSelf().each(function(){this==t.target&&(n=!0)}),n},_createHelper:function(t){var n=this.options,r=e.isFunction(n.helper)?e(n.helper.apply(this.element[0],[t])):n.helper=="clone"?this.element.clone().removeAttr("id"):this.element;return r.parents("body").length||r.appendTo(n.appendTo=="parent"?this.element[0].parentNode:n.appendTo),r[0]!=this.element[0]&&!/(fixed|absolute)/.test(r.css("position"))&&r.css("position","absolute"),r},_adjustOffsetFromHelper:function(t){typeof t=="string"&&(t=t.split(" ")),e.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&e.ui.ie)t={top:0,left:0};return{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var e=this.element.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t=this.options;t.containment=="parent"&&(t.containment=this.helper[0].parentNode);if(t.containment=="document"||t.containment=="window")this.containment=[t.containment=="document"?0:e(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,t.containment=="document"?0:e(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(t.containment=="document"?0:e(window).scrollLeft())+e(t.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(t.containment=="document"?0:e(window).scrollTop())+(e(t.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(t.containment)&&t.containment.constructor!=Array){var n=e(t.containment),r=n[0];if(!r)return;var i=n.offset(),s=e(r).css("overflow")!="hidden";this.containment=[(parseInt(e(r).css("borderLeftWidth"),10)||0)+(parseInt(e(r).css("paddingLeft"),10)||0),(parseInt(e(r).css("borderTopWidth"),10)||0)+(parseInt(e(r).css("paddingTop"),10)||0),(s?Math.max(r.scrollWidth,r.offsetWidth):r.offsetWidth)-(parseInt(e(r).css("borderLeftWidth"),10)||0)-(parseInt(e(r).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(s?Math.max(r.scrollHeight,r.offsetHeight):r.offsetHeight)-(parseInt(e(r).css("borderTopWidth"),10)||0)-(parseInt(e(r).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=n}else t.containment.constructor==Array&&(this.containment=t.containment)},_convertPositionTo:function(t,n){n||(n=this.position);var r=t=="absolute"?1:-1,i=this.options,s=this.cssPosition!="absolute"||this.scrollParent[0]!=document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(s[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():o?0:s.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():o?0:s.scrollLeft())*r}},_generatePosition:function(t){var n=this.options,r=this.cssPosition!="absolute"||this.scrollParent[0]!=document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,i=/(html|body)/i.test(r[0].tagName),s=t.pageX,o=t.pageY;if(this.originalPosition){var u;if(this.containment){if(this.relative_container){var a=this.relative_container.offset();u=[this.containment[0]+a.left,this.containment[1]+a.top,this.containment[2]+a.left,this.containment[3]+a.top]}else u=this.containment;t.pageX-this.offset.click.left<u[0]&&(s=u[0]+this.offset.click.left),t.pageY-this.offset.click.top<u[1]&&(o=u[1]+this.offset.click.top),t.pageX-this.offset.click.left>u[2]&&(s=u[2]+this.offset.click.left),t.pageY-this.offset.click.top>u[3]&&(o=u[3]+this.offset.click.top)}if(n.grid){var f=n.grid[1]?this.originalPageY+Math.round((o-this.originalPageY)/n.grid[1])*n.grid[1]:this.originalPageY;o=u?f-this.offset.click.top<u[1]||f-this.offset.click.top>u[3]?f-this.offset.click.top<u[1]?f+n.grid[1]:f-n.grid[1]:f:f;var l=n.grid[0]?this.originalPageX+Math.round((s-this.originalPageX)/n.grid[0])*n.grid[0]:this.originalPageX;s=u?l-this.offset.click.left<u[0]||l-this.offset.click.left>u[2]?l-this.offset.click.left<u[0]?l+n.grid[0]:l-n.grid[0]:l:l}}return{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():i?0:r.scrollTop()),left:s-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:r.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval&&this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1},_trigger:function(t,n,r){return r=r||this._uiHash(),e.ui.plugin.call(this,t,[n,r]),t=="drag"&&(this.positionAbs=this._convertPositionTo("absolute")),e.Widget.prototype._trigger.call(this,t,n,r)},plugins:{},_uiHash:function(e){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),e.ui.plugin.add("draggable","connectToSortable",{start:function(t,n){var r=e(this).data("draggable"),i=r.options,s=e.extend({},n,{item:r.element});r.sortables=[],e(i.connectToSortable).each(function(){var n=e.data(this,"sortable");n&&!n.options.disabled&&(r.sortables.push({instance:n,shouldRevert:n.options.revert}),n.refreshPositions(),n._trigger("activate",t,s))})},stop:function(t,n){var r=e(this).data("draggable"),i=e.extend({},n,{item:r.element});e.each(r.sortables,function(){this.instance.isOver?(this.instance.isOver=0,r.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=!0),this.instance._mouseStop(t),this.instance.options.helper=this.instance.options._helper,r.options.helper=="original"&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",t,i))})},drag:function(t,n){var r=e(this).data("draggable"),i=this,s=function(t){var n=this.offset.click.top,r=this.offset.click.left,i=this.positionAbs.top,s=this.positionAbs.left,o=t.height,u=t.width,a=t.top,f=t.left;return e.ui.isOver(i+n,s+r,a,f,o,u)};e.each(r.sortables,function(s){var o=!1,u=this;this.instance.positionAbs=r.positionAbs,this.instance.helperProportions=r.helperProportions,this.instance.offset.click=r.offset.click,this.instance._intersectsWith(this.instance.containerCache)&&(o=!0,e.each(r.sortables,function(){return this.instance.positionAbs=r.positionAbs,this.instance.helperProportions=r.helperProportions,this.instance.offset.click=r.offset.click,this!=u&&this.instance._intersectsWith(this.instance.containerCache)&&e.ui.contains(u.instance.element[0],this.instance.element[0])&&(o=!1),o})),o?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=e(i).clone().removeAttr("id").appendTo(this.instance.element).data("sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return n.helper[0]},t.target=this.instance.currentItem[0],this.instance._mouseCapture(t,!0),this.instance._mouseStart(t,!0,!0),this.instance.offset.click.top=r.offset.click.top,this.instance.offset.click.left=r.offset.click.left,this.instance.offset.parent.left-=r.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=r.offset.parent.top-this.instance.offset.parent.top,r._trigger("toSortable",t),r.dropped=this.instance.element,r.currentItem=r.element,this.instance.fromOutside=r),this.instance.currentItem&&this.instance._mouseDrag(t)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",t,this.instance._uiHash(this.instance)),this.instance._mouseStop(t,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),r._trigger("fromSortable",t),r.dropped=!1)})}}),e.ui.plugin.add("draggable","cursor",{start:function(t,n){var r=e("body"),i=e(this).data("draggable").options;r.css("cursor")&&(i._cursor=r.css("cursor")),r.css("cursor",i.cursor)},stop:function(t,n){var r=e(this).data("draggable").options;r._cursor&&e("body").css("cursor",r._cursor)}}),e.ui.plugin.add("draggable","opacity",{start:function(t,n){var r=e(n.helper),i=e(this).data("draggable").options;r.css("opacity")&&(i._opacity=r.css("opacity")),r.css("opacity",i.opacity)},stop:function(t,n){var r=e(this).data("draggable").options;r._opacity&&e(n.helper).css("opacity",r._opacity)}}),e.ui.plugin.add("draggable","scroll",{start:function(t,n){var r=e(this).data("draggable");r.scrollParent[0]!=document&&r.scrollParent[0].tagName!="HTML"&&(r.overflowOffset=r.scrollParent.offset())},drag:function(t,n){var r=e(this).data("draggable"),i=r.options,s=!1;if(r.scrollParent[0]!=document&&r.scrollParent[0].tagName!="HTML"){if(!i.axis||i.axis!="x")r.overflowOffset.top+r.scrollParent[0].offsetHeight-t.pageY<i.scrollSensitivity?r.scrollParent[0].scrollTop=s=r.scrollParent[0].scrollTop+i.scrollSpeed:t.pageY-r.overflowOffset.top<i.scrollSensitivity&&(r.scrollParent[0].scrollTop=s=r.scrollParent[0].scrollTop-i.scrollSpeed);if(!i.axis||i.axis!="y")r.overflowOffset.left+r.scrollParent[0].offsetWidth-t.pageX<i.scrollSensitivity?r.scrollParent[0].scrollLeft=s=r.scrollParent[0].scrollLeft+i.scrollSpeed:t.pageX-r.overflowOffset.left<i.scrollSensitivity&&(r.scrollParent[0].scrollLeft=s=r.scrollParent[0].scrollLeft-i.scrollSpeed)}else{if(!i.axis||i.axis!="x")t.pageY-e(document).scrollTop()<i.scrollSensitivity?s=e(document).scrollTop(e(document).scrollTop()-i.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<i.scrollSensitivity&&(s=e(document).scrollTop(e(document).scrollTop()+i.scrollSpeed));if(!i.axis||i.axis!="y")t.pageX-e(document).scrollLeft()<i.scrollSensitivity?s=e(document).scrollLeft(e(document).scrollLeft()-i.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<i.scrollSensitivity&&(s=e(document).scrollLeft(e(document).scrollLeft()+i.scrollSpeed))}s!==!1&&e.ui.ddmanager&&!i.dropBehaviour&&e.ui.ddmanager.prepareOffsets(r,t)}}),e.ui.plugin.add("draggable","snap",{start:function(t,n){var r=e(this).data("draggable"),i=r.options;r.snapElements=[],e(i.snap.constructor!=String?i.snap.items||":data(draggable)":i.snap).each(function(){var t=e(this),n=t.offset();this!=r.element[0]&&r.snapElements.push({item:this,width:t.outerWidth(),height:t.outerHeight(),top:n.top,left:n.left})})},drag:function(t,n){var r=e(this).data("draggable"),i=r.options,s=i.snapTolerance,o=n.offset.left,u=o+r.helperProportions.width,a=n.offset.top,f=a+r.helperProportions.height;for(var l=r.snapElements.length-1;l>=0;l--){var c=r.snapElements[l].left,h=c+r.snapElements[l].width,p=r.snapElements[l].top,d=p+r.snapElements[l].height;if(!(c-s<o&&o<h+s&&p-s<a&&a<d+s||c-s<o&&o<h+s&&p-s<f&&f<d+s||c-s<u&&u<h+s&&p-s<a&&a<d+s||c-s<u&&u<h+s&&p-s<f&&f<d+s)){r.snapElements[l].snapping&&r.options.snap.release&&r.options.snap.release.call(r.element,t,e.extend(r._uiHash(),{snapItem:r.snapElements[l].item})),r.snapElements[l].snapping=!1;continue}if(i.snapMode!="inner"){var v=Math.abs(p-f)<=s,m=Math.abs(d-a)<=s,g=Math.abs(c-u)<=s,y=Math.abs(h-o)<=s;v&&(n.position.top=r._convertPositionTo("relative",{top:p-r.helperProportions.height,left:0}).top-r.margins.top),m&&(n.position.top=r._convertPositionTo("relative",{top:d,left:0}).top-r.margins.top),g&&(n.position.left=r._convertPositionTo("relative",{top:0,left:c-r.helperProportions.width}).left-r.margins.left),y&&(n.position.left=r._convertPositionTo("relative",{top:0,left:h}).left-r.margins.left)}var b=v||m||g||y;if(i.snapMode!="outer"){var v=Math.abs(p-a)<=s,m=Math.abs(d-f)<=s,g=Math.abs(c-o)<=s,y=Math.abs(h-u)<=s;v&&(n.position.top=r._convertPositionTo("relative",{top:p,left:0}).top-r.margins.top),m&&(n.position.top=r._convertPositionTo("relative",{top:d-r.helperProportions.height,left:0}).top-r.margins.top),g&&(n.position.left=r._convertPositionTo("relative",{top:0,left:c}).left-r.margins.left),y&&(n.position.left=r._convertPositionTo("relative",{top:0,left:h-r.helperProportions.width}).left-r.margins.left)}!r.snapElements[l].snapping&&(v||m||g||y||b)&&r.options.snap.snap&&r.options.snap.snap.call(r.element,t,e.extend(r._uiHash(),{snapItem:r.snapElements[l].item})),r.snapElements[l].snapping=v||m||g||y||b}}}),e.ui.plugin.add("draggable","stack",{start:function(t,n){var r=e(this).data("draggable").options,i=e.makeArray(e(r.stack)).sort(function(t,n){return(parseInt(e(t).css("zIndex"),10)||0)-(parseInt(e(n).css("zIndex"),10)||0)});if(!i.length)return;var s=parseInt(i[0].style.zIndex)||0;e(i).each(function(e){this.style.zIndex=s+e}),this[0].style.zIndex=s+i.length}}),e.ui.plugin.add("draggable","zIndex",{start:function(t,n){var r=e(n.helper),i=e(this).data("draggable").options;r.css("zIndex")&&(i._zIndex=r.css("zIndex")),r.css("zIndex",i.zIndex)},stop:function(t,n){var r=e(this).data("draggable").options;r._zIndex&&e(n.helper).css("zIndex",r._zIndex)}})})(jQuery);(function(e,t){e.widget("ui.droppable",{version:"1.9.2",widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect"},_create:function(){var t=this.options,n=t.accept;this.isover=0,this.isout=1,this.accept=e.isFunction(n)?n:function(e){return e.is(n)},this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight},e.ui.ddmanager.droppables[t.scope]=e.ui.ddmanager.droppables[t.scope]||[],e.ui.ddmanager.droppables[t.scope].push(this),t.addClasses&&this.element.addClass("ui-droppable")},_destroy:function(){var t=e.ui.ddmanager.droppables[this.options.scope];for(var n=0;n<t.length;n++)t[n]==this&&t.splice(n,1);this.element.removeClass("ui-droppable ui-droppable-disabled")},_setOption:function(t,n){t=="accept"&&(this.accept=e.isFunction(n)?n:function(e){return e.is(n)}),e.Widget.prototype._setOption.apply(this,arguments)},_activate:function(t){var n=e.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass),n&&this._trigger("activate",t,this.ui(n))},_deactivate:function(t){var n=e.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass),n&&this._trigger("deactivate",t,this.ui(n))},_over:function(t){var n=e.ui.ddmanager.current;if(!n||(n.currentItem||n.element)[0]==this.element[0])return;this.accept.call(this.element[0],n.currentItem||n.element)&&(this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",t,this.ui(n)))},_out:function(t){var n=e.ui.ddmanager.current;if(!n||(n.currentItem||n.element)[0]==this.element[0])return;this.accept.call(this.element[0],n.currentItem||n.element)&&(this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",t,this.ui(n)))},_drop:function(t,n){var r=n||e.ui.ddmanager.current;if(!r||(r.currentItem||r.element)[0]==this.element[0])return!1;var i=!1;return this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var t=e.data(this,"droppable");if(t.options.greedy&&!t.options.disabled&&t.options.scope==r.options.scope&&t.accept.call(t.element[0],r.currentItem||r.element)&&e.ui.intersect(r,e.extend(t,{offset:t.element.offset()}),t.options.tolerance))return i=!0,!1}),i?!1:this.accept.call(this.element[0],r.currentItem||r.element)?(this.options.activeClass&&this.element.removeClass(this.options.activeClass),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("drop",t,this.ui(r)),this.element):!1},ui:function(e){return{draggable:e.currentItem||e.element,helper:e.helper,position:e.position,offset:e.positionAbs}}}),e.ui.intersect=function(t,n,r){if(!n.offset)return!1;var i=(t.positionAbs||t.position.absolute).left,s=i+t.helperProportions.width,o=(t.positionAbs||t.position.absolute).top,u=o+t.helperProportions.height,a=n.offset.left,f=a+n.proportions.width,l=n.offset.top,c=l+n.proportions.height;switch(r){case"fit":return a<=i&&s<=f&&l<=o&&u<=c;case"intersect":return a<i+t.helperProportions.width/2&&s-t.helperProportions.width/2<f&&l<o+t.helperProportions.height/2&&u-t.helperProportions.height/2<c;case"pointer":var h=(t.positionAbs||t.position.absolute).left+(t.clickOffset||t.offset.click).left,p=(t.positionAbs||t.position.absolute).top+(t.clickOffset||t.offset.click).top,d=e.ui.isOver(p,h,l,a,n.proportions.height,n.proportions.width);return d;case"touch":return(o>=l&&o<=c||u>=l&&u<=c||o<l&&u>c)&&(i>=a&&i<=f||s>=a&&s<=f||i<a&&s>f);default:return!1}},e.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(t,n){var r=e.ui.ddmanager.droppables[t.options.scope]||[],i=n?n.type:null,s=(t.currentItem||t.element).find(":data(droppable)").andSelf();e:for(var o=0;o<r.length;o++){if(r[o].options.disabled||t&&!r[o].accept.call(r[o].element[0],t.currentItem||t.element))continue;for(var u=0;u<s.length;u++)if(s[u]==r[o].element[0]){r[o].proportions.height=0;continue e}r[o].visible=r[o].element.css("display")!="none";if(!r[o].visible)continue;i=="mousedown"&&r[o]._activate.call(r[o],n),r[o].offset=r[o].element.offset(),r[o].proportions={width:r[o].element[0].offsetWidth,height:r[o].element[0].offsetHeight}}},drop:function(t,n){var r=!1;return e.each(e.ui.ddmanager.droppables[t.options.scope]||[],function(){if(!this.options)return;!this.options.disabled&&this.visible&&e.ui.intersect(t,this,this.options.tolerance)&&(r=this._drop.call(this,n)||r),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],t.currentItem||t.element)&&(this.isout=1,this.isover=0,this._deactivate.call(this,n))}),r},dragStart:function(t,n){t.element.parentsUntil("body").bind("scroll.droppable",function(){t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,n)})},drag:function(t,n){t.options.refreshPositions&&e.ui.ddmanager.prepareOffsets(t,n),e.each(e.ui.ddmanager.droppables[t.options.scope]||[],function(){if(this.options.disabled||this.greedyChild||!this.visible)return;var r=e.ui.intersect(t,this,this.options.tolerance),i=!r&&this.isover==1?"isout":r&&this.isover==0?"isover":null;if(!i)return;var s;if(this.options.greedy){var o=this.options.scope,u=this.element.parents(":data(droppable)").filter(function(){return e.data(this,"droppable").options.scope===o});u.length&&(s=e.data(u[0],"droppable"),s.greedyChild=i=="isover"?1:0)}s&&i=="isover"&&(s.isover=0,s.isout=1,s._out.call(s,n)),this[i]=1,this[i=="isout"?"isover":"isout"]=0,this[i=="isover"?"_over":"_out"].call(this,n),s&&i=="isout"&&(s.isout=0,s.isover=1,s._over.call(s,n))})},dragStop:function(t,n){t.element.parentsUntil("body").unbind("scroll.droppable"),t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,n)}}})(jQuery);(function(e,t){e.widget("ui.resizable",e.ui.mouse,{version:"1.9.2",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1e3},_create:function(){var t=this,n=this.options;this.element.addClass("ui-resizable"),e.extend(this,{_aspectRatio:!!n.aspectRatio,aspectRatio:n.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:n.helper||n.ghost||n.animate?n.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)&&(this.element.wrap(e('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("resizable",this.element.data("resizable")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=n.handles||(e(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se");if(this.handles.constructor==String){this.handles=="all"&&(this.handles="n,e,s,w,se,sw,ne,nw");var r=this.handles.split(",");this.handles={};for(var i=0;i<r.length;i++){var s=e.trim(r[i]),o="ui-resizable-"+s,u=e('<div class="ui-resizable-handle '+o+'"></div>');u.css({zIndex:n.zIndex}),"se"==s&&u.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[s]=".ui-resizable-"+s,this.element.append(u)}}this._renderAxis=function(t){t=t||this.element;for(var n in this.handles){this.handles[n].constructor==String&&(this.handles[n]=e(this.handles[n],this.element).show());if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var r=e(this.handles[n],this.element),i=0;i=/sw|ne|nw|se|n|s/.test(n)?r.outerHeight():r.outerWidth();var s=["padding",/ne|nw|n/.test(n)?"Top":/se|sw|s/.test(n)?"Bottom":/^e$/.test(n)?"Right":"Left"].join("");t.css(s,i),this._proportionallyResize()}if(!e(this.handles[n]).length)continue}},this._renderAxis(this.element),this._handles=e(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){if(!t.resizing){if(this.className)var e=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);t.axis=e&&e[1]?e[1]:"se"}}),n.autoHide&&(this._handles.hide(),e(this.element).addClass("ui-resizable-autohide").mouseenter(function(){if(n.disabled)return;e(this).removeClass("ui-resizable-autohide"),t._handles.show()}).mouseleave(function(){if(n.disabled)return;t.resizing||(e(this).addClass("ui-resizable-autohide"),t._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var t=function(t){e(t).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};if(this.elementIsWrapper){t(this.element);var n=this.element;this.originalElement.css({position:n.css("position"),width:n.outerWidth(),height:n.outerHeight(),top:n.css("top"),left:n.css("left")}).insertAfter(n),n.remove()}return this.originalElement.css("resize",this.originalResizeStyle),t(this.originalElement),this},_mouseCapture:function(t){var n=!1;for(var r in this.handles)e(this.handles[r])[0]==t.target&&(n=!0);return!this.options.disabled&&n},_mouseStart:function(t){var r=this.options,i=this.element.position(),s=this.element;this.resizing=!0,this.documentScroll={top:e(document).scrollTop(),left:e(document).scrollLeft()},(s.is(".ui-draggable")||/absolute/.test(s.css("position")))&&s.css({position:"absolute",top:i.top,left:i.left}),this._renderProxy();var o=n(this.helper.css("left")),u=n(this.helper.css("top"));r.containment&&(o+=e(r.containment).scrollLeft()||0,u+=e(r.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:o,top:u},this.size=this._helper?{width:s.outerWidth(),height:s.outerHeight()}:{width:s.width(),height:s.height()},this.originalSize=this._helper?{width:s.outerWidth(),height:s.outerHeight()}:{width:s.width(),height:s.height()},this.originalPosition={left:o,top:u},this.sizeDiff={width:s.outerWidth()-s.width(),height:s.outerHeight()-s.height()},this.originalMousePosition={left:t.pageX,top:t.pageY},this.aspectRatio=typeof r.aspectRatio=="number"?r.aspectRatio:this.originalSize.width/this.originalSize.height||1;var a=e(".ui-resizable-"+this.axis).css("cursor");return e("body").css("cursor",a=="auto"?this.axis+"-resize":a),s.addClass("ui-resizable-resizing"),this._propagate("start",t),!0},_mouseDrag:function(e){var t=this.helper,n=this.options,r={},i=this,s=this.originalMousePosition,o=this.axis,u=e.pageX-s.left||0,a=e.pageY-s.top||0,f=this._change[o];if(!f)return!1;var l=f.apply(this,[e,u,a]);this._updateVirtualBoundaries(e.shiftKey);if(this._aspectRatio||e.shiftKey)l=this._updateRatio(l,e);return l=this._respectSize(l,e),this._propagate("resize",e),t.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"}),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),this._updateCache(l),this._trigger("resize",e,this.ui()),!1},_mouseStop:function(t){this.resizing=!1;var n=this.options,r=this;if(this._helper){var i=this._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),o=s&&e.ui.hasScroll(i[0],"left")?0:r.sizeDiff.height,u=s?0:r.sizeDiff.width,a={width:r.helper.width()-u,height:r.helper.height()-o},f=parseInt(r.element.css("left"),10)+(r.position.left-r.originalPosition.left)||null,l=parseInt(r.element.css("top"),10)+(r.position.top-r.originalPosition.top)||null;n.animate||this.element.css(e.extend(a,{top:l,left:f})),r.helper.height(r.size.height),r.helper.width(r.size.width),this._helper&&!n.animate&&this._proportionallyResize()}return e("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",t),this._helper&&this.helper.remove(),!1},_updateVirtualBoundaries:function(e){var t=this.options,n,i,s,o,u;u={minWidth:r(t.minWidth)?t.minWidth:0,maxWidth:r(t.maxWidth)?t.maxWidth:Infinity,minHeight:r(t.minHeight)?t.minHeight:0,maxHeight:r(t.maxHeight)?t.maxHeight:Infinity};if(this._aspectRatio||e)n=u.minHeight*this.aspectRatio,s=u.minWidth/this.aspectRatio,i=u.maxHeight*this.aspectRatio,o=u.maxWidth/this.aspectRatio,n>u.minWidth&&(u.minWidth=n),s>u.minHeight&&(u.minHeight=s),i<u.maxWidth&&(u.maxWidth=i),o<u.maxHeight&&(u.maxHeight=o);this._vBoundaries=u},_updateCache:function(e){var t=this.options;this.offset=this.helper.offset(),r(e.left)&&(this.position.left=e.left),r(e.top)&&(this.position.top=e.top),r(e.height)&&(this.size.height=e.height),r(e.width)&&(this.size.width=e.width)},_updateRatio:function(e,t){var n=this.options,i=this.position,s=this.size,o=this.axis;return r(e.height)?e.width=e.height*this.aspectRatio:r(e.width)&&(e.height=e.width/this.aspectRatio),o=="sw"&&(e.left=i.left+(s.width-e.width),e.top=null),o=="nw"&&(e.top=i.top+(s.height-e.height),e.left=i.left+(s.width-e.width)),e},_respectSize:function(e,t){var n=this.helper,i=this._vBoundaries,s=this._aspectRatio||t.shiftKey,o=this.axis,u=r(e.width)&&i.maxWidth&&i.maxWidth<e.width,a=r(e.height)&&i.maxHeight&&i.maxHeight<e.height,f=r(e.width)&&i.minWidth&&i.minWidth>e.width,l=r(e.height)&&i.minHeight&&i.minHeight>e.height;f&&(e.width=i.minWidth),l&&(e.height=i.minHeight),u&&(e.width=i.maxWidth),a&&(e.height=i.maxHeight);var c=this.originalPosition.left+this.originalSize.width,h=this.position.top+this.size.height,p=/sw|nw|w/.test(o),d=/nw|ne|n/.test(o);f&&p&&(e.left=c-i.minWidth),u&&p&&(e.left=c-i.maxWidth),l&&d&&(e.top=h-i.minHeight),a&&d&&(e.top=h-i.maxHeight);var v=!e.width&&!e.height;return v&&!e.left&&e.top?e.top=null:v&&!e.top&&e.left&&(e.left=null),e},_proportionallyResize:function(){var t=this.options;if(!this._proportionallyResizeElements.length)return;var n=this.helper||this.element;for(var r=0;r<this._proportionallyResizeElements.length;r++){var i=this._proportionallyResizeElements[r];if(!this.borderDif){var s=[i.css("borderTopWidth"),i.css("borderRightWidth"),i.css("borderBottomWidth"),i.css("borderLeftWidth")],o=[i.css("paddingTop"),i.css("paddingRight"),i.css("paddingBottom"),i.css("paddingLeft")];this.borderDif=e.map(s,function(e,t){var n=parseInt(e,10)||0,r=parseInt(o[t],10)||0;return n+r})}i.css({height:n.height()-this.borderDif[0]-this.borderDif[2]||0,width:n.width()-this.borderDif[1]-this.borderDif[3]||0})}},_renderProxy:function(){var t=this.element,n=this.options;this.elementOffset=t.offset();if(this._helper){this.helper=this.helper||e('<div style="overflow:hidden;"></div>');var r=e.ui.ie6?1:0,i=e.ui.ie6?2:-1;this.helper.addClass(this._helper).css({width:this.element.outerWidth()+i,height:this.element.outerHeight()+i,position:"absolute",left:this.elementOffset.left-r+"px",top:this.elementOffset.top-r+"px",zIndex:++n.zIndex}),this.helper.appendTo("body").disableSelection()}else this.helper=this.element},_change:{e:function(e,t,n){return{width:this.originalSize.width+t}},w:function(e,t,n){var r=this.options,i=this.originalSize,s=this.originalPosition;return{left:s.left+t,width:i.width-t}},n:function(e,t,n){var r=this.options,i=this.originalSize,s=this.originalPosition;return{top:s.top+n,height:i.height-n}},s:function(e,t,n){return{height:this.originalSize.height+n}},se:function(t,n,r){return e.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[t,n,r]))},sw:function(t,n,r){return e.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[t,n,r]))},ne:function(t,n,r){return e.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[t,n,r]))},nw:function(t,n,r){return e.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[t,n,r]))}},_propagate:function(t,n){e.ui.plugin.call(this,t,[n,this.ui()]),t!="resize"&&this._trigger(t,n,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),e.ui.plugin.add("resizable","alsoResize",{start:function(t,n){var r=e(this).data("resizable"),i=r.options,s=function(t){e(t).each(function(){var t=e(this);t.data("resizable-alsoresize",{width:parseInt(t.width(),10),height:parseInt(t.height(),10),left:parseInt(t.css("left"),10),top:parseInt(t.css("top"),10)})})};typeof i.alsoResize=="object"&&!i.alsoResize.parentNode?i.alsoResize.length?(i.alsoResize=i.alsoResize[0],s(i.alsoResize)):e.each(i.alsoResize,function(e){s(e)}):s(i.alsoResize)},resize:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.originalSize,o=r.originalPosition,u={height:r.size.height-s.height||0,width:r.size.width-s.width||0,top:r.position.top-o.top||0,left:r.position.left-o.left||0},a=function(t,r){e(t).each(function(){var t=e(this),i=e(this).data("resizable-alsoresize"),s={},o=r&&r.length?r:t.parents(n.originalElement[0]).length?["width","height"]:["width","height","top","left"];e.each(o,function(e,t){var n=(i[t]||0)+(u[t]||0);n&&n>=0&&(s[t]=n||null)}),t.css(s)})};typeof i.alsoResize=="object"&&!i.alsoResize.nodeType?e.each(i.alsoResize,function(e,t){a(e,t)}):a(i.alsoResize)},stop:function(t,n){e(this).removeData("resizable-alsoresize")}}),e.ui.plugin.add("resizable","animate",{stop:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r._proportionallyResizeElements,o=s.length&&/textarea/i.test(s[0].nodeName),u=o&&e.ui.hasScroll(s[0],"left")?0:r.sizeDiff.height,a=o?0:r.sizeDiff.width,f={width:r.size.width-a,height:r.size.height-u},l=parseInt(r.element.css("left"),10)+(r.position.left-r.originalPosition.left)||null,c=parseInt(r.element.css("top"),10)+(r.position.top-r.originalPosition.top)||null;r.element.animate(e.extend(f,c&&l?{top:c,left:l}:{}),{duration:i.animateDuration,easing:i.animateEasing,step:function(){var n={width:parseInt(r.element.css("width"),10),height:parseInt(r.element.css("height"),10),top:parseInt(r.element.css("top"),10),left:parseInt(r.element.css("left"),10)};s&&s.length&&e(s[0]).css({width:n.width,height:n.height}),r._updateCache(n),r._propagate("resize",t)}})}}),e.ui.plugin.add("resizable","containment",{start:function(t,r){var i=e(this).data("resizable"),s=i.options,o=i.element,u=s.containment,a=u instanceof e?u.get(0):/parent/.test(u)?o.parent().get(0):u;if(!a)return;i.containerElement=e(a);if(/document/.test(u)||u==document)i.containerOffset={left:0,top:0},i.containerPosition={left:0,top:0},i.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight};else{var f=e(a),l=[];e(["Top","Right","Left","Bottom"]).each(function(e,t){l[e]=n(f.css("padding"+t))}),i.containerOffset=f.offset(),i.containerPosition=f.position(),i.containerSize={height:f.innerHeight()-l[3],width:f.innerWidth()-l[1]};var c=i.containerOffset,h=i.containerSize.height,p=i.containerSize.width,d=e.ui.hasScroll(a,"left")?a.scrollWidth:p,v=e.ui.hasScroll(a)?a.scrollHeight:h;i.parentData={element:a,left:c.left,top:c.top,width:d,height:v}}},resize:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.containerSize,o=r.containerOffset,u=r.size,a=r.position,f=r._aspectRatio||t.shiftKey,l={top:0,left:0},c=r.containerElement;c[0]!=document&&/static/.test(c.css("position"))&&(l=o),a.left<(r._helper?o.left:0)&&(r.size.width=r.size.width+(r._helper?r.position.left-o.left:r.position.left-l.left),f&&(r.size.height=r.size.width/r.aspectRatio),r.position.left=i.helper?o.left:0),a.top<(r._helper?o.top:0)&&(r.size.height=r.size.height+(r._helper?r.position.top-o.top:r.position.top),f&&(r.size.width=r.size.height*r.aspectRatio),r.position.top=r._helper?o.top:0),r.offset.left=r.parentData.left+r.position.left,r.offset.top=r.parentData.top+r.position.top;var h=Math.abs((r._helper?r.offset.left-l.left:r.offset.left-l.left)+r.sizeDiff.width),p=Math.abs((r._helper?r.offset.top-l.top:r.offset.top-o.top)+r.sizeDiff.height),d=r.containerElement.get(0)==r.element.parent().get(0),v=/relative|absolute/.test(r.containerElement.css("position"));d&&v&&(h-=r.parentData.left),h+r.size.width>=r.parentData.width&&(r.size.width=r.parentData.width-h,f&&(r.size.height=r.size.width/r.aspectRatio)),p+r.size.height>=r.parentData.height&&(r.size.height=r.parentData.height-p,f&&(r.size.width=r.size.height*r.aspectRatio))},stop:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.position,o=r.containerOffset,u=r.containerPosition,a=r.containerElement,f=e(r.helper),l=f.offset(),c=f.outerWidth()-r.sizeDiff.width,h=f.outerHeight()-r.sizeDiff.height;r._helper&&!i.animate&&/relative/.test(a.css("position"))&&e(this).css({left:l.left-u.left-o.left,width:c,height:h}),r._helper&&!i.animate&&/static/.test(a.css("position"))&&e(this).css({left:l.left-u.left-o.left,width:c,height:h})}}),e.ui.plugin.add("resizable","ghost",{start:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.size;r.ghost=r.originalElement.clone(),r.ghost.css({opacity:.25,display:"block",position:"relative",height:s.height,width:s.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof i.ghost=="string"?i.ghost:""),r.ghost.appendTo(r.helper)},resize:function(t,n){var r=e(this).data("resizable"),i=r.options;r.ghost&&r.ghost.css({position:"relative",height:r.size.height,width:r.size.width})},stop:function(t,n){var r=e(this).data("resizable"),i=r.options;r.ghost&&r.helper&&r.helper.get(0).removeChild(r.ghost.get(0))}}),e.ui.plugin.add("resizable","grid",{resize:function(t,n){var r=e(this).data("resizable"),i=r.options,s=r.size,o=r.originalSize,u=r.originalPosition,a=r.axis,f=i._aspectRatio||t.shiftKey;i.grid=typeof i.grid=="number"?[i.grid,i.grid]:i.grid;var l=Math.round((s.width-o.width)/(i.grid[0]||1))*(i.grid[0]||1),c=Math.round((s.height-o.height)/(i.grid[1]||1))*(i.grid[1]||1);/^(se|s|e)$/.test(a)?(r.size.width=o.width+l,r.size.height=o.height+c):/^(ne)$/.test(a)?(r.size.width=o.width+l,r.size.height=o.height+c,r.position.top=u.top-c):/^(sw)$/.test(a)?(r.size.width=o.width+l,r.size.height=o.height+c,r.position.left=u.left-l):(r.size.width=o.width+l,r.size.height=o.height+c,r.position.top=u.top-c,r.position.left=u.left-l)}});var n=function(e){return parseInt(e,10)||0},r=function(e){return!isNaN(parseInt(e,10))}})(jQuery);(function(e,t){e.widget("ui.sortable",e.ui.mouse,{version:"1.9.2",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3},_create:function(){var e=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?e.axis==="x"||/left|right/.test(this.items[0].item.css("float"))||/inline|table-cell/.test(this.items[0].item.css("display")):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var e=this.items.length-1;e>=0;e--)this.items[e].item.removeData(this.widgetName+"-item");return this},_setOption:function(t,n){t==="disabled"?(this.options[t]=n,this.widget().toggleClass("ui-sortable-disabled",!!n)):e.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(t,n){var r=this;if(this.reverting)return!1;if(this.options.disabled||this.options.type=="static")return!1;this._refreshItems(t);var i=null,s=e(t.target).parents().each(function(){if(e.data(this,r.widgetName+"-item")==r)return i=e(this),!1});e.data(t.target,r.widgetName+"-item")==r&&(i=e(t.target));if(!i)return!1;if(this.options.handle&&!n){var o=!1;e(this.options.handle,i).find("*").andSelf().each(function(){this==t.target&&(o=!0)});if(!o)return!1}return this.currentItem=i,this._removeCurrentsFromItems(),!0},_mouseStart:function(t,n,r){var i=this.options;this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(t),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,i.cursorAt&&this._adjustOffsetFromHelper(i.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!=this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),i.containment&&this._setContainment(),i.cursor&&(e("body").css("cursor")&&(this._storedCursor=e("body").css("cursor")),e("body").css("cursor",i.cursor)),i.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",i.opacity)),i.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",i.zIndex)),this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",t,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions();if(!r)for(var s=this.containers.length-1;s>=0;s--)this.containers[s]._trigger("activate",t,this._uiHash(this));return e.ui.ddmanager&&(e.ui.ddmanager.current=this),e.ui.ddmanager&&!i.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(t),!0},_mouseDrag:function(t){this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs);if(this.options.scroll){var n=this.options,r=!1;this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY<n.scrollSensitivity?this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop+n.scrollSpeed:t.pageY-this.overflowOffset.top<n.scrollSensitivity&&(this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop-n.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-t.pageX<n.scrollSensitivity?this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft+n.scrollSpeed:t.pageX-this.overflowOffset.left<n.scrollSensitivity&&(this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft-n.scrollSpeed)):(t.pageY-e(document).scrollTop()<n.scrollSensitivity?r=e(document).scrollTop(e(document).scrollTop()-n.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<n.scrollSensitivity&&(r=e(document).scrollTop(e(document).scrollTop()+n.scrollSpeed)),t.pageX-e(document).scrollLeft()<n.scrollSensitivity?r=e(document).scrollLeft(e(document).scrollLeft()-n.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<n.scrollSensitivity&&(r=e(document).scrollLeft(e(document).scrollLeft()+n.scrollSpeed))),r!==!1&&e.ui.ddmanager&&!n.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t)}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";for(var i=this.items.length-1;i>=0;i--){var s=this.items[i],o=s.item[0],u=this._intersectsWithPointer(s);if(!u)continue;if(s.instance!==this.currentContainer)continue;if(o!=this.currentItem[0]&&this.placeholder[u==1?"next":"prev"]()[0]!=o&&!e.contains(this.placeholder[0],o)&&(this.options.type=="semi-dynamic"?!e.contains(this.element[0],o):!0)){this.direction=u==1?"down":"up";if(this.options.tolerance!="pointer"&&!this._intersectsWithSides(s))break;this._rearrange(t,s),this._trigger("change",t,this._uiHash());break}}return this._contactContainers(t),e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),this._trigger("sort",t,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(t,n){if(!t)return;e.ui.ddmanager&&!this.options.dropBehaviour&&e.ui.ddmanager.drop(this,t);if(this.options.revert){var r=this,i=this.placeholder.offset();this.reverting=!0,e(this.helper).animate({left:i.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:i.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){r._clear(t)})}else this._clear(t,n);return!1},cancel:function(){if(this.dragging){this._mouseUp({target:null}),this.options.helper=="original"?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var t=this.containers.length-1;t>=0;t--)this.containers[t]._trigger("deactivate",null,this._uiHash(this)),this.containers[t].containerCache.over&&(this.containers[t]._trigger("out",null,this._uiHash(this)),this.containers[t].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.options.helper!="original"&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),e.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?e(this.domPosition.prev).after(this.currentItem):e(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(t){var n=this._getItemsAsjQuery(t&&t.connected),r=[];return t=t||{},e(n).each(function(){var n=(e(t.item||this).attr(t.attribute||"id")||"").match(t.expression||/(.+)[-=_](.+)/);n&&r.push((t.key||n[1]+"[]")+"="+(t.key&&t.expression?n[1]:n[2]))}),!r.length&&t.key&&r.push(t.key+"="),r.join("&")},toArray:function(t){var n=this._getItemsAsjQuery(t&&t.connected),r=[];return t=t||{},n.each(function(){r.push(e(t.item||this).attr(t.attribute||"id")||"")}),r},_intersectsWith:function(e){var t=this.positionAbs.left,n=t+this.helperProportions.width,r=this.positionAbs.top,i=r+this.helperProportions.height,s=e.left,o=s+e.width,u=e.top,a=u+e.height,f=this.offset.click.top,l=this.offset.click.left,c=r+f>u&&r+f<a&&t+l>s&&t+l<o;return this.options.tolerance=="pointer"||this.options.forcePointerForContainers||this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>e[this.floating?"width":"height"]?c:s<t+this.helperProportions.width/2&&n-this.helperProportions.width/2<o&&u<r+this.helperProportions.height/2&&i-this.helperProportions.height/2<a},_intersectsWithPointer:function(t){var n=this.options.axis==="x"||e.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,t.top,t.height),r=this.options.axis==="y"||e.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,t.left,t.width),i=n&&r,s=this._getDragVerticalDirection(),o=this._getDragHorizontalDirection();return i?this.floating?o&&o=="right"||s=="down"?2:1:s&&(s=="down"?2:1):!1},_intersectsWithSides:function(t){var n=e.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),r=e.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),i=this._getDragVerticalDirection(),s=this._getDragHorizontalDirection();return this.floating&&s?s=="right"&&r||s=="left"&&!r:i&&(i=="down"&&n||i=="up"&&!n)},_getDragVerticalDirection:function(){var e=this.positionAbs.top-this.lastPositionAbs.top;return e!=0&&(e>0?"down":"up")},_getDragHorizontalDirection:function(){var e=this.positionAbs.left-this.lastPositionAbs.left;return e!=0&&(e>0?"right":"left")},refresh:function(e){return this._refreshItems(e),this.refreshPositions(),this},_connectWith:function(){var e=this.options;return e.connectWith.constructor==String?[e.connectWith]:e.connectWith},_getItemsAsjQuery:function(t){var n=[],r=[],i=this._connectWith();if(i&&t)for(var s=i.length-1;s>=0;s--){var o=e(i[s]);for(var u=o.length-1;u>=0;u--){var a=e.data(o[u],this.widgetName);a&&a!=this&&!a.options.disabled&&r.push([e.isFunction(a.options.items)?a.options.items.call(a.element):e(a.options.items,a.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),a])}}r.push([e.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):e(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(var s=r.length-1;s>=0;s--)r[s][0].each(function(){n.push(this)});return e(n)},_removeCurrentsFromItems:function(){var t=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=e.grep(this.items,function(e){for(var n=0;n<t.length;n++)if(t[n]==e.item[0])return!1;return!0})},_refreshItems:function(t){this.items=[],this.containers=[this];var n=this.items,r=[[e.isFunction(this.options.items)?this.options.items.call(this.element[0],t,{item:this.currentItem}):e(this.options.items,this.element),this]],i=this._connectWith();if(i&&this.ready)for(var s=i.length-1;s>=0;s--){var o=e(i[s]);for(var u=o.length-1;u>=0;u--){var a=e.data(o[u],this.widgetName);a&&a!=this&&!a.options.disabled&&(r.push([e.isFunction(a.options.items)?a.options.items.call(a.element[0],t,{item:this.currentItem}):e(a.options.items,a.element),a]),this.containers.push(a))}}for(var s=r.length-1;s>=0;s--){var f=r[s][1],l=r[s][0];for(var u=0,c=l.length;u<c;u++){var h=e(l[u]);h.data(this.widgetName+"-item",f),n.push({item:h,instance:f,width:0,height:0,left:0,top:0})}}},refreshPositions:function(t){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());for(var n=this.items.length-1;n>=0;n--){var r=this.items[n];if(r.instance!=this.currentContainer&&this.currentContainer&&r.item[0]!=this.currentItem[0])continue;var i=this.options.toleranceElement?e(this.options.toleranceElement,r.item):r.item;t||(r.width=i.outerWidth(),r.height=i.outerHeight());var s=i.offset();r.left=s.left,r.top=s.top}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(var n=this.containers.length-1;n>=0;n--){var s=this.containers[n].element.offset();this.containers[n].containerCache.left=s.left,this.containers[n].containerCache.top=s.top,this.containers[n].containerCache.width=this.containers[n].element.outerWidth(),this.containers[n].containerCache.height=this.containers[n].element.outerHeight()}return this},_createPlaceholder:function(t){t=t||this;var n=t.options;if(!n.placeholder||n.placeholder.constructor==String){var r=n.placeholder;n.placeholder={element:function(){var n=e(document.createElement(t.currentItem[0].nodeName)).addClass(r||t.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];return r||(n.style.visibility="hidden"),n},update:function(e,i){if(r&&!n.forcePlaceholderSize)return;i.height()||i.height(t.currentItem.innerHeight()-parseInt(t.currentItem.css("paddingTop")||0,10)-parseInt(t.currentItem.css("paddingBottom")||0,10)),i.width()||i.width(t.currentItem.innerWidth()-parseInt(t.currentItem.css("paddingLeft")||0,10)-parseInt(t.currentItem.css("paddingRight")||0,10))}}}t.placeholder=e(n.placeholder.element.call(t.element,t.currentItem)),t.currentItem.after(t.placeholder),n.placeholder.update(t,t.placeholder)},_contactContainers:function(t){var n=null,r=null;for(var i=this.containers.length-1;i>=0;i--){if(e.contains(this.currentItem[0],this.containers[i].element[0]))continue;if(this._intersectsWith(this.containers[i].containerCache)){if(n&&e.contains(this.containers[i].element[0],n.element[0]))continue;n=this.containers[i],r=i}else this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",t,this._uiHash(this)),this.containers[i].containerCache.over=0)}if(!n)return;if(this.containers.length===1)this.containers[r]._trigger("over",t,this._uiHash(this)),this.containers[r].containerCache.over=1;else{var s=1e4,o=null,u=this.containers[r].floating?"left":"top",a=this.containers[r].floating?"width":"height",f=this.positionAbs[u]+this.offset.click[u];for(var l=this.items.length-1;l>=0;l--){if(!e.contains(this.containers[r].element[0],this.items[l].item[0]))continue;if(this.items[l].item[0]==this.currentItem[0])continue;var c=this.items[l].item.offset()[u],h=!1;Math.abs(c-f)>Math.abs(c+this.items[l][a]-f)&&(h=!0,c+=this.items[l][a]),Math.abs(c-f)<s&&(s=Math.abs(c-f),o=this.items[l],this.direction=h?"up":"down")}if(!o&&!this.options.dropOnEmpty)return;this.currentContainer=this.containers[r],o?this._rearrange(t,o,null,!0):this._rearrange(t,null,this.containers[r].element,!0),this._trigger("change",t,this._uiHash()),this.containers[r]._trigger("change",t,this._uiHash(this)),this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[r]._trigger("over",t,this._uiHash(this)),this.containers[r].containerCache.over=1}},_createHelper:function(t){var n=this.options,r=e.isFunction(n.helper)?e(n.helper.apply(this.element[0],[t,this.currentItem])):n.helper=="clone"?this.currentItem.clone():this.currentItem;return r.parents("body").length||e(n.appendTo!="parent"?n.appendTo:this.currentItem[0].parentNode)[0].appendChild(r[0]),r[0]==this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(r[0].style.width==""||n.forceHelperSize)&&r.width(this.currentItem.width()),(r[0].style.height==""||n.forceHelperSize)&&r.height(this.currentItem.height()),r},_adjustOffsetFromHelper:function(t){typeof t=="string"&&(t=t.split(" ")),e.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&e.ui.ie)t={top:0,left:0};return{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var e=this.currentItem.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t=this.options;t.containment=="parent"&&(t.containment=this.helper[0].parentNode);if(t.containment=="document"||t.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,e(t.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(e(t.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(t.containment)){var n=e(t.containment)[0],r=e(t.containment).offset(),i=e(n).css("overflow")!="hidden";this.containment=[r.left+(parseInt(e(n).css("borderLeftWidth"),10)||0)+(parseInt(e(n).css("paddingLeft"),10)||0)-this.margins.left,r.top+(parseInt(e(n).css("borderTopWidth"),10)||0)+(parseInt(e(n).css("paddingTop"),10)||0)-this.margins.top,r.left+(i?Math.max(n.scrollWidth,n.offsetWidth):n.offsetWidth)-(parseInt(e(n).css("borderLeftWidth"),10)||0)-(parseInt(e(n).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,r.top+(i?Math.max(n.scrollHeight,n.offsetHeight):n.offsetHeight)-(parseInt(e(n).css("borderTopWidth"),10)||0)-(parseInt(e(n).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(t,n){n||(n=this.position);var r=t=="absolute"?1:-1,i=this.options,s=this.cssPosition!="absolute"||this.scrollParent[0]!=document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,o=/(html|body)/i.test(s[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():o?0:s.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():o?0:s.scrollLeft())*r}},_generatePosition:function(t){var n=this.options,r=this.cssPosition!="absolute"||this.scrollParent[0]!=document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,i=/(html|body)/i.test(r[0].tagName);this.cssPosition=="relative"&&(this.scrollParent[0]==document||this.scrollParent[0]==this.offsetParent[0])&&(this.offset.relative=this._getRelativeOffset());var s=t.pageX,o=t.pageY;if(this.originalPosition){this.containment&&(t.pageX-this.offset.click.left<this.containment[0]&&(s=this.containment[0]+this.offset.click.left),t.pageY-this.offset.click.top<this.containment[1]&&(o=this.containment[1]+this.offset.click.top),t.pageX-this.offset.click.left>this.containment[2]&&(s=this.containment[2]+this.offset.click.left),t.pageY-this.offset.click.top>this.containment[3]&&(o=this.containment[3]+this.offset.click.top));if(n.grid){var u=this.originalPageY+Math.round((o-this.originalPageY)/n.grid[1])*n.grid[1];o=this.containment?u-this.offset.click.top<this.containment[1]||u-this.offset.click.top>this.containment[3]?u-this.offset.click.top<this.containment[1]?u+n.grid[1]:u-n.grid[1]:u:u;var a=this.originalPageX+Math.round((s-this.originalPageX)/n.grid[0])*n.grid[0];s=this.containment?a-this.offset.click.left<this.containment[0]||a-this.offset.click.left>this.containment[2]?a-this.offset.click.left<this.containment[0]?a+n.grid[0]:a-n.grid[0]:a:a}}return{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():i?0:r.scrollTop()),left:s-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:r.scrollLeft())}},_rearrange:function(e,t,n,r){n?n[0].appendChild(this.placeholder[0]):t.item[0].parentNode.insertBefore(this.placeholder[0],this.direction=="down"?t.item[0]:t.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var i=this.counter;this._delay(function(){i==this.counter&&this.refreshPositions(!r)})},_clear:function(t,n){this.reverting=!1;var r=[];!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var i in this._storedCSS)if(this._storedCSS[i]=="auto"||this._storedCSS[i]=="static")this._storedCSS[i]="";this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!n&&r.push(function(e){this._trigger("receive",e,this._uiHash(this.fromOutside))}),(this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!n&&r.push(function(e){this._trigger("update",e,this._uiHash())}),this!==this.currentContainer&&(n||(r.push(function(e){this._trigger("remove",e,this._uiHash())}),r.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer)),r.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer))));for(var i=this.containers.length-1;i>=0;i--)n||r.push(function(e){return function(t){e._trigger("deactivate",t,this._uiHash(this))}}.call(this,this.containers[i])),this.containers[i].containerCache.over&&(r.push(function(e){return function(t){e._trigger("out",t,this._uiHash(this))}}.call(this,this.containers[i])),this.containers[i].containerCache.over=0);this._storedCursor&&e("body").css("cursor",this._storedCursor),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex),this.dragging=!1;if(this.cancelHelperRemoval){if(!n){this._trigger("beforeStop",t,this._uiHash());for(var i=0;i<r.length;i++)r[i].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!1}n||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!=this.currentItem[0]&&this.helper.remove(),this.helper=null;if(!n){for(var i=0;i<r.length;i++)r[i].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){e.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(t){var n=t||this;return{helper:n.helper,placeholder:n.placeholder||e([]),position:n.position,originalPosition:n.originalPosition,offset:n.positionAbs,item:n.currentItem,sender:t?t.element:null}}})})(jQuery);(function(e,t){var n=0,r={},i={};r.height=r.paddingTop=r.paddingBottom=r.borderTopWidth=r.borderBottomWidth="hide",i.height=i.paddingTop=i.paddingBottom=i.borderTopWidth=i.borderBottomWidth="show",e.widget("ui.accordion",{version:"1.9.2",options:{active:0,animate:{},collapsible:!1,event:"click",header:"> li > :first-child,> :not(li):even",heightStyle:"auto",icons:{activeHeader:"ui-icon-triangle-1-s",header:"ui-icon-triangle-1-e"},activate:null,beforeActivate:null},_create:function(){var t=this.accordionId="ui-accordion-"+(this.element.attr("id")||++n),r=this.options;this.prevShow=this.prevHide=e(),this.element.addClass("ui-accordion ui-widget ui-helper-reset"),this.headers=this.element.find(r.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all"),this._hoverable(this.headers),this._focusable(this.headers),this.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom").hide(),!r.collapsible&&(r.active===!1||r.active==null)&&(r.active=0),r.active<0&&(r.active+=this.headers.length),this.active=this._findActive(r.active).addClass("ui-accordion-header-active ui-state-active").toggleClass("ui-corner-all ui-corner-top"),this.active.next().addClass("ui-accordion-content-active").show(),this._createIcons(),this.refresh(),this.element.attr("role","tablist"),this.headers.attr("role","tab").each(function(n){var r=e(this),i=r.attr("id"),s=r.next(),o=s.attr("id");i||(i=t+"-header-"+n,r.attr("id",i)),o||(o=t+"-panel-"+n,s.attr("id",o)),r.attr("aria-controls",o),s.attr("aria-labelledby",i)}).next().attr("role","tabpanel"),this.headers.not(this.active).attr({"aria-selected":"false",tabIndex:-1}).next().attr({"aria-expanded":"false","aria-hidden":"true"}).hide(),this.active.length?this.active.attr({"aria-selected":"true",tabIndex:0}).next().attr({"aria-expanded":"true","aria-hidden":"false"}):this.headers.eq(0).attr("tabIndex",0),this._on(this.headers,{keydown:"_keydown"}),this._on(this.headers.next(),{keydown:"_panelKeyDown"}),this._setupEvents(r.event)},_getCreateEventData:function(){return{header:this.active,content:this.active.length?this.active.next():e()}},_createIcons:function(){var t=this.options.icons;t&&(e("<span>").addClass("ui-accordion-header-icon ui-icon "+t.header).prependTo(this.headers),this.active.children(".ui-accordion-header-icon").removeClass(t.header).addClass(t.activeHeader),this.headers.addClass("ui-accordion-icons"))},_destroyIcons:function(){this.headers.removeClass("ui-accordion-icons").children(".ui-accordion-header-icon").remove()},_destroy:function(){var e;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role"),this.headers.removeClass("ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-selected").removeAttr("aria-controls").removeAttr("tabIndex").each(function(){/^ui-accordion/.test(this.id)&&this.removeAttribute("id")}),this._destroyIcons(),e=this.headers.next().css("display","").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-labelledby").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled").each(function(){/^ui-accordion/.test(this.id)&&this.removeAttribute("id")}),this.options.heightStyle!=="content"&&e.css("height","")},_setOption:function(e,t){if(e==="active"){this._activate(t);return}e==="event"&&(this.options.event&&this._off(this.headers,this.options.event),this._setupEvents(t)),this._super(e,t),e==="collapsible"&&!t&&this.options.active===!1&&this._activate(0),e==="icons"&&(this._destroyIcons(),t&&this._createIcons()),e==="disabled"&&this.headers.add(this.headers.next()).toggleClass("ui-state-disabled",!!t)},_keydown:function(t){if(t.altKey||t.ctrlKey)return;var n=e.ui.keyCode,r=this.headers.length,i=this.headers.index(t.target),s=!1;switch(t.keyCode){case n.RIGHT:case n.DOWN:s=this.headers[(i+1)%r];break;case n.LEFT:case n.UP:s=this.headers[(i-1+r)%r];break;case n.SPACE:case n.ENTER:this._eventHandler(t);break;case n.HOME:s=this.headers[0];break;case n.END:s=this.headers[r-1]}s&&(e(t.target).attr("tabIndex",-1),e(s).attr("tabIndex",0),s.focus(),t.preventDefault())},_panelKeyDown:function(t){t.keyCode===e.ui.keyCode.UP&&t.ctrlKey&&e(t.currentTarget).prev().focus()},refresh:function(){var t,n,r=this.options.heightStyle,i=this.element.parent();r==="fill"?(e.support.minHeight||(n=i.css("overflow"),i.css("overflow","hidden")),t=i.height(),this.element.siblings(":visible").each(function(){var n=e(this),r=n.css("position");if(r==="absolute"||r==="fixed")return;t-=n.outerHeight(!0)}),n&&i.css("overflow",n),this.headers.each(function(){t-=e(this).outerHeight(!0)}),this.headers.next().each(function(){e(this).height(Math.max(0,t-e(this).innerHeight()+e(this).height()))}).css("overflow","auto")):r==="auto"&&(t=0,this.headers.next().each(function(){t=Math.max(t,e(this).css("height","").height())}).height(t))},_activate:function(t){var n=this._findActive(t)[0];if(n===this.active[0])return;n=n||this.active[0],this._eventHandler({target:n,currentTarget:n,preventDefault:e.noop})},_findActive:function(t){return typeof t=="number"?this.headers.eq(t):e()},_setupEvents:function(t){var n={};if(!t)return;e.each(t.split(" "),function(e,t){n[t]="_eventHandler"}),this._on(this.headers,n)},_eventHandler:function(t){var n=this.options,r=this.active,i=e(t.currentTarget),s=i[0]===r[0],o=s&&n.collapsible,u=o?e():i.next(),a=r.next(),f={oldHeader:r,oldPanel:a,newHeader:o?e():i,newPanel:u};t.preventDefault();if(s&&!n.collapsible||this._trigger("beforeActivate",t,f)===!1)return;n.active=o?!1:this.headers.index(i),this.active=s?e():i,this._toggle(f),r.removeClass("ui-accordion-header-active ui-state-active"),n.icons&&r.children(".ui-accordion-header-icon").removeClass(n.icons.activeHeader).addClass(n.icons.header),s||(i.removeClass("ui-corner-all").addClass("ui-accordion-header-active ui-state-active ui-corner-top"),n.icons&&i.children(".ui-accordion-header-icon").removeClass(n.icons.header).addClass(n.icons.activeHeader),i.next().addClass("ui-accordion-content-active"))},_toggle:function(t){var n=t.newPanel,r=this.prevShow.length?this.prevShow:t.oldPanel;this.prevShow.add(this.prevHide).stop(!0,!0),this.prevShow=n,this.prevHide=r,this.options.animate?this._animate(n,r,t):(r.hide(),n.show(),this._toggleComplete(t)),r.attr({"aria-expanded":"false","aria-hidden":"true"}),r.prev().attr("aria-selected","false"),n.length&&r.length?r.prev().attr("tabIndex",-1):n.length&&this.headers.filter(function(){return e(this).attr("tabIndex")===0}).attr("tabIndex",-1),n.attr({"aria-expanded":"true","aria-hidden":"false"}).prev().attr({"aria-selected":"true",tabIndex:0})},_animate:function(e,t,n){var s,o,u,a=this,f=0,l=e.length&&(!t.length||e.index()<t.index()),c=this.options.animate||{},h=l&&c.down||c,p=function(){a._toggleComplete(n)};typeof h=="number"&&(u=h),typeof h=="string"&&(o=h),o=o||h.easing||c.easing,u=u||h.duration||c.duration;if(!t.length)return e.animate(i,u,o,p);if(!e.length)return t.animate(r,u,o,p);s=e.show().outerHeight(),t.animate(r,{duration:u,easing:o,step:function(e,t){t.now=Math.round(e)}}),e.hide().animate(i,{duration:u,easing:o,complete:p,step:function(e,n){n.now=Math.round(e),n.prop!=="height"?f+=n.now:a.options.heightStyle!=="content"&&(n.now=Math.round(s-t.outerHeight()-f),f=0)}})},_toggleComplete:function(e){var t=e.oldPanel;t.removeClass("ui-accordion-content-active").prev().removeClass("ui-corner-top").addClass("ui-corner-all"),t.length&&(t.parent()[0].className=t.parent()[0].className),this._trigger("activate",null,e)}}),e.uiBackCompat!==!1&&(function(e,t){e.extend(t.options,{navigation:!1,navigationFilter:function(){return this.href.toLowerCase()===location.href.toLowerCase()}});var n=t._create;t._create=function(){if(this.options.navigation){var t=this,r=this.element.find(this.options.header),i=r.next(),s=r.add(i).find("a").filter(this.options.navigationFilter)[0];s&&r.add(i).each(function(n){if(e.contains(this,s))return t.options.active=Math.floor(n/2),!1})}n.call(this)}}(jQuery,jQuery.ui.accordion.prototype),function(e,t){e.extend(t.options,{heightStyle:null,autoHeight:!0,clearStyle:!1,fillSpace:!1});var n=t._create,r=t._setOption;e.extend(t,{_create:function(){this.options.heightStyle=this.options.heightStyle||this._mergeHeightStyle(),n.call(this)},_setOption:function(e){if(e==="autoHeight"||e==="clearStyle"||e==="fillSpace")this.options.heightStyle=this._mergeHeightStyle();r.apply(this,arguments)},_mergeHeightStyle:function(){var e=this.options;if(e.fillSpace)return"fill";if(e.clearStyle)return"content";if(e.autoHeight)return"auto"}})}(jQuery,jQuery.ui.accordion.prototype),function(e,t){e.extend(t.options.icons,{activeHeader:null,headerSelected:"ui-icon-triangle-1-s"});var n=t._createIcons;t._createIcons=function(){this.options.icons&&(this.options.icons.activeHeader=this.options.icons.activeHeader||this.options.icons.headerSelected),n.call(this)}}(jQuery,jQuery.ui.accordion.prototype),function(e,t){t.activate=t._activate;var n=t._findActive;t._findActive=function(e){return e===-1&&(e=!1),e&&typeof e!="number"&&(e=this.headers.index(this.headers.filter(e)),e===-1&&(e=!1)),n.call(this,e)}}(jQuery,jQuery.ui.accordion.prototype),jQuery.ui.accordion.prototype.resize=jQuery.ui.accordion.prototype.refresh,function(e,t){e.extend(t.options,{change:null,changestart:null});var n=t._trigger;t._trigger=function(e,t,r){var i=n.apply(this,arguments);return i?(e==="beforeActivate"?i=n.call(this,"changestart",t,{oldHeader:r.oldHeader,oldContent:r.oldPanel,newHeader:r.newHeader,newContent:r.newPanel}):e==="activate"&&(i=n.call(this,"change",t,{oldHeader:r.oldHeader,oldContent:r.oldPanel,newHeader:r.newHeader,newContent:r.newPanel})),i):!1}}(jQuery,jQuery.ui.accordion.prototype),function(e,t){e.extend(t.options,{animate:null,animated:"slide"});var n=t._create;t._create=function(){var e=this.options;e.animate===null&&(e.animated?e.animated==="slide"?e.animate=300:e.animated==="bounceslide"?e.animate={duration:200,down:{easing:"easeOutBounce",duration:1e3}}:e.animate=e.animated:e.animate=!1),n.call(this)}}(jQuery,jQuery.ui.accordion.prototype))})(jQuery);(function(e,t){var n=0;e.widget("ui.autocomplete",{version:"1.9.2",defaultElement:"<input>",options:{appendTo:"body",autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null,change:null,close:null,focus:null,open:null,response:null,search:null,select:null},pending:0,_create:function(){var t,n,r;this.isMultiLine=this._isMultiLine(),this.valueMethod=this.element[this.element.is("input,textarea")?"val":"text"],this.isNewMenu=!0,this.element.addClass("ui-autocomplete-input").attr("autocomplete","off"),this._on(this.element,{keydown:function(i){if(this.element.prop("readOnly")){t=!0,r=!0,n=!0;return}t=!1,r=!1,n=!1;var s=e.ui.keyCode;switch(i.keyCode){case s.PAGE_UP:t=!0,this._move("previousPage",i);break;case s.PAGE_DOWN:t=!0,this._move("nextPage",i);break;case s.UP:t=!0,this._keyEvent("previous",i);break;case s.DOWN:t=!0,this._keyEvent("next",i);break;case s.ENTER:case s.NUMPAD_ENTER:this.menu.active&&(t=!0,i.preventDefault(),this.menu.select(i));break;case s.TAB:this.menu.active&&this.menu.select(i);break;case s.ESCAPE:this.menu.element.is(":visible")&&(this._value(this.term),this.close(i),i.preventDefault());break;default:n=!0,this._searchTimeout(i)}},keypress:function(r){if(t){t=!1,r.preventDefault();return}if(n)return;var i=e.ui.keyCode;switch(r.keyCode){case i.PAGE_UP:this._move("previousPage",r);break;case i.PAGE_DOWN:this._move("nextPage",r);break;case i.UP:this._keyEvent("previous",r);break;case i.DOWN:this._keyEvent("next",r)}},input:function(e){if(r){r=!1,e.preventDefault();return}this._searchTimeout(e)},focus:function(){this.selectedItem=null,this.previous=this._value()},blur:function(e){if(this.cancelBlur){delete this.cancelBlur;return}clearTimeout(this.searching),this.close(e),this._change(e)}}),this._initSource(),this.menu=e("<ul>").addClass("ui-autocomplete").appendTo(this.document.find(this.options.appendTo||"body")[0]).menu({input:e(),role:null}).zIndex(this.element.zIndex()+1).hide().data("menu"),this._on(this.menu.element,{mousedown:function(t){t.preventDefault(),this.cancelBlur=!0,this._delay(function(){delete this.cancelBlur});var n=this.menu.element[0];e(t.target).closest(".ui-menu-item").length||this._delay(function(){var t=this;this.document.one("mousedown",function(r){r.target!==t.element[0]&&r.target!==n&&!e.contains(n,r.target)&&t.close()})})},menufocus:function(t,n){if(this.isNewMenu){this.isNewMenu=!1;if(t.originalEvent&&/^mouse/.test(t.originalEvent.type)){this.menu.blur(),this.document.one("mousemove",function(){e(t.target).trigger(t.originalEvent)});return}}var r=n.item.data("ui-autocomplete-item")||n.item.data("item.autocomplete");!1!==this._trigger("focus",t,{item:r})?t.originalEvent&&/^key/.test(t.originalEvent.type)&&this._value(r.value):this.liveRegion.text(r.value)},menuselect:function(e,t){var n=t.item.data("ui-autocomplete-item")||t.item.data("item.autocomplete"),r=this.previous;this.element[0]!==this.document[0].activeElement&&(this.element.focus(),this.previous=r,this._delay(function(){this.previous=r,this.selectedItem=n})),!1!==this._trigger("select",e,{item:n})&&this._value(n.value),this.term=this._value(),this.close(e),this.selectedItem=n}}),this.liveRegion=e("<span>",{role:"status","aria-live":"polite"}).addClass("ui-helper-hidden-accessible").insertAfter(this.element),e.fn.bgiframe&&this.menu.element.bgiframe(),this._on(this.window,{beforeunload:function(){this.element.removeAttr("autocomplete")}})},_destroy:function(){clearTimeout(this.searching),this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete"),this.menu.element.remove(),this.liveRegion.remove()},_setOption:function(e,t){this._super(e,t),e==="source"&&this._initSource(),e==="appendTo"&&this.menu.element.appendTo(this.document.find(t||"body")[0]),e==="disabled"&&t&&this.xhr&&this.xhr.abort()},_isMultiLine:function(){return this.element.is("textarea")?!0:this.element.is("input")?!1:this.element.prop("isContentEditable")},_initSource:function(){var t,n,r=this;e.isArray(this.options.source)?(t=this.options.source,this.source=function(n,r){r(e.ui.autocomplete.filter(t,n.term))}):typeof this.options.source=="string"?(n=this.options.source,this.source=function(t,i){r.xhr&&r.xhr.abort(),r.xhr=e.ajax({url:n,data:t,dataType:"json",success:function(e){i(e)},error:function(){i([])}})}):this.source=this.options.source},_searchTimeout:function(e){clearTimeout(this.searching),this.searching=this._delay(function(){this.term!==this._value()&&(this.selectedItem=null,this.search(null,e))},this.options.delay)},search:function(e,t){e=e!=null?e:this._value(),this.term=this._value();if(e.length<this.options.minLength)return this.close(t);if(this._trigger("search",t)===!1)return;return this._search(e)},_search:function(e){this.pending++,this.element.addClass("ui-autocomplete-loading"),this.cancelSearch=!1,this.source({term:e},this._response())},_response:function(){var e=this,t=++n;return function(r){t===n&&e.__response(r),e.pending--,e.pending||e.element.removeClass("ui-autocomplete-loading")}},__response:function(e){e&&(e=this._normalize(e)),this._trigger("response",null,{content:e}),!this.options.disabled&&e&&e.length&&!this.cancelSearch?(this._suggest(e),this._trigger("open")):this._close()},close:function(e){this.cancelSearch=!0,this._close(e)},_close:function(e){this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.blur(),this.isNewMenu=!0,this._trigger("close",e))},_change:function(e){this.previous!==this._value()&&this._trigger("change",e,{item:this.selectedItem})},_normalize:function(t){return t.length&&t[0].label&&t[0].value?t:e.map(t,function(t){return typeof t=="string"?{label:t,value:t}:e.extend({label:t.label||t.value,value:t.value||t.label},t)})},_suggest:function(t){var n=this.menu.element.empty().zIndex(this.element.zIndex()+1);this._renderMenu(n,t),this.menu.refresh(),n.show(),this._resizeMenu(),n.position(e.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next()},_resizeMenu:function(){var e=this.menu.element;e.outerWidth(Math.max(e.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(t,n){var r=this;e.each(n,function(e,n){r._renderItemData(t,n)})},_renderItemData:function(e,t){return this._renderItem(e,t).data("ui-autocomplete-item",t)},_renderItem:function(t,n){return e("<li>").append(e("<a>").text(n.label)).appendTo(t)},_move:function(e,t){if(!this.menu.element.is(":visible")){this.search(null,t);return}if(this.menu.isFirstItem()&&/^previous/.test(e)||this.menu.isLastItem()&&/^next/.test(e)){this._value(this.term),this.menu.blur();return}this.menu[e](t)},widget:function(){return this.menu.element},_value:function(){return this.valueMethod.apply(this.element,arguments)},_keyEvent:function(e,t){if(!this.isMultiLine||this.menu.element.is(":visible"))this._move(e,t),t.preventDefault()}}),e.extend(e.ui.autocomplete,{escapeRegex:function(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")},filter:function(t,n){var r=new RegExp(e.ui.autocomplete.escapeRegex(n),"i");return e.grep(t,function(e){return r.test(e.label||e.value||e)})}}),e.widget("ui.autocomplete",e.ui.autocomplete,{options:{messages:{noResults:"No search results.",results:function(e){return e+(e>1?" results are":" result is")+" available, use up and down arrow keys to navigate."}}},__response:function(e){var t;this._superApply(arguments);if(this.options.disabled||this.cancelSearch)return;e&&e.length?t=this.options.messages.results(e.length):t=this.options.messages.noResults,this.liveRegion.text(t)}})})(jQuery);(function(e,t){var n,r,i,s,o="ui-button ui-widget ui-state-default ui-corner-all",u="ui-state-hover ui-state-active ",a="ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",f=function(){var t=e(this).find(":ui-button");setTimeout(function(){t.button("refresh")},1)},l=function(t){var n=t.name,r=t.form,i=e([]);return n&&(r?i=e(r).find("[name='"+n+"']"):i=e("[name='"+n+"']",t.ownerDocument).filter(function(){return!this.form})),i};e.widget("ui.button",{version:"1.9.2",defaultElement:"<button>",options:{disabled:null,text:!0,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset"+this.eventNamespace).bind("reset"+this.eventNamespace,f),typeof this.options.disabled!="boolean"?this.options.disabled=!!this.element.prop("disabled"):this.element.prop("disabled",this.options.disabled),this._determineButtonType(),this.hasTitle=!!this.buttonElement.attr("title");var t=this,u=this.options,a=this.type==="checkbox"||this.type==="radio",c=a?"":"ui-state-active",h="ui-state-focus";u.label===null&&(u.label=this.type==="input"?this.buttonElement.val():this.buttonElement.html()),this._hoverable(this.buttonElement),this.buttonElement.addClass(o).attr("role","button").bind("mouseenter"+this.eventNamespace,function(){if(u.disabled)return;this===n&&e(this).addClass("ui-state-active")}).bind("mouseleave"+this.eventNamespace,function(){if(u.disabled)return;e(this).removeClass(c)}).bind("click"+this.eventNamespace,function(e){u.disabled&&(e.preventDefault(),e.stopImmediatePropagation())}),this.element.bind("focus"+this.eventNamespace,function(){t.buttonElement.addClass(h)}).bind("blur"+this.eventNamespace,function(){t.buttonElement.removeClass(h)}),a&&(this.element.bind("change"+this.eventNamespace,function(){if(s)return;t.refresh()}),this.buttonElement.bind("mousedown"+this.eventNamespace,function(e){if(u.disabled)return;s=!1,r=e.pageX,i=e.pageY}).bind("mouseup"+this.eventNamespace,function(e){if(u.disabled)return;if(r!==e.pageX||i!==e.pageY)s=!0})),this.type==="checkbox"?this.buttonElement.bind("click"+this.eventNamespace,function(){if(u.disabled||s)return!1;e(this).toggleClass("ui-state-active"),t.buttonElement.attr("aria-pressed",t.element[0].checked)}):this.type==="radio"?this.buttonElement.bind("click"+this.eventNamespace,function(){if(u.disabled||s)return!1;e(this).addClass("ui-state-active"),t.buttonElement.attr("aria-pressed","true");var n=t.element[0];l(n).not(n).map(function(){return e(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")}):(this.buttonElement.bind("mousedown"+this.eventNamespace,function(){if(u.disabled)return!1;e(this).addClass("ui-state-active"),n=this,t.document.one("mouseup",function(){n=null})}).bind("mouseup"+this.eventNamespace,function(){if(u.disabled)return!1;e(this).removeClass("ui-state-active")}).bind("keydown"+this.eventNamespace,function(t){if(u.disabled)return!1;(t.keyCode===e.ui.keyCode.SPACE||t.keyCode===e.ui.keyCode.ENTER)&&e(this).addClass("ui-state-active")}).bind("keyup"+this.eventNamespace,function(){e(this).removeClass("ui-state-active")}),this.buttonElement.is("a")&&this.buttonElement.keyup(function(t){t.keyCode===e.ui.keyCode.SPACE&&e(this).click()})),this._setOption("disabled",u.disabled),this._resetButton()},_determineButtonType:function(){var e,t,n;this.element.is("[type=checkbox]")?this.type="checkbox":this.element.is("[type=radio]")?this.type="radio":this.element.is("input")?this.type="input":this.type="button",this.type==="checkbox"||this.type==="radio"?(e=this.element.parents().last(),t="label[for='"+this.element.attr("id")+"']",this.buttonElement=e.find(t),this.buttonElement.length||(e=e.length?e.siblings():this.element.siblings(),this.buttonElement=e.filter(t),this.buttonElement.length||(this.buttonElement=e.find(t))),this.element.addClass("ui-helper-hidden-accessible"),n=this.element.is(":checked"),n&&this.buttonElement.addClass("ui-state-active"),this.buttonElement.prop("aria-pressed",n)):this.buttonElement=this.element},widget:function(){return this.buttonElement},_destroy:function(){this.element.removeClass("ui-helper-hidden-accessible"),this.buttonElement.removeClass(o+" "+u+" "+a).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()),this.hasTitle||this.buttonElement.removeAttr("title")},_setOption:function(e,t){this._super(e,t);if(e==="disabled"){t?this.element.prop("disabled",!0):this.element.prop("disabled",!1);return}this._resetButton()},refresh:function(){var t=this.element.is("input, button")?this.element.is(":disabled"):this.element.hasClass("ui-button-disabled");t!==this.options.disabled&&this._setOption("disabled",t),this.type==="radio"?l(this.element[0]).each(function(){e(this).is(":checked")?e(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true"):e(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}):this.type==="checkbox"&&(this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true"):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false"))},_resetButton:function(){if(this.type==="input"){this.options.label&&this.element.val(this.options.label);return}var t=this.buttonElement.removeClass(a),n=e("<span></span>",this.document[0]).addClass("ui-button-text").html(this.options.label).appendTo(t.empty()).text(),r=this.options.icons,i=r.primary&&r.secondary,s=[];r.primary||r.secondary?(this.options.text&&s.push("ui-button-text-icon"+(i?"s":r.primary?"-primary":"-secondary")),r.primary&&t.prepend("<span class='ui-button-icon-primary ui-icon "+r.primary+"'></span>"),r.secondary&&t.append("<span class='ui-button-icon-secondary ui-icon "+r.secondary+"'></span>"),this.options.text||(s.push(i?"ui-button-icons-only":"ui-button-icon-only"),this.hasTitle||t.attr("title",e.trim(n)))):s.push("ui-button-text-only"),t.addClass(s.join(" "))}}),e.widget("ui.buttonset",{version:"1.9.2",options:{items:"button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(e,t){e==="disabled"&&this.buttons.button("option",e,t),this._super(e,t)},refresh:function(){var t=this.element.css("direction")==="rtl";this.buttons=this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(t?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(t?"ui-corner-left":"ui-corner-right").end().end()},_destroy:function(){this.element.removeClass("ui-buttonset"),this.buttons.map(function(){return e(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy")}})})(jQuery);(function($,undefined){function Datepicker(){this.debug=!1,this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},$.extend(this._defaults,this.regional[""]),this.dpDiv=bindHover($('<div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))}function bindHover(e){var t="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return e.delegate(t,"mouseout",function(){$(this).removeClass("ui-state-hover"),this.className.indexOf("ui-datepicker-prev")!=-1&&$(this).removeClass("ui-datepicker-prev-hover"),this.className.indexOf("ui-datepicker-next")!=-1&&$(this).removeClass("ui-datepicker-next-hover")}).delegate(t,"mouseover",function(){$.datepicker._isDisabledDatepicker(instActive.inline?e.parent()[0]:instActive.input[0])||($(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),$(this).addClass("ui-state-hover"),this.className.indexOf("ui-datepicker-prev")!=-1&&$(this).addClass("ui-datepicker-prev-hover"),this.className.indexOf("ui-datepicker-next")!=-1&&$(this).addClass("ui-datepicker-next-hover"))})}function extendRemove(e,t){$.extend(e,t);for(var n in t)if(t[n]==null||t[n]==undefined)e[n]=t[n];return e}$.extend($.ui,{datepicker:{version:"1.9.2"}});var PROP_NAME="datepicker",dpuuid=(new Date).getTime(),instActive;$.extend(Datepicker.prototype,{markerClassName:"hasDatepicker",maxRows:4,log:function(){this.debug&&console.log.apply("",arguments)},_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(e){return extendRemove(this._defaults,e||{}),this},_attachDatepicker:function(target,settings){var inlineSettings=null;for(var attrName in this._defaults){var attrValue=target.getAttribute("date:"+attrName);if(attrValue){inlineSettings=inlineSettings||{};try{inlineSettings[attrName]=eval(attrValue)}catch(err){inlineSettings[attrName]=attrValue}}}var nodeName=target.nodeName.toLowerCase(),inline=nodeName=="div"||nodeName=="span";target.id||(this.uuid+=1,target.id="dp"+this.uuid);var inst=this._newInst($(target),inline);inst.settings=$.extend({},settings||{},inlineSettings||{}),nodeName=="input"?this._connectDatepicker(target,inst):inline&&this._inlineDatepicker(target,inst)},_newInst:function(e,t){var n=e[0].id.replace(/([^A-Za-z0-9_-])/g,"\\\\$1");return{id:n,input:e,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:t,dpDiv:t?bindHover($('<div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')):this.dpDiv}},_connectDatepicker:function(e,t){var n=$(e);t.append=$([]),t.trigger=$([]);if(n.hasClass(this.markerClassName))return;this._attachments(n,t),n.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker",function(e,n,r){t.settings[n]=r}).bind("getData.datepicker",function(e,n){return this._get(t,n)}),this._autoSize(t),$.data(e,PROP_NAME,t),t.settings.disabled&&this._disableDatepicker(e)},_attachments:function(e,t){var n=this._get(t,"appendText"),r=this._get(t,"isRTL");t.append&&t.append.remove(),n&&(t.append=$('<span class="'+this._appendClass+'">'+n+"</span>"),e[r?"before":"after"](t.append)),e.unbind("focus",this._showDatepicker),t.trigger&&t.trigger.remove();var i=this._get(t,"showOn");(i=="focus"||i=="both")&&e.focus(this._showDatepicker);if(i=="button"||i=="both"){var s=this._get(t,"buttonText"),o=this._get(t,"buttonImage");t.trigger=$(this._get(t,"buttonImageOnly")?$("<img/>").addClass(this._triggerClass).attr({src:o,alt:s,title:s}):$('<button type="button"></button>').addClass(this._triggerClass).html(o==""?s:$("<img/>").attr({src:o,alt:s,title:s}))),e[r?"before":"after"](t.trigger),t.trigger.click(function(){return $.datepicker._datepickerShowing&&$.datepicker._lastInput==e[0]?$.datepicker._hideDatepicker():$.datepicker._datepickerShowing&&$.datepicker._lastInput!=e[0]?($.datepicker._hideDatepicker(),$.datepicker._showDatepicker(e[0])):$.datepicker._showDatepicker(e[0]),!1})}},_autoSize:function(e){if(this._get(e,"autoSize")&&!e.inline){var t=new Date(2009,11,20),n=this._get(e,"dateFormat");if(n.match(/[DM]/)){var r=function(e){var t=0,n=0;for(var r=0;r<e.length;r++)e[r].length>t&&(t=e[r].length,n=r);return n};t.setMonth(r(this._get(e,n.match(/MM/)?"monthNames":"monthNamesShort"))),t.setDate(r(this._get(e,n.match(/DD/)?"dayNames":"dayNamesShort"))+20-t.getDay())}e.input.attr("size",this._formatDate(e,t).length)}},_inlineDatepicker:function(e,t){var n=$(e);if(n.hasClass(this.markerClassName))return;n.addClass(this.markerClassName).append(t.dpDiv).bind("setData.datepicker",function(e,n,r){t.settings[n]=r}).bind("getData.datepicker",function(e,n){return this._get(t,n)}),$.data(e,PROP_NAME,t),this._setDate(t,this._getDefaultDate(t),!0),this._updateDatepicker(t),this._updateAlternate(t),t.settings.disabled&&this._disableDatepicker(e),t.dpDiv.css("display","block")},_dialogDatepicker:function(e,t,n,r,i){var s=this._dialogInst;if(!s){this.uuid+=1;var o="dp"+this.uuid;this._dialogInput=$('<input type="text" id="'+o+'" style="position: absolute; top: -100px; width: 0px;"/>'),this._dialogInput.keydown(this._doKeyDown),$("body").append(this._dialogInput),s=this._dialogInst=this._newInst(this._dialogInput,!1),s.settings={},$.data(this._dialogInput[0],PROP_NAME,s)}extendRemove(s.settings,r||{}),t=t&&t.constructor==Date?this._formatDate(s,t):t,this._dialogInput.val(t),this._pos=i?i.length?i:[i.pageX,i.pageY]:null;if(!this._pos){var u=document.documentElement.clientWidth,a=document.documentElement.clientHeight,f=document.documentElement.scrollLeft||document.body.scrollLeft,l=document.documentElement.scrollTop||document.body.scrollTop;this._pos=[u/2-100+f,a/2-150+l]}return this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),s.settings.onSelect=n,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),$.blockUI&&$.blockUI(this.dpDiv),$.data(this._dialogInput[0],PROP_NAME,s),this},_destroyDatepicker:function(e){var t=$(e),n=$.data(e,PROP_NAME);if(!t.hasClass(this.markerClassName))return;var r=e.nodeName.toLowerCase();$.removeData(e,PROP_NAME),r=="input"?(n.append.remove(),n.trigger.remove(),t.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):(r=="div"||r=="span")&&t.removeClass(this.markerClassName).empty()},_enableDatepicker:function(e){var t=$(e),n=$.data(e,PROP_NAME);if(!t.hasClass(this.markerClassName))return;var r=e.nodeName.toLowerCase();if(r=="input")e.disabled=!1,n.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""});else if(r=="div"||r=="span"){var i=t.children("."+this._inlineClass);i.children().removeClass("ui-state-disabled"),i.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!1)}this._disabledInputs=$.map(this._disabledInputs,function(t){return t==e?null:t})},_disableDatepicker:function(e){var t=$(e),n=$.data(e,PROP_NAME);if(!t.hasClass(this.markerClassName))return;var r=e.nodeName.toLowerCase();if(r=="input")e.disabled=!0,n.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"});else if(r=="div"||r=="span"){var i=t.children("."+this._inlineClass);i.children().addClass("ui-state-disabled"),i.find("select.ui-datepicker-month, select.ui-datepicker-year").prop("disabled",!0)}this._disabledInputs=$.map(this._disabledInputs,function(t){return t==e?null:t}),this._disabledInputs[this._disabledInputs.length]=e},_isDisabledDatepicker:function(e){if(!e)return!1;for(var t=0;t<this._disabledInputs.length;t++)if(this._disabledInputs[t]==e)return!0;return!1},_getInst:function(e){try{return $.data(e,PROP_NAME)}catch(t){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(e,t,n){var r=this._getInst(e);if(arguments.length==2&&typeof t=="string")return t=="defaults"?$.extend({},$.datepicker._defaults):r?t=="all"?$.extend({},r.settings):this._get(r,t):null;var i=t||{};typeof t=="string"&&(i={},i[t]=n);if(r){this._curInst==r&&this._hideDatepicker();var s=this._getDateDatepicker(e,!0),o=this._getMinMaxDate(r,"min"),u=this._getMinMaxDate(r,"max");extendRemove(r.settings,i),o!==null&&i.dateFormat!==undefined&&i.minDate===undefined&&(r.settings.minDate=this._formatDate(r,o)),u!==null&&i.dateFormat!==undefined&&i.maxDate===undefined&&(r.settings.maxDate=this._formatDate(r,u)),this._attachments($(e),r),this._autoSize(r),this._setDate(r,s),this._updateAlternate(r),this._updateDatepicker(r)}},_changeDatepicker:function(e,t,n){this._optionDatepicker(e,t,n)},_refreshDatepicker:function(e){var t=this._getInst(e);t&&this._updateDatepicker(t)},_setDateDatepicker:function(e,t){var n=this._getInst(e);n&&(this._setDate(n,t),this._updateDatepicker(n),this._updateAlternate(n))},_getDateDatepicker:function(e,t){var n=this._getInst(e);return n&&!n.inline&&this._setDateFromField(n,t),n?this._getDate(n):null},_doKeyDown:function(e){var t=$.datepicker._getInst(e.target),n=!0,r=t.dpDiv.is(".ui-datepicker-rtl");t._keyEvent=!0;if($.datepicker._datepickerShowing)switch(e.keyCode){case 9:$.datepicker._hideDatepicker(),n=!1;break;case 13:var i=$("td."+$.datepicker._dayOverClass+":not(."+$.datepicker._currentClass+")",t.dpDiv);i[0]&&$.datepicker._selectDay(e.target,t.selectedMonth,t.selectedYear,i[0]);var s=$.datepicker._get(t,"onSelect");if(s){var o=$.datepicker._formatDate(t);s.apply(t.input?t.input[0]:null,[o,t])}else $.datepicker._hideDatepicker();return!1;case 27:$.datepicker._hideDatepicker();break;case 33:$.datepicker._adjustDate(e.target,e.ctrlKey?-$.datepicker._get(t,"stepBigMonths"):-$.datepicker._get(t,"stepMonths"),"M");break;case 34:$.datepicker._adjustDate(e.target,e.ctrlKey?+$.datepicker._get(t,"stepBigMonths"):+$.datepicker._get(t,"stepMonths"),"M");break;case 35:(e.ctrlKey||e.metaKey)&&$.datepicker._clearDate(e.target),n=e.ctrlKey||e.metaKey;break;case 36:(e.ctrlKey||e.metaKey)&&$.datepicker._gotoToday(e.target),n=e.ctrlKey||e.metaKey;break;case 37:(e.ctrlKey||e.metaKey)&&$.datepicker._adjustDate(e.target,r?1:-1,"D"),n=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&$.datepicker._adjustDate(e.target,e.ctrlKey?-$.datepicker._get(t,"stepBigMonths"):-$.datepicker._get(t,"stepMonths"),"M");break;case 38:(e.ctrlKey||e.metaKey)&&$.datepicker._adjustDate(e.target,-7,"D"),n=e.ctrlKey||e.metaKey;break;case 39:(e.ctrlKey||e.metaKey)&&$.datepicker._adjustDate(e.target,r?-1:1,"D"),n=e.ctrlKey||e.metaKey,e.originalEvent.altKey&&$.datepicker._adjustDate(e.target,e.ctrlKey?+$.datepicker._get(t,"stepBigMonths"):+$.datepicker._get(t,"stepMonths"),"M");break;case 40:(e.ctrlKey||e.metaKey)&&$.datepicker._adjustDate(e.target,7,"D"),n=e.ctrlKey||e.metaKey;break;default:n=!1}else e.keyCode==36&&e.ctrlKey?$.datepicker._showDatepicker(this):n=!1;n&&(e.preventDefault(),e.stopPropagation())},_doKeyPress:function(e){var t=$.datepicker._getInst(e.target);if($.datepicker._get(t,"constrainInput")){var n=$.datepicker._possibleChars($.datepicker._get(t,"dateFormat")),r=String.fromCharCode(e.charCode==undefined?e.keyCode:e.charCode);return e.ctrlKey||e.metaKey||r<" "||!n||n.indexOf(r)>-1}},_doKeyUp:function(e){var t=$.datepicker._getInst(e.target);if(t.input.val()!=t.lastVal)try{var n=$.datepicker.parseDate($.datepicker._get(t,"dateFormat"),t.input?t.input.val():null,$.datepicker._getFormatConfig(t));n&&($.datepicker._setDateFromField(t),$.datepicker._updateAlternate(t),$.datepicker._updateDatepicker(t))}catch(r){$.datepicker.log(r)}return!0},_showDatepicker:function(e){e=e.target||e,e.nodeName.toLowerCase()!="input"&&(e=$("input",e.parentNode)[0]);if($.datepicker._isDisabledDatepicker(e)||$.datepicker._lastInput==e)return;var t=$.datepicker._getInst(e);$.datepicker._curInst&&$.datepicker._curInst!=t&&($.datepicker._curInst.dpDiv.stop(!0,!0),t&&$.datepicker._datepickerShowing&&$.datepicker._hideDatepicker($.datepicker._curInst.input[0]));var n=$.datepicker._get(t,"beforeShow"),r=n?n.apply(e,[e,t]):{};if(r===!1)return;extendRemove(t.settings,r),t.lastVal=null,$.datepicker._lastInput=e,$.datepicker._setDateFromField(t),$.datepicker._inDialog&&(e.value=""),$.datepicker._pos||($.datepicker._pos=$.datepicker._findPos(e),$.datepicker._pos[1]+=e.offsetHeight);var i=!1;$(e).parents().each(function(){return i|=$(this).css("position")=="fixed",!i});var s={left:$.datepicker._pos[0],top:$.datepicker._pos[1]};$.datepicker._pos=null,t.dpDiv.empty(),t.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),$.datepicker._updateDatepicker(t),s=$.datepicker._checkOffset(t,s,i),t.dpDiv.css({position:$.datepicker._inDialog&&$.blockUI?"static":i?"fixed":"absolute",display:"none",left:s.left+"px",top:s.top+"px"});if(!t.inline){var o=$.datepicker._get(t,"showAnim"),u=$.datepicker._get(t,"duration"),a=function(){var e=t.dpDiv.find("iframe.ui-datepicker-cover");if(!!e.length){var n=$.datepicker._getBorders(t.dpDiv);e.css({left:-n[0],top:-n[1],width:t.dpDiv.outerWidth(),height:t.dpDiv.outerHeight()})}};t.dpDiv.zIndex($(e).zIndex()+1),$.datepicker._datepickerShowing=!0,$.effects&&($.effects.effect[o]||$.effects[o])?t.dpDiv.show(o,$.datepicker._get(t,"showOptions"),u,a):t.dpDiv[o||"show"](o?u:null,a),(!o||!u)&&a(),t.input.is(":visible")&&!t.input.is(":disabled")&&t.input.focus(),$.datepicker._curInst=t}},_updateDatepicker:function(e){this.maxRows=4;var t=$.datepicker._getBorders(e.dpDiv);instActive=e,e.dpDiv.empty().append(this._generateHTML(e)),this._attachHandlers(e);var n=e.dpDiv.find("iframe.ui-datepicker-cover");!n.length||n.css({left:-t[0],top:-t[1],width:e.dpDiv.outerWidth(),height:e.dpDiv.outerHeight()}),e.dpDiv.find("."+this._dayOverClass+" a").mouseover();var r=this._getNumberOfMonths(e),i=r[1],s=17;e.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),i>1&&e.dpDiv.addClass("ui-datepicker-multi-"+i).css("width",s*i+"em"),e.dpDiv[(r[0]!=1||r[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi"),e.dpDiv[(this._get(e,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),e==$.datepicker._curInst&&$.datepicker._datepickerShowing&&e.input&&e.input.is(":visible")&&!e.input.is(":disabled")&&e.input[0]!=document.activeElement&&e.input.focus();if(e.yearshtml){var o=e.yearshtml;setTimeout(function(){o===e.yearshtml&&e.yearshtml&&e.dpDiv.find("select.ui-datepicker-year:first").replaceWith(e.yearshtml),o=e.yearshtml=null},0)}},_getBorders:function(e){var t=function(e){return{thin:1,medium:2,thick:3}[e]||e};return[parseFloat(t(e.css("border-left-width"))),parseFloat(t(e.css("border-top-width")))]},_checkOffset:function(e,t,n){var r=e.dpDiv.outerWidth(),i=e.dpDiv.outerHeight(),s=e.input?e.input.outerWidth():0,o=e.input?e.input.outerHeight():0,u=document.documentElement.clientWidth+(n?0:$(document).scrollLeft()),a=document.documentElement.clientHeight+(n?0:$(document).scrollTop());return t.left-=this._get(e,"isRTL")?r-s:0,t.left-=n&&t.left==e.input.offset().left?$(document).scrollLeft():0,t.top-=n&&t.top==e.input.offset().top+o?$(document).scrollTop():0,t.left-=Math.min(t.left,t.left+r>u&&u>r?Math.abs(t.left+r-u):0),t.top-=Math.min(t.top,t.top+i>a&&a>i?Math.abs(i+o):0),t},_findPos:function(e){var t=this._getInst(e),n=this._get(t,"isRTL");while(e&&(e.type=="hidden"||e.nodeType!=1||$.expr.filters.hidden(e)))e=e[n?"previousSibling":"nextSibling"];var r=$(e).offset();return[r.left,r.top]},_hideDatepicker:function(e){var t=this._curInst;if(!t||e&&t!=$.data(e,PROP_NAME))return;if(this._datepickerShowing){var n=this._get(t,"showAnim"),r=this._get(t,"duration"),i=function(){$.datepicker._tidyDialog(t)};$.effects&&($.effects.effect[n]||$.effects[n])?t.dpDiv.hide(n,$.datepicker._get(t,"showOptions"),r,i):t.dpDiv[n=="slideDown"?"slideUp":n=="fadeIn"?"fadeOut":"hide"](n?r:null,i),n||i(),this._datepickerShowing=!1;var s=this._get(t,"onClose");s&&s.apply(t.input?t.input[0]:null,[t.input?t.input.val():"",t]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),$.blockUI&&($.unblockUI(),$("body").append(this.dpDiv))),this._inDialog=!1}},_tidyDialog:function(e){e.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(e){if(!$.datepicker._curInst)return;var t=$(e.target),n=$.datepicker._getInst(t[0]);(t[0].id!=$.datepicker._mainDivId&&t.parents("#"+$.datepicker._mainDivId).length==0&&!t.hasClass($.datepicker.markerClassName)&&!t.closest("."+$.datepicker._triggerClass).length&&$.datepicker._datepickerShowing&&(!$.datepicker._inDialog||!$.blockUI)||t.hasClass($.datepicker.markerClassName)&&$.datepicker._curInst!=n)&&$.datepicker._hideDatepicker()},_adjustDate:function(e,t,n){var r=$(e),i=this._getInst(r[0]);if(this._isDisabledDatepicker(r[0]))return;this._adjustInstDate(i,t+(n=="M"?this._get(i,"showCurrentAtPos"):0),n),this._updateDatepicker(i)},_gotoToday:function(e){var t=$(e),n=this._getInst(t[0]);if(this._get(n,"gotoCurrent")&&n.currentDay)n.selectedDay=n.currentDay,n.drawMonth=n.selectedMonth=n.currentMonth,n.drawYear=n.selectedYear=n.currentYear;else{var r=new Date;n.selectedDay=r.getDate(),n.drawMonth=n.selectedMonth=r.getMonth(),n.drawYear=n.selectedYear=r.getFullYear()}this._notifyChange(n),this._adjustDate(t)},_selectMonthYear:function(e,t,n){var r=$(e),i=this._getInst(r[0]);i["selected"+(n=="M"?"Month":"Year")]=i["draw"+(n=="M"?"Month":"Year")]=parseInt(t.options[t.selectedIndex].value,10),this._notifyChange(i),this._adjustDate(r)},_selectDay:function(e,t,n,r){var i=$(e);if($(r).hasClass(this._unselectableClass)||this._isDisabledDatepicker(i[0]))return;var s=this._getInst(i[0]);s.selectedDay=s.currentDay=$("a",r).html(),s.selectedMonth=s.currentMonth=t,s.selectedYear=s.currentYear=n,this._selectDate(e,this._formatDate(s,s.currentDay,s.currentMonth,s.currentYear))},_clearDate:function(e){var t=$(e),n=this._getInst(t[0]);this._selectDate(t,"")},_selectDate:function(e,t){var n=$(e),r=this._getInst(n[0]);t=t!=null?t:this._formatDate(r),r.input&&r.input.val(t),this._updateAlternate(r);var i=this._get(r,"onSelect");i?i.apply(r.input?r.input[0]:null,[t,r]):r.input&&r.input.trigger("change"),r.inline?this._updateDatepicker(r):(this._hideDatepicker(),this._lastInput=r.input[0],typeof r.input[0]!="object"&&r.input.focus(),this._lastInput=null)},_updateAlternate:function(e){var t=this._get(e,"altField");if(t){var n=this._get(e,"altFormat")||this._get(e,"dateFormat"),r=this._getDate(e),i=this.formatDate(n,r,this._getFormatConfig(e));$(t).each(function(){$(this).val(i)})}},noWeekends:function(e){var t=e.getDay();return[t>0&&t<6,""]},iso8601Week:function(e){var t=new Date(e.getTime());t.setDate(t.getDate()+4-(t.getDay()||7));var n=t.getTime();return t.setMonth(0),t.setDate(1),Math.floor(Math.round((n-t)/864e5)/7)+1},parseDate:function(e,t,n){if(e==null||t==null)throw"Invalid arguments";t=typeof t=="object"?t.toString():t+"";if(t=="")return null;var r=(n?n.shortYearCutoff:null)||this._defaults.shortYearCutoff;r=typeof r!="string"?r:(new Date).getFullYear()%100+parseInt(r,10);var i=(n?n.dayNamesShort:null)||this._defaults.dayNamesShort,s=(n?n.dayNames:null)||this._defaults.dayNames,o=(n?n.monthNamesShort:null)||this._defaults.monthNamesShort,u=(n?n.monthNames:null)||this._defaults.monthNames,a=-1,f=-1,l=-1,c=-1,h=!1,p=function(t){var n=y+1<e.length&&e.charAt(y+1)==t;return n&&y++,n},d=function(e){var n=p(e),r=e=="@"?14:e=="!"?20:e=="y"&&n?4:e=="o"?3:2,i=new RegExp("^\\d{1,"+r+"}"),s=t.substring(g).match(i);if(!s)throw"Missing number at position "+g;return g+=s[0].length,parseInt(s[0],10)},v=function(e,n,r){var i=$.map(p(e)?r:n,function(e,t){return[[t,e]]}).sort(function(e,t){return-(e[1].length-t[1].length)}),s=-1;$.each(i,function(e,n){var r=n[1];if(t.substr(g,r.length).toLowerCase()==r.toLowerCase())return s=n[0],g+=r.length,!1});if(s!=-1)return s+1;throw"Unknown name at position "+g},m=function(){if(t.charAt(g)!=e.charAt(y))throw"Unexpected literal at position "+g;g++},g=0;for(var y=0;y<e.length;y++)if(h)e.charAt(y)=="'"&&!p("'")?h=!1:m();else switch(e.charAt(y)){case"d":l=d("d");break;case"D":v("D",i,s);break;case"o":c=d("o");break;case"m":f=d("m");break;case"M":f=v("M",o,u);break;case"y":a=d("y");break;case"@":var b=new Date(d("@"));a=b.getFullYear(),f=b.getMonth()+1,l=b.getDate();break;case"!":var b=new Date((d("!")-this._ticksTo1970)/1e4);a=b.getFullYear(),f=b.getMonth()+1,l=b.getDate();break;case"'":p("'")?m():h=!0;break;default:m()}if(g<t.length){var w=t.substr(g);if(!/^\s+/.test(w))throw"Extra/unparsed characters found in date: "+w}a==-1?a=(new Date).getFullYear():a<100&&(a+=(new Date).getFullYear()-(new Date).getFullYear()%100+(a<=r?0:-100));if(c>-1){f=1,l=c;do{var E=this._getDaysInMonth(a,f-1);if(l<=E)break;f++,l-=E}while(!0)}var b=this._daylightSavingAdjust(new Date(a,f-1,l));if(b.getFullYear()!=a||b.getMonth()+1!=f||b.getDate()!=l)throw"Invalid date";return b},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*24*60*60*1e7,formatDate:function(e,t,n){if(!t)return"";var r=(n?n.dayNamesShort:null)||this._defaults.dayNamesShort,i=(n?n.dayNames:null)||this._defaults.dayNames,s=(n?n.monthNamesShort:null)||this._defaults.monthNamesShort,o=(n?n.monthNames:null)||this._defaults.monthNames,u=function(t){var n=h+1<e.length&&e.charAt(h+1)==t;return n&&h++,n},a=function(e,t,n){var r=""+t;if(u(e))while(r.length<n)r="0"+r;return r},f=function(e,t,n,r){return u(e)?r[t]:n[t]},l="",c=!1;if(t)for(var h=0;h<e.length;h++)if(c)e.charAt(h)=="'"&&!u("'")?c=!1:l+=e.charAt(h);else switch(e.charAt(h)){case"d":l+=a("d",t.getDate(),2);break;case"D":l+=f("D",t.getDay(),r,i);break;case"o":l+=a("o",Math.round(((new Date(t.getFullYear(),t.getMonth(),t.getDate())).getTime()-(new Date(t.getFullYear(),0,0)).getTime())/864e5),3);break;case"m":l+=a("m",t.getMonth()+1,2);break;case"M":l+=f("M",t.getMonth(),s,o);break;case"y":l+=u("y")?t.getFullYear():(t.getYear()%100<10?"0":"")+t.getYear()%100;break;case"@":l+=t.getTime();break;case"!":l+=t.getTime()*1e4+this._ticksTo1970;break;case"'":u("'")?l+="'":c=!0;break;default:l+=e.charAt(h)}return l},_possibleChars:function(e){var t="",n=!1,r=function(t){var n=i+1<e.length&&e.charAt(i+1)==t;return n&&i++,n};for(var i=0;i<e.length;i++)if(n)e.charAt(i)=="'"&&!r("'")?n=!1:t+=e.charAt(i);else switch(e.charAt(i)){case"d":case"m":case"y":case"@":t+="0123456789";break;case"D":case"M":return null;case"'":r("'")?t+="'":n=!0;break;default:t+=e.charAt(i)}return t},_get:function(e,t){return e.settings[t]!==undefined?e.settings[t]:this._defaults[t]},_setDateFromField:function(e,t){if(e.input.val()==e.lastVal)return;var n=this._get(e,"dateFormat"),r=e.lastVal=e.input?e.input.val():null,i,s;i=s=this._getDefaultDate(e);var o=this._getFormatConfig(e);try{i=this.parseDate(n,r,o)||s}catch(u){this.log(u),r=t?"":r}e.selectedDay=i.getDate(),e.drawMonth=e.selectedMonth=i.getMonth(),e.drawYear=e.selectedYear=i.getFullYear(),e.currentDay=r?i.getDate():0,e.currentMonth=r?i.getMonth():0,e.currentYear=r?i.getFullYear():0,this._adjustInstDate(e)},_getDefaultDate:function(e){return this._restrictMinMax(e,this._determineDate(e,this._get(e,"defaultDate"),new Date))},_determineDate:function(e,t,n){var r=function(e){var t=new Date;return t.setDate(t.getDate()+e),t},i=function(t){try{return $.datepicker.parseDate($.datepicker._get(e,"dateFormat"),t,$.datepicker._getFormatConfig(e))}catch(n){}var r=(t.toLowerCase().match(/^c/)?$.datepicker._getDate(e):null)||new Date,i=r.getFullYear(),s=r.getMonth(),o=r.getDate(),u=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,a=u.exec(t);while(a){switch(a[2]||"d"){case"d":case"D":o+=parseInt(a[1],10);break;case"w":case"W":o+=parseInt(a[1],10)*7;break;case"m":case"M":s+=parseInt(a[1],10),o=Math.min(o,$.datepicker._getDaysInMonth(i,s));break;case"y":case"Y":i+=parseInt(a[1],10),o=Math.min(o,$.datepicker._getDaysInMonth(i,s))}a=u.exec(t)}return new Date(i,s,o)},s=t==null||t===""?n:typeof t=="string"?i(t):typeof t=="number"?isNaN(t)?n:r(t):new Date(t.getTime());return s=s&&s.toString()=="Invalid Date"?n:s,s&&(s.setHours(0),s.setMinutes(0),s.setSeconds(0),s.setMilliseconds(0)),this._daylightSavingAdjust(s)},_daylightSavingAdjust:function(e){return e?(e.setHours(e.getHours()>12?e.getHours()+2:0),e):null},_setDate:function(e,t,n){var r=!t,i=e.selectedMonth,s=e.selectedYear,o=this._restrictMinMax(e,this._determineDate(e,t,new Date));e.selectedDay=e.currentDay=o.getDate(),e.drawMonth=e.selectedMonth=e.currentMonth=o.getMonth(),e.drawYear=e.selectedYear=e.currentYear=o.getFullYear(),(i!=e.selectedMonth||s!=e.selectedYear)&&!n&&this._notifyChange(e),this._adjustInstDate(e),e.input&&e.input.val(r?"":this._formatDate(e))},_getDate:function(e){var t=!e.currentYear||e.input&&e.input.val()==""?null:this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return t},_attachHandlers:function(e){var t=this._get(e,"stepMonths"),n="#"+e.id.replace(/\\\\/g,"\\");e.dpDiv.find("[data-handler]").map(function(){var e={prev:function(){window["DP_jQuery_"+dpuuid].datepicker._adjustDate(n,-t,"M")},next:function(){window["DP_jQuery_"+dpuuid].datepicker._adjustDate(n,+t,"M")},hide:function(){window["DP_jQuery_"+dpuuid].datepicker._hideDatepicker()},today:function(){window["DP_jQuery_"+dpuuid].datepicker._gotoToday(n)},selectDay:function(){return window["DP_jQuery_"+dpuuid].datepicker._selectDay(n,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this),!1},selectMonth:function(){return window["DP_jQuery_"+dpuuid].datepicker._selectMonthYear(n,this,"M"),!1},selectYear:function(){return window["DP_jQuery_"+dpuuid].datepicker._selectMonthYear(n,this,"Y"),!1}};$(this).bind(this.getAttribute("data-event"),e[this.getAttribute("data-handler")])})},_generateHTML:function(e){var t=new Date;t=this._daylightSavingAdjust(new Date(t.getFullYear(),t.getMonth(),t.getDate()));var n=this._get(e,"isRTL"),r=this._get(e,"showButtonPanel"),i=this._get(e,"hideIfNoPrevNext"),s=this._get(e,"navigationAsDateFormat"),o=this._getNumberOfMonths(e),u=this._get(e,"showCurrentAtPos"),a=this._get(e,"stepMonths"),f=o[0]!=1||o[1]!=1,l=this._daylightSavingAdjust(e.currentDay?new Date(e.currentYear,e.currentMonth,e.currentDay):new Date(9999,9,9)),c=this._getMinMaxDate(e,"min"),h=this._getMinMaxDate(e,"max"),p=e.drawMonth-u,d=e.drawYear;p<0&&(p+=12,d--);if(h){var v=this._daylightSavingAdjust(new Date(h.getFullYear(),h.getMonth()-o[0]*o[1]+1,h.getDate()));v=c&&v<c?c:v;while(this._daylightSavingAdjust(new Date(d,p,1))>v)p--,p<0&&(p=11,d--)}e.drawMonth=p,e.drawYear=d;var m=this._get(e,"prevText");m=s?this.formatDate(m,this._daylightSavingAdjust(new Date(d,p-a,1)),this._getFormatConfig(e)):m;var g=this._canAdjustMonth(e,-1,d,p)?'<a class="ui-datepicker-prev ui-corner-all" data-handler="prev" data-event="click" title="'+m+'"><span class="ui-icon ui-icon-circle-triangle-'+(n?"e":"w")+'">'+m+"</span></a>":i?"":'<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+m+'"><span class="ui-icon ui-icon-circle-triangle-'+(n?"e":"w")+'">'+m+"</span></a>",y=this._get(e,"nextText");y=s?this.formatDate(y,this._daylightSavingAdjust(new Date(d,p+a,1)),this._getFormatConfig(e)):y;var b=this._canAdjustMonth(e,1,d,p)?'<a class="ui-datepicker-next ui-corner-all" data-handler="next" data-event="click" title="'+y+'"><span class="ui-icon ui-icon-circle-triangle-'+(n?"w":"e")+'">'+y+"</span></a>":i?"":'<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+y+'"><span class="ui-icon ui-icon-circle-triangle-'+(n?"w":"e")+'">'+y+"</span></a>",w=this._get(e,"currentText"),E=this._get(e,"gotoCurrent")&&e.currentDay?l:t;w=s?this.formatDate(w,E,this._getFormatConfig(e)):w;var S=e.inline?"":'<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">'+this._get(e,"closeText")+"</button>",x=r?'<div class="ui-datepicker-buttonpane ui-widget-content">'+(n?S:"")+(this._isInRange(e,E)?'<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" data-handler="today" data-event="click">'+w+"</button>":"")+(n?"":S)+"</div>":"",T=parseInt(this._get(e,"firstDay"),10);T=isNaN(T)?0:T;var N=this._get(e,"showWeek"),C=this._get(e,"dayNames"),k=this._get(e,"dayNamesShort"),L=this._get(e,"dayNamesMin"),A=this._get(e,"monthNames"),O=this._get(e,"monthNamesShort"),M=this._get(e,"beforeShowDay"),_=this._get(e,"showOtherMonths"),D=this._get(e,"selectOtherMonths"),P=this._get(e,"calculateWeek")||this.iso8601Week,H=this._getDefaultDate(e),B="";for(var j=0;j<o[0];j++){var F="";this.maxRows=4;for(var I=0;I<o[1];I++){var q=this._daylightSavingAdjust(new Date(d,p,e.selectedDay)),R=" ui-corner-all",U="";if(f){U+='<div class="ui-datepicker-group';if(o[1]>1)switch(I){case 0:U+=" ui-datepicker-group-first",R=" ui-corner-"+(n?"right":"left");break;case o[1]-1:U+=" ui-datepicker-group-last",R=" ui-corner-"+(n?"left":"right");break;default:U+=" ui-datepicker-group-middle",R=""}U+='">'}U+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+R+'">'+(/all|left/.test(R)&&j==0?n?b:g:"")+(/all|right/.test(R)&&j==0?n?g:b:"")+this._generateMonthYearHeader(e,p,d,c,h,j>0||I>0,A,O)+'</div><table class="ui-datepicker-calendar"><thead>'+"<tr>";var z=N?'<th class="ui-datepicker-week-col">'+this._get(e,"weekHeader")+"</th>":"";for(var W=0;W<7;W++){var X=(W+T)%7;z+="<th"+((W+T+6)%7>=5?' class="ui-datepicker-week-end"':"")+">"+'<span title="'+C[X]+'">'+L[X]+"</span></th>"}U+=z+"</tr></thead><tbody>";var V=this._getDaysInMonth(d,p);d==e.selectedYear&&p==e.selectedMonth&&(e.selectedDay=Math.min(e.selectedDay,V));var J=(this._getFirstDayOfMonth(d,p)-T+7)%7,K=Math.ceil((J+V)/7),Q=f?this.maxRows>K?this.maxRows:K:K;this.maxRows=Q;var G=this._daylightSavingAdjust(new Date(d,p,1-J));for(var Y=0;Y<Q;Y++){U+="<tr>";var Z=N?'<td class="ui-datepicker-week-col">'+this._get(e,"calculateWeek")(G)+"</td>":"";for(var W=0;W<7;W++){var et=M?M.apply(e.input?e.input[0]:null,[G]):[!0,""],tt=G.getMonth()!=p,nt=tt&&!D||!et[0]||c&&G<c||h&&G>h;Z+='<td class="'+((W+T+6)%7>=5?" ui-datepicker-week-end":"")+(tt?" ui-datepicker-other-month":"")+(G.getTime()==q.getTime()&&p==e.selectedMonth&&e._keyEvent||H.getTime()==G.getTime()&&H.getTime()==q.getTime()?" "+this._dayOverClass:"")+(nt?" "+this._unselectableClass+" ui-state-disabled":"")+(tt&&!_?"":" "+et[1]+(G.getTime()==l.getTime()?" "+this._currentClass:"")+(G.getTime()==t.getTime()?" ui-datepicker-today":""))+'"'+((!tt||_)&&et[2]?' title="'+et[2]+'"':"")+(nt?"":' data-handler="selectDay" data-event="click" data-month="'+G.getMonth()+'" data-year="'+G.getFullYear()+'"')+">"+(tt&&!_?"&#xa0;":nt?'<span class="ui-state-default">'+G.getDate()+"</span>":'<a class="ui-state-default'+(G.getTime()==t.getTime()?" ui-state-highlight":"")+(G.getTime()==l.getTime()?" ui-state-active":"")+(tt?" ui-priority-secondary":"")+'" href="#">'+G.getDate()+"</a>")+"</td>",G.setDate(G.getDate()+1),G=this._daylightSavingAdjust(G)}U+=Z+"</tr>"}p++,p>11&&(p=0,d++),U+="</tbody></table>"+(f?"</div>"+(o[0]>0&&I==o[1]-1?'<div class="ui-datepicker-row-break"></div>':""):""),F+=U}B+=F}return B+=x+($.ui.ie6&&!e.inline?'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>':""),e._keyEvent=!1,B},_generateMonthYearHeader:function(e,t,n,r,i,s,o,u){var a=this._get(e,"changeMonth"),f=this._get(e,"changeYear"),l=this._get(e,"showMonthAfterYear"),c='<div class="ui-datepicker-title">',h="";if(s||!a)h+='<span class="ui-datepicker-month">'+o[t]+"</span>";else{var p=r&&r.getFullYear()==n,d=i&&i.getFullYear()==n;h+='<select class="ui-datepicker-month" data-handler="selectMonth" data-event="change">';for(var v=0;v<12;v++)(!p||v>=r.getMonth())&&(!d||v<=i.getMonth())&&(h+='<option value="'+v+'"'+(v==t?' selected="selected"':"")+">"+u[v]+"</option>");h+="</select>"}l||(c+=h+(s||!a||!f?"&#xa0;":""));if(!e.yearshtml){e.yearshtml="";if(s||!f)c+='<span class="ui-datepicker-year">'+n+"</span>";else{var m=this._get(e,"yearRange").split(":"),g=(new Date).getFullYear(),y=function(e){var t=e.match(/c[+-].*/)?n+parseInt(e.substring(1),10):e.match(/[+-].*/)?g+parseInt(e,10):parseInt(e,10);return isNaN(t)?g:t},b=y(m[0]),w=Math.max(b,y(m[1]||""));b=r?Math.max(b,r.getFullYear()):b,w=i?Math.min(w,i.getFullYear()):w,e.yearshtml+='<select class="ui-datepicker-year" data-handler="selectYear" data-event="change">';for(;b<=w;b++)e.yearshtml+='<option value="'+b+'"'+(b==n?' selected="selected"':"")+">"+b+"</option>";e.yearshtml+="</select>",c+=e.yearshtml,e.yearshtml=null}}return c+=this._get(e,"yearSuffix"),l&&(c+=(s||!a||!f?"&#xa0;":"")+h),c+="</div>",c},_adjustInstDate:function(e,t,n){var r=e.drawYear+(n=="Y"?t:0),i=e.drawMonth+(n=="M"?t:0),s=Math.min(e.selectedDay,this._getDaysInMonth(r,i))+(n=="D"?t:0),o=this._restrictMinMax(e,this._daylightSavingAdjust(new Date(r,i,s)));e.selectedDay=o.getDate(),e.drawMonth=e.selectedMonth=o.getMonth(),e.drawYear=e.selectedYear=o.getFullYear(),(n=="M"||n=="Y")&&this._notifyChange(e)},_restrictMinMax:function(e,t){var n=this._getMinMaxDate(e,"min"),r=this._getMinMaxDate(e,"max"),i=n&&t<n?n:t;return i=r&&i>r?r:i,i},_notifyChange:function(e){var t=this._get(e,"onChangeMonthYear");t&&t.apply(e.input?e.input[0]:null,[e.selectedYear,e.selectedMonth+1,e])},_getNumberOfMonths:function(e){var t=this._get(e,"numberOfMonths");return t==null?[1,1]:typeof t=="number"?[1,t]:t},_getMinMaxDate:function(e,t){return this._determineDate(e,this._get(e,t+"Date"),null)},_getDaysInMonth:function(e,t){return 32-this._daylightSavingAdjust(new Date(e,t,32)).getDate()},_getFirstDayOfMonth:function(e,t){return(new Date(e,t,1)).getDay()},_canAdjustMonth:function(e,t,n,r){var i=this._getNumberOfMonths(e),s=this._daylightSavingAdjust(new Date(n,r+(t<0?t:i[0]*i[1]),1));return t<0&&s.setDate(this._getDaysInMonth(s.getFullYear(),s.getMonth())),this._isInRange(e,s)},_isInRange:function(e,t){var n=this._getMinMaxDate(e,"min"),r=this._getMinMaxDate(e,"max");return(!n||t.getTime()>=n.getTime())&&(!r||t.getTime()<=r.getTime())},_getFormatConfig:function(e){var t=this._get(e,"shortYearCutoff");return t=typeof t!="string"?t:(new Date).getFullYear()%100+parseInt(t,10),{shortYearCutoff:t,dayNamesShort:this._get(e,"dayNamesShort"),dayNames:this._get(e,"dayNames"),monthNamesShort:this._get(e,"monthNamesShort"),monthNames:this._get(e,"monthNames")}},_formatDate:function(e,t,n,r){t||(e.currentDay=e.selectedDay,e.currentMonth=e.selectedMonth,e.currentYear=e.selectedYear);var i=t?typeof t=="object"?t:this._daylightSavingAdjust(new Date(r,n,t)):this._daylightSavingAdjust(new Date(e.currentYear,e.currentMonth,e.currentDay));return this.formatDate(this._get(e,"dateFormat"),i,this._getFormatConfig(e))}}),$.fn.datepicker=function(e){if(!this.length)return this;$.datepicker.initialized||($(document).mousedown($.datepicker._checkExternalClick).find(document.body).append($.datepicker.dpDiv),$.datepicker.initialized=!0);var t=Array.prototype.slice.call(arguments,1);return typeof e!="string"||e!="isDisabled"&&e!="getDate"&&e!="widget"?e=="option"&&arguments.length==2&&typeof arguments[1]=="string"?$.datepicker["_"+e+"Datepicker"].apply($.datepicker,[this[0]].concat(t)):this.each(function(){typeof e=="string"?$.datepicker["_"+e+"Datepicker"].apply($.datepicker,[this].concat(t)):$.datepicker._attachDatepicker(this,e)}):$.datepicker["_"+e+"Datepicker"].apply($.datepicker,[this[0]].concat(t))},$.datepicker=new Datepicker,$.datepicker.initialized=!1,$.datepicker.uuid=(new Date).getTime(),$.datepicker.version="1.9.2",window["DP_jQuery_"+dpuuid]=$})(jQuery);(function(e,t){var n="ui-dialog ui-widget ui-widget-content ui-corner-all ",r={buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},i={maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0};e.widget("ui.dialog",{version:"1.9.2",options:{autoOpen:!0,buttons:{},closeOnEscape:!0,closeText:"close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:!1,maxWidth:!1,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",of:window,collision:"fit",using:function(t){var n=e(this).css(t).offset().top;n<0&&e(this).css("top",t.top-n)}},resizable:!0,show:null,stack:!0,title:"",width:300,zIndex:1e3},_create:function(){this.originalTitle=this.element.attr("title"),typeof this.originalTitle!="string"&&(this.originalTitle=""),this.oldPosition={parent:this.element.parent(),index:this.element.parent().children().index(this.element)},this.options.title=this.options.title||this.originalTitle;var t=this,r=this.options,i=r.title||"&#160;",s,o,u,a,f;s=(this.uiDialog=e("<div>")).addClass(n+r.dialogClass).css({display:"none",outline:0,zIndex:r.zIndex}).attr("tabIndex",-1).keydown(function(n){r.closeOnEscape&&!n.isDefaultPrevented()&&n.keyCode&&n.keyCode===e.ui.keyCode.ESCAPE&&(t.close(n),n.preventDefault())}).mousedown(function(e){t.moveToTop(!1,e)}).appendTo("body"),this.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(s),o=(this.uiDialogTitlebar=e("<div>")).addClass("ui-dialog-titlebar  ui-widget-header  ui-corner-all  ui-helper-clearfix").bind("mousedown",function(){s.focus()}).prependTo(s),u=e("<a href='#'></a>").addClass("ui-dialog-titlebar-close  ui-corner-all").attr("role","button").click(function(e){e.preventDefault(),t.close(e)}).appendTo(o),(this.uiDialogTitlebarCloseText=e("<span>")).addClass("ui-icon ui-icon-closethick").text(r.closeText).appendTo(u),a=e("<span>").uniqueId().addClass("ui-dialog-title").html(i).prependTo(o),f=(this.uiDialogButtonPane=e("<div>")).addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),(this.uiButtonSet=e("<div>")).addClass("ui-dialog-buttonset").appendTo(f),s.attr({role:"dialog","aria-labelledby":a.attr("id")}),o.find("*").add(o).disableSelection(),this._hoverable(u),this._focusable(u),r.draggable&&e.fn.draggable&&this._makeDraggable(),r.resizable&&e.fn.resizable&&this._makeResizable(),this._createButtons(r.buttons),this._isOpen=!1,e.fn.bgiframe&&s.bgiframe(),this._on(s,{keydown:function(t){if(!r.modal||t.keyCode!==e.ui.keyCode.TAB)return;var n=e(":tabbable",s),i=n.filter(":first"),o=n.filter(":last");if(t.target===o[0]&&!t.shiftKey)return i.focus(1),!1;if(t.target===i[0]&&t.shiftKey)return o.focus(1),!1}})},_init:function(){this.options.autoOpen&&this.open()},_destroy:function(){var e,t=this.oldPosition;this.overlay&&this.overlay.destroy(),this.uiDialog.hide(),this.element.removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body"),this.uiDialog.remove(),this.originalTitle&&this.element.attr("title",this.originalTitle),e=t.parent.children().eq(t.index),e.length&&e[0]!==this.element[0]?e.before(this.element):t.parent.append(this.element)},widget:function(){return this.uiDialog},close:function(t){var n=this,r,i;if(!this._isOpen)return;if(!1===this._trigger("beforeClose",t))return;return this._isOpen=!1,this.overlay&&this.overlay.destroy(),this.options.hide?this._hide(this.uiDialog,this.options.hide,function(){n._trigger("close",t)}):(this.uiDialog.hide(),this._trigger("close",t)),e.ui.dialog.overlay.resize(),this.options.modal&&(r=0,e(".ui-dialog").each(function(){this!==n.uiDialog[0]&&(i=e(this).css("z-index"),isNaN(i)||(r=Math.max(r,i)))}),e.ui.dialog.maxZ=r),this},isOpen:function(){return this._isOpen},moveToTop:function(t,n){var r=this.options,i;return r.modal&&!t||!r.stack&&!r.modal?this._trigger("focus",n):(r.zIndex>e.ui.dialog.maxZ&&(e.ui.dialog.maxZ=r.zIndex),this.overlay&&(e.ui.dialog.maxZ+=1,e.ui.dialog.overlay.maxZ=e.ui.dialog.maxZ,this.overlay.$el.css("z-index",e.ui.dialog.overlay.maxZ)),i={scrollTop:this.element.scrollTop(),scrollLeft:this.element.scrollLeft()},e.ui.dialog.maxZ+=1,this.uiDialog.css("z-index",e.ui.dialog.maxZ),this.element.attr(i),this._trigger("focus",n),this)},open:function(){if(this._isOpen)return;var t,n=this.options,r=this.uiDialog;return this._size(),this._position(n.position),r.show(n.show),this.overlay=n.modal?new e.ui.dialog.overlay(this):null,this.moveToTop(!0),t=this.element.find(":tabbable"),t.length||(t=this.uiDialogButtonPane.find(":tabbable"),t.length||(t=r)),t.eq(0).focus(),this._isOpen=!0,this._trigger("open"),this},_createButtons:function(t){var n=this,r=!1;this.uiDialogButtonPane.remove(),this.uiButtonSet.empty(),typeof t=="object"&&t!==null&&e.each(t,function(){return!(r=!0)}),r?(e.each(t,function(t,r){var i,s;r=e.isFunction(r)?{click:r,text:t}:r,r=e.extend({type:"button"},r),s=r.click,r.click=function(){s.apply(n.element[0],arguments)},i=e("<button></button>",r).appendTo(n.uiButtonSet),e.fn.button&&i.button()}),this.uiDialog.addClass("ui-dialog-buttons"),this.uiDialogButtonPane.appendTo(this.uiDialog)):this.uiDialog.removeClass("ui-dialog-buttons")},_makeDraggable:function(){function r(e){return{position:e.position,offset:e.offset}}var t=this,n=this.options;this.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(n,i){e(this).addClass("ui-dialog-dragging"),t._trigger("dragStart",n,r(i))},drag:function(e,n){t._trigger("drag",e,r(n))},stop:function(i,s){n.position=[s.position.left-t.document.scrollLeft(),s.position.top-t.document.scrollTop()],e(this).removeClass("ui-dialog-dragging"),t._trigger("dragStop",i,r(s)),e.ui.dialog.overlay.resize()}})},_makeResizable:function(n){function u(e){return{originalPosition:e.originalPosition,originalSize:e.originalSize,position:e.position,size:e.size}}n=n===t?this.options.resizable:n;var r=this,i=this.options,s=this.uiDialog.css("position"),o=typeof n=="string"?n:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:this.element,maxWidth:i.maxWidth,maxHeight:i.maxHeight,minWidth:i.minWidth,minHeight:this._minHeight(),handles:o,start:function(t,n){e(this).addClass("ui-dialog-resizing"),r._trigger("resizeStart",t,u(n))},resize:function(e,t){r._trigger("resize",e,u(t))},stop:function(t,n){e(this).removeClass("ui-dialog-resizing"),i.height=e(this).height(),i.width=e(this).width(),r._trigger("resizeStop",t,u(n)),e.ui.dialog.overlay.resize()}}).css("position",s).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_minHeight:function(){var e=this.options;return e.height==="auto"?e.minHeight:Math.min(e.minHeight,e.height)},_position:function(t){var n=[],r=[0,0],i;if(t){if(typeof t=="string"||typeof t=="object"&&"0"in t)n=t.split?t.split(" "):[t[0],t[1]],n.length===1&&(n[1]=n[0]),e.each(["left","top"],function(e,t){+n[e]===n[e]&&(r[e]=n[e],n[e]=t)}),t={my:n[0]+(r[0]<0?r[0]:"+"+r[0])+" "+n[1]+(r[1]<0?r[1]:"+"+r[1]),at:n.join(" ")};t=e.extend({},e.ui.dialog.prototype.options.position,t)}else t=e.ui.dialog.prototype.options.position;i=this.uiDialog.is(":visible"),i||this.uiDialog.show(),this.uiDialog.position(t),i||this.uiDialog.hide()},_setOptions:function(t){var n=this,s={},o=!1;e.each(t,function(e,t){n._setOption(e,t),e in r&&(o=!0),e in i&&(s[e]=t)}),o&&this._size(),this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option",s)},_setOption:function(t,r){var i,s,o=this.uiDialog;switch(t){case"buttons":this._createButtons(r);break;case"closeText":this.uiDialogTitlebarCloseText.text(""+r);break;case"dialogClass":o.removeClass(this.options.dialogClass).addClass(n+r);break;case"disabled":r?o.addClass("ui-dialog-disabled"):o.removeClass("ui-dialog-disabled");break;case"draggable":i=o.is(":data(draggable)"),i&&!r&&o.draggable("destroy"),!i&&r&&this._makeDraggable();break;case"position":this._position(r);break;case"resizable":s=o.is(":data(resizable)"),s&&!r&&o.resizable("destroy"),s&&typeof r=="string"&&o.resizable("option","handles",r),!s&&r!==!1&&this._makeResizable(r);break;case"title":e(".ui-dialog-title",this.uiDialogTitlebar).html(""+(r||"&#160;"))}this._super(t,r)},_size:function(){var t,n,r,i=this.options,s=this.uiDialog.is(":visible");this.element.show().css({width:"auto",minHeight:0,height:0}),i.minWidth>i.width&&(i.width=i.minWidth),t=this.uiDialog.css({height:"auto",width:i.width}).outerHeight(),n=Math.max(0,i.minHeight-t),i.height==="auto"?e.support.minHeight?this.element.css({minHeight:n,height:"auto"}):(this.uiDialog.show(),r=this.element.css("height","auto").height(),s||this.uiDialog.hide(),this.element.height(Math.max(r,n))):this.element.height(Math.max(i.height-t,0)),this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())}}),e.extend(e.ui.dialog,{uuid:0,maxZ:0,getTitleId:function(e){var t=e.attr("id");return t||(this.uuid+=1,t=this.uuid),"ui-dialog-title-"+t},overlay:function(t){this.$el=e.ui.dialog.overlay.create(t)}}),e.extend(e.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:e.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(e){return e+".dialog-overlay"}).join(" "),create:function(t){this.instances.length===0&&(setTimeout(function(){e.ui.dialog.overlay.instances.length&&e(document).bind(e.ui.dialog.overlay.events,function(t){if(e(t.target).zIndex()<e.ui.dialog.overlay.maxZ)return!1})},1),e(window).bind("resize.dialog-overlay",e.ui.dialog.overlay.resize));var n=this.oldInstances.pop()||e("<div>").addClass("ui-widget-overlay");return e(document).bind("keydown.dialog-overlay",function(r){var i=e.ui.dialog.overlay.instances;i.length!==0&&i[i.length-1]===n&&t.options.closeOnEscape&&!r.isDefaultPrevented()&&r.keyCode&&r.keyCode===e.ui.keyCode.ESCAPE&&(t.close(r),r.preventDefault())}),n.appendTo(document.body).css({width:this.width(),height:this.height()}),e.fn.bgiframe&&n.bgiframe(),this.instances.push(n),n},destroy:function(t){var n=e.inArray(t,this.instances),r=0;n!==-1&&this.oldInstances.push(this.instances.splice(n,1)[0]),this.instances.length===0&&e([document,window]).unbind(".dialog-overlay"),t.height(0).width(0).remove(),e.each(this.instances,function(){r=Math.max(r,this.css("z-index"))}),this.maxZ=r},height:function(){var t,n;return e.ui.ie?(t=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight),n=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight),t<n?e(window).height()+"px":t+"px"):e(document).height()+"px"},width:function(){var t,n;return e.ui.ie?(t=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth),n=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth),t<n?e(window).width()+"px":t+"px"):e(document).width()+"px"},resize:function(){var t=e([]);e.each(e.ui.dialog.overlay.instances,function(){t=t.add(this)}),t.css({width:0,height:0}).css({width:e.ui.dialog.overlay.width(),height:e.ui.dialog.overlay.height()})}}),e.extend(e.ui.dialog.overlay.prototype,{destroy:function(){e.ui.dialog.overlay.destroy(this.$el)}})})(jQuery);(function(e,t){var n=!1;e.widget("ui.menu",{version:"1.9.2",defaultElement:"<ul>",delay:300,options:{icons:{submenu:"ui-icon-carat-1-e"},menus:"ul",position:{my:"left top",at:"right top"},role:"menu",blur:null,focus:null,select:null},_create:function(){this.activeMenu=this.element,this.element.uniqueId().addClass("ui-menu ui-widget ui-widget-content ui-corner-all").toggleClass("ui-menu-icons",!!this.element.find(".ui-icon").length).attr({role:this.options.role,tabIndex:0}).bind("click"+this.eventNamespace,e.proxy(function(e){this.options.disabled&&e.preventDefault()},this)),this.options.disabled&&this.element.addClass("ui-state-disabled").attr("aria-disabled","true"),this._on({"mousedown .ui-menu-item > a":function(e){e.preventDefault()},"click .ui-state-disabled > a":function(e){e.preventDefault()},"click .ui-menu-item:has(a)":function(t){var r=e(t.target).closest(".ui-menu-item");!n&&r.not(".ui-state-disabled").length&&(n=!0,this.select(t),r.has(".ui-menu").length?this.expand(t):this.element.is(":focus")||(this.element.trigger("focus",[!0]),this.active&&this.active.parents(".ui-menu").length===1&&clearTimeout(this.timer)))},"mouseenter .ui-menu-item":function(t){var n=e(t.currentTarget);n.siblings().children(".ui-state-active").removeClass("ui-state-active"),this.focus(t,n)},mouseleave:"collapseAll","mouseleave .ui-menu":"collapseAll",focus:function(e,t){var n=this.active||this.element.children(".ui-menu-item").eq(0);t||this.focus(e,n)},blur:function(t){this._delay(function(){e.contains(this.element[0],this.document[0].activeElement)||this.collapseAll(t)})},keydown:"_keydown"}),this.refresh(),this._on(this.document,{click:function(t){e(t.target).closest(".ui-menu").length||this.collapseAll(t),n=!1}})},_destroy:function(){this.element.removeAttr("aria-activedescendant").find(".ui-menu").andSelf().removeClass("ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons").removeAttr("role").removeAttr("tabIndex").removeAttr("aria-labelledby").removeAttr("aria-expanded").removeAttr("aria-hidden").removeAttr("aria-disabled").removeUniqueId().show(),this.element.find(".ui-menu-item").removeClass("ui-menu-item").removeAttr("role").removeAttr("aria-disabled").children("a").removeUniqueId().removeClass("ui-corner-all ui-state-hover").removeAttr("tabIndex").removeAttr("role").removeAttr("aria-haspopup").children().each(function(){var t=e(this);t.data("ui-menu-submenu-carat")&&t.remove()}),this.element.find(".ui-menu-divider").removeClass("ui-menu-divider ui-widget-content")},_keydown:function(t){function a(e){return e.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}var n,r,i,s,o,u=!0;switch(t.keyCode){case e.ui.keyCode.PAGE_UP:this.previousPage(t);break;case e.ui.keyCode.PAGE_DOWN:this.nextPage(t);break;case e.ui.keyCode.HOME:this._move("first","first",t);break;case e.ui.keyCode.END:this._move("last","last",t);break;case e.ui.keyCode.UP:this.previous(t);break;case e.ui.keyCode.DOWN:this.next(t);break;case e.ui.keyCode.LEFT:this.collapse(t);break;case e.ui.keyCode.RIGHT:this.active&&!this.active.is(".ui-state-disabled")&&this.expand(t);break;case e.ui.keyCode.ENTER:case e.ui.keyCode.SPACE:this._activate(t);break;case e.ui.keyCode.ESCAPE:this.collapse(t);break;default:u=!1,r=this.previousFilter||"",i=String.fromCharCode(t.keyCode),s=!1,clearTimeout(this.filterTimer),i===r?s=!0:i=r+i,o=new RegExp("^"+a(i),"i"),n=this.activeMenu.children(".ui-menu-item").filter(function(){return o.test(e(this).children("a").text())}),n=s&&n.index(this.active.next())!==-1?this.active.nextAll(".ui-menu-item"):n,n.length||(i=String.fromCharCode(t.keyCode),o=new RegExp("^"+a(i),"i"),n=this.activeMenu.children(".ui-menu-item").filter(function(){return o.test(e(this).children("a").text())})),n.length?(this.focus(t,n),n.length>1?(this.previousFilter=i,this.filterTimer=this._delay(function(){delete this.previousFilter},1e3)):delete this.previousFilter):delete this.previousFilter}u&&t.preventDefault()},_activate:function(e){this.active.is(".ui-state-disabled")||(this.active.children("a[aria-haspopup='true']").length?this.expand(e):this.select(e))},refresh:function(){var t,n=this.options.icons.submenu,r=this.element.find(this.options.menus);r.filter(":not(.ui-menu)").addClass("ui-menu ui-widget ui-widget-content ui-corner-all").hide().attr({role:this.options.role,"aria-hidden":"true","aria-expanded":"false"}).each(function(){var t=e(this),r=t.prev("a"),i=e("<span>").addClass("ui-menu-icon ui-icon "+n).data("ui-menu-submenu-carat",!0);r.attr("aria-haspopup","true").prepend(i),t.attr("aria-labelledby",r.attr("id"))}),t=r.add(this.element),t.children(":not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","presentation").children("a").uniqueId().addClass("ui-corner-all").attr({tabIndex:-1,role:this._itemRole()}),t.children(":not(.ui-menu-item)").each(function(){var t=e(this);/[^\-—–\s]/.test(t.text())||t.addClass("ui-widget-content ui-menu-divider")}),t.children(".ui-state-disabled").attr("aria-disabled","true"),this.active&&!e.contains(this.element[0],this.active[0])&&this.blur()},_itemRole:function(){return{menu:"menuitem",listbox:"option"}[this.options.role]},focus:function(e,t){var n,r;this.blur(e,e&&e.type==="focus"),this._scrollIntoView(t),this.active=t.first(),r=this.active.children("a").addClass("ui-state-focus"),this.options.role&&this.element.attr("aria-activedescendant",r.attr("id")),this.active.parent().closest(".ui-menu-item").children("a:first").addClass("ui-state-active"),e&&e.type==="keydown"?this._close():this.timer=this._delay(function(){this._close()},this.delay),n=t.children(".ui-menu"),n.length&&/^mouse/.test(e.type)&&this._startOpening(n),this.activeMenu=t.parent(),this._trigger("focus",e,{item:t})},_scrollIntoView:function(t){var n,r,i,s,o,u;this._hasScroll()&&(n=parseFloat(e.css(this.activeMenu[0],"borderTopWidth"))||0,r=parseFloat(e.css(this.activeMenu[0],"paddingTop"))||0,i=t.offset().top-this.activeMenu.offset().top-n-r,s=this.activeMenu.scrollTop(),o=this.activeMenu.height(),u=t.height(),i<0?this.activeMenu.scrollTop(s+i):i+u>o&&this.activeMenu.scrollTop(s+i-o+u))},blur:function(e,t){t||clearTimeout(this.timer);if(!this.active)return;this.active.children("a").removeClass("ui-state-focus"),this.active=null,this._trigger("blur",e,{item:this.active})},_startOpening:function(e){clearTimeout(this.timer);if(e.attr("aria-hidden")!=="true")return;this.timer=this._delay(function(){this._close(),this._open(e)},this.delay)},_open:function(t){var n=e.extend({of:this.active},this.options.position);clearTimeout(this.timer),this.element.find(".ui-menu").not(t.parents(".ui-menu")).hide().attr("aria-hidden","true"),t.show().removeAttr("aria-hidden").attr("aria-expanded","true").position(n)},collapseAll:function(t,n){clearTimeout(this.timer),this.timer=this._delay(function(){var r=n?this.element:e(t&&t.target).closest(this.element.find(".ui-menu"));r.length||(r=this.element),this._close(r),this.blur(t),this.activeMenu=r},this.delay)},_close:function(e){e||(e=this.active?this.active.parent():this.element),e.find(".ui-menu").hide().attr("aria-hidden","true").attr("aria-expanded","false").end().find("a.ui-state-active").removeClass("ui-state-active")},collapse:function(e){var t=this.active&&this.active.parent().closest(".ui-menu-item",this.element);t&&t.length&&(this._close(),this.focus(e,t))},expand:function(e){var t=this.active&&this.active.children(".ui-menu ").children(".ui-menu-item").first();t&&t.length&&(this._open(t.parent()),this._delay(function(){this.focus(e,t)}))},next:function(e){this._move("next","first",e)},previous:function(e){this._move("prev","last",e)},isFirstItem:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},isLastItem:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},_move:function(e,t,n){var r;this.active&&(e==="first"||e==="last"?r=this.active[e==="first"?"prevAll":"nextAll"](".ui-menu-item").eq(-1):r=this.active[e+"All"](".ui-menu-item").eq(0));if(!r||!r.length||!this.active)r=this.activeMenu.children(".ui-menu-item")[t]();this.focus(n,r)},nextPage:function(t){var n,r,i;if(!this.active){this.next(t);return}if(this.isLastItem())return;this._hasScroll()?(r=this.active.offset().top,i=this.element.height(),this.active.nextAll(".ui-menu-item").each(function(){return n=e(this),n.offset().top-r-i<0}),this.focus(t,n)):this.focus(t,this.activeMenu.children(".ui-menu-item")[this.active?"last":"first"]())},previousPage:function(t){var n,r,i;if(!this.active){this.next(t);return}if(this.isFirstItem())return;this._hasScroll()?(r=this.active.offset().top,i=this.element.height(),this.active.prevAll(".ui-menu-item").each(function(){return n=e(this),n.offset().top-r+i>0}),this.focus(t,n)):this.focus(t,this.activeMenu.children(".ui-menu-item").first())},_hasScroll:function(){return this.element.outerHeight()<this.element.prop("scrollHeight")},select:function(t){this.active=this.active||e(t.target).closest(".ui-menu-item");var n={item:this.active};this.active.has(".ui-menu").length||this.collapseAll(t,!0),this._trigger("select",t,n)}})})(jQuery);(function(e,t){var n=5;e.widget("ui.slider",e.ui.mouse,{version:"1.9.2",widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null},_create:function(){var t,r,i=this.options,s=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),o="<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",u=[];this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget"+" ui-widget-content"+" ui-corner-all"+(i.disabled?" ui-slider-disabled ui-disabled":"")),this.range=e([]),i.range&&(i.range===!0&&(i.values||(i.values=[this._valueMin(),this._valueMin()]),i.values.length&&i.values.length!==2&&(i.values=[i.values[0],i.values[0]])),this.range=e("<div></div>").appendTo(this.element).addClass("ui-slider-range ui-widget-header"+(i.range==="min"||i.range==="max"?" ui-slider-range-"+i.range:""))),r=i.values&&i.values.length||1;for(t=s.length;t<r;t++)u.push(o);this.handles=s.add(e(u.join("")).appendTo(this.element)),this.handle=this.handles.eq(0),this.handles.add(this.range).filter("a").click(function(e){e.preventDefault()}).mouseenter(function(){i.disabled||e(this).addClass("ui-state-hover")}).mouseleave(function(){e(this).removeClass("ui-state-hover")}).focus(function(){i.disabled?e(this).blur():(e(".ui-slider .ui-state-focus").removeClass("ui-state-focus"),e(this).addClass("ui-state-focus"))}).blur(function(){e(this).removeClass("ui-state-focus")}),this.handles.each(function(t){e(this).data("ui-slider-handle-index",t)}),this._on(this.handles,{keydown:function(t){var r,i,s,o,u=e(t.target).data("ui-slider-handle-index");switch(t.keyCode){case e.ui.keyCode.HOME:case e.ui.keyCode.END:case e.ui.keyCode.PAGE_UP:case e.ui.keyCode.PAGE_DOWN:case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:t.preventDefault();if(!this._keySliding){this._keySliding=!0,e(t.target).addClass("ui-state-active"),r=this._start(t,u);if(r===!1)return}}o=this.options.step,this.options.values&&this.options.values.length?i=s=this.values(u):i=s=this.value();switch(t.keyCode){case e.ui.keyCode.HOME:s=this._valueMin();break;case e.ui.keyCode.END:s=this._valueMax();break;case e.ui.keyCode.PAGE_UP:s=this._trimAlignValue(i+(this._valueMax()-this._valueMin())/n);break;case e.ui.keyCode.PAGE_DOWN:s=this._trimAlignValue(i-(this._valueMax()-this._valueMin())/n);break;case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:if(i===this._valueMax())return;s=this._trimAlignValue(i+o);break;case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:if(i===this._valueMin())return;s=this._trimAlignValue(i-o)}this._slide(t,u,s)},keyup:function(t){var n=e(t.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(t,n),this._change(t,n),e(t.target).removeClass("ui-state-active"))}}),this._refreshValue(),this._animateOff=!1},_destroy:function(){this.handles.remove(),this.range.remove(),this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all"),this._mouseDestroy()},_mouseCapture:function(t){var n,r,i,s,o,u,a,f,l=this,c=this.options;return c.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),n={x:t.pageX,y:t.pageY},r=this._normValueFromMouse(n),i=this._valueMax()-this._valueMin()+1,this.handles.each(function(t){var n=Math.abs(r-l.values(t));i>n&&(i=n,s=e(this),o=t)}),c.range===!0&&this.values(1)===c.min&&(o+=1,s=e(this.handles[o])),u=this._start(t,o),u===!1?!1:(this._mouseSliding=!0,this._handleIndex=o,s.addClass("ui-state-active").focus(),a=s.offset(),f=!e(t.target).parents().andSelf().is(".ui-slider-handle"),this._clickOffset=f?{left:0,top:0}:{left:t.pageX-a.left-s.width()/2,top:t.pageY-a.top-s.height()/2-(parseInt(s.css("borderTopWidth"),10)||0)-(parseInt(s.css("borderBottomWidth"),10)||0)+(parseInt(s.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(t,o,r),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(e){var t={x:e.pageX,y:e.pageY},n=this._normValueFromMouse(t);return this._slide(e,this._handleIndex,n),!1},_mouseStop:function(e){return this.handles.removeClass("ui-state-active"),this._mouseSliding=!1,this._stop(e,this._handleIndex),this._change(e,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(e){var t,n,r,i,s;return this.orientation==="horizontal"?(t=this.elementSize.width,n=e.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(t=this.elementSize.height,n=e.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),r=n/t,r>1&&(r=1),r<0&&(r=0),this.orientation==="vertical"&&(r=1-r),i=this._valueMax()-this._valueMin(),s=this._valueMin()+r*i,this._trimAlignValue(s)},_start:function(e,t){var n={handle:this.handles[t],value:this.value()};return this.options.values&&this.options.values.length&&(n.value=this.values(t),n.values=this.values()),this._trigger("start",e,n)},_slide:function(e,t,n){var r,i,s;this.options.values&&this.options.values.length?(r=this.values(t?0:1),this.options.values.length===2&&this.options.range===!0&&(t===0&&n>r||t===1&&n<r)&&(n=r),n!==this.values(t)&&(i=this.values(),i[t]=n,s=this._trigger("slide",e,{handle:this.handles[t],value:n,values:i}),r=this.values(t?0:1),s!==!1&&this.values(t,n,!0))):n!==this.value()&&(s=this._trigger("slide",e,{handle:this.handles[t],value:n}),s!==!1&&this.value(n))},_stop:function(e,t){var n={handle:this.handles[t],value:this.value()};this.options.values&&this.options.values.length&&(n.value=this.values(t),n.values=this.values()),this._trigger("stop",e,n)},_change:function(e,t){if(!this._keySliding&&!this._mouseSliding){var n={handle:this.handles[t],value:this.value()};this.options.values&&this.options.values.length&&(n.value=this.values(t),n.values=this.values()),this._trigger("change",e,n)}},value:function(e){if(arguments.length){this.options.value=this._trimAlignValue(e),this._refreshValue(),this._change(null,0);return}return this._value()},values:function(t,n){var r,i,s;if(arguments.length>1){this.options.values[t]=this._trimAlignValue(n),this._refreshValue(),this._change(null,t);return}if(!arguments.length)return this._values();if(!e.isArray(arguments[0]))return this.options.values&&this.options.values.length?this._values(t):this.value();r=this.options.values,i=arguments[0];for(s=0;s<r.length;s+=1)r[s]=this._trimAlignValue(i[s]),this._change(null,s);this._refreshValue()},_setOption:function(t,n){var r,i=0;e.isArray(this.options.values)&&(i=this.options.values.length),e.Widget.prototype._setOption.apply(this,arguments);switch(t){case"disabled":n?(this.handles.filter(".ui-state-focus").blur(),this.handles.removeClass("ui-state-hover"),this.handles.prop("disabled",!0),this.element.addClass("ui-disabled")):(this.handles.prop("disabled",!1),this.element.removeClass("ui-disabled"));break;case"orientation":this._detectOrientation(),this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation),this._refreshValue();break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":this._animateOff=!0,this._refreshValue();for(r=0;r<i;r+=1)this._change(null,r);this._animateOff=!1;break;case"min":case"max":this._animateOff=!0,this._refreshValue(),this._animateOff=!1}},_value:function(){var e=this.options.value;return e=this._trimAlignValue(e),e},_values:function(e){var t,n,r;if(arguments.length)return t=this.options.values[e],t=this._trimAlignValue(t),t;n=this.options.values.slice();for(r=0;r<n.length;r+=1)n[r]=this._trimAlignValue(n[r]);return n},_trimAlignValue:function(e){if(e<=this._valueMin())return this._valueMin();if(e>=this._valueMax())return this._valueMax();var t=this.options.step>0?this.options.step:1,n=(e-this._valueMin())%t,r=e-n;return Math.abs(n)*2>=t&&(r+=n>0?t:-t),parseFloat(r.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var t,n,r,i,s,o=this.options.range,u=this.options,a=this,f=this._animateOff?!1:u.animate,l={};this.options.values&&this.options.values.length?this.handles.each(function(r){n=(a.values(r)-a._valueMin())/(a._valueMax()-a._valueMin())*100,l[a.orientation==="horizontal"?"left":"bottom"]=n+"%",e(this).stop(1,1)[f?"animate":"css"](l,u.animate),a.options.range===!0&&(a.orientation==="horizontal"?(r===0&&a.range.stop(1,1)[f?"animate":"css"]({left:n+"%"},u.animate),r===1&&a.range[f?"animate":"css"]({width:n-t+"%"},{queue:!1,duration:u.animate})):(r===0&&a.range.stop(1,1)[f?"animate":"css"]({bottom:n+"%"},u.animate),r===1&&a.range[f?"animate":"css"]({height:n-t+"%"},{queue:!1,duration:u.animate}))),t=n}):(r=this.value(),i=this._valueMin(),s=this._valueMax(),n=s!==i?(r-i)/(s-i)*100:0,l[this.orientation==="horizontal"?"left":"bottom"]=n+"%",this.handle.stop(1,1)[f?"animate":"css"](l,u.animate),o==="min"&&this.orientation==="horizontal"&&this.range.stop(1,1)[f?"animate":"css"]({width:n+"%"},u.animate),o==="max"&&this.orientation==="horizontal"&&this.range[f?"animate":"css"]({width:100-n+"%"},{queue:!1,duration:u.animate}),o==="min"&&this.orientation==="vertical"&&this.range.stop(1,1)[f?"animate":"css"]({height:n+"%"},u.animate),o==="max"&&this.orientation==="vertical"&&this.range[f?"animate":"css"]({height:100-n+"%"},{queue:!1,duration:u.animate}))}})})(jQuery);(function(e,t){function i(){return++n}function s(e){return e.hash.length>1&&e.href.replace(r,"")===location.href.replace(r,"").replace(/\s/g,"%20")}var n=0,r=/#.*$/;e.widget("ui.tabs",{version:"1.9.2",delay:300,options:{active:null,collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_create:function(){var t=this,n=this.options,r=n.active,i=location.hash.substring(1);this.running=!1,this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all").toggleClass("ui-tabs-collapsible",n.collapsible).delegate(".ui-tabs-nav > li","mousedown"+this.eventNamespace,function(t){e(this).is(".ui-state-disabled")&&t.preventDefault()}).delegate(".ui-tabs-anchor","focus"+this.eventNamespace,function(){e(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this._processTabs();if(r===null){i&&this.tabs.each(function(t,n){if(e(n).attr("aria-controls")===i)return r=t,!1}),r===null&&(r=this.tabs.index(this.tabs.filter(".ui-tabs-active")));if(r===null||r===-1)r=this.tabs.length?0:!1}r!==!1&&(r=this.tabs.index(this.tabs.eq(r)),r===-1&&(r=n.collapsible?!1:0)),n.active=r,!n.collapsible&&n.active===!1&&this.anchors.length&&(n.active=0),e.isArray(n.disabled)&&(n.disabled=e.unique(n.disabled.concat(e.map(this.tabs.filter(".ui-state-disabled"),function(e){return t.tabs.index(e)}))).sort()),this.options.active!==!1&&this.anchors.length?this.active=this._findActive(this.options.active):this.active=e(),this._refresh(),this.active.length&&this.load(n.active)},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):e()}},_tabKeydown:function(t){var n=e(this.document[0].activeElement).closest("li"),r=this.tabs.index(n),i=!0;if(this._handlePageNav(t))return;switch(t.keyCode){case e.ui.keyCode.RIGHT:case e.ui.keyCode.DOWN:r++;break;case e.ui.keyCode.UP:case e.ui.keyCode.LEFT:i=!1,r--;break;case e.ui.keyCode.END:r=this.anchors.length-1;break;case e.ui.keyCode.HOME:r=0;break;case e.ui.keyCode.SPACE:t.preventDefault(),clearTimeout(this.activating),this._activate(r);return;case e.ui.keyCode.ENTER:t.preventDefault(),clearTimeout(this.activating),this._activate(r===this.options.active?!1:r);return;default:return}t.preventDefault(),clearTimeout(this.activating),r=this._focusNextTab(r,i),t.ctrlKey||(n.attr("aria-selected","false"),this.tabs.eq(r).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",r)},this.delay))},_panelKeydown:function(t){if(this._handlePageNav(t))return;t.ctrlKey&&t.keyCode===e.ui.keyCode.UP&&(t.preventDefault(),this.active.focus())},_handlePageNav:function(t){if(t.altKey&&t.keyCode===e.ui.keyCode.PAGE_UP)return this._activate(this._focusNextTab(this.options.active-1,!1)),!0;if(t.altKey&&t.keyCode===e.ui.keyCode.PAGE_DOWN)return this._activate(this._focusNextTab(this.options.active+1,!0)),!0},_findNextTab:function(t,n){function i(){return t>r&&(t=0),t<0&&(t=r),t}var r=this.tabs.length-1;while(e.inArray(i(),this.options.disabled)!==-1)t=n?t+1:t-1;return t},_focusNextTab:function(e,t){return e=this._findNextTab(e,t),this.tabs.eq(e).focus(),e},_setOption:function(e,t){if(e==="active"){this._activate(t);return}if(e==="disabled"){this._setupDisabled(t);return}this._super(e,t),e==="collapsible"&&(this.element.toggleClass("ui-tabs-collapsible",t),!t&&this.options.active===!1&&this._activate(0)),e==="event"&&this._setupEvents(t),e==="heightStyle"&&this._setupHeightStyle(t)},_tabId:function(e){return e.attr("aria-controls")||"ui-tabs-"+i()},_sanitizeSelector:function(e){return e?e.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var t=this.options,n=this.tablist.children(":has(a[href])");t.disabled=e.map(n.filter(".ui-state-disabled"),function(e){return n.index(e)}),this._processTabs(),t.active===!1||!this.anchors.length?(t.active=!1,this.active=e()):this.active.length&&!e.contains(this.tablist[0],this.active[0])?this.tabs.length===t.disabled.length?(t.active=!1,this.active=e()):this._activate(this._findNextTab(Math.max(0,t.active-1),!1)):t.active=this.tabs.index(this.active),this._refresh()},_refresh:function(){this._setupDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-expanded":"false","aria-hidden":"true"}),this.active.length?(this.active.addClass("ui-tabs-active ui-state-active").attr({"aria-selected":"true",tabIndex:0}),this._getPanelForTab(this.active).show().attr({"aria-expanded":"true","aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var t=this;this.tablist=this._getList().addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").attr("role","tablist"),this.tabs=this.tablist.find("> li:has(a[href])").addClass("ui-state-default ui-corner-top").attr({role:"tab",tabIndex:-1}),this.anchors=this.tabs.map(function(){return e("a",this)[0]}).addClass("ui-tabs-anchor").attr({role:"presentation",tabIndex:-1}),this.panels=e(),this.anchors.each(function(n,r){var i,o,u,a=e(r).uniqueId().attr("id"),f=e(r).closest("li"),l=f.attr("aria-controls");s(r)?(i=r.hash,o=t.element.find(t._sanitizeSelector(i))):(u=t._tabId(f),i="#"+u,o=t.element.find(i),o.length||(o=t._createPanel(u),o.insertAfter(t.panels[n-1]||t.tablist)),o.attr("aria-live","polite")),o.length&&(t.panels=t.panels.add(o)),l&&f.data("ui-tabs-aria-controls",l),f.attr({"aria-controls":i.substring(1),"aria-labelledby":a}),o.attr("aria-labelledby",a)}),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").attr("role","tabpanel")},_getList:function(){return this.element.find("ol,ul").eq(0)},_createPanel:function(t){return e("<div>").attr("id",t).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)},_setupDisabled:function(t){e.isArray(t)&&(t.length?t.length===this.anchors.length&&(t=!0):t=!1);for(var n=0,r;r=this.tabs[n];n++)t===!0||e.inArray(n,t)!==-1?e(r).addClass("ui-state-disabled").attr("aria-disabled","true"):e(r).removeClass("ui-state-disabled").removeAttr("aria-disabled");this.options.disabled=t},_setupEvents:function(t){var n={click:function(e){e.preventDefault()}};t&&e.each(t.split(" "),function(e,t){n[t]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(this.anchors,n),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(t){var n,r,i=this.element.parent();t==="fill"?(e.support.minHeight||(r=i.css("overflow"),i.css("overflow","hidden")),n=i.height(),this.element.siblings(":visible").each(function(){var t=e(this),r=t.css("position");if(r==="absolute"||r==="fixed")return;n-=t.outerHeight(!0)}),r&&i.css("overflow",r),this.element.children().not(this.panels).each(function(){n-=e(this).outerHeight(!0)}),this.panels.each(function(){e(this).height(Math.max(0,n-e(this).innerHeight()+e(this).height()))}).css("overflow","auto")):t==="auto"&&(n=0,this.panels.each(function(){n=Math.max(n,e(this).height("").height())}).height(n))},_eventHandler:function(t){var n=this.options,r=this.active,i=e(t.currentTarget),s=i.closest("li"),o=s[0]===r[0],u=o&&n.collapsible,a=u?e():this._getPanelForTab(s),f=r.length?this._getPanelForTab(r):e(),l={oldTab:r,oldPanel:f,newTab:u?e():s,newPanel:a};t.preventDefault();if(s.hasClass("ui-state-disabled")||s.hasClass("ui-tabs-loading")||this.running||o&&!n.collapsible||this._trigger("beforeActivate",t,l)===!1)return;n.active=u?!1:this.tabs.index(s),this.active=o?e():s,this.xhr&&this.xhr.abort(),!f.length&&!a.length&&e.error("jQuery UI Tabs: Mismatching fragment identifier."),a.length&&this.load(this.tabs.index(s),t),this._toggle(t,l)},_toggle:function(t,n){function o(){r.running=!1,r._trigger("activate",t,n)}function u(){n.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),i.length&&r.options.show?r._show(i,r.options.show,o):(i.show(),o())}var r=this,i=n.newPanel,s=n.oldPanel;this.running=!0,s.length&&this.options.hide?this._hide(s,this.options.hide,function(){n.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),u()}):(n.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),s.hide(),u()),s.attr({"aria-expanded":"false","aria-hidden":"true"}),n.oldTab.attr("aria-selected","false"),i.length&&s.length?n.oldTab.attr("tabIndex",-1):i.length&&this.tabs.filter(function(){return e(this).attr("tabIndex")===0}).attr("tabIndex",-1),i.attr({"aria-expanded":"true","aria-hidden":"false"}),n.newTab.attr({"aria-selected":"true",tabIndex:0})},_activate:function(t){var n,r=this._findActive(t);if(r[0]===this.active[0])return;r.length||(r=this.active),n=r.find(".ui-tabs-anchor")[0],this._eventHandler({target:n,currentTarget:n,preventDefault:e.noop})},_findActive:function(t){return t===!1?e():this.tabs.eq(t)},_getIndex:function(e){return typeof e=="string"&&(e=this.anchors.index(this.anchors.filter("[href$='"+e+"']"))),e},_destroy:function(){this.xhr&&this.xhr.abort(),this.element.removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible"),this.tablist.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").removeAttr("role"),this.anchors.removeClass("ui-tabs-anchor").removeAttr("role").removeAttr("tabIndex").removeData("href.tabs").removeData("load.tabs").removeUniqueId(),this.tabs.add(this.panels).each(function(){e.data(this,"ui-tabs-destroy")?e(this).remove():e(this).removeClass("ui-state-default ui-state-active ui-state-disabled ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel").removeAttr("tabIndex").removeAttr("aria-live").removeAttr("aria-busy").removeAttr("aria-selected").removeAttr("aria-labelledby").removeAttr("aria-hidden").removeAttr("aria-expanded").removeAttr("role")}),this.tabs.each(function(){var t=e(this),n=t.data("ui-tabs-aria-controls");n?t.attr("aria-controls",n):t.removeAttr("aria-controls")}),this.panels.show(),this.options.heightStyle!=="content"&&this.panels.css("height","")},enable:function(n){var r=this.options.disabled;if(r===!1)return;n===t?r=!1:(n=this._getIndex(n),e.isArray(r)?r=e.map(r,function(e){return e!==n?e:null}):r=e.map(this.tabs,function(e,t){return t!==n?t:null})),this._setupDisabled(r)},disable:function(n){var r=this.options.disabled;if(r===!0)return;if(n===t)r=!0;else{n=this._getIndex(n);if(e.inArray(n,r)!==-1)return;e.isArray(r)?r=e.merge([n],r).sort():r=[n]}this._setupDisabled(r)},load:function(t,n){t=this._getIndex(t);var r=this,i=this.tabs.eq(t),o=i.find(".ui-tabs-anchor"),u=this._getPanelForTab(i),a={tab:i,panel:u};if(s(o[0]))return;this.xhr=e.ajax(this._ajaxSettings(o,n,a)),this.xhr&&this.xhr.statusText!=="canceled"&&(i.addClass("ui-tabs-loading"),u.attr("aria-busy","true"),this.xhr.success(function(e){setTimeout(function(){u.html(e),r._trigger("load",n,a)},1)}).complete(function(e,t){setTimeout(function(){t==="abort"&&r.panels.stop(!1,!0),i.removeClass("ui-tabs-loading"),u.removeAttr("aria-busy"),e===r.xhr&&delete r.xhr},1)}))},_ajaxSettings:function(t,n,r){var i=this;return{url:t.attr("href"),beforeSend:function(t,s){return i._trigger("beforeLoad",n,e.extend({jqXHR:t,ajaxSettings:s},r))}}},_getPanelForTab:function(t){var n=e(t).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+n))}}),e.uiBackCompat!==!1&&(e.ui.tabs.prototype._ui=function(e,t){return{tab:e,panel:t,index:this.anchors.index(e)}},e.widget("ui.tabs",e.ui.tabs,{url:function(e,t){this.anchors.eq(e).attr("href",t)}}),e.widget("ui.tabs",e.ui.tabs,{options:{ajaxOptions:null,cache:!1},_create:function(){this._super();var t=this;this._on({tabsbeforeload:function(n,r){if(e.data(r.tab[0],"cache.tabs")){n.preventDefault();return}r.jqXHR.success(function(){t.options.cache&&e.data(r.tab[0],"cache.tabs",!0)})}})},_ajaxSettings:function(t,n,r){var i=this.options.ajaxOptions;return e.extend({},i,{error:function(e,t){try{i.error(e,t,r.tab.closest("li").index(),r.tab[0])}catch(n){}}},this._superApply(arguments))},_setOption:function(e,t){e==="cache"&&t===!1&&this.anchors.removeData("cache.tabs"),this._super(e,t)},_destroy:function(){this.anchors.removeData("cache.tabs"),this._super()},url:function(e){this.anchors.eq(e).removeData("cache.tabs"),this._superApply(arguments)}}),e.widget("ui.tabs",e.ui.tabs,{abort:function(){this.xhr&&this.xhr.abort()}}),e.widget("ui.tabs",e.ui.tabs,{options:{spinner:"<em>Loading&#8230;</em>"},_create:function(){this._super(),this._on({tabsbeforeload:function(e,t){if(e.target!==this.element[0]||!this.options.spinner)return;var n=t.tab.find("span"),r=n.html();n.html(this.options.spinner),t.jqXHR.complete(function(){n.html(r)})}})}}),e.widget("ui.tabs",e.ui.tabs,{options:{enable:null,disable:null},enable:function(t){var n=this.options,r;if(t&&n.disabled===!0||e.isArray(n.disabled)&&e.inArray(t,n.disabled)!==-1)r=!0;this._superApply(arguments),r&&this._trigger("enable",null,this._ui(this.anchors[t],this.panels[t]))},disable:function(t){var n=this.options,r;if(t&&n.disabled===!1||e.isArray(n.disabled)&&e.inArray(t,n.disabled)===-1)r=!0;this._superApply(arguments),r&&this._trigger("disable",null,this._ui(this.anchors[t],this.panels[t]))}}),e.widget("ui.tabs",e.ui.tabs,{options:{add:null,remove:null,tabTemplate:"<li><a href='#{href}'><span>#{label}</span></a></li>"},add:function(n,r,i){i===t&&(i=this.anchors.length);var s,o,u=this.options,a=e(u.tabTemplate.replace(/#\{href\}/g,n).replace(/#\{label\}/g,r)),f=n.indexOf("#")?this._tabId(a):n.replace("#","");return a.addClass("ui-state-default ui-corner-top").data("ui-tabs-destroy",!0),a.attr("aria-controls",f),s=i>=this.tabs.length,o=this.element.find("#"+f),o.length||(o=this._createPanel(f),s?i>0?o.insertAfter(this.panels.eq(-1)):o.appendTo(this.element):o.insertBefore(this.panels[i])),o.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").hide(),s?a.appendTo(this.tablist):a.insertBefore(this.tabs[i]),u.disabled=e.map(u.disabled,function(e){return e>=i?++e:e}),this.refresh(),this.tabs.length===1&&u.active===!1&&this.option("active",0),this._trigger("add",null,this._ui(this.anchors[i],this.panels[i])),this},remove:function(t){t=this._getIndex(t);var n=this.options,r=this.tabs.eq(t).remove(),i=this._getPanelForTab(r).remove();return r.hasClass("ui-tabs-active")&&this.anchors.length>2&&this._activate(t+(t+1<this.anchors.length?1:-1)),n.disabled=e.map(e.grep(n.disabled,function(e){return e!==t}),function(e){return e>=t?--e:e}),this.refresh(),this._trigger("remove",null,this._ui(r.find("a")[0],i[0])),this}}),e.widget("ui.tabs",e.ui.tabs,{length:function(){return this.anchors.length}}),e.widget("ui.tabs",e.ui.tabs,{options:{idPrefix:"ui-tabs-"},_tabId:function(t){var n=t.is("li")?t.find("a[href]"):t;return n=n[0],e(n).closest("li").attr("aria-controls")||n.title&&n.title.replace(/\s/g,"_").replace(/[^\w\u00c0-\uFFFF\-]/g,"")||this.options.idPrefix+i()}}),e.widget("ui.tabs",e.ui.tabs,{options:{panelTemplate:"<div></div>"},_createPanel:function(t){return e(this.options.panelTemplate).attr("id",t).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)}}),e.widget("ui.tabs",e.ui.tabs,{_create:function(){var e=this.options;e.active===null&&e.selected!==t&&(e.active=e.selected===-1?!1:e.selected),this._super(),e.selected=e.active,e.selected===!1&&(e.selected=-1)},_setOption:function(e,t){if(e!=="selected")return this._super(e,t);var n=this.options;this._super("active",t===-1?!1:t),n.selected=n.active,n.selected===!1&&(n.selected=-1)},_eventHandler:function(){this._superApply(arguments),this.options.selected=this.options.active,this.options.selected===!1&&(this.options.selected=-1)}}),e.widget("ui.tabs",e.ui.tabs,{options:{show:null,select:null},_create:function(){this._super(),this.options.active!==!1&&this._trigger("show",null,this._ui(this.active.find(".ui-tabs-anchor")[0],this._getPanelForTab(this.active)[0]))},_trigger:function(e,t,n){var r,i,s=this._superApply(arguments);return s?(e==="beforeActivate"?(r=n.newTab.length?n.newTab:n.oldTab,i=n.newPanel.length?n.newPanel:n.oldPanel,s=this._super("select",t,{tab:r.find(".ui-tabs-anchor")[0],panel:i[0],index:r.closest("li").index()})):e==="activate"&&n.newTab.length&&(s=this._super("show",t,{tab:n.newTab.find(".ui-tabs-anchor")[0],panel:n.newPanel[0],index:n.newTab.closest("li").index()})),s):!1}}),e.widget("ui.tabs",e.ui.tabs,{select:function(e){e=this._getIndex(e);if(e===-1){if(!this.options.collapsible||this.options.selected===-1)return;e=this.options.selected}this.anchors.eq(e).trigger(this.options.event+this.eventNamespace)}}),function(){var t=0;e.widget("ui.tabs",e.ui.tabs,{options:{cookie:null},_create:function(){var e=this.options,t;e.active==null&&e.cookie&&(t=parseInt(this._cookie(),10),t===-1&&(t=!1),e.active=t),this._super()},_cookie:function(n){var r=[this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+ ++t)];return arguments.length&&(r.push(n===!1?-1:n),r.push(this.options.cookie)),e.cookie.apply(null,r)},_refresh:function(){this._super(),this.options.cookie&&this._cookie(this.options.active,this.options.cookie)},_eventHandler:function(){this._superApply(arguments),this.options.cookie&&this._cookie(this.options.active,this.options.cookie)},_destroy:function(){this._super(),this.options.cookie&&this._cookie(null,this.options.cookie)}})}(),e.widget("ui.tabs",e.ui.tabs,{_trigger:function(t,n,r){var i=e.extend({},r);return t==="load"&&(i.panel=i.panel[0],i.tab=i.tab.find(".ui-tabs-anchor")[0]),this._super(t,n,i)}}),e.widget("ui.tabs",e.ui.tabs,{options:{fx:null},_getFx:function(){var t,n,r=this.options.fx;return r&&(e.isArray(r)?(t=r[0],n=r[1]):t=n=r),r?{show:n,hide:t}:null},_toggle:function(e,t){function o(){n.running=!1,n._trigger("activate",e,t)}function u(){t.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),r.length&&s.show?r.animate(s.show,s.show.duration,function(){o()}):(r.show(),o())}var n=this,r=t.newPanel,i=t.oldPanel,s=this._getFx();if(!s)return this._super(e,t);n.running=!0,i.length&&s.hide?i.animate(s.hide,s.hide.duration,function(){t.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),u()}):(t.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),i.hide(),u())}}))})(jQuery);jQuery.effects||function(e,t){var n=e.uiBackCompat!==!1,r="ui-effects-";e.effects={effect:{}},function(t,n){function p(e,t,n){var r=a[t.type]||{};return e==null?n||!t.def?null:t.def:(e=r.floor?~~e:parseFloat(e),isNaN(e)?t.def:r.mod?(e+r.mod)%r.mod:0>e?0:r.max<e?r.max:e)}function d(e){var n=o(),r=n._rgba=[];return e=e.toLowerCase(),h(s,function(t,i){var s,o=i.re.exec(e),a=o&&i.parse(o),f=i.space||"rgba";if(a)return s=n[f](a),n[u[f].cache]=s[u[f].cache],r=n._rgba=s._rgba,!1}),r.length?(r.join()==="0,0,0,0"&&t.extend(r,c.transparent),n):c[e]}function v(e,t,n){return n=(n+1)%1,n*6<1?e+(t-e)*n*6:n*2<1?t:n*3<2?e+(t-e)*(2/3-n)*6:e}var r="backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor".split(" "),i=/^([\-+])=\s*(\d+\.?\d*)/,s=[{re:/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,parse:function(e){return[e[1],e[2],e[3],e[4]]}},{re:/rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,parse:function(e){return[e[1]*2.55,e[2]*2.55,e[3]*2.55,e[4]]}},{re:/#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,parse:function(e){return[parseInt(e[1],16),parseInt(e[2],16),parseInt(e[3],16)]}},{re:/#([a-f0-9])([a-f0-9])([a-f0-9])/,parse:function(e){return[parseInt(e[1]+e[1],16),parseInt(e[2]+e[2],16),parseInt(e[3]+e[3],16)]}},{re:/hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,space:"hsla",parse:function(e){return[e[1],e[2]/100,e[3]/100,e[4]]}}],o=t.Color=function(e,n,r,i){return new t.Color.fn.parse(e,n,r,i)},u={rgba:{props:{red:{idx:0,type:"byte"},green:{idx:1,type:"byte"},blue:{idx:2,type:"byte"}}},hsla:{props:{hue:{idx:0,type:"degrees"},saturation:{idx:1,type:"percent"},lightness:{idx:2,type:"percent"}}}},a={"byte":{floor:!0,max:255},percent:{max:1},degrees:{mod:360,floor:!0}},f=o.support={},l=t("<p>")[0],c,h=t.each;l.style.cssText="background-color:rgba(1,1,1,.5)",f.rgba=l.style.backgroundColor.indexOf("rgba")>-1,h(u,function(e,t){t.cache="_"+e,t.props.alpha={idx:3,type:"percent",def:1}}),o.fn=t.extend(o.prototype,{parse:function(r,i,s,a){if(r===n)return this._rgba=[null,null,null,null],this;if(r.jquery||r.nodeType)r=t(r).css(i),i=n;var f=this,l=t.type(r),v=this._rgba=[];i!==n&&(r=[r,i,s,a],l="array");if(l==="string")return this.parse(d(r)||c._default);if(l==="array")return h(u.rgba.props,function(e,t){v[t.idx]=p(r[t.idx],t)}),this;if(l==="object")return r instanceof o?h(u,function(e,t){r[t.cache]&&(f[t.cache]=r[t.cache].slice())}):h(u,function(t,n){var i=n.cache;h(n.props,function(e,t){if(!f[i]&&n.to){if(e==="alpha"||r[e]==null)return;f[i]=n.to(f._rgba)}f[i][t.idx]=p(r[e],t,!0)}),f[i]&&e.inArray(null,f[i].slice(0,3))<0&&(f[i][3]=1,n.from&&(f._rgba=n.from(f[i])))}),this},is:function(e){var t=o(e),n=!0,r=this;return h(u,function(e,i){var s,o=t[i.cache];return o&&(s=r[i.cache]||i.to&&i.to(r._rgba)||[],h(i.props,function(e,t){if(o[t.idx]!=null)return n=o[t.idx]===s[t.idx],n})),n}),n},_space:function(){var e=[],t=this;return h(u,function(n,r){t[r.cache]&&e.push(n)}),e.pop()},transition:function(e,t){var n=o(e),r=n._space(),i=u[r],s=this.alpha()===0?o("transparent"):this,f=s[i.cache]||i.to(s._rgba),l=f.slice();return n=n[i.cache],h(i.props,function(e,r){var i=r.idx,s=f[i],o=n[i],u=a[r.type]||{};if(o===null)return;s===null?l[i]=o:(u.mod&&(o-s>u.mod/2?s+=u.mod:s-o>u.mod/2&&(s-=u.mod)),l[i]=p((o-s)*t+s,r))}),this[r](l)},blend:function(e){if(this._rgba[3]===1)return this;var n=this._rgba.slice(),r=n.pop(),i=o(e)._rgba;return o(t.map(n,function(e,t){return(1-r)*i[t]+r*e}))},toRgbaString:function(){var e="rgba(",n=t.map(this._rgba,function(e,t){return e==null?t>2?1:0:e});return n[3]===1&&(n.pop(),e="rgb("),e+n.join()+")"},toHslaString:function(){var e="hsla(",n=t.map(this.hsla(),function(e,t){return e==null&&(e=t>2?1:0),t&&t<3&&(e=Math.round(e*100)+"%"),e});return n[3]===1&&(n.pop(),e="hsl("),e+n.join()+")"},toHexString:function(e){var n=this._rgba.slice(),r=n.pop();return e&&n.push(~~(r*255)),"#"+t.map(n,function(e){return e=(e||0).toString(16),e.length===1?"0"+e:e}).join("")},toString:function(){return this._rgba[3]===0?"transparent":this.toRgbaString()}}),o.fn.parse.prototype=o.fn,u.hsla.to=function(e){if(e[0]==null||e[1]==null||e[2]==null)return[null,null,null,e[3]];var t=e[0]/255,n=e[1]/255,r=e[2]/255,i=e[3],s=Math.max(t,n,r),o=Math.min(t,n,r),u=s-o,a=s+o,f=a*.5,l,c;return o===s?l=0:t===s?l=60*(n-r)/u+360:n===s?l=60*(r-t)/u+120:l=60*(t-n)/u+240,f===0||f===1?c=f:f<=.5?c=u/a:c=u/(2-a),[Math.round(l)%360,c,f,i==null?1:i]},u.hsla.from=function(e){if(e[0]==null||e[1]==null||e[2]==null)return[null,null,null,e[3]];var t=e[0]/360,n=e[1],r=e[2],i=e[3],s=r<=.5?r*(1+n):r+n-r*n,o=2*r-s;return[Math.round(v(o,s,t+1/3)*255),Math.round(v(o,s,t)*255),Math.round(v(o,s,t-1/3)*255),i]},h(u,function(e,r){var s=r.props,u=r.cache,a=r.to,f=r.from;o.fn[e]=function(e){a&&!this[u]&&(this[u]=a(this._rgba));if(e===n)return this[u].slice();var r,i=t.type(e),l=i==="array"||i==="object"?e:arguments,c=this[u].slice();return h(s,function(e,t){var n=l[i==="object"?e:t.idx];n==null&&(n=c[t.idx]),c[t.idx]=p(n,t)}),f?(r=o(f(c)),r[u]=c,r):o(c)},h(s,function(n,r){if(o.fn[n])return;o.fn[n]=function(s){var o=t.type(s),u=n==="alpha"?this._hsla?"hsla":"rgba":e,a=this[u](),f=a[r.idx],l;return o==="undefined"?f:(o==="function"&&(s=s.call(this,f),o=t.type(s)),s==null&&r.empty?this:(o==="string"&&(l=i.exec(s),l&&(s=f+parseFloat(l[2])*(l[1]==="+"?1:-1))),a[r.idx]=s,this[u](a)))}})}),h(r,function(e,n){t.cssHooks[n]={set:function(e,r){var i,s,u="";if(t.type(r)!=="string"||(i=d(r))){r=o(i||r);if(!f.rgba&&r._rgba[3]!==1){s=n==="backgroundColor"?e.parentNode:e;while((u===""||u==="transparent")&&s&&s.style)try{u=t.css(s,"backgroundColor"),s=s.parentNode}catch(a){}r=r.blend(u&&u!=="transparent"?u:"_default")}r=r.toRgbaString()}try{e.style[n]=r}catch(l){}}},t.fx.step[n]=function(e){e.colorInit||(e.start=o(e.elem,n),e.end=o(e.end),e.colorInit=!0),t.cssHooks[n].set(e.elem,e.start.transition(e.end,e.pos))}}),t.cssHooks.borderColor={expand:function(e){var t={};return h(["Top","Right","Bottom","Left"],function(n,r){t["border"+r+"Color"]=e}),t}},c=t.Color.names={aqua:"#00ffff",black:"#000000",blue:"#0000ff",fuchsia:"#ff00ff",gray:"#808080",green:"#008000",lime:"#00ff00",maroon:"#800000",navy:"#000080",olive:"#808000",purple:"#800080",red:"#ff0000",silver:"#c0c0c0",teal:"#008080",white:"#ffffff",yellow:"#ffff00",transparent:[null,null,null,0],_default:"#ffffff"}}(jQuery),function(){function i(){var t=this.ownerDocument.defaultView?this.ownerDocument.defaultView.getComputedStyle(this,null):this.currentStyle,n={},r,i;if(t&&t.length&&t[0]&&t[t[0]]){i=t.length;while(i--)r=t[i],typeof t[r]=="string"&&(n[e.camelCase(r)]=t[r])}else for(r in t)typeof t[r]=="string"&&(n[r]=t[r]);return n}function s(t,n){var i={},s,o;for(s in n)o=n[s],t[s]!==o&&!r[s]&&(e.fx.step[s]||!isNaN(parseFloat(o)))&&(i[s]=o);return i}var n=["add","remove","toggle"],r={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};e.each(["borderLeftStyle","borderRightStyle","borderBottomStyle","borderTopStyle"],function(t,n){e.fx.step[n]=function(e){if(e.end!=="none"&&!e.setAttr||e.pos===1&&!e.setAttr)jQuery.style(e.elem,n,e.end),e.setAttr=!0}}),e.effects.animateClass=function(t,r,o,u){var a=e.speed(r,o,u);return this.queue(function(){var r=e(this),o=r.attr("class")||"",u,f=a.children?r.find("*").andSelf():r;f=f.map(function(){var t=e(this);return{el:t,start:i.call(this)}}),u=function(){e.each(n,function(e,n){t[n]&&r[n+"Class"](t[n])})},u(),f=f.map(function(){return this.end=i.call(this.el[0]),this.diff=s(this.start,this.end),this}),r.attr("class",o),f=f.map(function(){var t=this,n=e.Deferred(),r=jQuery.extend({},a,{queue:!1,complete:function(){n.resolve(t)}});return this.el.animate(this.diff,r),n.promise()}),e.when.apply(e,f.get()).done(function(){u(),e.each(arguments,function(){var t=this.el;e.each(this.diff,function(e){t.css(e,"")})}),a.complete.call(r[0])})})},e.fn.extend({_addClass:e.fn.addClass,addClass:function(t,n,r,i){return n?e.effects.animateClass.call(this,{add:t},n,r,i):this._addClass(t)},_removeClass:e.fn.removeClass,removeClass:function(t,n,r,i){return n?e.effects.animateClass.call(this,{remove:t},n,r,i):this._removeClass(t)},_toggleClass:e.fn.toggleClass,toggleClass:function(n,r,i,s,o){return typeof r=="boolean"||r===t?i?e.effects.animateClass.call(this,r?{add:n}:{remove:n},i,s,o):this._toggleClass(n,r):e.effects.animateClass.call(this,{toggle:n},r,i,s)},switchClass:function(t,n,r,i,s){return e.effects.animateClass.call(this,{add:n,remove:t},r,i,s)}})}(),function(){function i(t,n,r,i){e.isPlainObject(t)&&(n=t,t=t.effect),t={effect:t},n==null&&(n={}),e.isFunction(n)&&(i=n,r=null,n={});if(typeof n=="number"||e.fx.speeds[n])i=r,r=n,n={};return e.isFunction(r)&&(i=r,r=null),n&&e.extend(t,n),r=r||n.duration,t.duration=e.fx.off?0:typeof r=="number"?r:r in e.fx.speeds?e.fx.speeds[r]:e.fx.speeds._default,t.complete=i||n.complete,t}function s(t){return!t||typeof t=="number"||e.fx.speeds[t]?!0:typeof t=="string"&&!e.effects.effect[t]?n&&e.effects[t]?!1:!0:!1}e.extend(e.effects,{version:"1.9.2",save:function(e,t){for(var n=0;n<t.length;n++)t[n]!==null&&e.data(r+t[n],e[0].style[t[n]])},restore:function(e,n){var i,s;for(s=0;s<n.length;s++)n[s]!==null&&(i=e.data(r+n[s]),i===t&&(i=""),e.css(n[s],i))},setMode:function(e,t){return t==="toggle"&&(t=e.is(":hidden")?"show":"hide"),t},getBaseline:function(e,t){var n,r;switch(e[0]){case"top":n=0;break;case"middle":n=.5;break;case"bottom":n=1;break;default:n=e[0]/t.height}switch(e[1]){case"left":r=0;break;case"center":r=.5;break;case"right":r=1;break;default:r=e[1]/t.width}return{x:r,y:n}},createWrapper:function(t){if(t.parent().is(".ui-effects-wrapper"))return t.parent();var n={width:t.outerWidth(!0),height:t.outerHeight(!0),"float":t.css("float")},r=e("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),i={width:t.width(),height:t.height()},s=document.activeElement;try{s.id}catch(o){s=document.body}return t.wrap(r),(t[0]===s||e.contains(t[0],s))&&e(s).focus(),r=t.parent(),t.css("position")==="static"?(r.css({position:"relative"}),t.css({position:"relative"})):(e.extend(n,{position:t.css("position"),zIndex:t.css("z-index")}),e.each(["top","left","bottom","right"],function(e,r){n[r]=t.css(r),isNaN(parseInt(n[r],10))&&(n[r]="auto")}),t.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),t.css(i),r.css(n).show()},removeWrapper:function(t){var n=document.activeElement;return t.parent().is(".ui-effects-wrapper")&&(t.parent().replaceWith(t),(t[0]===n||e.contains(t[0],n))&&e(n).focus()),t},setTransition:function(t,n,r,i){return i=i||{},e.each(n,function(e,n){var s=t.cssUnit(n);s[0]>0&&(i[n]=s[0]*r+s[1])}),i}}),e.fn.extend({effect:function(){function a(n){function u(){e.isFunction(i)&&i.call(r[0]),e.isFunction(n)&&n()}var r=e(this),i=t.complete,s=t.mode;(r.is(":hidden")?s==="hide":s==="show")?u():o.call(r[0],t,u)}var t=i.apply(this,arguments),r=t.mode,s=t.queue,o=e.effects.effect[t.effect],u=!o&&n&&e.effects[t.effect];return e.fx.off||!o&&!u?r?this[r](t.duration,t.complete):this.each(function(){t.complete&&t.complete.call(this)}):o?s===!1?this.each(a):this.queue(s||"fx",a):u.call(this,{options:t,duration:t.duration,callback:t.complete,mode:t.mode})},_show:e.fn.show,show:function(e){if(s(e))return this._show.apply(this,arguments);var t=i.apply(this,arguments);return t.mode="show",this.effect.call(this,t)},_hide:e.fn.hide,hide:function(e){if(s(e))return this._hide.apply(this,arguments);var t=i.apply(this,arguments);return t.mode="hide",this.effect.call(this,t)},__toggle:e.fn.toggle,toggle:function(t){if(s(t)||typeof t=="boolean"||e.isFunction(t))return this.__toggle.apply(this,arguments);var n=i.apply(this,arguments);return n.mode="toggle",this.effect.call(this,n)},cssUnit:function(t){var n=this.css(t),r=[];return e.each(["em","px","%","pt"],function(e,t){n.indexOf(t)>0&&(r=[parseFloat(n),t])}),r}})}(),function(){var t={};e.each(["Quad","Cubic","Quart","Quint","Expo"],function(e,n){t[n]=function(t){return Math.pow(t,e+2)}}),e.extend(t,{Sine:function(e){return 1-Math.cos(e*Math.PI/2)},Circ:function(e){return 1-Math.sqrt(1-e*e)},Elastic:function(e){return e===0||e===1?e:-Math.pow(2,8*(e-1))*Math.sin(((e-1)*80-7.5)*Math.PI/15)},Back:function(e){return e*e*(3*e-2)},Bounce:function(e){var t,n=4;while(e<((t=Math.pow(2,--n))-1)/11);return 1/Math.pow(4,3-n)-7.5625*Math.pow((t*3-2)/22-e,2)}}),e.each(t,function(t,n){e.easing["easeIn"+t]=n,e.easing["easeOut"+t]=function(e){return 1-n(1-e)},e.easing["easeInOut"+t]=function(e){return e<.5?n(e*2)/2:1-n(e*-2+2)/2}})}()}(jQuery);
\ No newline at end of file
diff --git a/pub/lib/jquery/jquery-ui.js b/pub/lib/jquery/jquery-ui.js
new file mode 100644
index 0000000000000000000000000000000000000000..2f83e5a2ae9167a8280ee073b5fa1ad2b3ca4062
--- /dev/null
+++ b/pub/lib/jquery/jquery-ui.js
@@ -0,0 +1,14912 @@
+/*! jQuery UI - v1.9.2 - 2012-11-23
+* http://jqueryui.com
+* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.ui.effect.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js, jquery.ui.menu.js, jquery.ui.position.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.spinner.js, jquery.ui.tabs.js, jquery.ui.tooltip.js
+* Copyright 2012 jQuery Foundation and other contributors; Licensed MIT */
+
+(function( $, undefined ) {
+
+var uuid = 0,
+	runiqueId = /^ui-id-\d+$/;
+
+// prevent duplicate loading
+// this is only a problem because we proxy existing functions
+// and we don't want to double proxy them
+$.ui = $.ui || {};
+if ( $.ui.version ) {
+	return;
+}
+
+$.extend( $.ui, {
+	version: "1.9.2",
+
+	keyCode: {
+		BACKSPACE: 8,
+		COMMA: 188,
+		DELETE: 46,
+		DOWN: 40,
+		END: 35,
+		ENTER: 13,
+		ESCAPE: 27,
+		HOME: 36,
+		LEFT: 37,
+		NUMPAD_ADD: 107,
+		NUMPAD_DECIMAL: 110,
+		NUMPAD_DIVIDE: 111,
+		NUMPAD_ENTER: 108,
+		NUMPAD_MULTIPLY: 106,
+		NUMPAD_SUBTRACT: 109,
+		PAGE_DOWN: 34,
+		PAGE_UP: 33,
+		PERIOD: 190,
+		RIGHT: 39,
+		SPACE: 32,
+		TAB: 9,
+		UP: 38
+	}
+});
+
+// plugins
+$.fn.extend({
+	_focus: $.fn.focus,
+	focus: function( delay, fn ) {
+		return typeof delay === "number" ?
+			this.each(function() {
+				var elem = this;
+				setTimeout(function() {
+					$( elem ).focus();
+					if ( fn ) {
+						fn.call( elem );
+					}
+				}, delay );
+			}) :
+			this._focus.apply( this, arguments );
+	},
+
+	scrollParent: function() {
+		var scrollParent;
+		if (($.ui.ie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) {
+			scrollParent = this.parents().filter(function() {
+				return (/(relative|absolute|fixed)/).test($.css(this,'position')) && (/(auto|scroll)/).test($.css(this,'overflow')+$.css(this,'overflow-y')+$.css(this,'overflow-x'));
+			}).eq(0);
+		} else {
+			scrollParent = this.parents().filter(function() {
+				return (/(auto|scroll)/).test($.css(this,'overflow')+$.css(this,'overflow-y')+$.css(this,'overflow-x'));
+			}).eq(0);
+		}
+
+		return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent;
+	},
+
+	zIndex: function( zIndex ) {
+		if ( zIndex !== undefined ) {
+			return this.css( "zIndex", zIndex );
+		}
+
+		if ( this.length ) {
+			var elem = $( this[ 0 ] ), position, value;
+			while ( elem.length && elem[ 0 ] !== document ) {
+				// Ignore z-index if position is set to a value where z-index is ignored by the browser
+				// This makes behavior of this function consistent across browsers
+				// WebKit always returns auto if the element is positioned
+				position = elem.css( "position" );
+				if ( position === "absolute" || position === "relative" || position === "fixed" ) {
+					// IE returns 0 when zIndex is not specified
+					// other browsers return a string
+					// we ignore the case of nested elements with an explicit value of 0
+					// <div style="z-index: -10;"><div style="z-index: 0;"></div></div>
+					value = parseInt( elem.css( "zIndex" ), 10 );
+					if ( !isNaN( value ) && value !== 0 ) {
+						return value;
+					}
+				}
+				elem = elem.parent();
+			}
+		}
+
+		return 0;
+	},
+
+	uniqueId: function() {
+		return this.each(function() {
+			if ( !this.id ) {
+				this.id = "ui-id-" + (++uuid);
+			}
+		});
+	},
+
+	removeUniqueId: function() {
+		return this.each(function() {
+			if ( runiqueId.test( this.id ) ) {
+				$( this ).removeAttr( "id" );
+			}
+		});
+	}
+});
+
+// selectors
+function focusable( element, isTabIndexNotNaN ) {
+	var map, mapName, img,
+		nodeName = element.nodeName.toLowerCase();
+	if ( "area" === nodeName ) {
+		map = element.parentNode;
+		mapName = map.name;
+		if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
+			return false;
+		}
+		img = $( "img[usemap=#" + mapName + "]" )[0];
+		return !!img && visible( img );
+	}
+	return ( /input|select|textarea|button|object/.test( nodeName ) ?
+		!element.disabled :
+		"a" === nodeName ?
+			element.href || isTabIndexNotNaN :
+			isTabIndexNotNaN) &&
+		// the element and all of its ancestors must be visible
+		visible( element );
+}
+
+function visible( element ) {
+	return $.expr.filters.visible( element ) &&
+		!$( element ).parents().andSelf().filter(function() {
+			return $.css( this, "visibility" ) === "hidden";
+		}).length;
+}
+
+$.extend( $.expr[ ":" ], {
+	data: $.expr.createPseudo ?
+		$.expr.createPseudo(function( dataName ) {
+			return function( elem ) {
+				return !!$.data( elem, dataName );
+			};
+		}) :
+		// support: jQuery <1.8
+		function( elem, i, match ) {
+			return !!$.data( elem, match[ 3 ] );
+		},
+
+	focusable: function( element ) {
+		return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) );
+	},
+
+	tabbable: function( element ) {
+		var tabIndex = $.attr( element, "tabindex" ),
+			isTabIndexNaN = isNaN( tabIndex );
+		return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN );
+	}
+});
+
+// support
+$(function() {
+	var body = document.body,
+		div = body.appendChild( div = document.createElement( "div" ) );
+
+	// access offsetHeight before setting the style to prevent a layout bug
+	// in IE 9 which causes the element to continue to take up space even
+	// after it is removed from the DOM (#8026)
+	div.offsetHeight;
+
+	$.extend( div.style, {
+		minHeight: "100px",
+		height: "auto",
+		padding: 0,
+		borderWidth: 0
+	});
+
+	$.support.minHeight = div.offsetHeight === 100;
+	$.support.selectstart = "onselectstart" in div;
+
+	// set display to none to avoid a layout bug in IE
+	// http://dev.jquery.com/ticket/4014
+	body.removeChild( div ).style.display = "none";
+});
+
+// support: jQuery <1.8
+if ( !$( "<a>" ).outerWidth( 1 ).jquery ) {
+	$.each( [ "Width", "Height" ], function( i, name ) {
+		var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ],
+			type = name.toLowerCase(),
+			orig = {
+				innerWidth: $.fn.innerWidth,
+				innerHeight: $.fn.innerHeight,
+				outerWidth: $.fn.outerWidth,
+				outerHeight: $.fn.outerHeight
+			};
+
+		function reduce( elem, size, border, margin ) {
+			$.each( side, function() {
+				size -= parseFloat( $.css( elem, "padding" + this ) ) || 0;
+				if ( border ) {
+					size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0;
+				}
+				if ( margin ) {
+					size -= parseFloat( $.css( elem, "margin" + this ) ) || 0;
+				}
+			});
+			return size;
+		}
+
+		$.fn[ "inner" + name ] = function( size ) {
+			if ( size === undefined ) {
+				return orig[ "inner" + name ].call( this );
+			}
+
+			return this.each(function() {
+				$( this ).css( type, reduce( this, size ) + "px" );
+			});
+		};
+
+		$.fn[ "outer" + name] = function( size, margin ) {
+			if ( typeof size !== "number" ) {
+				return orig[ "outer" + name ].call( this, size );
+			}
+
+			return this.each(function() {
+				$( this).css( type, reduce( this, size, true, margin ) + "px" );
+			});
+		};
+	});
+}
+
+// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413)
+if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) {
+	$.fn.removeData = (function( removeData ) {
+		return function( key ) {
+			if ( arguments.length ) {
+				return removeData.call( this, $.camelCase( key ) );
+			} else {
+				return removeData.call( this );
+			}
+		};
+	})( $.fn.removeData );
+}
+
+
+
+
+
+// deprecated
+
+(function() {
+	var uaMatch = /msie ([\w.]+)/.exec( navigator.userAgent.toLowerCase() ) || [];
+	$.ui.ie = uaMatch.length ? true : false;
+	$.ui.ie6 = parseFloat( uaMatch[ 1 ], 10 ) === 6;
+})();
+
+$.fn.extend({
+	disableSelection: function() {
+		return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
+			".ui-disableSelection", function( event ) {
+				event.preventDefault();
+			});
+	},
+
+	enableSelection: function() {
+		return this.unbind( ".ui-disableSelection" );
+	}
+});
+
+$.extend( $.ui, {
+	// $.ui.plugin is deprecated.  Use the proxy pattern instead.
+	plugin: {
+		add: function( module, option, set ) {
+			var i,
+				proto = $.ui[ module ].prototype;
+			for ( i in set ) {
+				proto.plugins[ i ] = proto.plugins[ i ] || [];
+				proto.plugins[ i ].push( [ option, set[ i ] ] );
+			}
+		},
+		call: function( instance, name, args ) {
+			var i,
+				set = instance.plugins[ name ];
+			if ( !set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) {
+				return;
+			}
+
+			for ( i = 0; i < set.length; i++ ) {
+				if ( instance.options[ set[ i ][ 0 ] ] ) {
+					set[ i ][ 1 ].apply( instance.element, args );
+				}
+			}
+		}
+	},
+
+	contains: $.contains,
+
+	// only used by resizable
+	hasScroll: function( el, a ) {
+
+		//If overflow is hidden, the element might have extra content, but the user wants to hide it
+		if ( $( el ).css( "overflow" ) === "hidden") {
+			return false;
+		}
+
+		var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop",
+			has = false;
+
+		if ( el[ scroll ] > 0 ) {
+			return true;
+		}
+
+		// TODO: determine which cases actually cause this to happen
+		// if the element doesn't have the scroll set, see if it's possible to
+		// set the scroll
+		el[ scroll ] = 1;
+		has = ( el[ scroll ] > 0 );
+		el[ scroll ] = 0;
+		return has;
+	},
+
+	// these are odd functions, fix the API or move into individual plugins
+	isOverAxis: function( x, reference, size ) {
+		//Determines when x coordinate is over "b" element axis
+		return ( x > reference ) && ( x < ( reference + size ) );
+	},
+	isOver: function( y, x, top, left, height, width ) {
+		//Determines when x, y coordinates is over "b" element
+		return $.ui.isOverAxis( y, top, height ) && $.ui.isOverAxis( x, left, width );
+	}
+});
+
+})( jQuery );
+
+(function( $, undefined ) {
+
+var uuid = 0,
+	slice = Array.prototype.slice,
+	_cleanData = $.cleanData;
+$.cleanData = function( elems ) {
+	for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
+		try {
+			$( elem ).triggerHandler( "remove" );
+		// http://bugs.jquery.com/ticket/8235
+		} catch( e ) {}
+	}
+	_cleanData( elems );
+};
+
+$.widget = function( name, base, prototype ) {
+	var fullName, existingConstructor, constructor, basePrototype,
+		namespace = name.split( "." )[ 0 ];
+
+	name = name.split( "." )[ 1 ];
+	fullName = namespace + "-" + name;
+
+	if ( !prototype ) {
+		prototype = base;
+		base = $.Widget;
+	}
+
+	// create selector for plugin
+	$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
+		return !!$.data( elem, fullName );
+	};
+
+	$[ namespace ] = $[ namespace ] || {};
+	existingConstructor = $[ namespace ][ name ];
+	constructor = $[ namespace ][ name ] = function( options, element ) {
+		// allow instantiation without "new" keyword
+		if ( !this._createWidget ) {
+			return new constructor( options, element );
+		}
+
+		// allow instantiation without initializing for simple inheritance
+		// must use "new" keyword (the code above always passes args)
+		if ( arguments.length ) {
+			this._createWidget( options, element );
+		}
+	};
+	// extend with the existing constructor to carry over any static properties
+	$.extend( constructor, existingConstructor, {
+		version: prototype.version,
+		// copy the object used to create the prototype in case we need to
+		// redefine the widget later
+		_proto: $.extend( {}, prototype ),
+		// track widgets that inherit from this widget in case this widget is
+		// redefined after a widget inherits from it
+		_childConstructors: []
+	});
+
+	basePrototype = new base();
+	// we need to make the options hash a property directly on the new instance
+	// otherwise we'll modify the options hash on the prototype that we're
+	// inheriting from
+	basePrototype.options = $.widget.extend( {}, basePrototype.options );
+	$.each( prototype, function( prop, value ) {
+		if ( $.isFunction( value ) ) {
+			prototype[ prop ] = (function() {
+				var _super = function() {
+						return base.prototype[ prop ].apply( this, arguments );
+					},
+					_superApply = function( args ) {
+						return base.prototype[ prop ].apply( this, args );
+					};
+				return function() {
+					var __super = this._super,
+						__superApply = this._superApply,
+						returnValue;
+
+					this._super = _super;
+					this._superApply = _superApply;
+
+					returnValue = value.apply( this, arguments );
+
+					this._super = __super;
+					this._superApply = __superApply;
+
+					return returnValue;
+				};
+			})();
+		}
+	});
+	constructor.prototype = $.widget.extend( basePrototype, {
+		// TODO: remove support for widgetEventPrefix
+		// always use the name + a colon as the prefix, e.g., draggable:start
+		// don't prefix for widgets that aren't DOM-based
+		widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name
+	}, prototype, {
+		constructor: constructor,
+		namespace: namespace,
+		widgetName: name,
+		// TODO remove widgetBaseClass, see #8155
+		widgetBaseClass: fullName,
+		widgetFullName: fullName
+	});
+
+	// If this widget is being redefined then we need to find all widgets that
+	// are inheriting from it and redefine all of them so that they inherit from
+	// the new version of this widget. We're essentially trying to replace one
+	// level in the prototype chain.
+	if ( existingConstructor ) {
+		$.each( existingConstructor._childConstructors, function( i, child ) {
+			var childPrototype = child.prototype;
+
+			// redefine the child widget using the same prototype that was
+			// originally used, but inherit from the new version of the base
+			$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
+		});
+		// remove the list of existing child constructors from the old constructor
+		// so the old child constructors can be garbage collected
+		delete existingConstructor._childConstructors;
+	} else {
+		base._childConstructors.push( constructor );
+	}
+
+	$.widget.bridge( name, constructor );
+};
+
+$.widget.extend = function( target ) {
+	var input = slice.call( arguments, 1 ),
+		inputIndex = 0,
+		inputLength = input.length,
+		key,
+		value;
+	for ( ; inputIndex < inputLength; inputIndex++ ) {
+		for ( key in input[ inputIndex ] ) {
+			value = input[ inputIndex ][ key ];
+			if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
+				// Clone objects
+				if ( $.isPlainObject( value ) ) {
+					target[ key ] = $.isPlainObject( target[ key ] ) ?
+						$.widget.extend( {}, target[ key ], value ) :
+						// Don't extend strings, arrays, etc. with objects
+						$.widget.extend( {}, value );
+				// Copy everything else by reference
+				} else {
+					target[ key ] = value;
+				}
+			}
+		}
+	}
+	return target;
+};
+
+$.widget.bridge = function( name, object ) {
+	var fullName = object.prototype.widgetFullName || name;
+	$.fn[ name ] = function( options ) {
+		var isMethodCall = typeof options === "string",
+			args = slice.call( arguments, 1 ),
+			returnValue = this;
+
+		// allow multiple hashes to be passed on init
+		options = !isMethodCall && args.length ?
+			$.widget.extend.apply( null, [ options ].concat(args) ) :
+			options;
+
+		if ( isMethodCall ) {
+			this.each(function() {
+				var methodValue,
+					instance = $.data( this, fullName );
+				if ( !instance ) {
+					return $.error( "cannot call methods on " + name + " prior to initialization; " +
+						"attempted to call method '" + options + "'" );
+				}
+				if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
+					return $.error( "no such method '" + options + "' for " + name + " widget instance" );
+				}
+				methodValue = instance[ options ].apply( instance, args );
+				if ( methodValue !== instance && methodValue !== undefined ) {
+					returnValue = methodValue && methodValue.jquery ?
+						returnValue.pushStack( methodValue.get() ) :
+						methodValue;
+					return false;
+				}
+			});
+		} else {
+			this.each(function() {
+				var instance = $.data( this, fullName );
+				if ( instance ) {
+					instance.option( options || {} )._init();
+				} else {
+					$.data( this, fullName, new object( options, this ) );
+				}
+			});
+		}
+
+		return returnValue;
+	};
+};
+
+$.Widget = function( /* options, element */ ) {};
+$.Widget._childConstructors = [];
+
+$.Widget.prototype = {
+	widgetName: "widget",
+	widgetEventPrefix: "",
+	defaultElement: "<div>",
+	options: {
+		disabled: false,
+
+		// callbacks
+		create: null
+	},
+	_createWidget: function( options, element ) {
+		element = $( element || this.defaultElement || this )[ 0 ];
+		this.element = $( element );
+		this.uuid = uuid++;
+		this.eventNamespace = "." + this.widgetName + this.uuid;
+		this.options = $.widget.extend( {},
+			this.options,
+			this._getCreateOptions(),
+			options );
+
+		this.bindings = $();
+		this.hoverable = $();
+		this.focusable = $();
+
+		if ( element !== this ) {
+			// 1.9 BC for #7810
+			// TODO remove dual storage
+			$.data( element, this.widgetName, this );
+			$.data( element, this.widgetFullName, this );
+			this._on( true, this.element, {
+				remove: function( event ) {
+					if ( event.target === element ) {
+						this.destroy();
+					}
+				}
+			});
+			this.document = $( element.style ?
+				// element within the document
+				element.ownerDocument :
+				// element is window or document
+				element.document || element );
+			this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
+		}
+
+		this._create();
+		this._trigger( "create", null, this._getCreateEventData() );
+		this._init();
+	},
+	_getCreateOptions: $.noop,
+	_getCreateEventData: $.noop,
+	_create: $.noop,
+	_init: $.noop,
+
+	destroy: function() {
+		this._destroy();
+		// we can probably remove the unbind calls in 2.0
+		// all event bindings should go through this._on()
+		this.element
+			.unbind( this.eventNamespace )
+			// 1.9 BC for #7810
+			// TODO remove dual storage
+			.removeData( this.widgetName )
+			.removeData( this.widgetFullName )
+			// support: jquery <1.6.3
+			// http://bugs.jquery.com/ticket/9413
+			.removeData( $.camelCase( this.widgetFullName ) );
+		this.widget()
+			.unbind( this.eventNamespace )
+			.removeAttr( "aria-disabled" )
+			.removeClass(
+				this.widgetFullName + "-disabled " +
+				"ui-state-disabled" );
+
+		// clean up events and states
+		this.bindings.unbind( this.eventNamespace );
+		this.hoverable.removeClass( "ui-state-hover" );
+		this.focusable.removeClass( "ui-state-focus" );
+	},
+	_destroy: $.noop,
+
+	widget: function() {
+		return this.element;
+	},
+
+	option: function( key, value ) {
+		var options = key,
+			parts,
+			curOption,
+			i;
+
+		if ( arguments.length === 0 ) {
+			// don't return a reference to the internal hash
+			return $.widget.extend( {}, this.options );
+		}
+
+		if ( typeof key === "string" ) {
+			// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
+			options = {};
+			parts = key.split( "." );
+			key = parts.shift();
+			if ( parts.length ) {
+				curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
+				for ( i = 0; i < parts.length - 1; i++ ) {
+					curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
+					curOption = curOption[ parts[ i ] ];
+				}
+				key = parts.pop();
+				if ( value === undefined ) {
+					return curOption[ key ] === undefined ? null : curOption[ key ];
+				}
+				curOption[ key ] = value;
+			} else {
+				if ( value === undefined ) {
+					return this.options[ key ] === undefined ? null : this.options[ key ];
+				}
+				options[ key ] = value;
+			}
+		}
+
+		this._setOptions( options );
+
+		return this;
+	},
+	_setOptions: function( options ) {
+		var key;
+
+		for ( key in options ) {
+			this._setOption( key, options[ key ] );
+		}
+
+		return this;
+	},
+	_setOption: function( key, value ) {
+		this.options[ key ] = value;
+
+		if ( key === "disabled" ) {
+			this.widget()
+				.toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
+				.attr( "aria-disabled", value );
+			this.hoverable.removeClass( "ui-state-hover" );
+			this.focusable.removeClass( "ui-state-focus" );
+		}
+
+		return this;
+	},
+
+	enable: function() {
+		return this._setOption( "disabled", false );
+	},
+	disable: function() {
+		return this._setOption( "disabled", true );
+	},
+
+	_on: function( suppressDisabledCheck, element, handlers ) {
+		var delegateElement,
+			instance = this;
+
+		// no suppressDisabledCheck flag, shuffle arguments
+		if ( typeof suppressDisabledCheck !== "boolean" ) {
+			handlers = element;
+			element = suppressDisabledCheck;
+			suppressDisabledCheck = false;
+		}
+
+		// no element argument, shuffle and use this.element
+		if ( !handlers ) {
+			handlers = element;
+			element = this.element;
+			delegateElement = this.widget();
+		} else {
+			// accept selectors, DOM elements
+			element = delegateElement = $( element );
+			this.bindings = this.bindings.add( element );
+		}
+
+		$.each( handlers, function( event, handler ) {
+			function handlerProxy() {
+				// allow widgets to customize the disabled handling
+				// - disabled as an array instead of boolean
+				// - disabled class as method for disabling individual parts
+				if ( !suppressDisabledCheck &&
+						( instance.options.disabled === true ||
+							$( this ).hasClass( "ui-state-disabled" ) ) ) {
+					return;
+				}
+				return ( typeof handler === "string" ? instance[ handler ] : handler )
+					.apply( instance, arguments );
+			}
+
+			// copy the guid so direct unbinding works
+			if ( typeof handler !== "string" ) {
+				handlerProxy.guid = handler.guid =
+					handler.guid || handlerProxy.guid || $.guid++;
+			}
+
+			var match = event.match( /^(\w+)\s*(.*)$/ ),
+				eventName = match[1] + instance.eventNamespace,
+				selector = match[2];
+			if ( selector ) {
+				delegateElement.delegate( selector, eventName, handlerProxy );
+			} else {
+				element.bind( eventName, handlerProxy );
+			}
+		});
+	},
+
+	_off: function( element, eventName ) {
+		eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
+		element.unbind( eventName ).undelegate( eventName );
+	},
+
+	_delay: function( handler, delay ) {
+		function handlerProxy() {
+			return ( typeof handler === "string" ? instance[ handler ] : handler )
+				.apply( instance, arguments );
+		}
+		var instance = this;
+		return setTimeout( handlerProxy, delay || 0 );
+	},
+
+	_hoverable: function( element ) {
+		this.hoverable = this.hoverable.add( element );
+		this._on( element, {
+			mouseenter: function( event ) {
+				$( event.currentTarget ).addClass( "ui-state-hover" );
+			},
+			mouseleave: function( event ) {
+				$( event.currentTarget ).removeClass( "ui-state-hover" );
+			}
+		});
+	},
+
+	_focusable: function( element ) {
+		this.focusable = this.focusable.add( element );
+		this._on( element, {
+			focusin: function( event ) {
+				$( event.currentTarget ).addClass( "ui-state-focus" );
+			},
+			focusout: function( event ) {
+				$( event.currentTarget ).removeClass( "ui-state-focus" );
+			}
+		});
+	},
+
+	_trigger: function( type, event, data ) {
+		var prop, orig,
+			callback = this.options[ type ];
+
+		data = data || {};
+		event = $.Event( event );
+		event.type = ( type === this.widgetEventPrefix ?
+			type :
+			this.widgetEventPrefix + type ).toLowerCase();
+		// the original event may come from any element
+		// so we need to reset the target on the new event
+		event.target = this.element[ 0 ];
+
+		// copy original event properties over to the new event
+		orig = event.originalEvent;
+		if ( orig ) {
+			for ( prop in orig ) {
+				if ( !( prop in event ) ) {
+					event[ prop ] = orig[ prop ];
+				}
+			}
+		}
+
+		this.element.trigger( event, data );
+		return !( $.isFunction( callback ) &&
+			callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
+			event.isDefaultPrevented() );
+	}
+};
+
+$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
+	$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
+		if ( typeof options === "string" ) {
+			options = { effect: options };
+		}
+		var hasOptions,
+			effectName = !options ?
+				method :
+				options === true || typeof options === "number" ?
+					defaultEffect :
+					options.effect || defaultEffect;
+		options = options || {};
+		if ( typeof options === "number" ) {
+			options = { duration: options };
+		}
+		hasOptions = !$.isEmptyObject( options );
+		options.complete = callback;
+		if ( options.delay ) {
+			element.delay( options.delay );
+		}
+		if ( hasOptions && $.effects && ( $.effects.effect[ effectName ] || $.uiBackCompat !== false && $.effects[ effectName ] ) ) {
+			element[ method ]( options );
+		} else if ( effectName !== method && element[ effectName ] ) {
+			element[ effectName ]( options.duration, options.easing, callback );
+		} else {
+			element.queue(function( next ) {
+				$( this )[ method ]();
+				if ( callback ) {
+					callback.call( element[ 0 ] );
+				}
+				next();
+			});
+		}
+	};
+});
+
+// DEPRECATED
+if ( $.uiBackCompat !== false ) {
+	$.Widget.prototype._getCreateOptions = function() {
+		return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ];
+	};
+}
+
+})( jQuery );
+
+(function( $, undefined ) {
+
+var mouseHandled = false;
+$( document ).mouseup( function( e ) {
+	mouseHandled = false;
+});
+
+$.widget("ui.mouse", {
+	version: "1.9.2",
+	options: {
+		cancel: 'input,textarea,button,select,option',
+		distance: 1,
+		delay: 0
+	},
+	_mouseInit: function() {
+		var that = this;
+
+		this.element
+			.bind('mousedown.'+this.widgetName, function(event) {
+				return that._mouseDown(event);
+			})
+			.bind('click.'+this.widgetName, function(event) {
+				if (true === $.data(event.target, that.widgetName + '.preventClickEvent')) {
+					$.removeData(event.target, that.widgetName + '.preventClickEvent');
+					event.stopImmediatePropagation();
+					return false;
+				}
+			});
+
+		this.started = false;
+	},
+
+	// TODO: make sure destroying one instance of mouse doesn't mess with
+	// other instances of mouse
+	_mouseDestroy: function() {
+		this.element.unbind('.'+this.widgetName);
+		if ( this._mouseMoveDelegate ) {
+			$(document)
+				.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
+				.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);
+		}
+	},
+
+	_mouseDown: function(event) {
+		// don't let more than one widget handle mouseStart
+		if( mouseHandled ) { return; }
+
+		// we may have missed mouseup (out of window)
+		(this._mouseStarted && this._mouseUp(event));
+
+		this._mouseDownEvent = event;
+
+		var that = this,
+			btnIsLeft = (event.which === 1),
+			// event.target.nodeName works around a bug in IE 8 with
+			// disabled inputs (#7620)
+			elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
+		if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
+			return true;
+		}
+
+		this.mouseDelayMet = !this.options.delay;
+		if (!this.mouseDelayMet) {
+			this._mouseDelayTimer = setTimeout(function() {
+				that.mouseDelayMet = true;
+			}, this.options.delay);
+		}
+
+		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
+			this._mouseStarted = (this._mouseStart(event) !== false);
+			if (!this._mouseStarted) {
+				event.preventDefault();
+				return true;
+			}
+		}
+
+		// Click event may never have fired (Gecko & Opera)
+		if (true === $.data(event.target, this.widgetName + '.preventClickEvent')) {
+			$.removeData(event.target, this.widgetName + '.preventClickEvent');
+		}
+
+		// these delegates are required to keep context
+		this._mouseMoveDelegate = function(event) {
+			return that._mouseMove(event);
+		};
+		this._mouseUpDelegate = function(event) {
+			return that._mouseUp(event);
+		};
+		$(document)
+			.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
+			.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);
+
+		event.preventDefault();
+
+		mouseHandled = true;
+		return true;
+	},
+
+	_mouseMove: function(event) {
+		// IE mouseup check - mouseup happened when mouse was out of window
+		if ($.ui.ie && !(document.documentMode >= 9) && !event.button) {
+			return this._mouseUp(event);
+		}
+
+		if (this._mouseStarted) {
+			this._mouseDrag(event);
+			return event.preventDefault();
+		}
+
+		if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
+			this._mouseStarted =
+				(this._mouseStart(this._mouseDownEvent, event) !== false);
+			(this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
+		}
+
+		return !this._mouseStarted;
+	},
+
+	_mouseUp: function(event) {
+		$(document)
+			.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
+			.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);
+
+		if (this._mouseStarted) {
+			this._mouseStarted = false;
+
+			if (event.target === this._mouseDownEvent.target) {
+				$.data(event.target, this.widgetName + '.preventClickEvent', true);
+			}
+
+			this._mouseStop(event);
+		}
+
+		return false;
+	},
+
+	_mouseDistanceMet: function(event) {
+		return (Math.max(
+				Math.abs(this._mouseDownEvent.pageX - event.pageX),
+				Math.abs(this._mouseDownEvent.pageY - event.pageY)
+			) >= this.options.distance
+		);
+	},
+
+	_mouseDelayMet: function(event) {
+		return this.mouseDelayMet;
+	},
+
+	// These are placeholder methods, to be overriden by extending plugin
+	_mouseStart: function(event) {},
+	_mouseDrag: function(event) {},
+	_mouseStop: function(event) {},
+	_mouseCapture: function(event) { return true; }
+});
+
+})(jQuery);
+
+(function( $, undefined ) {
+
+$.widget("ui.draggable", $.ui.mouse, {
+	version: "1.9.2",
+	widgetEventPrefix: "drag",
+	options: {
+		addClasses: true,
+		appendTo: "parent",
+		axis: false,
+		connectToSortable: false,
+		containment: false,
+		cursor: "auto",
+		cursorAt: false,
+		grid: false,
+		handle: false,
+		helper: "original",
+		iframeFix: false,
+		opacity: false,
+		refreshPositions: false,
+		revert: false,
+		revertDuration: 500,
+		scope: "default",
+		scroll: true,
+		scrollSensitivity: 20,
+		scrollSpeed: 20,
+		snap: false,
+		snapMode: "both",
+		snapTolerance: 20,
+		stack: false,
+		zIndex: false
+	},
+	_create: function() {
+
+		if (this.options.helper == 'original' && !(/^(?:r|a|f)/).test(this.element.css("position")))
+			this.element[0].style.position = 'relative';
+
+		(this.options.addClasses && this.element.addClass("ui-draggable"));
+		(this.options.disabled && this.element.addClass("ui-draggable-disabled"));
+
+		this._mouseInit();
+
+	},
+
+	_destroy: function() {
+		this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" );
+		this._mouseDestroy();
+	},
+
+	_mouseCapture: function(event) {
+
+		var o = this.options;
+
+		// among others, prevent a drag on a resizable-handle
+		if (this.helper || o.disabled || $(event.target).is('.ui-resizable-handle'))
+			return false;
+
+		//Quit if we're not on a valid handle
+		this.handle = this._getHandle(event);
+		if (!this.handle)
+			return false;
+
+		$(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() {
+			$('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>')
+			.css({
+				width: this.offsetWidth+"px", height: this.offsetHeight+"px",
+				position: "absolute", opacity: "0.001", zIndex: 1000
+			})
+			.css($(this).offset())
+			.appendTo("body");
+		});
+
+		return true;
+
+	},
+
+	_mouseStart: function(event) {
+
+		var o = this.options;
+
+		//Create and append the visible helper
+		this.helper = this._createHelper(event);
+
+		this.helper.addClass("ui-draggable-dragging");
+
+		//Cache the helper size
+		this._cacheHelperProportions();
+
+		//If ddmanager is used for droppables, set the global draggable
+		if($.ui.ddmanager)
+			$.ui.ddmanager.current = this;
+
+		/*
+		 * - Position generation -
+		 * This block generates everything position related - it's the core of draggables.
+		 */
+
+		//Cache the margins of the original element
+		this._cacheMargins();
+
+		//Store the helper's css position
+		this.cssPosition = this.helper.css("position");
+		this.scrollParent = this.helper.scrollParent();
+
+		//The element's absolute position on the page minus margins
+		this.offset = this.positionAbs = this.element.offset();
+		this.offset = {
+			top: this.offset.top - this.margins.top,
+			left: this.offset.left - this.margins.left
+		};
+
+		$.extend(this.offset, {
+			click: { //Where the click happened, relative to the element
+				left: event.pageX - this.offset.left,
+				top: event.pageY - this.offset.top
+			},
+			parent: this._getParentOffset(),
+			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
+		});
+
+		//Generate the original position
+		this.originalPosition = this.position = this._generatePosition(event);
+		this.originalPageX = event.pageX;
+		this.originalPageY = event.pageY;
+
+		//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
+		(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
+
+		//Set a containment if given in the options
+		if(o.containment)
+			this._setContainment();
+
+		//Trigger event + callbacks
+		if(this._trigger("start", event) === false) {
+			this._clear();
+			return false;
+		}
+
+		//Recache the helper size
+		this._cacheHelperProportions();
+
+		//Prepare the droppable offsets
+		if ($.ui.ddmanager && !o.dropBehaviour)
+			$.ui.ddmanager.prepareOffsets(this, event);
+
+
+		this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position
+
+		//If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003)
+		if ( $.ui.ddmanager ) $.ui.ddmanager.dragStart(this, event);
+
+		return true;
+	},
+
+	_mouseDrag: function(event, noPropagation) {
+
+		//Compute the helpers position
+		this.position = this._generatePosition(event);
+		this.positionAbs = this._convertPositionTo("absolute");
+
+		//Call plugins and callbacks and use the resulting position if something is returned
+		if (!noPropagation) {
+			var ui = this._uiHash();
+			if(this._trigger('drag', event, ui) === false) {
+				this._mouseUp({});
+				return false;
+			}
+			this.position = ui.position;
+		}
+
+		if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
+		if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';
+		if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);
+
+		return false;
+	},
+
+	_mouseStop: function(event) {
+
+		//If we are using droppables, inform the manager about the drop
+		var dropped = false;
+		if ($.ui.ddmanager && !this.options.dropBehaviour)
+			dropped = $.ui.ddmanager.drop(this, event);
+
+		//if a drop comes from outside (a sortable)
+		if(this.dropped) {
+			dropped = this.dropped;
+			this.dropped = false;
+		}
+
+		//if the original element is no longer in the DOM don't bother to continue (see #8269)
+		var element = this.element[0], elementInDom = false;
+		while ( element && (element = element.parentNode) ) {
+			if (element == document ) {
+				elementInDom = true;
+			}
+		}
+		if ( !elementInDom && this.options.helper === "original" )
+			return false;
+
+		if((this.options.revert == "invalid" && !dropped) || (this.options.revert == "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
+			var that = this;
+			$(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
+				if(that._trigger("stop", event) !== false) {
+					that._clear();
+				}
+			});
+		} else {
+			if(this._trigger("stop", event) !== false) {
+				this._clear();
+			}
+		}
+
+		return false;
+	},
+
+	_mouseUp: function(event) {
+		//Remove frame helpers
+		$("div.ui-draggable-iframeFix").each(function() {
+			this.parentNode.removeChild(this);
+		});
+
+		//If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003)
+		if( $.ui.ddmanager ) $.ui.ddmanager.dragStop(this, event);
+
+		return $.ui.mouse.prototype._mouseUp.call(this, event);
+	},
+
+	cancel: function() {
+
+		if(this.helper.is(".ui-draggable-dragging")) {
+			this._mouseUp({});
+		} else {
+			this._clear();
+		}
+
+		return this;
+
+	},
+
+	_getHandle: function(event) {
+
+		var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false;
+		$(this.options.handle, this.element)
+			.find("*")
+			.andSelf()
+			.each(function() {
+				if(this == event.target) handle = true;
+			});
+
+		return handle;
+
+	},
+
+	_createHelper: function(event) {
+
+		var o = this.options;
+		var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper == 'clone' ? this.element.clone().removeAttr('id') : this.element);
+
+		if(!helper.parents('body').length)
+			helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo));
+
+		if(helper[0] != this.element[0] && !(/(fixed|absolute)/).test(helper.css("position")))
+			helper.css("position", "absolute");
+
+		return helper;
+
+	},
+
+	_adjustOffsetFromHelper: function(obj) {
+		if (typeof obj == 'string') {
+			obj = obj.split(' ');
+		}
+		if ($.isArray(obj)) {
+			obj = {left: +obj[0], top: +obj[1] || 0};
+		}
+		if ('left' in obj) {
+			this.offset.click.left = obj.left + this.margins.left;
+		}
+		if ('right' in obj) {
+			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
+		}
+		if ('top' in obj) {
+			this.offset.click.top = obj.top + this.margins.top;
+		}
+		if ('bottom' in obj) {
+			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
+		}
+	},
+
+	_getParentOffset: function() {
+
+		//Get the offsetParent and cache its position
+		this.offsetParent = this.helper.offsetParent();
+		var po = this.offsetParent.offset();
+
+		// This is a special case where we need to modify a offset calculated on start, since the following happened:
+		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
+		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
+		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
+		if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
+			po.left += this.scrollParent.scrollLeft();
+			po.top += this.scrollParent.scrollTop();
+		}
+
+		if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information
+		|| (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.ui.ie)) //Ugly IE fix
+			po = { top: 0, left: 0 };
+
+		return {
+			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
+			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
+		};
+
+	},
+
+	_getRelativeOffset: function() {
+
+		if(this.cssPosition == "relative") {
+			var p = this.element.position();
+			return {
+				top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
+				left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
+			};
+		} else {
+			return { top: 0, left: 0 };
+		}
+
+	},
+
+	_cacheMargins: function() {
+		this.margins = {
+			left: (parseInt(this.element.css("marginLeft"),10) || 0),
+			top: (parseInt(this.element.css("marginTop"),10) || 0),
+			right: (parseInt(this.element.css("marginRight"),10) || 0),
+			bottom: (parseInt(this.element.css("marginBottom"),10) || 0)
+		};
+	},
+
+	_cacheHelperProportions: function() {
+		this.helperProportions = {
+			width: this.helper.outerWidth(),
+			height: this.helper.outerHeight()
+		};
+	},
+
+	_setContainment: function() {
+
+		var o = this.options;
+		if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
+		if(o.containment == 'document' || o.containment == 'window') this.containment = [
+			o.containment == 'document' ? 0 : $(window).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
+			o.containment == 'document' ? 0 : $(window).scrollTop() - this.offset.relative.top - this.offset.parent.top,
+			(o.containment == 'document' ? 0 : $(window).scrollLeft()) + $(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left,
+			(o.containment == 'document' ? 0 : $(window).scrollTop()) + ($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
+		];
+
+		if(!(/^(document|window|parent)$/).test(o.containment) && o.containment.constructor != Array) {
+			var c = $(o.containment);
+			var ce = c[0]; if(!ce) return;
+			var co = c.offset();
+			var over = ($(ce).css("overflow") != 'hidden');
+
+			this.containment = [
+				(parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0),
+				(parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0),
+				(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left - this.margins.right,
+				(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top  - this.margins.bottom
+			];
+			this.relative_container = c;
+
+		} else if(o.containment.constructor == Array) {
+			this.containment = o.containment;
+		}
+
+	},
+
+	_convertPositionTo: function(d, pos) {
+
+		if(!pos) pos = this.position;
+		var mod = d == "absolute" ? 1 : -1;
+		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
+
+		return {
+			top: (
+				pos.top																	// The absolute mouse position
+				+ this.offset.relative.top * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
+				+ this.offset.parent.top * mod											// The offsetParent's offset without borders (offset + border)
+				- ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
+			),
+			left: (
+				pos.left																// The absolute mouse position
+				+ this.offset.relative.left * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
+				+ this.offset.parent.left * mod											// The offsetParent's offset without borders (offset + border)
+				- ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
+			)
+		};
+
+	},
+
+	_generatePosition: function(event) {
+
+		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
+		var pageX = event.pageX;
+		var pageY = event.pageY;
+
+		/*
+		 * - Position constraining -
+		 * Constrain the position to a mix of grid, containment.
+		 */
+
+		if(this.originalPosition) { //If we are not dragging yet, we won't check for options
+			var containment;
+			if(this.containment) {
+			if (this.relative_container){
+				var co = this.relative_container.offset();
+				containment = [ this.containment[0] + co.left,
+					this.containment[1] + co.top,
+					this.containment[2] + co.left,
+					this.containment[3] + co.top ];
+			}
+			else {
+				containment = this.containment;
+			}
+
+				if(event.pageX - this.offset.click.left < containment[0]) pageX = containment[0] + this.offset.click.left;
+				if(event.pageY - this.offset.click.top < containment[1]) pageY = containment[1] + this.offset.click.top;
+				if(event.pageX - this.offset.click.left > containment[2]) pageX = containment[2] + this.offset.click.left;
+				if(event.pageY - this.offset.click.top > containment[3]) pageY = containment[3] + this.offset.click.top;
+			}
+
+			if(o.grid) {
+				//Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950)
+				var top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY;
+				pageY = containment ? (!(top - this.offset.click.top < containment[1] || top - this.offset.click.top > containment[3]) ? top : (!(top - this.offset.click.top < containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
+
+				var left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX;
+				pageX = containment ? (!(left - this.offset.click.left < containment[0] || left - this.offset.click.left > containment[2]) ? left : (!(left - this.offset.click.left < containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
+			}
+
+		}
+
+		return {
+			top: (
+				pageY																// The absolute mouse position
+				- this.offset.click.top													// Click offset (relative to the element)
+				- this.offset.relative.top												// Only for relative positioned nodes: Relative offset from element to offset parent
+				- this.offset.parent.top												// The offsetParent's offset without borders (offset + border)
+				+ ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
+			),
+			left: (
+				pageX																// The absolute mouse position
+				- this.offset.click.left												// Click offset (relative to the element)
+				- this.offset.relative.left												// Only for relative positioned nodes: Relative offset from element to offset parent
+				- this.offset.parent.left												// The offsetParent's offset without borders (offset + border)
+				+ ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
+			)
+		};
+
+	},
+
+	_clear: function() {
+		this.helper.removeClass("ui-draggable-dragging");
+		if(this.helper[0] != this.element[0] && !this.cancelHelperRemoval) this.helper.remove();
+		//if($.ui.ddmanager) $.ui.ddmanager.current = null;
+		this.helper = null;
+		this.cancelHelperRemoval = false;
+	},
+
+	// From now on bulk stuff - mainly helpers
+
+	_trigger: function(type, event, ui) {
+		ui = ui || this._uiHash();
+		$.ui.plugin.call(this, type, [event, ui]);
+		if(type == "drag") this.positionAbs = this._convertPositionTo("absolute"); //The absolute position has to be recalculated after plugins
+		return $.Widget.prototype._trigger.call(this, type, event, ui);
+	},
+
+	plugins: {},
+
+	_uiHash: function(event) {
+		return {
+			helper: this.helper,
+			position: this.position,
+			originalPosition: this.originalPosition,
+			offset: this.positionAbs
+		};
+	}
+
+});
+
+$.ui.plugin.add("draggable", "connectToSortable", {
+	start: function(event, ui) {
+
+		var inst = $(this).data("draggable"), o = inst.options,
+			uiSortable = $.extend({}, ui, { item: inst.element });
+		inst.sortables = [];
+		$(o.connectToSortable).each(function() {
+			var sortable = $.data(this, 'sortable');
+			if (sortable && !sortable.options.disabled) {
+				inst.sortables.push({
+					instance: sortable,
+					shouldRevert: sortable.options.revert
+				});
+				sortable.refreshPositions();	// Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page).
+				sortable._trigger("activate", event, uiSortable);
+			}
+		});
+
+	},
+	stop: function(event, ui) {
+
+		//If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
+		var inst = $(this).data("draggable"),
+			uiSortable = $.extend({}, ui, { item: inst.element });
+
+		$.each(inst.sortables, function() {
+			if(this.instance.isOver) {
+
+				this.instance.isOver = 0;
+
+				inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
+				this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)
+
+				//The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: 'valid/invalid'
+				if(this.shouldRevert) this.instance.options.revert = true;
+
+				//Trigger the stop of the sortable
+				this.instance._mouseStop(event);
+
+				this.instance.options.helper = this.instance.options._helper;
+
+				//If the helper has been the original item, restore properties in the sortable
+				if(inst.options.helper == 'original')
+					this.instance.currentItem.css({ top: 'auto', left: 'auto' });
+
+			} else {
+				this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
+				this.instance._trigger("deactivate", event, uiSortable);
+			}
+
+		});
+
+	},
+	drag: function(event, ui) {
+
+		var inst = $(this).data("draggable"), that = this;
+
+		var checkPos = function(o) {
+			var dyClick = this.offset.click.top, dxClick = this.offset.click.left;
+			var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left;
+			var itemHeight = o.height, itemWidth = o.width;
+			var itemTop = o.top, itemLeft = o.left;
+
+			return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth);
+		};
+
+		$.each(inst.sortables, function(i) {
+
+			var innermostIntersecting = false;
+			var thisSortable = this;
+			//Copy over some variables to allow calling the sortable's native _intersectsWith
+			this.instance.positionAbs = inst.positionAbs;
+			this.instance.helperProportions = inst.helperProportions;
+			this.instance.offset.click = inst.offset.click;
+
+			if(this.instance._intersectsWith(this.instance.containerCache)) {
+				innermostIntersecting = true;
+				$.each(inst.sortables, function () {
+					this.instance.positionAbs = inst.positionAbs;
+					this.instance.helperProportions = inst.helperProportions;
+					this.instance.offset.click = inst.offset.click;
+					if  (this != thisSortable
+						&& this.instance._intersectsWith(this.instance.containerCache)
+						&& $.ui.contains(thisSortable.instance.element[0], this.instance.element[0]))
+						innermostIntersecting = false;
+						return innermostIntersecting;
+				});
+			}
+
+
+			if(innermostIntersecting) {
+				//If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
+				if(!this.instance.isOver) {
+
+					this.instance.isOver = 1;
+					//Now we fake the start of dragging for the sortable instance,
+					//by cloning the list group item, appending it to the sortable and using it as inst.currentItem
+					//We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
+					this.instance.currentItem = $(that).clone().removeAttr('id').appendTo(this.instance.element).data("sortable-item", true);
+					this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
+					this.instance.options.helper = function() { return ui.helper[0]; };
+
+					event.target = this.instance.currentItem[0];
+					this.instance._mouseCapture(event, true);
+					this.instance._mouseStart(event, true, true);
+
+					//Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
+					this.instance.offset.click.top = inst.offset.click.top;
+					this.instance.offset.click.left = inst.offset.click.left;
+					this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
+					this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;
+
+					inst._trigger("toSortable", event);
+					inst.dropped = this.instance.element; //draggable revert needs that
+					//hack so receive/update callbacks work (mostly)
+					inst.currentItem = inst.element;
+					this.instance.fromOutside = inst;
+
+				}
+
+				//Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
+				if(this.instance.currentItem) this.instance._mouseDrag(event);
+
+			} else {
+
+				//If it doesn't intersect with the sortable, and it intersected before,
+				//we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
+				if(this.instance.isOver) {
+
+					this.instance.isOver = 0;
+					this.instance.cancelHelperRemoval = true;
+
+					//Prevent reverting on this forced stop
+					this.instance.options.revert = false;
+
+					// The out event needs to be triggered independently
+					this.instance._trigger('out', event, this.instance._uiHash(this.instance));
+
+					this.instance._mouseStop(event, true);
+					this.instance.options.helper = this.instance.options._helper;
+
+					//Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
+					this.instance.currentItem.remove();
+					if(this.instance.placeholder) this.instance.placeholder.remove();
+
+					inst._trigger("fromSortable", event);
+					inst.dropped = false; //draggable revert needs that
+				}
+
+			};
+
+		});
+
+	}
+});
+
+$.ui.plugin.add("draggable", "cursor", {
+	start: function(event, ui) {
+		var t = $('body'), o = $(this).data('draggable').options;
+		if (t.css("cursor")) o._cursor = t.css("cursor");
+		t.css("cursor", o.cursor);
+	},
+	stop: function(event, ui) {
+		var o = $(this).data('draggable').options;
+		if (o._cursor) $('body').css("cursor", o._cursor);
+	}
+});
+
+$.ui.plugin.add("draggable", "opacity", {
+	start: function(event, ui) {
+		var t = $(ui.helper), o = $(this).data('draggable').options;
+		if(t.css("opacity")) o._opacity = t.css("opacity");
+		t.css('opacity', o.opacity);
+	},
+	stop: function(event, ui) {
+		var o = $(this).data('draggable').options;
+		if(o._opacity) $(ui.helper).css('opacity', o._opacity);
+	}
+});
+
+$.ui.plugin.add("draggable", "scroll", {
+	start: function(event, ui) {
+		var i = $(this).data("draggable");
+		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') i.overflowOffset = i.scrollParent.offset();
+	},
+	drag: function(event, ui) {
+
+		var i = $(this).data("draggable"), o = i.options, scrolled = false;
+
+		if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') {
+
+			if(!o.axis || o.axis != 'x') {
+				if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
+					i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
+				else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity)
+					i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;
+			}
+
+			if(!o.axis || o.axis != 'y') {
+				if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
+					i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
+				else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity)
+					i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;
+			}
+
+		} else {
+
+			if(!o.axis || o.axis != 'x') {
+				if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
+					scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
+				else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
+					scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
+			}
+
+			if(!o.axis || o.axis != 'y') {
+				if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
+					scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
+				else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
+					scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
+			}
+
+		}
+
+		if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
+			$.ui.ddmanager.prepareOffsets(i, event);
+
+	}
+});
+
+$.ui.plugin.add("draggable", "snap", {
+	start: function(event, ui) {
+
+		var i = $(this).data("draggable"), o = i.options;
+		i.snapElements = [];
+
+		$(o.snap.constructor != String ? ( o.snap.items || ':data(draggable)' ) : o.snap).each(function() {
+			var $t = $(this); var $o = $t.offset();
+			if(this != i.element[0]) i.snapElements.push({
+				item: this,
+				width: $t.outerWidth(), height: $t.outerHeight(),
+				top: $o.top, left: $o.left
+			});
+		});
+
+	},
+	drag: function(event, ui) {
+
+		var inst = $(this).data("draggable"), o = inst.options;
+		var d = o.snapTolerance;
+
+		var x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
+			y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;
+
+		for (var i = inst.snapElements.length - 1; i >= 0; i--){
+
+			var l = inst.snapElements[i].left, r = l + inst.snapElements[i].width,
+				t = inst.snapElements[i].top, b = t + inst.snapElements[i].height;
+
+			//Yes, I know, this is insane ;)
+			if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) {
+				if(inst.snapElements[i].snapping) (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
+				inst.snapElements[i].snapping = false;
+				continue;
+			}
+
+			if(o.snapMode != 'inner') {
+				var ts = Math.abs(t - y2) <= d;
+				var bs = Math.abs(b - y1) <= d;
+				var ls = Math.abs(l - x2) <= d;
+				var rs = Math.abs(r - x1) <= d;
+				if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
+				if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
+				if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
+				if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left;
+			}
+
+			var first = (ts || bs || ls || rs);
+
+			if(o.snapMode != 'outer') {
+				var ts = Math.abs(t - y1) <= d;
+				var bs = Math.abs(b - y2) <= d;
+				var ls = Math.abs(l - x1) <= d;
+				var rs = Math.abs(r - x2) <= d;
+				if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top;
+				if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
+				if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left;
+				if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left;
+			}
+
+			if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first))
+				(inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
+			inst.snapElements[i].snapping = (ts || bs || ls || rs || first);
+
+		};
+
+	}
+});
+
+$.ui.plugin.add("draggable", "stack", {
+	start: function(event, ui) {
+
+		var o = $(this).data("draggable").options;
+
+		var group = $.makeArray($(o.stack)).sort(function(a,b) {
+			return (parseInt($(a).css("zIndex"),10) || 0) - (parseInt($(b).css("zIndex"),10) || 0);
+		});
+		if (!group.length) { return; }
+
+		var min = parseInt(group[0].style.zIndex) || 0;
+		$(group).each(function(i) {
+			this.style.zIndex = min + i;
+		});
+
+		this[0].style.zIndex = min + group.length;
+
+	}
+});
+
+$.ui.plugin.add("draggable", "zIndex", {
+	start: function(event, ui) {
+		var t = $(ui.helper), o = $(this).data("draggable").options;
+		if(t.css("zIndex")) o._zIndex = t.css("zIndex");
+		t.css('zIndex', o.zIndex);
+	},
+	stop: function(event, ui) {
+		var o = $(this).data("draggable").options;
+		if(o._zIndex) $(ui.helper).css('zIndex', o._zIndex);
+	}
+});
+
+})(jQuery);
+
+(function( $, undefined ) {
+
+$.widget("ui.droppable", {
+	version: "1.9.2",
+	widgetEventPrefix: "drop",
+	options: {
+		accept: '*',
+		activeClass: false,
+		addClasses: true,
+		greedy: false,
+		hoverClass: false,
+		scope: 'default',
+		tolerance: 'intersect'
+	},
+	_create: function() {
+
+		var o = this.options, accept = o.accept;
+		this.isover = 0; this.isout = 1;
+
+		this.accept = $.isFunction(accept) ? accept : function(d) {
+			return d.is(accept);
+		};
+
+		//Store the droppable's proportions
+		this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight };
+
+		// Add the reference and positions to the manager
+		$.ui.ddmanager.droppables[o.scope] = $.ui.ddmanager.droppables[o.scope] || [];
+		$.ui.ddmanager.droppables[o.scope].push(this);
+
+		(o.addClasses && this.element.addClass("ui-droppable"));
+
+	},
+
+	_destroy: function() {
+		var drop = $.ui.ddmanager.droppables[this.options.scope];
+		for ( var i = 0; i < drop.length; i++ )
+			if ( drop[i] == this )
+				drop.splice(i, 1);
+
+		this.element.removeClass("ui-droppable ui-droppable-disabled");
+	},
+
+	_setOption: function(key, value) {
+
+		if(key == 'accept') {
+			this.accept = $.isFunction(value) ? value : function(d) {
+				return d.is(value);
+			};
+		}
+		$.Widget.prototype._setOption.apply(this, arguments);
+	},
+
+	_activate: function(event) {
+		var draggable = $.ui.ddmanager.current;
+		if(this.options.activeClass) this.element.addClass(this.options.activeClass);
+		(draggable && this._trigger('activate', event, this.ui(draggable)));
+	},
+
+	_deactivate: function(event) {
+		var draggable = $.ui.ddmanager.current;
+		if(this.options.activeClass) this.element.removeClass(this.options.activeClass);
+		(draggable && this._trigger('deactivate', event, this.ui(draggable)));
+	},
+
+	_over: function(event) {
+
+		var draggable = $.ui.ddmanager.current;
+		if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element
+
+		if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
+			if(this.options.hoverClass) this.element.addClass(this.options.hoverClass);
+			this._trigger('over', event, this.ui(draggable));
+		}
+
+	},
+
+	_out: function(event) {
+
+		var draggable = $.ui.ddmanager.current;
+		if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element
+
+		if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
+			if(this.options.hoverClass) this.element.removeClass(this.options.hoverClass);
+			this._trigger('out', event, this.ui(draggable));
+		}
+
+	},
+
+	_drop: function(event,custom) {
+
+		var draggable = custom || $.ui.ddmanager.current;
+		if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return false; // Bail if draggable and droppable are same element
+
+		var childrenIntersection = false;
+		this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function() {
+			var inst = $.data(this, 'droppable');
+			if(
+				inst.options.greedy
+				&& !inst.options.disabled
+				&& inst.options.scope == draggable.options.scope
+				&& inst.accept.call(inst.element[0], (draggable.currentItem || draggable.element))
+				&& $.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance)
+			) { childrenIntersection = true; return false; }
+		});
+		if(childrenIntersection) return false;
+
+		if(this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
+			if(this.options.activeClass) this.element.removeClass(this.options.activeClass);
+			if(this.options.hoverClass) this.element.removeClass(this.options.hoverClass);
+			this._trigger('drop', event, this.ui(draggable));
+			return this.element;
+		}
+
+		return false;
+
+	},
+
+	ui: function(c) {
+		return {
+			draggable: (c.currentItem || c.element),
+			helper: c.helper,
+			position: c.position,
+			offset: c.positionAbs
+		};
+	}
+
+});
+
+$.ui.intersect = function(draggable, droppable, toleranceMode) {
+
+	if (!droppable.offset) return false;
+
+	var x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width,
+		y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height;
+	var l = droppable.offset.left, r = l + droppable.proportions.width,
+		t = droppable.offset.top, b = t + droppable.proportions.height;
+
+	switch (toleranceMode) {
+		case 'fit':
+			return (l <= x1 && x2 <= r
+				&& t <= y1 && y2 <= b);
+			break;
+		case 'intersect':
+			return (l < x1 + (draggable.helperProportions.width / 2) // Right Half
+				&& x2 - (draggable.helperProportions.width / 2) < r // Left Half
+				&& t < y1 + (draggable.helperProportions.height / 2) // Bottom Half
+				&& y2 - (draggable.helperProportions.height / 2) < b ); // Top Half
+			break;
+		case 'pointer':
+			var draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left),
+				draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top),
+				isOver = $.ui.isOver(draggableTop, draggableLeft, t, l, droppable.proportions.height, droppable.proportions.width);
+			return isOver;
+			break;
+		case 'touch':
+			return (
+					(y1 >= t && y1 <= b) ||	// Top edge touching
+					(y2 >= t && y2 <= b) ||	// Bottom edge touching
+					(y1 < t && y2 > b)		// Surrounded vertically
+				) && (
+					(x1 >= l && x1 <= r) ||	// Left edge touching
+					(x2 >= l && x2 <= r) ||	// Right edge touching
+					(x1 < l && x2 > r)		// Surrounded horizontally
+				);
+			break;
+		default:
+			return false;
+			break;
+		}
+
+};
+
+/*
+	This manager tracks offsets of draggables and droppables
+*/
+$.ui.ddmanager = {
+	current: null,
+	droppables: { 'default': [] },
+	prepareOffsets: function(t, event) {
+
+		var m = $.ui.ddmanager.droppables[t.options.scope] || [];
+		var type = event ? event.type : null; // workaround for #2317
+		var list = (t.currentItem || t.element).find(":data(droppable)").andSelf();
+
+		droppablesLoop: for (var i = 0; i < m.length; i++) {
+
+			if(m[i].options.disabled || (t && !m[i].accept.call(m[i].element[0],(t.currentItem || t.element)))) continue;	//No disabled and non-accepted
+			for (var j=0; j < list.length; j++) { if(list[j] == m[i].element[0]) { m[i].proportions.height = 0; continue droppablesLoop; } }; //Filter out elements in the current dragged item
+			m[i].visible = m[i].element.css("display") != "none"; if(!m[i].visible) continue; 									//If the element is not visible, continue
+
+			if(type == "mousedown") m[i]._activate.call(m[i], event); //Activate the droppable if used directly from draggables
+
+			m[i].offset = m[i].element.offset();
+			m[i].proportions = { width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight };
+
+		}
+
+	},
+	drop: function(draggable, event) {
+
+		var dropped = false;
+		$.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() {
+
+			if(!this.options) return;
+			if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance))
+				dropped = this._drop.call(this, event) || dropped;
+
+			if (!this.options.disabled && this.visible && this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
+				this.isout = 1; this.isover = 0;
+				this._deactivate.call(this, event);
+			}
+
+		});
+		return dropped;
+
+	},
+	dragStart: function( draggable, event ) {
+		//Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003)
+		draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() {
+			if( !draggable.options.refreshPositions ) $.ui.ddmanager.prepareOffsets( draggable, event );
+		});
+	},
+	drag: function(draggable, event) {
+
+		//If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse.
+		if(draggable.options.refreshPositions) $.ui.ddmanager.prepareOffsets(draggable, event);
+
+		//Run through all droppables and check their positions based on specific tolerance options
+		$.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() {
+
+			if(this.options.disabled || this.greedyChild || !this.visible) return;
+			var intersects = $.ui.intersect(draggable, this, this.options.tolerance);
+
+			var c = !intersects && this.isover == 1 ? 'isout' : (intersects && this.isover == 0 ? 'isover' : null);
+			if(!c) return;
+
+			var parentInstance;
+			if (this.options.greedy) {
+				// find droppable parents with same scope
+				var scope = this.options.scope;
+				var parent = this.element.parents(':data(droppable)').filter(function () {
+					return $.data(this, 'droppable').options.scope === scope;
+				});
+
+				if (parent.length) {
+					parentInstance = $.data(parent[0], 'droppable');
+					parentInstance.greedyChild = (c == 'isover' ? 1 : 0);
+				}
+			}
+
+			// we just moved into a greedy child
+			if (parentInstance && c == 'isover') {
+				parentInstance['isover'] = 0;
+				parentInstance['isout'] = 1;
+				parentInstance._out.call(parentInstance, event);
+			}
+
+			this[c] = 1; this[c == 'isout' ? 'isover' : 'isout'] = 0;
+			this[c == "isover" ? "_over" : "_out"].call(this, event);
+
+			// we just moved out of a greedy child
+			if (parentInstance && c == 'isout') {
+				parentInstance['isout'] = 0;
+				parentInstance['isover'] = 1;
+				parentInstance._over.call(parentInstance, event);
+			}
+		});
+
+	},
+	dragStop: function( draggable, event ) {
+		draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" );
+		//Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003)
+		if( !draggable.options.refreshPositions ) $.ui.ddmanager.prepareOffsets( draggable, event );
+	}
+};
+
+})(jQuery);
+
+(function( $, undefined ) {
+
+$.widget("ui.resizable", $.ui.mouse, {
+	version: "1.9.2",
+	widgetEventPrefix: "resize",
+	options: {
+		alsoResize: false,
+		animate: false,
+		animateDuration: "slow",
+		animateEasing: "swing",
+		aspectRatio: false,
+		autoHide: false,
+		containment: false,
+		ghost: false,
+		grid: false,
+		handles: "e,s,se",
+		helper: false,
+		maxHeight: null,
+		maxWidth: null,
+		minHeight: 10,
+		minWidth: 10,
+		zIndex: 1000
+	},
+	_create: function() {
+
+		var that = this, o = this.options;
+		this.element.addClass("ui-resizable");
+
+		$.extend(this, {
+			_aspectRatio: !!(o.aspectRatio),
+			aspectRatio: o.aspectRatio,
+			originalElement: this.element,
+			_proportionallyResizeElements: [],
+			_helper: o.helper || o.ghost || o.animate ? o.helper || 'ui-resizable-helper' : null
+		});
+
+		//Wrap the element if it cannot hold child nodes
+		if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) {
+
+			//Create a wrapper element and set the wrapper to the new current internal element
+			this.element.wrap(
+				$('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({
+					position: this.element.css('position'),
+					width: this.element.outerWidth(),
+					height: this.element.outerHeight(),
+					top: this.element.css('top'),
+					left: this.element.css('left')
+				})
+			);
+
+			//Overwrite the original this.element
+			this.element = this.element.parent().data(
+				"resizable", this.element.data('resizable')
+			);
+
+			this.elementIsWrapper = true;
+
+			//Move margins to the wrapper
+			this.element.css({ marginLeft: this.originalElement.css("marginLeft"), marginTop: this.originalElement.css("marginTop"), marginRight: this.originalElement.css("marginRight"), marginBottom: this.originalElement.css("marginBottom") });
+			this.originalElement.css({ marginLeft: 0, marginTop: 0, marginRight: 0, marginBottom: 0});
+
+			//Prevent Safari textarea resize
+			this.originalResizeStyle = this.originalElement.css('resize');
+			this.originalElement.css('resize', 'none');
+
+			//Push the actual element to our proportionallyResize internal array
+			this._proportionallyResizeElements.push(this.originalElement.css({ position: 'static', zoom: 1, display: 'block' }));
+
+			// avoid IE jump (hard set the margin)
+			this.originalElement.css({ margin: this.originalElement.css('margin') });
+
+			// fix handlers offset
+			this._proportionallyResize();
+
+		}
+
+		this.handles = o.handles || (!$('.ui-resizable-handle', this.element).length ? "e,s,se" : { n: '.ui-resizable-n', e: '.ui-resizable-e', s: '.ui-resizable-s', w: '.ui-resizable-w', se: '.ui-resizable-se', sw: '.ui-resizable-sw', ne: '.ui-resizable-ne', nw: '.ui-resizable-nw' });
+		if(this.handles.constructor == String) {
+
+			if(this.handles == 'all') this.handles = 'n,e,s,w,se,sw,ne,nw';
+			var n = this.handles.split(","); this.handles = {};
+
+			for(var i = 0; i < n.length; i++) {
+
+				var handle = $.trim(n[i]), hname = 'ui-resizable-'+handle;
+				var axis = $('<div class="ui-resizable-handle ' + hname + '"></div>');
+
+				// Apply zIndex to all handles - see #7960
+				axis.css({ zIndex: o.zIndex });
+
+				//TODO : What's going on here?
+				if ('se' == handle) {
+					axis.addClass('ui-icon ui-icon-gripsmall-diagonal-se');
+				};
+
+				//Insert into internal handles object and append to element
+				this.handles[handle] = '.ui-resizable-'+handle;
+				this.element.append(axis);
+			}
+
+		}
+
+		this._renderAxis = function(target) {
+
+			target = target || this.element;
+
+			for(var i in this.handles) {
+
+				if(this.handles[i].constructor == String)
+					this.handles[i] = $(this.handles[i], this.element).show();
+
+				//Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls)
+				if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) {
+
+					var axis = $(this.handles[i], this.element), padWrapper = 0;
+
+					//Checking the correct pad and border
+					padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth();
+
+					//The padding type i have to apply...
+					var padPos = [ 'padding',
+						/ne|nw|n/.test(i) ? 'Top' :
+						/se|sw|s/.test(i) ? 'Bottom' :
+						/^e$/.test(i) ? 'Right' : 'Left' ].join("");
+
+					target.css(padPos, padWrapper);
+
+					this._proportionallyResize();
+
+				}
+
+				//TODO: What's that good for? There's not anything to be executed left
+				if(!$(this.handles[i]).length)
+					continue;
+
+			}
+		};
+
+		//TODO: make renderAxis a prototype function
+		this._renderAxis(this.element);
+
+		this._handles = $('.ui-resizable-handle', this.element)
+			.disableSelection();
+
+		//Matching axis name
+		this._handles.mouseover(function() {
+			if (!that.resizing) {
+				if (this.className)
+					var axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);
+				//Axis, default = se
+				that.axis = axis && axis[1] ? axis[1] : 'se';
+			}
+		});
+
+		//If we want to auto hide the elements
+		if (o.autoHide) {
+			this._handles.hide();
+			$(this.element)
+				.addClass("ui-resizable-autohide")
+				.mouseenter(function() {
+					if (o.disabled) return;
+					$(this).removeClass("ui-resizable-autohide");
+					that._handles.show();
+				})
+				.mouseleave(function(){
+					if (o.disabled) return;
+					if (!that.resizing) {
+						$(this).addClass("ui-resizable-autohide");
+						that._handles.hide();
+					}
+				});
+		}
+
+		//Initialize the mouse interaction
+		this._mouseInit();
+
+	},
+
+	_destroy: function() {
+
+		this._mouseDestroy();
+
+		var _destroy = function(exp) {
+			$(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing")
+				.removeData("resizable").removeData("ui-resizable").unbind(".resizable").find('.ui-resizable-handle').remove();
+		};
+
+		//TODO: Unwrap at same DOM position
+		if (this.elementIsWrapper) {
+			_destroy(this.element);
+			var wrapper = this.element;
+			this.originalElement.css({
+				position: wrapper.css('position'),
+				width: wrapper.outerWidth(),
+				height: wrapper.outerHeight(),
+				top: wrapper.css('top'),
+				left: wrapper.css('left')
+			}).insertAfter( wrapper );
+			wrapper.remove();
+		}
+
+		this.originalElement.css('resize', this.originalResizeStyle);
+		_destroy(this.originalElement);
+
+		return this;
+	},
+
+	_mouseCapture: function(event) {
+		var handle = false;
+		for (var i in this.handles) {
+			if ($(this.handles[i])[0] == event.target) {
+				handle = true;
+			}
+		}
+
+		return !this.options.disabled && handle;
+	},
+
+	_mouseStart: function(event) {
+
+		var o = this.options, iniPos = this.element.position(), el = this.element;
+
+		this.resizing = true;
+		this.documentScroll = { top: $(document).scrollTop(), left: $(document).scrollLeft() };
+
+		// bugfix for http://dev.jquery.com/ticket/1749
+		if (el.is('.ui-draggable') || (/absolute/).test(el.css('position'))) {
+			el.css({ position: 'absolute', top: iniPos.top, left: iniPos.left });
+		}
+
+		this._renderProxy();
+
+		var curleft = num(this.helper.css('left')), curtop = num(this.helper.css('top'));
+
+		if (o.containment) {
+			curleft += $(o.containment).scrollLeft() || 0;
+			curtop += $(o.containment).scrollTop() || 0;
+		}
+
+		//Store needed variables
+		this.offset = this.helper.offset();
+		this.position = { left: curleft, top: curtop };
+		this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
+		this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() };
+		this.originalPosition = { left: curleft, top: curtop };
+		this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() };
+		this.originalMousePosition = { left: event.pageX, top: event.pageY };
+
+		//Aspect Ratio
+		this.aspectRatio = (typeof o.aspectRatio == 'number') ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1);
+
+		var cursor = $('.ui-resizable-' + this.axis).css('cursor');
+		$('body').css('cursor', cursor == 'auto' ? this.axis + '-resize' : cursor);
+
+		el.addClass("ui-resizable-resizing");
+		this._propagate("start", event);
+		return true;
+	},
+
+	_mouseDrag: function(event) {
+
+		//Increase performance, avoid regex
+		var el = this.helper, o = this.options, props = {},
+			that = this, smp = this.originalMousePosition, a = this.axis;
+
+		var dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0;
+		var trigger = this._change[a];
+		if (!trigger) return false;
+
+		// Calculate the attrs that will be change
+		var data = trigger.apply(this, [event, dx, dy]);
+
+		// Put this in the mouseDrag handler since the user can start pressing shift while resizing
+		this._updateVirtualBoundaries(event.shiftKey);
+		if (this._aspectRatio || event.shiftKey)
+			data = this._updateRatio(data, event);
+
+		data = this._respectSize(data, event);
+
+		// plugins callbacks need to be called first
+		this._propagate("resize", event);
+
+		el.css({
+			top: this.position.top + "px", left: this.position.left + "px",
+			width: this.size.width + "px", height: this.size.height + "px"
+		});
+
+		if (!this._helper && this._proportionallyResizeElements.length)
+			this._proportionallyResize();
+
+		this._updateCache(data);
+
+		// calling the user callback at the end
+		this._trigger('resize', event, this.ui());
+
+		return false;
+	},
+
+	_mouseStop: function(event) {
+
+		this.resizing = false;
+		var o = this.options, that = this;
+
+		if(this._helper) {
+			var pr = this._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName),
+				soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : that.sizeDiff.height,
+				soffsetw = ista ? 0 : that.sizeDiff.width;
+
+			var s = { width: (that.helper.width()  - soffsetw), height: (that.helper.height() - soffseth) },
+				left = (parseInt(that.element.css('left'), 10) + (that.position.left - that.originalPosition.left)) || null,
+				top = (parseInt(that.element.css('top'), 10) + (that.position.top - that.originalPosition.top)) || null;
+
+			if (!o.animate)
+				this.element.css($.extend(s, { top: top, left: left }));
+
+			that.helper.height(that.size.height);
+			that.helper.width(that.size.width);
+
+			if (this._helper && !o.animate) this._proportionallyResize();
+		}
+
+		$('body').css('cursor', 'auto');
+
+		this.element.removeClass("ui-resizable-resizing");
+
+		this._propagate("stop", event);
+
+		if (this._helper) this.helper.remove();
+		return false;
+
+	},
+
+	_updateVirtualBoundaries: function(forceAspectRatio) {
+		var o = this.options, pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b;
+
+		b = {
+			minWidth: isNumber(o.minWidth) ? o.minWidth : 0,
+			maxWidth: isNumber(o.maxWidth) ? o.maxWidth : Infinity,
+			minHeight: isNumber(o.minHeight) ? o.minHeight : 0,
+			maxHeight: isNumber(o.maxHeight) ? o.maxHeight : Infinity
+		};
+
+		if(this._aspectRatio || forceAspectRatio) {
+			// We want to create an enclosing box whose aspect ration is the requested one
+			// First, compute the "projected" size for each dimension based on the aspect ratio and other dimension
+			pMinWidth = b.minHeight * this.aspectRatio;
+			pMinHeight = b.minWidth / this.aspectRatio;
+			pMaxWidth = b.maxHeight * this.aspectRatio;
+			pMaxHeight = b.maxWidth / this.aspectRatio;
+
+			if(pMinWidth > b.minWidth) b.minWidth = pMinWidth;
+			if(pMinHeight > b.minHeight) b.minHeight = pMinHeight;
+			if(pMaxWidth < b.maxWidth) b.maxWidth = pMaxWidth;
+			if(pMaxHeight < b.maxHeight) b.maxHeight = pMaxHeight;
+		}
+		this._vBoundaries = b;
+	},
+
+	_updateCache: function(data) {
+		var o = this.options;
+		this.offset = this.helper.offset();
+		if (isNumber(data.left)) this.position.left = data.left;
+		if (isNumber(data.top)) this.position.top = data.top;
+		if (isNumber(data.height)) this.size.height = data.height;
+		if (isNumber(data.width)) this.size.width = data.width;
+	},
+
+	_updateRatio: function(data, event) {
+
+		var o = this.options, cpos = this.position, csize = this.size, a = this.axis;
+
+		if (isNumber(data.height)) data.width = (data.height * this.aspectRatio);
+		else if (isNumber(data.width)) data.height = (data.width / this.aspectRatio);
+
+		if (a == 'sw') {
+			data.left = cpos.left + (csize.width - data.width);
+			data.top = null;
+		}
+		if (a == 'nw') {
+			data.top = cpos.top + (csize.height - data.height);
+			data.left = cpos.left + (csize.width - data.width);
+		}
+
+		return data;
+	},
+
+	_respectSize: function(data, event) {
+
+		var el = this.helper, o = this._vBoundaries, pRatio = this._aspectRatio || event.shiftKey, a = this.axis,
+				ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height),
+					isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height);
+
+		if (isminw) data.width = o.minWidth;
+		if (isminh) data.height = o.minHeight;
+		if (ismaxw) data.width = o.maxWidth;
+		if (ismaxh) data.height = o.maxHeight;
+
+		var dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height;
+		var cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a);
+
+		if (isminw && cw) data.left = dw - o.minWidth;
+		if (ismaxw && cw) data.left = dw - o.maxWidth;
+		if (isminh && ch)	data.top = dh - o.minHeight;
+		if (ismaxh && ch)	data.top = dh - o.maxHeight;
+
+		// fixing jump error on top/left - bug #2330
+		var isNotwh = !data.width && !data.height;
+		if (isNotwh && !data.left && data.top) data.top = null;
+		else if (isNotwh && !data.top && data.left) data.left = null;
+
+		return data;
+	},
+
+	_proportionallyResize: function() {
+
+		var o = this.options;
+		if (!this._proportionallyResizeElements.length) return;
+		var element = this.helper || this.element;
+
+		for (var i=0; i < this._proportionallyResizeElements.length; i++) {
+
+			var prel = this._proportionallyResizeElements[i];
+
+			if (!this.borderDif) {
+				var b = [prel.css('borderTopWidth'), prel.css('borderRightWidth'), prel.css('borderBottomWidth'), prel.css('borderLeftWidth')],
+					p = [prel.css('paddingTop'), prel.css('paddingRight'), prel.css('paddingBottom'), prel.css('paddingLeft')];
+
+				this.borderDif = $.map(b, function(v, i) {
+					var border = parseInt(v,10)||0, padding = parseInt(p[i],10)||0;
+					return border + padding;
+				});
+			}
+
+			prel.css({
+				height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0,
+				width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0
+			});
+
+		};
+
+	},
+
+	_renderProxy: function() {
+
+		var el = this.element, o = this.options;
+		this.elementOffset = el.offset();
+
+		if(this._helper) {
+
+			this.helper = this.helper || $('<div style="overflow:hidden;"></div>');
+
+			// fix ie6 offset TODO: This seems broken
+			var ie6offset = ($.ui.ie6 ? 1 : 0),
+			pxyoffset = ( $.ui.ie6 ? 2 : -1 );
+
+			this.helper.addClass(this._helper).css({
+				width: this.element.outerWidth() + pxyoffset,
+				height: this.element.outerHeight() + pxyoffset,
+				position: 'absolute',
+				left: this.elementOffset.left - ie6offset +'px',
+				top: this.elementOffset.top - ie6offset +'px',
+				zIndex: ++o.zIndex //TODO: Don't modify option
+			});
+
+			this.helper
+				.appendTo("body")
+				.disableSelection();
+
+		} else {
+			this.helper = this.element;
+		}
+
+	},
+
+	_change: {
+		e: function(event, dx, dy) {
+			return { width: this.originalSize.width + dx };
+		},
+		w: function(event, dx, dy) {
+			var o = this.options, cs = this.originalSize, sp = this.originalPosition;
+			return { left: sp.left + dx, width: cs.width - dx };
+		},
+		n: function(event, dx, dy) {
+			var o = this.options, cs = this.originalSize, sp = this.originalPosition;
+			return { top: sp.top + dy, height: cs.height - dy };
+		},
+		s: function(event, dx, dy) {
+			return { height: this.originalSize.height + dy };
+		},
+		se: function(event, dx, dy) {
+			return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
+		},
+		sw: function(event, dx, dy) {
+			return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
+		},
+		ne: function(event, dx, dy) {
+			return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy]));
+		},
+		nw: function(event, dx, dy) {
+			return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy]));
+		}
+	},
+
+	_propagate: function(n, event) {
+		$.ui.plugin.call(this, n, [event, this.ui()]);
+		(n != "resize" && this._trigger(n, event, this.ui()));
+	},
+
+	plugins: {},
+
+	ui: function() {
+		return {
+			originalElement: this.originalElement,
+			element: this.element,
+			helper: this.helper,
+			position: this.position,
+			size: this.size,
+			originalSize: this.originalSize,
+			originalPosition: this.originalPosition
+		};
+	}
+
+});
+
+/*
+ * Resizable Extensions
+ */
+
+$.ui.plugin.add("resizable", "alsoResize", {
+
+	start: function (event, ui) {
+		var that = $(this).data("resizable"), o = that.options;
+
+		var _store = function (exp) {
+			$(exp).each(function() {
+				var el = $(this);
+				el.data("resizable-alsoresize", {
+					width: parseInt(el.width(), 10), height: parseInt(el.height(), 10),
+					left: parseInt(el.css('left'), 10), top: parseInt(el.css('top'), 10)
+				});
+			});
+		};
+
+		if (typeof(o.alsoResize) == 'object' && !o.alsoResize.parentNode) {
+			if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); }
+			else { $.each(o.alsoResize, function (exp) { _store(exp); }); }
+		}else{
+			_store(o.alsoResize);
+		}
+	},
+
+	resize: function (event, ui) {
+		var that = $(this).data("resizable"), o = that.options, os = that.originalSize, op = that.originalPosition;
+
+		var delta = {
+			height: (that.size.height - os.height) || 0, width: (that.size.width - os.width) || 0,
+			top: (that.position.top - op.top) || 0, left: (that.position.left - op.left) || 0
+		},
+
+		_alsoResize = function (exp, c) {
+			$(exp).each(function() {
+				var el = $(this), start = $(this).data("resizable-alsoresize"), style = {},
+					css = c && c.length ? c : el.parents(ui.originalElement[0]).length ? ['width', 'height'] : ['width', 'height', 'top', 'left'];
+
+				$.each(css, function (i, prop) {
+					var sum = (start[prop]||0) + (delta[prop]||0);
+					if (sum && sum >= 0)
+						style[prop] = sum || null;
+				});
+
+				el.css(style);
+			});
+		};
+
+		if (typeof(o.alsoResize) == 'object' && !o.alsoResize.nodeType) {
+			$.each(o.alsoResize, function (exp, c) { _alsoResize(exp, c); });
+		}else{
+			_alsoResize(o.alsoResize);
+		}
+	},
+
+	stop: function (event, ui) {
+		$(this).removeData("resizable-alsoresize");
+	}
+});
+
+$.ui.plugin.add("resizable", "animate", {
+
+	stop: function(event, ui) {
+		var that = $(this).data("resizable"), o = that.options;
+
+		var pr = that._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName),
+					soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : that.sizeDiff.height,
+						soffsetw = ista ? 0 : that.sizeDiff.width;
+
+		var style = { width: (that.size.width - soffsetw), height: (that.size.height - soffseth) },
+					left = (parseInt(that.element.css('left'), 10) + (that.position.left - that.originalPosition.left)) || null,
+						top = (parseInt(that.element.css('top'), 10) + (that.position.top - that.originalPosition.top)) || null;
+
+		that.element.animate(
+			$.extend(style, top && left ? { top: top, left: left } : {}), {
+				duration: o.animateDuration,
+				easing: o.animateEasing,
+				step: function() {
+
+					var data = {
+						width: parseInt(that.element.css('width'), 10),
+						height: parseInt(that.element.css('height'), 10),
+						top: parseInt(that.element.css('top'), 10),
+						left: parseInt(that.element.css('left'), 10)
+					};
+
+					if (pr && pr.length) $(pr[0]).css({ width: data.width, height: data.height });
+
+					// propagating resize, and updating values for each animation step
+					that._updateCache(data);
+					that._propagate("resize", event);
+
+				}
+			}
+		);
+	}
+
+});
+
+$.ui.plugin.add("resizable", "containment", {
+
+	start: function(event, ui) {
+		var that = $(this).data("resizable"), o = that.options, el = that.element;
+		var oc = o.containment,	ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc;
+		if (!ce) return;
+
+		that.containerElement = $(ce);
+
+		if (/document/.test(oc) || oc == document) {
+			that.containerOffset = { left: 0, top: 0 };
+			that.containerPosition = { left: 0, top: 0 };
+
+			that.parentData = {
+				element: $(document), left: 0, top: 0,
+				width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight
+			};
+		}
+
+		// i'm a node, so compute top, left, right, bottom
+		else {
+			var element = $(ce), p = [];
+			$([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); });
+
+			that.containerOffset = element.offset();
+			that.containerPosition = element.position();
+			that.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) };
+
+			var co = that.containerOffset, ch = that.containerSize.height,	cw = that.containerSize.width,
+						width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ), height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch);
+
+			that.parentData = {
+				element: ce, left: co.left, top: co.top, width: width, height: height
+			};
+		}
+	},
+
+	resize: function(event, ui) {
+		var that = $(this).data("resizable"), o = that.options,
+				ps = that.containerSize, co = that.containerOffset, cs = that.size, cp = that.position,
+				pRatio = that._aspectRatio || event.shiftKey, cop = { top:0, left:0 }, ce = that.containerElement;
+
+		if (ce[0] != document && (/static/).test(ce.css('position'))) cop = co;
+
+		if (cp.left < (that._helper ? co.left : 0)) {
+			that.size.width = that.size.width + (that._helper ? (that.position.left - co.left) : (that.position.left - cop.left));
+			if (pRatio) that.size.height = that.size.width / that.aspectRatio;
+			that.position.left = o.helper ? co.left : 0;
+		}
+
+		if (cp.top < (that._helper ? co.top : 0)) {
+			that.size.height = that.size.height + (that._helper ? (that.position.top - co.top) : that.position.top);
+			if (pRatio) that.size.width = that.size.height * that.aspectRatio;
+			that.position.top = that._helper ? co.top : 0;
+		}
+
+		that.offset.left = that.parentData.left+that.position.left;
+		that.offset.top = that.parentData.top+that.position.top;
+
+		var woset = Math.abs( (that._helper ? that.offset.left - cop.left : (that.offset.left - cop.left)) + that.sizeDiff.width ),
+					hoset = Math.abs( (that._helper ? that.offset.top - cop.top : (that.offset.top - co.top)) + that.sizeDiff.height );
+
+		var isParent = that.containerElement.get(0) == that.element.parent().get(0),
+			isOffsetRelative = /relative|absolute/.test(that.containerElement.css('position'));
+
+		if(isParent && isOffsetRelative) woset -= that.parentData.left;
+
+		if (woset + that.size.width >= that.parentData.width) {
+			that.size.width = that.parentData.width - woset;
+			if (pRatio) that.size.height = that.size.width / that.aspectRatio;
+		}
+
+		if (hoset + that.size.height >= that.parentData.height) {
+			that.size.height = that.parentData.height - hoset;
+			if (pRatio) that.size.width = that.size.height * that.aspectRatio;
+		}
+	},
+
+	stop: function(event, ui){
+		var that = $(this).data("resizable"), o = that.options, cp = that.position,
+				co = that.containerOffset, cop = that.containerPosition, ce = that.containerElement;
+
+		var helper = $(that.helper), ho = helper.offset(), w = helper.outerWidth() - that.sizeDiff.width, h = helper.outerHeight() - that.sizeDiff.height;
+
+		if (that._helper && !o.animate && (/relative/).test(ce.css('position')))
+			$(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });
+
+		if (that._helper && !o.animate && (/static/).test(ce.css('position')))
+			$(this).css({ left: ho.left - cop.left - co.left, width: w, height: h });
+
+	}
+});
+
+$.ui.plugin.add("resizable", "ghost", {
+
+	start: function(event, ui) {
+
+		var that = $(this).data("resizable"), o = that.options, cs = that.size;
+
+		that.ghost = that.originalElement.clone();
+		that.ghost
+			.css({ opacity: .25, display: 'block', position: 'relative', height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 })
+			.addClass('ui-resizable-ghost')
+			.addClass(typeof o.ghost == 'string' ? o.ghost : '');
+
+		that.ghost.appendTo(that.helper);
+
+	},
+
+	resize: function(event, ui){
+		var that = $(this).data("resizable"), o = that.options;
+		if (that.ghost) that.ghost.css({ position: 'relative', height: that.size.height, width: that.size.width });
+	},
+
+	stop: function(event, ui){
+		var that = $(this).data("resizable"), o = that.options;
+		if (that.ghost && that.helper) that.helper.get(0).removeChild(that.ghost.get(0));
+	}
+
+});
+
+$.ui.plugin.add("resizable", "grid", {
+
+	resize: function(event, ui) {
+		var that = $(this).data("resizable"), o = that.options, cs = that.size, os = that.originalSize, op = that.originalPosition, a = that.axis, ratio = o._aspectRatio || event.shiftKey;
+		o.grid = typeof o.grid == "number" ? [o.grid, o.grid] : o.grid;
+		var ox = Math.round((cs.width - os.width) / (o.grid[0]||1)) * (o.grid[0]||1), oy = Math.round((cs.height - os.height) / (o.grid[1]||1)) * (o.grid[1]||1);
+
+		if (/^(se|s|e)$/.test(a)) {
+			that.size.width = os.width + ox;
+			that.size.height = os.height + oy;
+		}
+		else if (/^(ne)$/.test(a)) {
+			that.size.width = os.width + ox;
+			that.size.height = os.height + oy;
+			that.position.top = op.top - oy;
+		}
+		else if (/^(sw)$/.test(a)) {
+			that.size.width = os.width + ox;
+			that.size.height = os.height + oy;
+			that.position.left = op.left - ox;
+		}
+		else {
+			that.size.width = os.width + ox;
+			that.size.height = os.height + oy;
+			that.position.top = op.top - oy;
+			that.position.left = op.left - ox;
+		}
+	}
+
+});
+
+var num = function(v) {
+	return parseInt(v, 10) || 0;
+};
+
+var isNumber = function(value) {
+	return !isNaN(parseInt(value, 10));
+};
+
+})(jQuery);
+
+(function( $, undefined ) {
+
+$.widget("ui.selectable", $.ui.mouse, {
+	version: "1.9.2",
+	options: {
+		appendTo: 'body',
+		autoRefresh: true,
+		distance: 0,
+		filter: '*',
+		tolerance: 'touch'
+	},
+	_create: function() {
+		var that = this;
+
+		this.element.addClass("ui-selectable");
+
+		this.dragged = false;
+
+		// cache selectee children based on filter
+		var selectees;
+		this.refresh = function() {
+			selectees = $(that.options.filter, that.element[0]);
+			selectees.addClass("ui-selectee");
+			selectees.each(function() {
+				var $this = $(this);
+				var pos = $this.offset();
+				$.data(this, "selectable-item", {
+					element: this,
+					$element: $this,
+					left: pos.left,
+					top: pos.top,
+					right: pos.left + $this.outerWidth(),
+					bottom: pos.top + $this.outerHeight(),
+					startselected: false,
+					selected: $this.hasClass('ui-selected'),
+					selecting: $this.hasClass('ui-selecting'),
+					unselecting: $this.hasClass('ui-unselecting')
+				});
+			});
+		};
+		this.refresh();
+
+		this.selectees = selectees.addClass("ui-selectee");
+
+		this._mouseInit();
+
+		this.helper = $("<div class='ui-selectable-helper'></div>");
+	},
+
+	_destroy: function() {
+		this.selectees
+			.removeClass("ui-selectee")
+			.removeData("selectable-item");
+		this.element
+			.removeClass("ui-selectable ui-selectable-disabled");
+		this._mouseDestroy();
+	},
+
+	_mouseStart: function(event) {
+		var that = this;
+
+		this.opos = [event.pageX, event.pageY];
+
+		if (this.options.disabled)
+			return;
+
+		var options = this.options;
+
+		this.selectees = $(options.filter, this.element[0]);
+
+		this._trigger("start", event);
+
+		$(options.appendTo).append(this.helper);
+		// position helper (lasso)
+		this.helper.css({
+			"left": event.clientX,
+			"top": event.clientY,
+			"width": 0,
+			"height": 0
+		});
+
+		if (options.autoRefresh) {
+			this.refresh();
+		}
+
+		this.selectees.filter('.ui-selected').each(function() {
+			var selectee = $.data(this, "selectable-item");
+			selectee.startselected = true;
+			if (!event.metaKey && !event.ctrlKey) {
+				selectee.$element.removeClass('ui-selected');
+				selectee.selected = false;
+				selectee.$element.addClass('ui-unselecting');
+				selectee.unselecting = true;
+				// selectable UNSELECTING callback
+				that._trigger("unselecting", event, {
+					unselecting: selectee.element
+				});
+			}
+		});
+
+		$(event.target).parents().andSelf().each(function() {
+			var selectee = $.data(this, "selectable-item");
+			if (selectee) {
+				var doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass('ui-selected');
+				selectee.$element
+					.removeClass(doSelect ? "ui-unselecting" : "ui-selected")
+					.addClass(doSelect ? "ui-selecting" : "ui-unselecting");
+				selectee.unselecting = !doSelect;
+				selectee.selecting = doSelect;
+				selectee.selected = doSelect;
+				// selectable (UN)SELECTING callback
+				if (doSelect) {
+					that._trigger("selecting", event, {
+						selecting: selectee.element
+					});
+				} else {
+					that._trigger("unselecting", event, {
+						unselecting: selectee.element
+					});
+				}
+				return false;
+			}
+		});
+
+	},
+
+	_mouseDrag: function(event) {
+		var that = this;
+		this.dragged = true;
+
+		if (this.options.disabled)
+			return;
+
+		var options = this.options;
+
+		var x1 = this.opos[0], y1 = this.opos[1], x2 = event.pageX, y2 = event.pageY;
+		if (x1 > x2) { var tmp = x2; x2 = x1; x1 = tmp; }
+		if (y1 > y2) { var tmp = y2; y2 = y1; y1 = tmp; }
+		this.helper.css({left: x1, top: y1, width: x2-x1, height: y2-y1});
+
+		this.selectees.each(function() {
+			var selectee = $.data(this, "selectable-item");
+			//prevent helper from being selected if appendTo: selectable
+			if (!selectee || selectee.element == that.element[0])
+				return;
+			var hit = false;
+			if (options.tolerance == 'touch') {
+				hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) );
+			} else if (options.tolerance == 'fit') {
+				hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2);
+			}
+
+			if (hit) {
+				// SELECT
+				if (selectee.selected) {
+					selectee.$element.removeClass('ui-selected');
+					selectee.selected = false;
+				}
+				if (selectee.unselecting) {
+					selectee.$element.removeClass('ui-unselecting');
+					selectee.unselecting = false;
+				}
+				if (!selectee.selecting) {
+					selectee.$element.addClass('ui-selecting');
+					selectee.selecting = true;
+					// selectable SELECTING callback
+					that._trigger("selecting", event, {
+						selecting: selectee.element
+					});
+				}
+			} else {
+				// UNSELECT
+				if (selectee.selecting) {
+					if ((event.metaKey || event.ctrlKey) && selectee.startselected) {
+						selectee.$element.removeClass('ui-selecting');
+						selectee.selecting = false;
+						selectee.$element.addClass('ui-selected');
+						selectee.selected = true;
+					} else {
+						selectee.$element.removeClass('ui-selecting');
+						selectee.selecting = false;
+						if (selectee.startselected) {
+							selectee.$element.addClass('ui-unselecting');
+							selectee.unselecting = true;
+						}
+						// selectable UNSELECTING callback
+						that._trigger("unselecting", event, {
+							unselecting: selectee.element
+						});
+					}
+				}
+				if (selectee.selected) {
+					if (!event.metaKey && !event.ctrlKey && !selectee.startselected) {
+						selectee.$element.removeClass('ui-selected');
+						selectee.selected = false;
+
+						selectee.$element.addClass('ui-unselecting');
+						selectee.unselecting = true;
+						// selectable UNSELECTING callback
+						that._trigger("unselecting", event, {
+							unselecting: selectee.element
+						});
+					}
+				}
+			}
+		});
+
+		return false;
+	},
+
+	_mouseStop: function(event) {
+		var that = this;
+
+		this.dragged = false;
+
+		var options = this.options;
+
+		$('.ui-unselecting', this.element[0]).each(function() {
+			var selectee = $.data(this, "selectable-item");
+			selectee.$element.removeClass('ui-unselecting');
+			selectee.unselecting = false;
+			selectee.startselected = false;
+			that._trigger("unselected", event, {
+				unselected: selectee.element
+			});
+		});
+		$('.ui-selecting', this.element[0]).each(function() {
+			var selectee = $.data(this, "selectable-item");
+			selectee.$element.removeClass('ui-selecting').addClass('ui-selected');
+			selectee.selecting = false;
+			selectee.selected = true;
+			selectee.startselected = true;
+			that._trigger("selected", event, {
+				selected: selectee.element
+			});
+		});
+		this._trigger("stop", event);
+
+		this.helper.remove();
+
+		return false;
+	}
+
+});
+
+})(jQuery);
+
+(function( $, undefined ) {
+
+$.widget("ui.sortable", $.ui.mouse, {
+	version: "1.9.2",
+	widgetEventPrefix: "sort",
+	ready: false,
+	options: {
+		appendTo: "parent",
+		axis: false,
+		connectWith: false,
+		containment: false,
+		cursor: 'auto',
+		cursorAt: false,
+		dropOnEmpty: true,
+		forcePlaceholderSize: false,
+		forceHelperSize: false,
+		grid: false,
+		handle: false,
+		helper: "original",
+		items: '> *',
+		opacity: false,
+		placeholder: false,
+		revert: false,
+		scroll: true,
+		scrollSensitivity: 20,
+		scrollSpeed: 20,
+		scope: "default",
+		tolerance: "intersect",
+		zIndex: 1000
+	},
+	_create: function() {
+
+		var o = this.options;
+		this.containerCache = {};
+		this.element.addClass("ui-sortable");
+
+		//Get the items
+		this.refresh();
+
+		//Let's determine if the items are being displayed horizontally
+		this.floating = this.items.length ? o.axis === 'x' || (/left|right/).test(this.items[0].item.css('float')) || (/inline|table-cell/).test(this.items[0].item.css('display')) : false;
+
+		//Let's determine the parent's offset
+		this.offset = this.element.offset();
+
+		//Initialize mouse events for interaction
+		this._mouseInit();
+
+		//We're ready to go
+		this.ready = true
+
+	},
+
+	_destroy: function() {
+		this.element
+			.removeClass("ui-sortable ui-sortable-disabled");
+		this._mouseDestroy();
+
+		for ( var i = this.items.length - 1; i >= 0; i-- )
+			this.items[i].item.removeData(this.widgetName + "-item");
+
+		return this;
+	},
+
+	_setOption: function(key, value){
+		if ( key === "disabled" ) {
+			this.options[ key ] = value;
+
+			this.widget().toggleClass( "ui-sortable-disabled", !!value );
+		} else {
+			// Don't call widget base _setOption for disable as it adds ui-state-disabled class
+			$.Widget.prototype._setOption.apply(this, arguments);
+		}
+	},
+
+	_mouseCapture: function(event, overrideHandle) {
+		var that = this;
+
+		if (this.reverting) {
+			return false;
+		}
+
+		if(this.options.disabled || this.options.type == 'static') return false;
+
+		//We have to refresh the items data once first
+		this._refreshItems(event);
+
+		//Find out if the clicked node (or one of its parents) is a actual item in this.items
+		var currentItem = null, nodes = $(event.target).parents().each(function() {
+			if($.data(this, that.widgetName + '-item') == that) {
+				currentItem = $(this);
+				return false;
+			}
+		});
+		if($.data(event.target, that.widgetName + '-item') == that) currentItem = $(event.target);
+
+		if(!currentItem) return false;
+		if(this.options.handle && !overrideHandle) {
+			var validHandle = false;
+
+			$(this.options.handle, currentItem).find("*").andSelf().each(function() { if(this == event.target) validHandle = true; });
+			if(!validHandle) return false;
+		}
+
+		this.currentItem = currentItem;
+		this._removeCurrentsFromItems();
+		return true;
+
+	},
+
+	_mouseStart: function(event, overrideHandle, noActivation) {
+
+		var o = this.options;
+		this.currentContainer = this;
+
+		//We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
+		this.refreshPositions();
+
+		//Create and append the visible helper
+		this.helper = this._createHelper(event);
+
+		//Cache the helper size
+		this._cacheHelperProportions();
+
+		/*
+		 * - Position generation -
+		 * This block generates everything position related - it's the core of draggables.
+		 */
+
+		//Cache the margins of the original element
+		this._cacheMargins();
+
+		//Get the next scrolling parent
+		this.scrollParent = this.helper.scrollParent();
+
+		//The element's absolute position on the page minus margins
+		this.offset = this.currentItem.offset();
+		this.offset = {
+			top: this.offset.top - this.margins.top,
+			left: this.offset.left - this.margins.left
+		};
+
+		$.extend(this.offset, {
+			click: { //Where the click happened, relative to the element
+				left: event.pageX - this.offset.left,
+				top: event.pageY - this.offset.top
+			},
+			parent: this._getParentOffset(),
+			relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
+		});
+
+		// Only after we got the offset, we can change the helper's position to absolute
+		// TODO: Still need to figure out a way to make relative sorting possible
+		this.helper.css("position", "absolute");
+		this.cssPosition = this.helper.css("position");
+
+		//Generate the original position
+		this.originalPosition = this._generatePosition(event);
+		this.originalPageX = event.pageX;
+		this.originalPageY = event.pageY;
+
+		//Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
+		(o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
+
+		//Cache the former DOM position
+		this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };
+
+		//If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
+		if(this.helper[0] != this.currentItem[0]) {
+			this.currentItem.hide();
+		}
+
+		//Create the placeholder
+		this._createPlaceholder();
+
+		//Set a containment if given in the options
+		if(o.containment)
+			this._setContainment();
+
+		if(o.cursor) { // cursor option
+			if ($('body').css("cursor")) this._storedCursor = $('body').css("cursor");
+			$('body').css("cursor", o.cursor);
+		}
+
+		if(o.opacity) { // opacity option
+			if (this.helper.css("opacity")) this._storedOpacity = this.helper.css("opacity");
+			this.helper.css("opacity", o.opacity);
+		}
+
+		if(o.zIndex) { // zIndex option
+			if (this.helper.css("zIndex")) this._storedZIndex = this.helper.css("zIndex");
+			this.helper.css("zIndex", o.zIndex);
+		}
+
+		//Prepare scrolling
+		if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML')
+			this.overflowOffset = this.scrollParent.offset();
+
+		//Call callbacks
+		this._trigger("start", event, this._uiHash());
+
+		//Recache the helper size
+		if(!this._preserveHelperProportions)
+			this._cacheHelperProportions();
+
+
+		//Post 'activate' events to possible containers
+		if(!noActivation) {
+			 for (var i = this.containers.length - 1; i >= 0; i--) { this.containers[i]._trigger("activate", event, this._uiHash(this)); }
+		}
+
+		//Prepare possible droppables
+		if($.ui.ddmanager)
+			$.ui.ddmanager.current = this;
+
+		if ($.ui.ddmanager && !o.dropBehaviour)
+			$.ui.ddmanager.prepareOffsets(this, event);
+
+		this.dragging = true;
+
+		this.helper.addClass("ui-sortable-helper");
+		this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
+		return true;
+
+	},
+
+	_mouseDrag: function(event) {
+
+		//Compute the helpers position
+		this.position = this._generatePosition(event);
+		this.positionAbs = this._convertPositionTo("absolute");
+
+		if (!this.lastPositionAbs) {
+			this.lastPositionAbs = this.positionAbs;
+		}
+
+		//Do scrolling
+		if(this.options.scroll) {
+			var o = this.options, scrolled = false;
+			if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML') {
+
+				if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
+					this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
+				else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity)
+					this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
+
+				if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
+					this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
+				else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity)
+					this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;
+
+			} else {
+
+				if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
+					scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
+				else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
+					scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
+
+				if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
+					scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
+				else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
+					scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
+
+			}
+
+			if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
+				$.ui.ddmanager.prepareOffsets(this, event);
+		}
+
+		//Regenerate the absolute position used for position checks
+		this.positionAbs = this._convertPositionTo("absolute");
+
+		//Set the helper position
+		if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
+		if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';
+
+		//Rearrange
+		for (var i = this.items.length - 1; i >= 0; i--) {
+
+			//Cache variables and intersection, continue if no intersection
+			var item = this.items[i], itemElement = item.item[0], intersection = this._intersectsWithPointer(item);
+			if (!intersection) continue;
+
+			// Only put the placeholder inside the current Container, skip all
+			// items form other containers. This works because when moving
+			// an item from one container to another the
+			// currentContainer is switched before the placeholder is moved.
+			//
+			// Without this moving items in "sub-sortables" can cause the placeholder to jitter
+			// beetween the outer and inner container.
+			if (item.instance !== this.currentContainer) continue;
+
+			if (itemElement != this.currentItem[0] //cannot intersect with itself
+				&&	this.placeholder[intersection == 1 ? "next" : "prev"]()[0] != itemElement //no useless actions that have been done before
+				&&	!$.contains(this.placeholder[0], itemElement) //no action if the item moved is the parent of the item checked
+				&& (this.options.type == 'semi-dynamic' ? !$.contains(this.element[0], itemElement) : true)
+				//&& itemElement.parentNode == this.placeholder[0].parentNode // only rearrange items within the same container
+			) {
+
+				this.direction = intersection == 1 ? "down" : "up";
+
+				if (this.options.tolerance == "pointer" || this._intersectsWithSides(item)) {
+					this._rearrange(event, item);
+				} else {
+					break;
+				}
+
+				this._trigger("change", event, this._uiHash());
+				break;
+			}
+		}
+
+		//Post events to containers
+		this._contactContainers(event);
+
+		//Interconnect with droppables
+		if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);
+
+		//Call callbacks
+		this._trigger('sort', event, this._uiHash());
+
+		this.lastPositionAbs = this.positionAbs;
+		return false;
+
+	},
+
+	_mouseStop: function(event, noPropagation) {
+
+		if(!event) return;
+
+		//If we are using droppables, inform the manager about the drop
+		if ($.ui.ddmanager && !this.options.dropBehaviour)
+			$.ui.ddmanager.drop(this, event);
+
+		if(this.options.revert) {
+			var that = this;
+			var cur = this.placeholder.offset();
+
+			this.reverting = true;
+
+			$(this.helper).animate({
+				left: cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft),
+				top: cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop)
+			}, parseInt(this.options.revert, 10) || 500, function() {
+				that._clear(event);
+			});
+		} else {
+			this._clear(event, noPropagation);
+		}
+
+		return false;
+
+	},
+
+	cancel: function() {
+
+		if(this.dragging) {
+
+			this._mouseUp({ target: null });
+
+			if(this.options.helper == "original")
+				this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
+			else
+				this.currentItem.show();
+
+			//Post deactivating events to containers
+			for (var i = this.containers.length - 1; i >= 0; i--){
+				this.containers[i]._trigger("deactivate", null, this._uiHash(this));
+				if(this.containers[i].containerCache.over) {
+					this.containers[i]._trigger("out", null, this._uiHash(this));
+					this.containers[i].containerCache.over = 0;
+				}
+			}
+
+		}
+
+		if (this.placeholder) {
+			//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
+			if(this.placeholder[0].parentNode) this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
+			if(this.options.helper != "original" && this.helper && this.helper[0].parentNode) this.helper.remove();
+
+			$.extend(this, {
+				helper: null,
+				dragging: false,
+				reverting: false,
+				_noFinalSort: null
+			});
+
+			if(this.domPosition.prev) {
+				$(this.domPosition.prev).after(this.currentItem);
+			} else {
+				$(this.domPosition.parent).prepend(this.currentItem);
+			}
+		}
+
+		return this;
+
+	},
+
+	serialize: function(o) {
+
+		var items = this._getItemsAsjQuery(o && o.connected);
+		var str = []; o = o || {};
+
+		$(items).each(function() {
+			var res = ($(o.item || this).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
+			if(res) str.push((o.key || res[1]+'[]')+'='+(o.key && o.expression ? res[1] : res[2]));
+		});
+
+		if(!str.length && o.key) {
+			str.push(o.key + '=');
+		}
+
+		return str.join('&');
+
+	},
+
+	toArray: function(o) {
+
+		var items = this._getItemsAsjQuery(o && o.connected);
+		var ret = []; o = o || {};
+
+		items.each(function() { ret.push($(o.item || this).attr(o.attribute || 'id') || ''); });
+		return ret;
+
+	},
+
+	/* Be careful with the following core functions */
+	_intersectsWith: function(item) {
+
+		var x1 = this.positionAbs.left,
+			x2 = x1 + this.helperProportions.width,
+			y1 = this.positionAbs.top,
+			y2 = y1 + this.helperProportions.height;
+
+		var l = item.left,
+			r = l + item.width,
+			t = item.top,
+			b = t + item.height;
+
+		var dyClick = this.offset.click.top,
+			dxClick = this.offset.click.left;
+
+		var isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r;
+
+		if(	   this.options.tolerance == "pointer"
+			|| this.options.forcePointerForContainers
+			|| (this.options.tolerance != "pointer" && this.helperProportions[this.floating ? 'width' : 'height'] > item[this.floating ? 'width' : 'height'])
+		) {
+			return isOverElement;
+		} else {
+
+			return (l < x1 + (this.helperProportions.width / 2) // Right Half
+				&& x2 - (this.helperProportions.width / 2) < r // Left Half
+				&& t < y1 + (this.helperProportions.height / 2) // Bottom Half
+				&& y2 - (this.helperProportions.height / 2) < b ); // Top Half
+
+		}
+	},
+
+	_intersectsWithPointer: function(item) {
+
+		var isOverElementHeight = (this.options.axis === 'x') || $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
+			isOverElementWidth = (this.options.axis === 'y') || $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
+			isOverElement = isOverElementHeight && isOverElementWidth,
+			verticalDirection = this._getDragVerticalDirection(),
+			horizontalDirection = this._getDragHorizontalDirection();
+
+		if (!isOverElement)
+			return false;
+
+		return this.floating ?
+			( ((horizontalDirection && horizontalDirection == "right") || verticalDirection == "down") ? 2 : 1 )
+			: ( verticalDirection && (verticalDirection == "down" ? 2 : 1) );
+
+	},
+
+	_intersectsWithSides: function(item) {
+
+		var isOverBottomHalf = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
+			isOverRightHalf = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
+			verticalDirection = this._getDragVerticalDirection(),
+			horizontalDirection = this._getDragHorizontalDirection();
+
+		if (this.floating && horizontalDirection) {
+			return ((horizontalDirection == "right" && isOverRightHalf) || (horizontalDirection == "left" && !isOverRightHalf));
+		} else {
+			return verticalDirection && ((verticalDirection == "down" && isOverBottomHalf) || (verticalDirection == "up" && !isOverBottomHalf));
+		}
+
+	},
+
+	_getDragVerticalDirection: function() {
+		var delta = this.positionAbs.top - this.lastPositionAbs.top;
+		return delta != 0 && (delta > 0 ? "down" : "up");
+	},
+
+	_getDragHorizontalDirection: function() {
+		var delta = this.positionAbs.left - this.lastPositionAbs.left;
+		return delta != 0 && (delta > 0 ? "right" : "left");
+	},
+
+	refresh: function(event) {
+		this._refreshItems(event);
+		this.refreshPositions();
+		return this;
+	},
+
+	_connectWith: function() {
+		var options = this.options;
+		return options.connectWith.constructor == String
+			? [options.connectWith]
+			: options.connectWith;
+	},
+
+	_getItemsAsjQuery: function(connected) {
+
+		var items = [];
+		var queries = [];
+		var connectWith = this._connectWith();
+
+		if(connectWith && connected) {
+			for (var i = connectWith.length - 1; i >= 0; i--){
+				var cur = $(connectWith[i]);
+				for (var j = cur.length - 1; j >= 0; j--){
+					var inst = $.data(cur[j], this.widgetName);
+					if(inst && inst != this && !inst.options.disabled) {
+						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not('.ui-sortable-placeholder'), inst]);
+					}
+				};
+			};
+		}
+
+		queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not('.ui-sortable-placeholder'), this]);
+
+		for (var i = queries.length - 1; i >= 0; i--){
+			queries[i][0].each(function() {
+				items.push(this);
+			});
+		};
+
+		return $(items);
+
+	},
+
+	_removeCurrentsFromItems: function() {
+
+		var list = this.currentItem.find(":data(" + this.widgetName + "-item)");
+
+		this.items = $.grep(this.items, function (item) {
+			for (var j=0; j < list.length; j++) {
+				if(list[j] == item.item[0])
+					return false;
+			};
+			return true;
+		});
+
+	},
+
+	_refreshItems: function(event) {
+
+		this.items = [];
+		this.containers = [this];
+		var items = this.items;
+		var queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]];
+		var connectWith = this._connectWith();
+
+		if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down
+			for (var i = connectWith.length - 1; i >= 0; i--){
+				var cur = $(connectWith[i]);
+				for (var j = cur.length - 1; j >= 0; j--){
+					var inst = $.data(cur[j], this.widgetName);
+					if(inst && inst != this && !inst.options.disabled) {
+						queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
+						this.containers.push(inst);
+					}
+				};
+			};
+		}
+
+		for (var i = queries.length - 1; i >= 0; i--) {
+			var targetData = queries[i][1];
+			var _queries = queries[i][0];
+
+			for (var j=0, queriesLength = _queries.length; j < queriesLength; j++) {
+				var item = $(_queries[j]);
+
+				item.data(this.widgetName + '-item', targetData); // Data for target checking (mouse manager)
+
+				items.push({
+					item: item,
+					instance: targetData,
+					width: 0, height: 0,
+					left: 0, top: 0
+				});
+			};
+		};
+
+	},
+
+	refreshPositions: function(fast) {
+
+		//This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
+		if(this.offsetParent && this.helper) {
+			this.offset.parent = this._getParentOffset();
+		}
+
+		for (var i = this.items.length - 1; i >= 0; i--){
+			var item = this.items[i];
+
+			//We ignore calculating positions of all connected containers when we're not over them
+			if(item.instance != this.currentContainer && this.currentContainer && item.item[0] != this.currentItem[0])
+				continue;
+
+			var t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;
+
+			if (!fast) {
+				item.width = t.outerWidth();
+				item.height = t.outerHeight();
+			}
+
+			var p = t.offset();
+			item.left = p.left;
+			item.top = p.top;
+		};
+
+		if(this.options.custom && this.options.custom.refreshContainers) {
+			this.options.custom.refreshContainers.call(this);
+		} else {
+			for (var i = this.containers.length - 1; i >= 0; i--){
+				var p = this.containers[i].element.offset();
+				this.containers[i].containerCache.left = p.left;
+				this.containers[i].containerCache.top = p.top;
+				this.containers[i].containerCache.width	= this.containers[i].element.outerWidth();
+				this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
+			};
+		}
+
+		return this;
+	},
+
+	_createPlaceholder: function(that) {
+		that = that || this;
+		var o = that.options;
+
+		if(!o.placeholder || o.placeholder.constructor == String) {
+			var className = o.placeholder;
+			o.placeholder = {
+				element: function() {
+
+					var el = $(document.createElement(that.currentItem[0].nodeName))
+						.addClass(className || that.currentItem[0].className+" ui-sortable-placeholder")
+						.removeClass("ui-sortable-helper")[0];
+
+					if(!className)
+						el.style.visibility = "hidden";
+
+					return el;
+				},
+				update: function(container, p) {
+
+					// 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
+					// 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
+					if(className && !o.forcePlaceholderSize) return;
+
+					//If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
+					if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css('paddingTop')||0, 10) - parseInt(that.currentItem.css('paddingBottom')||0, 10)); };
+					if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css('paddingLeft')||0, 10) - parseInt(that.currentItem.css('paddingRight')||0, 10)); };
+				}
+			};
+		}
+
+		//Create the placeholder
+		that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem));
+
+		//Append it after the actual current item
+		that.currentItem.after(that.placeholder);
+
+		//Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
+		o.placeholder.update(that, that.placeholder);
+
+	},
+
+	_contactContainers: function(event) {
+
+		// get innermost container that intersects with item
+		var innermostContainer = null, innermostIndex = null;
+
+
+		for (var i = this.containers.length - 1; i >= 0; i--){
+
+			// never consider a container that's located within the item itself
+			if($.contains(this.currentItem[0], this.containers[i].element[0]))
+				continue;
+
+			if(this._intersectsWith(this.containers[i].containerCache)) {
+
+				// if we've already found a container and it's more "inner" than this, then continue
+				if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0]))
+					continue;
+
+				innermostContainer = this.containers[i];
+				innermostIndex = i;
+
+			} else {
+				// container doesn't intersect. trigger "out" event if necessary
+				if(this.containers[i].containerCache.over) {
+					this.containers[i]._trigger("out", event, this._uiHash(this));
+					this.containers[i].containerCache.over = 0;
+				}
+			}
+
+		}
+
+		// if no intersecting containers found, return
+		if(!innermostContainer) return;
+
+		// move the item into the container if it's not there already
+		if(this.containers.length === 1) {
+			this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
+			this.containers[innermostIndex].containerCache.over = 1;
+		} else {
+
+			//When entering a new container, we will find the item with the least distance and append our item near it
+			var dist = 10000; var itemWithLeastDistance = null;
+			var posProperty = this.containers[innermostIndex].floating ? 'left' : 'top';
+			var sizeProperty = this.containers[innermostIndex].floating ? 'width' : 'height';
+			var base = this.positionAbs[posProperty] + this.offset.click[posProperty];
+			for (var j = this.items.length - 1; j >= 0; j--) {
+				if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) continue;
+				if(this.items[j].item[0] == this.currentItem[0]) continue;
+				var cur = this.items[j].item.offset()[posProperty];
+				var nearBottom = false;
+				if(Math.abs(cur - base) > Math.abs(cur + this.items[j][sizeProperty] - base)){
+					nearBottom = true;
+					cur += this.items[j][sizeProperty];
+				}
+
+				if(Math.abs(cur - base) < dist) {
+					dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j];
+					this.direction = nearBottom ? "up": "down";
+				}
+			}
+
+			if(!itemWithLeastDistance && !this.options.dropOnEmpty) //Check if dropOnEmpty is enabled
+				return;
+
+			this.currentContainer = this.containers[innermostIndex];
+			itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true);
+			this._trigger("change", event, this._uiHash());
+			this.containers[innermostIndex]._trigger("change", event, this._uiHash(this));
+
+			//Update the placeholder
+			this.options.placeholder.update(this.currentContainer, this.placeholder);
+
+			this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
+			this.containers[innermostIndex].containerCache.over = 1;
+		}
+
+
+	},
+
+	_createHelper: function(event) {
+
+		var o = this.options;
+		var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper == 'clone' ? this.currentItem.clone() : this.currentItem);
+
+		if(!helper.parents('body').length) //Add the helper to the DOM if that didn't happen already
+			$(o.appendTo != 'parent' ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);
+
+		if(helper[0] == this.currentItem[0])
+			this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") };
+
+		if(helper[0].style.width == '' || o.forceHelperSize) helper.width(this.currentItem.width());
+		if(helper[0].style.height == '' || o.forceHelperSize) helper.height(this.currentItem.height());
+
+		return helper;
+
+	},
+
+	_adjustOffsetFromHelper: function(obj) {
+		if (typeof obj == 'string') {
+			obj = obj.split(' ');
+		}
+		if ($.isArray(obj)) {
+			obj = {left: +obj[0], top: +obj[1] || 0};
+		}
+		if ('left' in obj) {
+			this.offset.click.left = obj.left + this.margins.left;
+		}
+		if ('right' in obj) {
+			this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
+		}
+		if ('top' in obj) {
+			this.offset.click.top = obj.top + this.margins.top;
+		}
+		if ('bottom' in obj) {
+			this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
+		}
+	},
+
+	_getParentOffset: function() {
+
+
+		//Get the offsetParent and cache its position
+		this.offsetParent = this.helper.offsetParent();
+		var po = this.offsetParent.offset();
+
+		// This is a special case where we need to modify a offset calculated on start, since the following happened:
+		// 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
+		// 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
+		//    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
+		if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
+			po.left += this.scrollParent.scrollLeft();
+			po.top += this.scrollParent.scrollTop();
+		}
+
+		if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information
+		|| (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.ui.ie)) //Ugly IE fix
+			po = { top: 0, left: 0 };
+
+		return {
+			top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
+			left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
+		};
+
+	},
+
+	_getRelativeOffset: function() {
+
+		if(this.cssPosition == "relative") {
+			var p = this.currentItem.position();
+			return {
+				top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
+				left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
+			};
+		} else {
+			return { top: 0, left: 0 };
+		}
+
+	},
+
+	_cacheMargins: function() {
+		this.margins = {
+			left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
+			top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
+		};
+	},
+
+	_cacheHelperProportions: function() {
+		this.helperProportions = {
+			width: this.helper.outerWidth(),
+			height: this.helper.outerHeight()
+		};
+	},
+
+	_setContainment: function() {
+
+		var o = this.options;
+		if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
+		if(o.containment == 'document' || o.containment == 'window') this.containment = [
+			0 - this.offset.relative.left - this.offset.parent.left,
+			0 - this.offset.relative.top - this.offset.parent.top,
+			$(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left,
+			($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
+		];
+
+		if(!(/^(document|window|parent)$/).test(o.containment)) {
+			var ce = $(o.containment)[0];
+			var co = $(o.containment).offset();
+			var over = ($(ce).css("overflow") != 'hidden');
+
+			this.containment = [
+				co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
+				co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
+				co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
+				co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
+			];
+		}
+
+	},
+
+	_convertPositionTo: function(d, pos) {
+
+		if(!pos) pos = this.position;
+		var mod = d == "absolute" ? 1 : -1;
+		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
+
+		return {
+			top: (
+				pos.top																	// The absolute mouse position
+				+ this.offset.relative.top * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
+				+ this.offset.parent.top * mod											// The offsetParent's offset without borders (offset + border)
+				- ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
+			),
+			left: (
+				pos.left																// The absolute mouse position
+				+ this.offset.relative.left * mod										// Only for relative positioned nodes: Relative offset from element to offset parent
+				+ this.offset.parent.left * mod											// The offsetParent's offset without borders (offset + border)
+				- ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
+			)
+		};
+
+	},
+
+	_generatePosition: function(event) {
+
+		var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
+
+		// This is another very weird special case that only happens for relative elements:
+		// 1. If the css position is relative
+		// 2. and the scroll parent is the document or similar to the offset parent
+		// we have to refresh the relative offset during the scroll so there are no jumps
+		if(this.cssPosition == 'relative' && !(this.scrollParent[0] != document && this.scrollParent[0] != this.offsetParent[0])) {
+			this.offset.relative = this._getRelativeOffset();
+		}
+
+		var pageX = event.pageX;
+		var pageY = event.pageY;
+
+		/*
+		 * - Position constraining -
+		 * Constrain the position to a mix of grid, containment.
+		 */
+
+		if(this.originalPosition) { //If we are not dragging yet, we won't check for options
+
+			if(this.containment) {
+				if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left;
+				if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top;
+				if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left;
+				if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top;
+			}
+
+			if(o.grid) {
+				var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
+				pageY = this.containment ? (!(top - this.offset.click.top < this.containment[1] || top - this.offset.click.top > this.containment[3]) ? top : (!(top - this.offset.click.top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
+
+				var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
+				pageX = this.containment ? (!(left - this.offset.click.left < this.containment[0] || left - this.offset.click.left > this.containment[2]) ? left : (!(left - this.offset.click.left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
+			}
+
+		}
+
+		return {
+			top: (
+				pageY																// The absolute mouse position
+				- this.offset.click.top													// Click offset (relative to the element)
+				- this.offset.relative.top												// Only for relative positioned nodes: Relative offset from element to offset parent
+				- this.offset.parent.top												// The offsetParent's offset without borders (offset + border)
+				+ ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
+			),
+			left: (
+				pageX																// The absolute mouse position
+				- this.offset.click.left												// Click offset (relative to the element)
+				- this.offset.relative.left												// Only for relative positioned nodes: Relative offset from element to offset parent
+				- this.offset.parent.left												// The offsetParent's offset without borders (offset + border)
+				+ ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
+			)
+		};
+
+	},
+
+	_rearrange: function(event, i, a, hardRefresh) {
+
+		a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction == 'down' ? i.item[0] : i.item[0].nextSibling));
+
+		//Various things done here to improve the performance:
+		// 1. we create a setTimeout, that calls refreshPositions
+		// 2. on the instance, we have a counter variable, that get's higher after every append
+		// 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
+		// 4. this lets only the last addition to the timeout stack through
+		this.counter = this.counter ? ++this.counter : 1;
+		var counter = this.counter;
+
+		this._delay(function() {
+			if(counter == this.counter) this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
+		});
+
+	},
+
+	_clear: function(event, noPropagation) {
+
+		this.reverting = false;
+		// We delay all events that have to be triggered to after the point where the placeholder has been removed and
+		// everything else normalized again
+		var delayedTriggers = [];
+
+		// We first have to update the dom position of the actual currentItem
+		// Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
+		if(!this._noFinalSort && this.currentItem.parent().length) this.placeholder.before(this.currentItem);
+		this._noFinalSort = null;
+
+		if(this.helper[0] == this.currentItem[0]) {
+			for(var i in this._storedCSS) {
+				if(this._storedCSS[i] == 'auto' || this._storedCSS[i] == 'static') this._storedCSS[i] = '';
+			}
+			this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
+		} else {
+			this.currentItem.show();
+		}
+
+		if(this.fromOutside && !noPropagation) delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
+		if((this.fromOutside || this.domPosition.prev != this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent != this.currentItem.parent()[0]) && !noPropagation) delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
+
+		// Check if the items Container has Changed and trigger appropriate
+		// events.
+		if (this !== this.currentContainer) {
+			if(!noPropagation) {
+				delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
+				delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); };  }).call(this, this.currentContainer));
+				delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this));  }; }).call(this, this.currentContainer));
+			}
+		}
+
+
+		//Post events to containers
+		for (var i = this.containers.length - 1; i >= 0; i--){
+			if(!noPropagation) delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
+			if(this.containers[i].containerCache.over) {
+				delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
+				this.containers[i].containerCache.over = 0;
+			}
+		}
+
+		//Do what was originally in plugins
+		if(this._storedCursor) $('body').css("cursor", this._storedCursor); //Reset cursor
+		if(this._storedOpacity) this.helper.css("opacity", this._storedOpacity); //Reset opacity
+		if(this._storedZIndex) this.helper.css("zIndex", this._storedZIndex == 'auto' ? '' : this._storedZIndex); //Reset z-index
+
+		this.dragging = false;
+		if(this.cancelHelperRemoval) {
+			if(!noPropagation) {
+				this._trigger("beforeStop", event, this._uiHash());
+				for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events
+				this._trigger("stop", event, this._uiHash());
+			}
+
+			this.fromOutside = false;
+			return false;
+		}
+
+		if(!noPropagation) this._trigger("beforeStop", event, this._uiHash());
+
+		//$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
+		this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
+
+		if(this.helper[0] != this.currentItem[0]) this.helper.remove(); this.helper = null;
+
+		if(!noPropagation) {
+			for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events
+			this._trigger("stop", event, this._uiHash());
+		}
+
+		this.fromOutside = false;
+		return true;
+
+	},
+
+	_trigger: function() {
+		if ($.Widget.prototype._trigger.apply(this, arguments) === false) {
+			this.cancel();
+		}
+	},
+
+	_uiHash: function(_inst) {
+		var inst = _inst || this;
+		return {
+			helper: inst.helper,
+			placeholder: inst.placeholder || $([]),
+			position: inst.position,
+			originalPosition: inst.originalPosition,
+			offset: inst.positionAbs,
+			item: inst.currentItem,
+			sender: _inst ? _inst.element : null
+		};
+	}
+
+});
+
+})(jQuery);
+
+;(jQuery.effects || (function($, undefined) {
+
+var backCompat = $.uiBackCompat !== false,
+	// prefix used for storing data on .data()
+	dataSpace = "ui-effects-";
+
+$.effects = {
+	effect: {}
+};
+
+/*!
+ * jQuery Color Animations v2.0.0
+ * http://jquery.com/
+ *
+ * Copyright 2012 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * Date: Mon Aug 13 13:41:02 2012 -0500
+ */
+(function( jQuery, undefined ) {
+
+	var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor".split(" "),
+
+	// plusequals test for += 100 -= 100
+	rplusequals = /^([\-+])=\s*(\d+\.?\d*)/,
+	// a set of RE's that can match strings and generate color tuples.
+	stringParsers = [{
+			re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,
+			parse: function( execResult ) {
+				return [
+					execResult[ 1 ],
+					execResult[ 2 ],
+					execResult[ 3 ],
+					execResult[ 4 ]
+				];
+			}
+		}, {
+			re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,
+			parse: function( execResult ) {
+				return [
+					execResult[ 1 ] * 2.55,
+					execResult[ 2 ] * 2.55,
+					execResult[ 3 ] * 2.55,
+					execResult[ 4 ]
+				];
+			}
+		}, {
+			// this regex ignores A-F because it's compared against an already lowercased string
+			re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/,
+			parse: function( execResult ) {
+				return [
+					parseInt( execResult[ 1 ], 16 ),
+					parseInt( execResult[ 2 ], 16 ),
+					parseInt( execResult[ 3 ], 16 )
+				];
+			}
+		}, {
+			// this regex ignores A-F because it's compared against an already lowercased string
+			re: /#([a-f0-9])([a-f0-9])([a-f0-9])/,
+			parse: function( execResult ) {
+				return [
+					parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ),
+					parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ),
+					parseInt( execResult[ 3 ] + execResult[ 3 ], 16 )
+				];
+			}
+		}, {
+			re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/,
+			space: "hsla",
+			parse: function( execResult ) {
+				return [
+					execResult[ 1 ],
+					execResult[ 2 ] / 100,
+					execResult[ 3 ] / 100,
+					execResult[ 4 ]
+				];
+			}
+		}],
+
+	// jQuery.Color( )
+	color = jQuery.Color = function( color, green, blue, alpha ) {
+		return new jQuery.Color.fn.parse( color, green, blue, alpha );
+	},
+	spaces = {
+		rgba: {
+			props: {
+				red: {
+					idx: 0,
+					type: "byte"
+				},
+				green: {
+					idx: 1,
+					type: "byte"
+				},
+				blue: {
+					idx: 2,
+					type: "byte"
+				}
+			}
+		},
+
+		hsla: {
+			props: {
+				hue: {
+					idx: 0,
+					type: "degrees"
+				},
+				saturation: {
+					idx: 1,
+					type: "percent"
+				},
+				lightness: {
+					idx: 2,
+					type: "percent"
+				}
+			}
+		}
+	},
+	propTypes = {
+		"byte": {
+			floor: true,
+			max: 255
+		},
+		"percent": {
+			max: 1
+		},
+		"degrees": {
+			mod: 360,
+			floor: true
+		}
+	},
+	support = color.support = {},
+
+	// element for support tests
+	supportElem = jQuery( "<p>" )[ 0 ],
+
+	// colors = jQuery.Color.names
+	colors,
+
+	// local aliases of functions called often
+	each = jQuery.each;
+
+// determine rgba support immediately
+supportElem.style.cssText = "background-color:rgba(1,1,1,.5)";
+support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1;
+
+// define cache name and alpha properties
+// for rgba and hsla spaces
+each( spaces, function( spaceName, space ) {
+	space.cache = "_" + spaceName;
+	space.props.alpha = {
+		idx: 3,
+		type: "percent",
+		def: 1
+	};
+});
+
+function clamp( value, prop, allowEmpty ) {
+	var type = propTypes[ prop.type ] || {};
+
+	if ( value == null ) {
+		return (allowEmpty || !prop.def) ? null : prop.def;
+	}
+
+	// ~~ is an short way of doing floor for positive numbers
+	value = type.floor ? ~~value : parseFloat( value );
+
+	// IE will pass in empty strings as value for alpha,
+	// which will hit this case
+	if ( isNaN( value ) ) {
+		return prop.def;
+	}
+
+	if ( type.mod ) {
+		// we add mod before modding to make sure that negatives values
+		// get converted properly: -10 -> 350
+		return (value + type.mod) % type.mod;
+	}
+
+	// for now all property types without mod have min and max
+	return 0 > value ? 0 : type.max < value ? type.max : value;
+}
+
+function stringParse( string ) {
+	var inst = color(),
+		rgba = inst._rgba = [];
+
+	string = string.toLowerCase();
+
+	each( stringParsers, function( i, parser ) {
+		var parsed,
+			match = parser.re.exec( string ),
+			values = match && parser.parse( match ),
+			spaceName = parser.space || "rgba";
+
+		if ( values ) {
+			parsed = inst[ spaceName ]( values );
+
+			// if this was an rgba parse the assignment might happen twice
+			// oh well....
+			inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ];
+			rgba = inst._rgba = parsed._rgba;
+
+			// exit each( stringParsers ) here because we matched
+			return false;
+		}
+	});
+
+	// Found a stringParser that handled it
+	if ( rgba.length ) {
+
+		// if this came from a parsed string, force "transparent" when alpha is 0
+		// chrome, (and maybe others) return "transparent" as rgba(0,0,0,0)
+		if ( rgba.join() === "0,0,0,0" ) {
+			jQuery.extend( rgba, colors.transparent );
+		}
+		return inst;
+	}
+
+	// named colors
+	return colors[ string ];
+}
+
+color.fn = jQuery.extend( color.prototype, {
+	parse: function( red, green, blue, alpha ) {
+		if ( red === undefined ) {
+			this._rgba = [ null, null, null, null ];
+			return this;
+		}
+		if ( red.jquery || red.nodeType ) {
+			red = jQuery( red ).css( green );
+			green = undefined;
+		}
+
+		var inst = this,
+			type = jQuery.type( red ),
+			rgba = this._rgba = [];
+
+		// more than 1 argument specified - assume ( red, green, blue, alpha )
+		if ( green !== undefined ) {
+			red = [ red, green, blue, alpha ];
+			type = "array";
+		}
+
+		if ( type === "string" ) {
+			return this.parse( stringParse( red ) || colors._default );
+		}
+
+		if ( type === "array" ) {
+			each( spaces.rgba.props, function( key, prop ) {
+				rgba[ prop.idx ] = clamp( red[ prop.idx ], prop );
+			});
+			return this;
+		}
+
+		if ( type === "object" ) {
+			if ( red instanceof color ) {
+				each( spaces, function( spaceName, space ) {
+					if ( red[ space.cache ] ) {
+						inst[ space.cache ] = red[ space.cache ].slice();
+					}
+				});
+			} else {
+				each( spaces, function( spaceName, space ) {
+					var cache = space.cache;
+					each( space.props, function( key, prop ) {
+
+						// if the cache doesn't exist, and we know how to convert
+						if ( !inst[ cache ] && space.to ) {
+
+							// if the value was null, we don't need to copy it
+							// if the key was alpha, we don't need to copy it either
+							if ( key === "alpha" || red[ key ] == null ) {
+								return;
+							}
+							inst[ cache ] = space.to( inst._rgba );
+						}
+
+						// this is the only case where we allow nulls for ALL properties.
+						// call clamp with alwaysAllowEmpty
+						inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true );
+					});
+
+					// everything defined but alpha?
+					if ( inst[ cache ] && $.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) {
+						// use the default of 1
+						inst[ cache ][ 3 ] = 1;
+						if ( space.from ) {
+							inst._rgba = space.from( inst[ cache ] );
+						}
+					}
+				});
+			}
+			return this;
+		}
+	},
+	is: function( compare ) {
+		var is = color( compare ),
+			same = true,
+			inst = this;
+
+		each( spaces, function( _, space ) {
+			var localCache,
+				isCache = is[ space.cache ];
+			if (isCache) {
+				localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || [];
+				each( space.props, function( _, prop ) {
+					if ( isCache[ prop.idx ] != null ) {
+						same = ( isCache[ prop.idx ] === localCache[ prop.idx ] );
+						return same;
+					}
+				});
+			}
+			return same;
+		});
+		return same;
+	},
+	_space: function() {
+		var used = [],
+			inst = this;
+		each( spaces, function( spaceName, space ) {
+			if ( inst[ space.cache ] ) {
+				used.push( spaceName );
+			}
+		});
+		return used.pop();
+	},
+	transition: function( other, distance ) {
+		var end = color( other ),
+			spaceName = end._space(),
+			space = spaces[ spaceName ],
+			startColor = this.alpha() === 0 ? color( "transparent" ) : this,
+			start = startColor[ space.cache ] || space.to( startColor._rgba ),
+			result = start.slice();
+
+		end = end[ space.cache ];
+		each( space.props, function( key, prop ) {
+			var index = prop.idx,
+				startValue = start[ index ],
+				endValue = end[ index ],
+				type = propTypes[ prop.type ] || {};
+
+			// if null, don't override start value
+			if ( endValue === null ) {
+				return;
+			}
+			// if null - use end
+			if ( startValue === null ) {
+				result[ index ] = endValue;
+			} else {
+				if ( type.mod ) {
+					if ( endValue - startValue > type.mod / 2 ) {
+						startValue += type.mod;
+					} else if ( startValue - endValue > type.mod / 2 ) {
+						startValue -= type.mod;
+					}
+				}
+				result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop );
+			}
+		});
+		return this[ spaceName ]( result );
+	},
+	blend: function( opaque ) {
+		// if we are already opaque - return ourself
+		if ( this._rgba[ 3 ] === 1 ) {
+			return this;
+		}
+
+		var rgb = this._rgba.slice(),
+			a = rgb.pop(),
+			blend = color( opaque )._rgba;
+
+		return color( jQuery.map( rgb, function( v, i ) {
+			return ( 1 - a ) * blend[ i ] + a * v;
+		}));
+	},
+	toRgbaString: function() {
+		var prefix = "rgba(",
+			rgba = jQuery.map( this._rgba, function( v, i ) {
+				return v == null ? ( i > 2 ? 1 : 0 ) : v;
+			});
+
+		if ( rgba[ 3 ] === 1 ) {
+			rgba.pop();
+			prefix = "rgb(";
+		}
+
+		return prefix + rgba.join() + ")";
+	},
+	toHslaString: function() {
+		var prefix = "hsla(",
+			hsla = jQuery.map( this.hsla(), function( v, i ) {
+				if ( v == null ) {
+					v = i > 2 ? 1 : 0;
+				}
+
+				// catch 1 and 2
+				if ( i && i < 3 ) {
+					v = Math.round( v * 100 ) + "%";
+				}
+				return v;
+			});
+
+		if ( hsla[ 3 ] === 1 ) {
+			hsla.pop();
+			prefix = "hsl(";
+		}
+		return prefix + hsla.join() + ")";
+	},
+	toHexString: function( includeAlpha ) {
+		var rgba = this._rgba.slice(),
+			alpha = rgba.pop();
+
+		if ( includeAlpha ) {
+			rgba.push( ~~( alpha * 255 ) );
+		}
+
+		return "#" + jQuery.map( rgba, function( v ) {
+
+			// default to 0 when nulls exist
+			v = ( v || 0 ).toString( 16 );
+			return v.length === 1 ? "0" + v : v;
+		}).join("");
+	},
+	toString: function() {
+		return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString();
+	}
+});
+color.fn.parse.prototype = color.fn;
+
+// hsla conversions adapted from:
+// https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021
+
+function hue2rgb( p, q, h ) {
+	h = ( h + 1 ) % 1;
+	if ( h * 6 < 1 ) {
+		return p + (q - p) * h * 6;
+	}
+	if ( h * 2 < 1) {
+		return q;
+	}
+	if ( h * 3 < 2 ) {
+		return p + (q - p) * ((2/3) - h) * 6;
+	}
+	return p;
+}
+
+spaces.hsla.to = function ( rgba ) {
+	if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) {
+		return [ null, null, null, rgba[ 3 ] ];
+	}
+	var r = rgba[ 0 ] / 255,
+		g = rgba[ 1 ] / 255,
+		b = rgba[ 2 ] / 255,
+		a = rgba[ 3 ],
+		max = Math.max( r, g, b ),
+		min = Math.min( r, g, b ),
+		diff = max - min,
+		add = max + min,
+		l = add * 0.5,
+		h, s;
+
+	if ( min === max ) {
+		h = 0;
+	} else if ( r === max ) {
+		h = ( 60 * ( g - b ) / diff ) + 360;
+	} else if ( g === max ) {
+		h = ( 60 * ( b - r ) / diff ) + 120;
+	} else {
+		h = ( 60 * ( r - g ) / diff ) + 240;
+	}
+
+	if ( l === 0 || l === 1 ) {
+		s = l;
+	} else if ( l <= 0.5 ) {
+		s = diff / add;
+	} else {
+		s = diff / ( 2 - add );
+	}
+	return [ Math.round(h) % 360, s, l, a == null ? 1 : a ];
+};
+
+spaces.hsla.from = function ( hsla ) {
+	if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) {
+		return [ null, null, null, hsla[ 3 ] ];
+	}
+	var h = hsla[ 0 ] / 360,
+		s = hsla[ 1 ],
+		l = hsla[ 2 ],
+		a = hsla[ 3 ],
+		q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s,
+		p = 2 * l - q;
+
+	return [
+		Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ),
+		Math.round( hue2rgb( p, q, h ) * 255 ),
+		Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ),
+		a
+	];
+};
+
+
+each( spaces, function( spaceName, space ) {
+	var props = space.props,
+		cache = space.cache,
+		to = space.to,
+		from = space.from;
+
+	// makes rgba() and hsla()
+	color.fn[ spaceName ] = function( value ) {
+
+		// generate a cache for this space if it doesn't exist
+		if ( to && !this[ cache ] ) {
+			this[ cache ] = to( this._rgba );
+		}
+		if ( value === undefined ) {
+			return this[ cache ].slice();
+		}
+
+		var ret,
+			type = jQuery.type( value ),
+			arr = ( type === "array" || type === "object" ) ? value : arguments,
+			local = this[ cache ].slice();
+
+		each( props, function( key, prop ) {
+			var val = arr[ type === "object" ? key : prop.idx ];
+			if ( val == null ) {
+				val = local[ prop.idx ];
+			}
+			local[ prop.idx ] = clamp( val, prop );
+		});
+
+		if ( from ) {
+			ret = color( from( local ) );
+			ret[ cache ] = local;
+			return ret;
+		} else {
+			return color( local );
+		}
+	};
+
+	// makes red() green() blue() alpha() hue() saturation() lightness()
+	each( props, function( key, prop ) {
+		// alpha is included in more than one space
+		if ( color.fn[ key ] ) {
+			return;
+		}
+		color.fn[ key ] = function( value ) {
+			var vtype = jQuery.type( value ),
+				fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ),
+				local = this[ fn ](),
+				cur = local[ prop.idx ],
+				match;
+
+			if ( vtype === "undefined" ) {
+				return cur;
+			}
+
+			if ( vtype === "function" ) {
+				value = value.call( this, cur );
+				vtype = jQuery.type( value );
+			}
+			if ( value == null && prop.empty ) {
+				return this;
+			}
+			if ( vtype === "string" ) {
+				match = rplusequals.exec( value );
+				if ( match ) {
+					value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 );
+				}
+			}
+			local[ prop.idx ] = value;
+			return this[ fn ]( local );
+		};
+	});
+});
+
+// add .fx.step functions
+each( stepHooks, function( i, hook ) {
+	jQuery.cssHooks[ hook ] = {
+		set: function( elem, value ) {
+			var parsed, curElem,
+				backgroundColor = "";
+
+			if ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) {
+				value = color( parsed || value );
+				if ( !support.rgba && value._rgba[ 3 ] !== 1 ) {
+					curElem = hook === "backgroundColor" ? elem.parentNode : elem;
+					while (
+						(backgroundColor === "" || backgroundColor === "transparent") &&
+						curElem && curElem.style
+					) {
+						try {
+							backgroundColor = jQuery.css( curElem, "backgroundColor" );
+							curElem = curElem.parentNode;
+						} catch ( e ) {
+						}
+					}
+
+					value = value.blend( backgroundColor && backgroundColor !== "transparent" ?
+						backgroundColor :
+						"_default" );
+				}
+
+				value = value.toRgbaString();
+			}
+			try {
+				elem.style[ hook ] = value;
+			} catch( error ) {
+				// wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit'
+			}
+		}
+	};
+	jQuery.fx.step[ hook ] = function( fx ) {
+		if ( !fx.colorInit ) {
+			fx.start = color( fx.elem, hook );
+			fx.end = color( fx.end );
+			fx.colorInit = true;
+		}
+		jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) );
+	};
+});
+
+jQuery.cssHooks.borderColor = {
+	expand: function( value ) {
+		var expanded = {};
+
+		each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) {
+			expanded[ "border" + part + "Color" ] = value;
+		});
+		return expanded;
+	}
+};
+
+// Basic color names only.
+// Usage of any of the other color names requires adding yourself or including
+// jquery.color.svg-names.js.
+colors = jQuery.Color.names = {
+	// 4.1. Basic color keywords
+	aqua: "#00ffff",
+	black: "#000000",
+	blue: "#0000ff",
+	fuchsia: "#ff00ff",
+	gray: "#808080",
+	green: "#008000",
+	lime: "#00ff00",
+	maroon: "#800000",
+	navy: "#000080",
+	olive: "#808000",
+	purple: "#800080",
+	red: "#ff0000",
+	silver: "#c0c0c0",
+	teal: "#008080",
+	white: "#ffffff",
+	yellow: "#ffff00",
+
+	// 4.2.3. "transparent" color keyword
+	transparent: [ null, null, null, 0 ],
+
+	_default: "#ffffff"
+};
+
+})( jQuery );
+
+
+
+/******************************************************************************/
+/****************************** CLASS ANIMATIONS ******************************/
+/******************************************************************************/
+(function() {
+
+var classAnimationActions = [ "add", "remove", "toggle" ],
+	shorthandStyles = {
+		border: 1,
+		borderBottom: 1,
+		borderColor: 1,
+		borderLeft: 1,
+		borderRight: 1,
+		borderTop: 1,
+		borderWidth: 1,
+		margin: 1,
+		padding: 1
+	};
+
+$.each([ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) {
+	$.fx.step[ prop ] = function( fx ) {
+		if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) {
+			jQuery.style( fx.elem, prop, fx.end );
+			fx.setAttr = true;
+		}
+	};
+});
+
+function getElementStyles() {
+	var style = this.ownerDocument.defaultView ?
+			this.ownerDocument.defaultView.getComputedStyle( this, null ) :
+			this.currentStyle,
+		newStyle = {},
+		key,
+		len;
+
+	// webkit enumerates style porperties
+	if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) {
+		len = style.length;
+		while ( len-- ) {
+			key = style[ len ];
+			if ( typeof style[ key ] === "string" ) {
+				newStyle[ $.camelCase( key ) ] = style[ key ];
+			}
+		}
+	} else {
+		for ( key in style ) {
+			if ( typeof style[ key ] === "string" ) {
+				newStyle[ key ] = style[ key ];
+			}
+		}
+	}
+
+	return newStyle;
+}
+
+
+function styleDifference( oldStyle, newStyle ) {
+	var diff = {},
+		name, value;
+
+	for ( name in newStyle ) {
+		value = newStyle[ name ];
+		if ( oldStyle[ name ] !== value ) {
+			if ( !shorthandStyles[ name ] ) {
+				if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) {
+					diff[ name ] = value;
+				}
+			}
+		}
+	}
+
+	return diff;
+}
+
+$.effects.animateClass = function( value, duration, easing, callback ) {
+	var o = $.speed( duration, easing, callback );
+
+	return this.queue( function() {
+		var animated = $( this ),
+			baseClass = animated.attr( "class" ) || "",
+			applyClassChange,
+			allAnimations = o.children ? animated.find( "*" ).andSelf() : animated;
+
+		// map the animated objects to store the original styles.
+		allAnimations = allAnimations.map(function() {
+			var el = $( this );
+			return {
+				el: el,
+				start: getElementStyles.call( this )
+			};
+		});
+
+		// apply class change
+		applyClassChange = function() {
+			$.each( classAnimationActions, function(i, action) {
+				if ( value[ action ] ) {
+					animated[ action + "Class" ]( value[ action ] );
+				}
+			});
+		};
+		applyClassChange();
+
+		// map all animated objects again - calculate new styles and diff
+		allAnimations = allAnimations.map(function() {
+			this.end = getElementStyles.call( this.el[ 0 ] );
+			this.diff = styleDifference( this.start, this.end );
+			return this;
+		});
+
+		// apply original class
+		animated.attr( "class", baseClass );
+
+		// map all animated objects again - this time collecting a promise
+		allAnimations = allAnimations.map(function() {
+			var styleInfo = this,
+				dfd = $.Deferred(),
+				opts = jQuery.extend({}, o, {
+					queue: false,
+					complete: function() {
+						dfd.resolve( styleInfo );
+					}
+				});
+
+			this.el.animate( this.diff, opts );
+			return dfd.promise();
+		});
+
+		// once all animations have completed:
+		$.when.apply( $, allAnimations.get() ).done(function() {
+
+			// set the final class
+			applyClassChange();
+
+			// for each animated element,
+			// clear all css properties that were animated
+			$.each( arguments, function() {
+				var el = this.el;
+				$.each( this.diff, function(key) {
+					el.css( key, '' );
+				});
+			});
+
+			// this is guarnteed to be there if you use jQuery.speed()
+			// it also handles dequeuing the next anim...
+			o.complete.call( animated[ 0 ] );
+		});
+	});
+};
+
+$.fn.extend({
+	_addClass: $.fn.addClass,
+	addClass: function( classNames, speed, easing, callback ) {
+		return speed ?
+			$.effects.animateClass.call( this,
+				{ add: classNames }, speed, easing, callback ) :
+			this._addClass( classNames );
+	},
+
+	_removeClass: $.fn.removeClass,
+	removeClass: function( classNames, speed, easing, callback ) {
+		return speed ?
+			$.effects.animateClass.call( this,
+				{ remove: classNames }, speed, easing, callback ) :
+			this._removeClass( classNames );
+	},
+
+	_toggleClass: $.fn.toggleClass,
+	toggleClass: function( classNames, force, speed, easing, callback ) {
+		if ( typeof force === "boolean" || force === undefined ) {
+			if ( !speed ) {
+				// without speed parameter
+				return this._toggleClass( classNames, force );
+			} else {
+				return $.effects.animateClass.call( this,
+					(force ? { add: classNames } : { remove: classNames }),
+					speed, easing, callback );
+			}
+		} else {
+			// without force parameter
+			return $.effects.animateClass.call( this,
+				{ toggle: classNames }, force, speed, easing );
+		}
+	},
+
+	switchClass: function( remove, add, speed, easing, callback) {
+		return $.effects.animateClass.call( this, {
+			add: add,
+			remove: remove
+		}, speed, easing, callback );
+	}
+});
+
+})();
+
+/******************************************************************************/
+/*********************************** EFFECTS **********************************/
+/******************************************************************************/
+
+(function() {
+
+$.extend( $.effects, {
+	version: "1.9.2",
+
+	// Saves a set of properties in a data storage
+	save: function( element, set ) {
+		for( var i=0; i < set.length; i++ ) {
+			if ( set[ i ] !== null ) {
+				element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] );
+			}
+		}
+	},
+
+	// Restores a set of previously saved properties from a data storage
+	restore: function( element, set ) {
+		var val, i;
+		for( i=0; i < set.length; i++ ) {
+			if ( set[ i ] !== null ) {
+				val = element.data( dataSpace + set[ i ] );
+				// support: jQuery 1.6.2
+				// http://bugs.jquery.com/ticket/9917
+				// jQuery 1.6.2 incorrectly returns undefined for any falsy value.
+				// We can't differentiate between "" and 0 here, so we just assume
+				// empty string since it's likely to be a more common value...
+				if ( val === undefined ) {
+					val = "";
+				}
+				element.css( set[ i ], val );
+			}
+		}
+	},
+
+	setMode: function( el, mode ) {
+		if (mode === "toggle") {
+			mode = el.is( ":hidden" ) ? "show" : "hide";
+		}
+		return mode;
+	},
+
+	// Translates a [top,left] array into a baseline value
+	// this should be a little more flexible in the future to handle a string & hash
+	getBaseline: function( origin, original ) {
+		var y, x;
+		switch ( origin[ 0 ] ) {
+			case "top": y = 0; break;
+			case "middle": y = 0.5; break;
+			case "bottom": y = 1; break;
+			default: y = origin[ 0 ] / original.height;
+		}
+		switch ( origin[ 1 ] ) {
+			case "left": x = 0; break;
+			case "center": x = 0.5; break;
+			case "right": x = 1; break;
+			default: x = origin[ 1 ] / original.width;
+		}
+		return {
+			x: x,
+			y: y
+		};
+	},
+
+	// Wraps the element around a wrapper that copies position properties
+	createWrapper: function( element ) {
+
+		// if the element is already wrapped, return it
+		if ( element.parent().is( ".ui-effects-wrapper" )) {
+			return element.parent();
+		}
+
+		// wrap the element
+		var props = {
+				width: element.outerWidth(true),
+				height: element.outerHeight(true),
+				"float": element.css( "float" )
+			},
+			wrapper = $( "<div></div>" )
+				.addClass( "ui-effects-wrapper" )
+				.css({
+					fontSize: "100%",
+					background: "transparent",
+					border: "none",
+					margin: 0,
+					padding: 0
+				}),
+			// Store the size in case width/height are defined in % - Fixes #5245
+			size = {
+				width: element.width(),
+				height: element.height()
+			},
+			active = document.activeElement;
+
+		// support: Firefox
+		// Firefox incorrectly exposes anonymous content
+		// https://bugzilla.mozilla.org/show_bug.cgi?id=561664
+		try {
+			active.id;
+		} catch( e ) {
+			active = document.body;
+		}
+
+		element.wrap( wrapper );
+
+		// Fixes #7595 - Elements lose focus when wrapped.
+		if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
+			$( active ).focus();
+		}
+
+		wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element
+
+		// transfer positioning properties to the wrapper
+		if ( element.css( "position" ) === "static" ) {
+			wrapper.css({ position: "relative" });
+			element.css({ position: "relative" });
+		} else {
+			$.extend( props, {
+				position: element.css( "position" ),
+				zIndex: element.css( "z-index" )
+			});
+			$.each([ "top", "left", "bottom", "right" ], function(i, pos) {
+				props[ pos ] = element.css( pos );
+				if ( isNaN( parseInt( props[ pos ], 10 ) ) ) {
+					props[ pos ] = "auto";
+				}
+			});
+			element.css({
+				position: "relative",
+				top: 0,
+				left: 0,
+				right: "auto",
+				bottom: "auto"
+			});
+		}
+		element.css(size);
+
+		return wrapper.css( props ).show();
+	},
+
+	removeWrapper: function( element ) {
+		var active = document.activeElement;
+
+		if ( element.parent().is( ".ui-effects-wrapper" ) ) {
+			element.parent().replaceWith( element );
+
+			// Fixes #7595 - Elements lose focus when wrapped.
+			if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) {
+				$( active ).focus();
+			}
+		}
+
+
+		return element;
+	},
+
+	setTransition: function( element, list, factor, value ) {
+		value = value || {};
+		$.each( list, function( i, x ) {
+			var unit = element.cssUnit( x );
+			if ( unit[ 0 ] > 0 ) {
+				value[ x ] = unit[ 0 ] * factor + unit[ 1 ];
+			}
+		});
+		return value;
+	}
+});
+
+// return an effect options object for the given parameters:
+function _normalizeArguments( effect, options, speed, callback ) {
+
+	// allow passing all options as the first parameter
+	if ( $.isPlainObject( effect ) ) {
+		options = effect;
+		effect = effect.effect;
+	}
+
+	// convert to an object
+	effect = { effect: effect };
+
+	// catch (effect, null, ...)
+	if ( options == null ) {
+		options = {};
+	}
+
+	// catch (effect, callback)
+	if ( $.isFunction( options ) ) {
+		callback = options;
+		speed = null;
+		options = {};
+	}
+
+	// catch (effect, speed, ?)
+	if ( typeof options === "number" || $.fx.speeds[ options ] ) {
+		callback = speed;
+		speed = options;
+		options = {};
+	}
+
+	// catch (effect, options, callback)
+	if ( $.isFunction( speed ) ) {
+		callback = speed;
+		speed = null;
+	}
+
+	// add options to effect
+	if ( options ) {
+		$.extend( effect, options );
+	}
+
+	speed = speed || options.duration;
+	effect.duration = $.fx.off ? 0 :
+		typeof speed === "number" ? speed :
+		speed in $.fx.speeds ? $.fx.speeds[ speed ] :
+		$.fx.speeds._default;
+
+	effect.complete = callback || options.complete;
+
+	return effect;
+}
+
+function standardSpeed( speed ) {
+	// valid standard speeds
+	if ( !speed || typeof speed === "number" || $.fx.speeds[ speed ] ) {
+		return true;
+	}
+
+	// invalid strings - treat as "normal" speed
+	if ( typeof speed === "string" && !$.effects.effect[ speed ] ) {
+		// TODO: remove in 2.0 (#7115)
+		if ( backCompat && $.effects[ speed ] ) {
+			return false;
+		}
+		return true;
+	}
+
+	return false;
+}
+
+$.fn.extend({
+	effect: function( /* effect, options, speed, callback */ ) {
+		var args = _normalizeArguments.apply( this, arguments ),
+			mode = args.mode,
+			queue = args.queue,
+			effectMethod = $.effects.effect[ args.effect ],
+
+			// DEPRECATED: remove in 2.0 (#7115)
+			oldEffectMethod = !effectMethod && backCompat && $.effects[ args.effect ];
+
+		if ( $.fx.off || !( effectMethod || oldEffectMethod ) ) {
+			// delegate to the original method (e.g., .show()) if possible
+			if ( mode ) {
+				return this[ mode ]( args.duration, args.complete );
+			} else {
+				return this.each( function() {
+					if ( args.complete ) {
+						args.complete.call( this );
+					}
+				});
+			}
+		}
+
+		function run( next ) {
+			var elem = $( this ),
+				complete = args.complete,
+				mode = args.mode;
+
+			function done() {
+				if ( $.isFunction( complete ) ) {
+					complete.call( elem[0] );
+				}
+				if ( $.isFunction( next ) ) {
+					next();
+				}
+			}
+
+			// if the element is hiddden and mode is hide,
+			// or element is visible and mode is show
+			if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) {
+				done();
+			} else {
+				effectMethod.call( elem[0], args, done );
+			}
+		}
+
+		// TODO: remove this check in 2.0, effectMethod will always be true
+		if ( effectMethod ) {
+			return queue === false ? this.each( run ) : this.queue( queue || "fx", run );
+		} else {
+			// DEPRECATED: remove in 2.0 (#7115)
+			return oldEffectMethod.call(this, {
+				options: args,
+				duration: args.duration,
+				callback: args.complete,
+				mode: args.mode
+			});
+		}
+	},
+
+	_show: $.fn.show,
+	show: function( speed ) {
+		if ( standardSpeed( speed ) ) {
+			return this._show.apply( this, arguments );
+		} else {
+			var args = _normalizeArguments.apply( this, arguments );
+			args.mode = "show";
+			return this.effect.call( this, args );
+		}
+	},
+
+	_hide: $.fn.hide,
+	hide: function( speed ) {
+		if ( standardSpeed( speed ) ) {
+			return this._hide.apply( this, arguments );
+		} else {
+			var args = _normalizeArguments.apply( this, arguments );
+			args.mode = "hide";
+			return this.effect.call( this, args );
+		}
+	},
+
+	// jQuery core overloads toggle and creates _toggle
+	__toggle: $.fn.toggle,
+	toggle: function( speed ) {
+		if ( standardSpeed( speed ) || typeof speed === "boolean" || $.isFunction( speed ) ) {
+			return this.__toggle.apply( this, arguments );
+		} else {
+			var args = _normalizeArguments.apply( this, arguments );
+			args.mode = "toggle";
+			return this.effect.call( this, args );
+		}
+	},
+
+	// helper functions
+	cssUnit: function(key) {
+		var style = this.css( key ),
+			val = [];
+
+		$.each( [ "em", "px", "%", "pt" ], function( i, unit ) {
+			if ( style.indexOf( unit ) > 0 ) {
+				val = [ parseFloat( style ), unit ];
+			}
+		});
+		return val;
+	}
+});
+
+})();
+
+/******************************************************************************/
+/*********************************** EASING ***********************************/
+/******************************************************************************/
+
+(function() {
+
+// based on easing equations from Robert Penner (http://www.robertpenner.com/easing)
+
+var baseEasings = {};
+
+$.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) {
+	baseEasings[ name ] = function( p ) {
+		return Math.pow( p, i + 2 );
+	};
+});
+
+$.extend( baseEasings, {
+	Sine: function ( p ) {
+		return 1 - Math.cos( p * Math.PI / 2 );
+	},
+	Circ: function ( p ) {
+		return 1 - Math.sqrt( 1 - p * p );
+	},
+	Elastic: function( p ) {
+		return p === 0 || p === 1 ? p :
+			-Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 );
+	},
+	Back: function( p ) {
+		return p * p * ( 3 * p - 2 );
+	},
+	Bounce: function ( p ) {
+		var pow2,
+			bounce = 4;
+
+		while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {}
+		return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 );
+	}
+});
+
+$.each( baseEasings, function( name, easeIn ) {
+	$.easing[ "easeIn" + name ] = easeIn;
+	$.easing[ "easeOut" + name ] = function( p ) {
+		return 1 - easeIn( 1 - p );
+	};
+	$.easing[ "easeInOut" + name ] = function( p ) {
+		return p < 0.5 ?
+			easeIn( p * 2 ) / 2 :
+			1 - easeIn( p * -2 + 2 ) / 2;
+	};
+});
+
+})();
+
+})(jQuery));
+
+(function( $, undefined ) {
+
+var uid = 0,
+	hideProps = {},
+	showProps = {};
+
+hideProps.height = hideProps.paddingTop = hideProps.paddingBottom =
+	hideProps.borderTopWidth = hideProps.borderBottomWidth = "hide";
+showProps.height = showProps.paddingTop = showProps.paddingBottom =
+	showProps.borderTopWidth = showProps.borderBottomWidth = "show";
+
+$.widget( "ui.accordion", {
+	version: "1.9.2",
+	options: {
+		active: 0,
+		animate: {},
+		collapsible: false,
+		event: "click",
+		header: "> li > :first-child,> :not(li):even",
+		heightStyle: "auto",
+		icons: {
+			activeHeader: "ui-icon-triangle-1-s",
+			header: "ui-icon-triangle-1-e"
+		},
+
+		// callbacks
+		activate: null,
+		beforeActivate: null
+	},
+
+	_create: function() {
+		var accordionId = this.accordionId = "ui-accordion-" +
+				(this.element.attr( "id" ) || ++uid),
+			options = this.options;
+
+		this.prevShow = this.prevHide = $();
+		this.element.addClass( "ui-accordion ui-widget ui-helper-reset" );
+
+		this.headers = this.element.find( options.header )
+			.addClass( "ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" );
+		this._hoverable( this.headers );
+		this._focusable( this.headers );
+
+		this.headers.next()
+			.addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" )
+			.hide();
+
+		// don't allow collapsible: false and active: false / null
+		if ( !options.collapsible && (options.active === false || options.active == null) ) {
+			options.active = 0;
+		}
+		// handle negative values
+		if ( options.active < 0 ) {
+			options.active += this.headers.length;
+		}
+		this.active = this._findActive( options.active )
+			.addClass( "ui-accordion-header-active ui-state-active" )
+			.toggleClass( "ui-corner-all ui-corner-top" );
+		this.active.next()
+			.addClass( "ui-accordion-content-active" )
+			.show();
+
+		this._createIcons();
+		this.refresh();
+
+		// ARIA
+		this.element.attr( "role", "tablist" );
+
+		this.headers
+			.attr( "role", "tab" )
+			.each(function( i ) {
+				var header = $( this ),
+					headerId = header.attr( "id" ),
+					panel = header.next(),
+					panelId = panel.attr( "id" );
+				if ( !headerId ) {
+					headerId = accordionId + "-header-" + i;
+					header.attr( "id", headerId );
+				}
+				if ( !panelId ) {
+					panelId = accordionId + "-panel-" + i;
+					panel.attr( "id", panelId );
+				}
+				header.attr( "aria-controls", panelId );
+				panel.attr( "aria-labelledby", headerId );
+			})
+			.next()
+				.attr( "role", "tabpanel" );
+
+		this.headers
+			.not( this.active )
+			.attr({
+				"aria-selected": "false",
+				tabIndex: -1
+			})
+			.next()
+				.attr({
+					"aria-expanded": "false",
+					"aria-hidden": "true"
+				})
+				.hide();
+
+		// make sure at least one header is in the tab order
+		if ( !this.active.length ) {
+			this.headers.eq( 0 ).attr( "tabIndex", 0 );
+		} else {
+			this.active.attr({
+				"aria-selected": "true",
+				tabIndex: 0
+			})
+			.next()
+				.attr({
+					"aria-expanded": "true",
+					"aria-hidden": "false"
+				});
+		}
+
+		this._on( this.headers, { keydown: "_keydown" });
+		this._on( this.headers.next(), { keydown: "_panelKeyDown" });
+		this._setupEvents( options.event );
+	},
+
+	_getCreateEventData: function() {
+		return {
+			header: this.active,
+			content: !this.active.length ? $() : this.active.next()
+		};
+	},
+
+	_createIcons: function() {
+		var icons = this.options.icons;
+		if ( icons ) {
+			$( "<span>" )
+				.addClass( "ui-accordion-header-icon ui-icon " + icons.header )
+				.prependTo( this.headers );
+			this.active.children( ".ui-accordion-header-icon" )
+				.removeClass( icons.header )
+				.addClass( icons.activeHeader );
+			this.headers.addClass( "ui-accordion-icons" );
+		}
+	},
+
+	_destroyIcons: function() {
+		this.headers
+			.removeClass( "ui-accordion-icons" )
+			.children( ".ui-accordion-header-icon" )
+				.remove();
+	},
+
+	_destroy: function() {
+		var contents;
+
+		// clean up main element
+		this.element
+			.removeClass( "ui-accordion ui-widget ui-helper-reset" )
+			.removeAttr( "role" );
+
+		// clean up headers
+		this.headers
+			.removeClass( "ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top" )
+			.removeAttr( "role" )
+			.removeAttr( "aria-selected" )
+			.removeAttr( "aria-controls" )
+			.removeAttr( "tabIndex" )
+			.each(function() {
+				if ( /^ui-accordion/.test( this.id ) ) {
+					this.removeAttribute( "id" );
+				}
+			});
+		this._destroyIcons();
+
+		// clean up content panels
+		contents = this.headers.next()
+			.css( "display", "" )
+			.removeAttr( "role" )
+			.removeAttr( "aria-expanded" )
+			.removeAttr( "aria-hidden" )
+			.removeAttr( "aria-labelledby" )
+			.removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled" )
+			.each(function() {
+				if ( /^ui-accordion/.test( this.id ) ) {
+					this.removeAttribute( "id" );
+				}
+			});
+		if ( this.options.heightStyle !== "content" ) {
+			contents.css( "height", "" );
+		}
+	},
+
+	_setOption: function( key, value ) {
+		if ( key === "active" ) {
+			// _activate() will handle invalid values and update this.options
+			this._activate( value );
+			return;
+		}
+
+		if ( key === "event" ) {
+			if ( this.options.event ) {
+				this._off( this.headers, this.options.event );
+			}
+			this._setupEvents( value );
+		}
+
+		this._super( key, value );
+
+		// setting collapsible: false while collapsed; open first panel
+		if ( key === "collapsible" && !value && this.options.active === false ) {
+			this._activate( 0 );
+		}
+
+		if ( key === "icons" ) {
+			this._destroyIcons();
+			if ( value ) {
+				this._createIcons();
+			}
+		}
+
+		// #5332 - opacity doesn't cascade to positioned elements in IE
+		// so we need to add the disabled class to the headers and panels
+		if ( key === "disabled" ) {
+			this.headers.add( this.headers.next() )
+				.toggleClass( "ui-state-disabled", !!value );
+		}
+	},
+
+	_keydown: function( event ) {
+		if ( event.altKey || event.ctrlKey ) {
+			return;
+		}
+
+		var keyCode = $.ui.keyCode,
+			length = this.headers.length,
+			currentIndex = this.headers.index( event.target ),
+			toFocus = false;
+
+		switch ( event.keyCode ) {
+			case keyCode.RIGHT:
+			case keyCode.DOWN:
+				toFocus = this.headers[ ( currentIndex + 1 ) % length ];
+				break;
+			case keyCode.LEFT:
+			case keyCode.UP:
+				toFocus = this.headers[ ( currentIndex - 1 + length ) % length ];
+				break;
+			case keyCode.SPACE:
+			case keyCode.ENTER:
+				this._eventHandler( event );
+				break;
+			case keyCode.HOME:
+				toFocus = this.headers[ 0 ];
+				break;
+			case keyCode.END:
+				toFocus = this.headers[ length - 1 ];
+				break;
+		}
+
+		if ( toFocus ) {
+			$( event.target ).attr( "tabIndex", -1 );
+			$( toFocus ).attr( "tabIndex", 0 );
+			toFocus.focus();
+			event.preventDefault();
+		}
+	},
+
+	_panelKeyDown : function( event ) {
+		if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) {
+			$( event.currentTarget ).prev().focus();
+		}
+	},
+
+	refresh: function() {
+		var maxHeight, overflow,
+			heightStyle = this.options.heightStyle,
+			parent = this.element.parent();
+
+
+		if ( heightStyle === "fill" ) {
+			// IE 6 treats height like minHeight, so we need to turn off overflow
+			// in order to get a reliable height
+			// we use the minHeight support test because we assume that only
+			// browsers that don't support minHeight will treat height as minHeight
+			if ( !$.support.minHeight ) {
+				overflow = parent.css( "overflow" );
+				parent.css( "overflow", "hidden");
+			}
+			maxHeight = parent.height();
+			this.element.siblings( ":visible" ).each(function() {
+				var elem = $( this ),
+					position = elem.css( "position" );
+
+				if ( position === "absolute" || position === "fixed" ) {
+					return;
+				}
+				maxHeight -= elem.outerHeight( true );
+			});
+			if ( overflow ) {
+				parent.css( "overflow", overflow );
+			}
+
+			this.headers.each(function() {
+				maxHeight -= $( this ).outerHeight( true );
+			});
+
+			this.headers.next()
+				.each(function() {
+					$( this ).height( Math.max( 0, maxHeight -
+						$( this ).innerHeight() + $( this ).height() ) );
+				})
+				.css( "overflow", "auto" );
+		} else if ( heightStyle === "auto" ) {
+			maxHeight = 0;
+			this.headers.next()
+				.each(function() {
+					maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() );
+				})
+				.height( maxHeight );
+		}
+	},
+
+	_activate: function( index ) {
+		var active = this._findActive( index )[ 0 ];
+
+		// trying to activate the already active panel
+		if ( active === this.active[ 0 ] ) {
+			return;
+		}
+
+		// trying to collapse, simulate a click on the currently active header
+		active = active || this.active[ 0 ];
+
+		this._eventHandler({
+			target: active,
+			currentTarget: active,
+			preventDefault: $.noop
+		});
+	},
+
+	_findActive: function( selector ) {
+		return typeof selector === "number" ? this.headers.eq( selector ) : $();
+	},
+
+	_setupEvents: function( event ) {
+		var events = {};
+		if ( !event ) {
+			return;
+		}
+		$.each( event.split(" "), function( index, eventName ) {
+			events[ eventName ] = "_eventHandler";
+		});
+		this._on( this.headers, events );
+	},
+
+	_eventHandler: function( event ) {
+		var options = this.options,
+			active = this.active,
+			clicked = $( event.currentTarget ),
+			clickedIsActive = clicked[ 0 ] === active[ 0 ],
+			collapsing = clickedIsActive && options.collapsible,
+			toShow = collapsing ? $() : clicked.next(),
+			toHide = active.next(),
+			eventData = {
+				oldHeader: active,
+				oldPanel: toHide,
+				newHeader: collapsing ? $() : clicked,
+				newPanel: toShow
+			};
+
+		event.preventDefault();
+
+		if (
+				// click on active header, but not collapsible
+				( clickedIsActive && !options.collapsible ) ||
+				// allow canceling activation
+				( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
+			return;
+		}
+
+		options.active = collapsing ? false : this.headers.index( clicked );
+
+		// when the call to ._toggle() comes after the class changes
+		// it causes a very odd bug in IE 8 (see #6720)
+		this.active = clickedIsActive ? $() : clicked;
+		this._toggle( eventData );
+
+		// switch classes
+		// corner classes on the previously active header stay after the animation
+		active.removeClass( "ui-accordion-header-active ui-state-active" );
+		if ( options.icons ) {
+			active.children( ".ui-accordion-header-icon" )
+				.removeClass( options.icons.activeHeader )
+				.addClass( options.icons.header );
+		}
+
+		if ( !clickedIsActive ) {
+			clicked
+				.removeClass( "ui-corner-all" )
+				.addClass( "ui-accordion-header-active ui-state-active ui-corner-top" );
+			if ( options.icons ) {
+				clicked.children( ".ui-accordion-header-icon" )
+					.removeClass( options.icons.header )
+					.addClass( options.icons.activeHeader );
+			}
+
+			clicked
+				.next()
+				.addClass( "ui-accordion-content-active" );
+		}
+	},
+
+	_toggle: function( data ) {
+		var toShow = data.newPanel,
+			toHide = this.prevShow.length ? this.prevShow : data.oldPanel;
+
+		// handle activating a panel during the animation for another activation
+		this.prevShow.add( this.prevHide ).stop( true, true );
+		this.prevShow = toShow;
+		this.prevHide = toHide;
+
+		if ( this.options.animate ) {
+			this._animate( toShow, toHide, data );
+		} else {
+			toHide.hide();
+			toShow.show();
+			this._toggleComplete( data );
+		}
+
+		toHide.attr({
+			"aria-expanded": "false",
+			"aria-hidden": "true"
+		});
+		toHide.prev().attr( "aria-selected", "false" );
+		// if we're switching panels, remove the old header from the tab order
+		// if we're opening from collapsed state, remove the previous header from the tab order
+		// if we're collapsing, then keep the collapsing header in the tab order
+		if ( toShow.length && toHide.length ) {
+			toHide.prev().attr( "tabIndex", -1 );
+		} else if ( toShow.length ) {
+			this.headers.filter(function() {
+				return $( this ).attr( "tabIndex" ) === 0;
+			})
+			.attr( "tabIndex", -1 );
+		}
+
+		toShow
+			.attr({
+				"aria-expanded": "true",
+				"aria-hidden": "false"
+			})
+			.prev()
+				.attr({
+					"aria-selected": "true",
+					tabIndex: 0
+				});
+	},
+
+	_animate: function( toShow, toHide, data ) {
+		var total, easing, duration,
+			that = this,
+			adjust = 0,
+			down = toShow.length &&
+				( !toHide.length || ( toShow.index() < toHide.index() ) ),
+			animate = this.options.animate || {},
+			options = down && animate.down || animate,
+			complete = function() {
+				that._toggleComplete( data );
+			};
+
+		if ( typeof options === "number" ) {
+			duration = options;
+		}
+		if ( typeof options === "string" ) {
+			easing = options;
+		}
+		// fall back from options to animation in case of partial down settings
+		easing = easing || options.easing || animate.easing;
+		duration = duration || options.duration || animate.duration;
+
+		if ( !toHide.length ) {
+			return toShow.animate( showProps, duration, easing, complete );
+		}
+		if ( !toShow.length ) {
+			return toHide.animate( hideProps, duration, easing, complete );
+		}
+
+		total = toShow.show().outerHeight();
+		toHide.animate( hideProps, {
+			duration: duration,
+			easing: easing,
+			step: function( now, fx ) {
+				fx.now = Math.round( now );
+			}
+		});
+		toShow
+			.hide()
+			.animate( showProps, {
+				duration: duration,
+				easing: easing,
+				complete: complete,
+				step: function( now, fx ) {
+					fx.now = Math.round( now );
+					if ( fx.prop !== "height" ) {
+						adjust += fx.now;
+					} else if ( that.options.heightStyle !== "content" ) {
+						fx.now = Math.round( total - toHide.outerHeight() - adjust );
+						adjust = 0;
+					}
+				}
+			});
+	},
+
+	_toggleComplete: function( data ) {
+		var toHide = data.oldPanel;
+
+		toHide
+			.removeClass( "ui-accordion-content-active" )
+			.prev()
+				.removeClass( "ui-corner-top" )
+				.addClass( "ui-corner-all" );
+
+		// Work around for rendering bug in IE (#5421)
+		if ( toHide.length ) {
+			toHide.parent()[0].className = toHide.parent()[0].className;
+		}
+
+		this._trigger( "activate", null, data );
+	}
+});
+
+
+
+// DEPRECATED
+if ( $.uiBackCompat !== false ) {
+	// navigation options
+	(function( $, prototype ) {
+		$.extend( prototype.options, {
+			navigation: false,
+			navigationFilter: function() {
+				return this.href.toLowerCase() === location.href.toLowerCase();
+			}
+		});
+
+		var _create = prototype._create;
+		prototype._create = function() {
+			if ( this.options.navigation ) {
+				var that = this,
+					headers = this.element.find( this.options.header ),
+					content = headers.next(),
+					current = headers.add( content )
+						.find( "a" )
+						.filter( this.options.navigationFilter )
+						[ 0 ];
+				if ( current ) {
+					headers.add( content ).each( function( index ) {
+						if ( $.contains( this, current ) ) {
+							that.options.active = Math.floor( index / 2 );
+							return false;
+						}
+					});
+				}
+			}
+			_create.call( this );
+		};
+	}( jQuery, jQuery.ui.accordion.prototype ) );
+
+	// height options
+	(function( $, prototype ) {
+		$.extend( prototype.options, {
+			heightStyle: null, // remove default so we fall back to old values
+			autoHeight: true, // use heightStyle: "auto"
+			clearStyle: false, // use heightStyle: "content"
+			fillSpace: false // use heightStyle: "fill"
+		});
+
+		var _create = prototype._create,
+			_setOption = prototype._setOption;
+
+		$.extend( prototype, {
+			_create: function() {
+				this.options.heightStyle = this.options.heightStyle ||
+					this._mergeHeightStyle();
+
+				_create.call( this );
+			},
+
+			_setOption: function( key ) {
+				if ( key === "autoHeight" || key === "clearStyle" || key === "fillSpace" ) {
+					this.options.heightStyle = this._mergeHeightStyle();
+				}
+				_setOption.apply( this, arguments );
+			},
+
+			_mergeHeightStyle: function() {
+				var options = this.options;
+
+				if ( options.fillSpace ) {
+					return "fill";
+				}
+
+				if ( options.clearStyle ) {
+					return "content";
+				}
+
+				if ( options.autoHeight ) {
+					return "auto";
+				}
+			}
+		});
+	}( jQuery, jQuery.ui.accordion.prototype ) );
+
+	// icon options
+	(function( $, prototype ) {
+		$.extend( prototype.options.icons, {
+			activeHeader: null, // remove default so we fall back to old values
+			headerSelected: "ui-icon-triangle-1-s"
+		});
+
+		var _createIcons = prototype._createIcons;
+		prototype._createIcons = function() {
+			if ( this.options.icons ) {
+				this.options.icons.activeHeader = this.options.icons.activeHeader ||
+					this.options.icons.headerSelected;
+			}
+			_createIcons.call( this );
+		};
+	}( jQuery, jQuery.ui.accordion.prototype ) );
+
+	// expanded active option, activate method
+	(function( $, prototype ) {
+		prototype.activate = prototype._activate;
+
+		var _findActive = prototype._findActive;
+		prototype._findActive = function( index ) {
+			if ( index === -1 ) {
+				index = false;
+			}
+			if ( index && typeof index !== "number" ) {
+				index = this.headers.index( this.headers.filter( index ) );
+				if ( index === -1 ) {
+					index = false;
+				}
+			}
+			return _findActive.call( this, index );
+		};
+	}( jQuery, jQuery.ui.accordion.prototype ) );
+
+	// resize method
+	jQuery.ui.accordion.prototype.resize = jQuery.ui.accordion.prototype.refresh;
+
+	// change events
+	(function( $, prototype ) {
+		$.extend( prototype.options, {
+			change: null,
+			changestart: null
+		});
+
+		var _trigger = prototype._trigger;
+		prototype._trigger = function( type, event, data ) {
+			var ret = _trigger.apply( this, arguments );
+			if ( !ret ) {
+				return false;
+			}
+
+			if ( type === "beforeActivate" ) {
+				ret = _trigger.call( this, "changestart", event, {
+					oldHeader: data.oldHeader,
+					oldContent: data.oldPanel,
+					newHeader: data.newHeader,
+					newContent: data.newPanel
+				});
+			} else if ( type === "activate" ) {
+				ret = _trigger.call( this, "change", event, {
+					oldHeader: data.oldHeader,
+					oldContent: data.oldPanel,
+					newHeader: data.newHeader,
+					newContent: data.newPanel
+				});
+			}
+			return ret;
+		};
+	}( jQuery, jQuery.ui.accordion.prototype ) );
+
+	// animated option
+	// NOTE: this only provides support for "slide", "bounceslide", and easings
+	// not the full $.ui.accordion.animations API
+	(function( $, prototype ) {
+		$.extend( prototype.options, {
+			animate: null,
+			animated: "slide"
+		});
+
+		var _create = prototype._create;
+		prototype._create = function() {
+			var options = this.options;
+			if ( options.animate === null ) {
+				if ( !options.animated ) {
+					options.animate = false;
+				} else if ( options.animated === "slide" ) {
+					options.animate = 300;
+				} else if ( options.animated === "bounceslide" ) {
+					options.animate = {
+						duration: 200,
+						down: {
+							easing: "easeOutBounce",
+							duration: 1000
+						}
+					};
+				} else {
+					options.animate = options.animated;
+				}
+			}
+
+			_create.call( this );
+		};
+	}( jQuery, jQuery.ui.accordion.prototype ) );
+}
+
+})( jQuery );
+
+(function( $, undefined ) {
+
+// used to prevent race conditions with remote data sources
+var requestIndex = 0;
+
+$.widget( "ui.autocomplete", {
+	version: "1.9.2",
+	defaultElement: "<input>",
+	options: {
+		appendTo: "body",
+		autoFocus: false,
+		delay: 300,
+		minLength: 1,
+		position: {
+			my: "left top",
+			at: "left bottom",
+			collision: "none"
+		},
+		source: null,
+
+		// callbacks
+		change: null,
+		close: null,
+		focus: null,
+		open: null,
+		response: null,
+		search: null,
+		select: null
+	},
+
+	pending: 0,
+
+	_create: function() {
+		// Some browsers only repeat keydown events, not keypress events,
+		// so we use the suppressKeyPress flag to determine if we've already
+		// handled the keydown event. #7269
+		// Unfortunately the code for & in keypress is the same as the up arrow,
+		// so we use the suppressKeyPressRepeat flag to avoid handling keypress
+		// events when we know the keydown event was used to modify the
+		// search term. #7799
+		var suppressKeyPress, suppressKeyPressRepeat, suppressInput;
+
+		this.isMultiLine = this._isMultiLine();
+		this.valueMethod = this.element[ this.element.is( "input,textarea" ) ? "val" : "text" ];
+		this.isNewMenu = true;
+
+		this.element
+			.addClass( "ui-autocomplete-input" )
+			.attr( "autocomplete", "off" );
+
+		this._on( this.element, {
+			keydown: function( event ) {
+				if ( this.element.prop( "readOnly" ) ) {
+					suppressKeyPress = true;
+					suppressInput = true;
+					suppressKeyPressRepeat = true;
+					return;
+				}
+
+				suppressKeyPress = false;
+				suppressInput = false;
+				suppressKeyPressRepeat = false;
+				var keyCode = $.ui.keyCode;
+				switch( event.keyCode ) {
+				case keyCode.PAGE_UP:
+					suppressKeyPress = true;
+					this._move( "previousPage", event );
+					break;
+				case keyCode.PAGE_DOWN:
+					suppressKeyPress = true;
+					this._move( "nextPage", event );
+					break;
+				case keyCode.UP:
+					suppressKeyPress = true;
+					this._keyEvent( "previous", event );
+					break;
+				case keyCode.DOWN:
+					suppressKeyPress = true;
+					this._keyEvent( "next", event );
+					break;
+				case keyCode.ENTER:
+				case keyCode.NUMPAD_ENTER:
+					// when menu is open and has focus
+					if ( this.menu.active ) {
+						// #6055 - Opera still allows the keypress to occur
+						// which causes forms to submit
+						suppressKeyPress = true;
+						event.preventDefault();
+						this.menu.select( event );
+					}
+					break;
+				case keyCode.TAB:
+					if ( this.menu.active ) {
+						this.menu.select( event );
+					}
+					break;
+				case keyCode.ESCAPE:
+					if ( this.menu.element.is( ":visible" ) ) {
+						this._value( this.term );
+						this.close( event );
+						// Different browsers have different default behavior for escape
+						// Single press can mean undo or clear
+						// Double press in IE means clear the whole form
+						event.preventDefault();
+					}
+					break;
+				default:
+					suppressKeyPressRepeat = true;
+					// search timeout should be triggered before the input value is changed
+					this._searchTimeout( event );
+					break;
+				}
+			},
+			keypress: function( event ) {
+				if ( suppressKeyPress ) {
+					suppressKeyPress = false;
+					event.preventDefault();
+					return;
+				}
+				if ( suppressKeyPressRepeat ) {
+					return;
+				}
+
+				// replicate some key handlers to allow them to repeat in Firefox and Opera
+				var keyCode = $.ui.keyCode;
+				switch( event.keyCode ) {
+				case keyCode.PAGE_UP:
+					this._move( "previousPage", event );
+					break;
+				case keyCode.PAGE_DOWN:
+					this._move( "nextPage", event );
+					break;
+				case keyCode.UP:
+					this._keyEvent( "previous", event );
+					break;
+				case keyCode.DOWN:
+					this._keyEvent( "next", event );
+					break;
+				}
+			},
+			input: function( event ) {
+				if ( suppressInput ) {
+					suppressInput = false;
+					event.preventDefault();
+					return;
+				}
+				this._searchTimeout( event );
+			},
+			focus: function() {
+				this.selectedItem = null;
+				this.previous = this._value();
+			},
+			blur: function( event ) {
+				if ( this.cancelBlur ) {
+					delete this.cancelBlur;
+					return;
+				}
+
+				clearTimeout( this.searching );
+				this.close( event );
+				this._change( event );
+			}
+		});
+
+		this._initSource();
+		this.menu = $( "<ul>" )
+			.addClass( "ui-autocomplete" )
+			.appendTo( this.document.find( this.options.appendTo || "body" )[ 0 ] )
+			.menu({
+				// custom key handling for now
+				input: $(),
+				// disable ARIA support, the live region takes care of that
+				role: null
+			})
+			.zIndex( this.element.zIndex() + 1 )
+			.hide()
+			.data( "menu" );
+
+		this._on( this.menu.element, {
+			mousedown: function( event ) {
+				// prevent moving focus out of the text field
+				event.preventDefault();
+
+				// IE doesn't prevent moving focus even with event.preventDefault()
+				// so we set a flag to know when we should ignore the blur event
+				this.cancelBlur = true;
+				this._delay(function() {
+					delete this.cancelBlur;
+				});
+
+				// clicking on the scrollbar causes focus to shift to the body
+				// but we can't detect a mouseup or a click immediately afterward
+				// so we have to track the next mousedown and close the menu if
+				// the user clicks somewhere outside of the autocomplete
+				var menuElement = this.menu.element[ 0 ];
+				if ( !$( event.target ).closest( ".ui-menu-item" ).length ) {
+					this._delay(function() {
+						var that = this;
+						this.document.one( "mousedown", function( event ) {
+							if ( event.target !== that.element[ 0 ] &&
+									event.target !== menuElement &&
+									!$.contains( menuElement, event.target ) ) {
+								that.close();
+							}
+						});
+					});
+				}
+			},
+			menufocus: function( event, ui ) {
+				// #7024 - Prevent accidental activation of menu items in Firefox
+				if ( this.isNewMenu ) {
+					this.isNewMenu = false;
+					if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) {
+						this.menu.blur();
+
+						this.document.one( "mousemove", function() {
+							$( event.target ).trigger( event.originalEvent );
+						});
+
+						return;
+					}
+				}
+
+				// back compat for _renderItem using item.autocomplete, via #7810
+				// TODO remove the fallback, see #8156
+				var item = ui.item.data( "ui-autocomplete-item" ) || ui.item.data( "item.autocomplete" );
+				if ( false !== this._trigger( "focus", event, { item: item } ) ) {
+					// use value to match what will end up in the input, if it was a key event
+					if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) {
+						this._value( item.value );
+					}
+				} else {
+					// Normally the input is populated with the item's value as the
+					// menu is navigated, causing screen readers to notice a change and
+					// announce the item. Since the focus event was canceled, this doesn't
+					// happen, so we update the live region so that screen readers can
+					// still notice the change and announce it.
+					this.liveRegion.text( item.value );
+				}
+			},
+			menuselect: function( event, ui ) {
+				// back compat for _renderItem using item.autocomplete, via #7810
+				// TODO remove the fallback, see #8156
+				var item = ui.item.data( "ui-autocomplete-item" ) || ui.item.data( "item.autocomplete" ),
+					previous = this.previous;
+
+				// only trigger when focus was lost (click on menu)
+				if ( this.element[0] !== this.document[0].activeElement ) {
+					this.element.focus();
+					this.previous = previous;
+					// #6109 - IE triggers two focus events and the second
+					// is asynchronous, so we need to reset the previous
+					// term synchronously and asynchronously :-(
+					this._delay(function() {
+						this.previous = previous;
+						this.selectedItem = item;
+					});
+				}
+
+				if ( false !== this._trigger( "select", event, { item: item } ) ) {
+					this._value( item.value );
+				}
+				// reset the term after the select event
+				// this allows custom select handling to work properly
+				this.term = this._value();
+
+				this.close( event );
+				this.selectedItem = item;
+			}
+		});
+
+		this.liveRegion = $( "<span>", {
+				role: "status",
+				"aria-live": "polite"
+			})
+			.addClass( "ui-helper-hidden-accessible" )
+			.insertAfter( this.element );
+
+		if ( $.fn.bgiframe ) {
+			this.menu.element.bgiframe();
+		}
+
+		// turning off autocomplete prevents the browser from remembering the
+		// value when navigating through history, so we re-enable autocomplete
+		// if the page is unloaded before the widget is destroyed. #7790
+		this._on( this.window, {
+			beforeunload: function() {
+				this.element.removeAttr( "autocomplete" );
+			}
+		});
+	},
+
+	_destroy: function() {
+		clearTimeout( this.searching );
+		this.element
+			.removeClass( "ui-autocomplete-input" )
+			.removeAttr( "autocomplete" );
+		this.menu.element.remove();
+		this.liveRegion.remove();
+	},
+
+	_setOption: function( key, value ) {
+		this._super( key, value );
+		if ( key === "source" ) {
+			this._initSource();
+		}
+		if ( key === "appendTo" ) {
+			this.menu.element.appendTo( this.document.find( value || "body" )[0] );
+		}
+		if ( key === "disabled" && value && this.xhr ) {
+			this.xhr.abort();
+		}
+	},
+
+	_isMultiLine: function() {
+		// Textareas are always multi-line
+		if ( this.element.is( "textarea" ) ) {
+			return true;
+		}
+		// Inputs are always single-line, even if inside a contentEditable element
+		// IE also treats inputs as contentEditable
+		if ( this.element.is( "input" ) ) {
+			return false;
+		}
+		// All other element types are determined by whether or not they're contentEditable
+		return this.element.prop( "isContentEditable" );
+	},
+
+	_initSource: function() {
+		var array, url,
+			that = this;
+		if ( $.isArray(this.options.source) ) {
+			array = this.options.source;
+			this.source = function( request, response ) {
+				response( $.ui.autocomplete.filter( array, request.term ) );
+			};
+		} else if ( typeof this.options.source === "string" ) {
+			url = this.options.source;
+			this.source = function( request, response ) {
+				if ( that.xhr ) {
+					that.xhr.abort();
+				}
+				that.xhr = $.ajax({
+					url: url,
+					data: request,
+					dataType: "json",
+					success: function( data ) {
+						response( data );
+					},
+					error: function() {
+						response( [] );
+					}
+				});
+			};
+		} else {
+			this.source = this.options.source;
+		}
+	},
+
+	_searchTimeout: function( event ) {
+		clearTimeout( this.searching );
+		this.searching = this._delay(function() {
+			// only search if the value has changed
+			if ( this.term !== this._value() ) {
+				this.selectedItem = null;
+				this.search( null, event );
+			}
+		}, this.options.delay );
+	},
+
+	search: function( value, event ) {
+		value = value != null ? value : this._value();
+
+		// always save the actual value, not the one passed as an argument
+		this.term = this._value();
+
+		if ( value.length < this.options.minLength ) {
+			return this.close( event );
+		}
+
+		if ( this._trigger( "search", event ) === false ) {
+			return;
+		}
+
+		return this._search( value );
+	},
+
+	_search: function( value ) {
+		this.pending++;
+		this.element.addClass( "ui-autocomplete-loading" );
+		this.cancelSearch = false;
+
+		this.source( { term: value }, this._response() );
+	},
+
+	_response: function() {
+		var that = this,
+			index = ++requestIndex;
+
+		return function( content ) {
+			if ( index === requestIndex ) {
+				that.__response( content );
+			}
+
+			that.pending--;
+			if ( !that.pending ) {
+				that.element.removeClass( "ui-autocomplete-loading" );
+			}
+		};
+	},
+
+	__response: function( content ) {
+		if ( content ) {
+			content = this._normalize( content );
+		}
+		this._trigger( "response", null, { content: content } );
+		if ( !this.options.disabled && content && content.length && !this.cancelSearch ) {
+			this._suggest( content );
+			this._trigger( "open" );
+		} else {
+			// use ._close() instead of .close() so we don't cancel future searches
+			this._close();
+		}
+	},
+
+	close: function( event ) {
+		this.cancelSearch = true;
+		this._close( event );
+	},
+
+	_close: function( event ) {
+		if ( this.menu.element.is( ":visible" ) ) {
+			this.menu.element.hide();
+			this.menu.blur();
+			this.isNewMenu = true;
+			this._trigger( "close", event );
+		}
+	},
+
+	_change: function( event ) {
+		if ( this.previous !== this._value() ) {
+			this._trigger( "change", event, { item: this.selectedItem } );
+		}
+	},
+
+	_normalize: function( items ) {
+		// assume all items have the right format when the first item is complete
+		if ( items.length && items[0].label && items[0].value ) {
+			return items;
+		}
+		return $.map( items, function( item ) {
+			if ( typeof item === "string" ) {
+				return {
+					label: item,
+					value: item
+				};
+			}
+			return $.extend({
+				label: item.label || item.value,
+				value: item.value || item.label
+			}, item );
+		});
+	},
+
+	_suggest: function( items ) {
+		var ul = this.menu.element
+			.empty()
+			.zIndex( this.element.zIndex() + 1 );
+		this._renderMenu( ul, items );
+		this.menu.refresh();
+
+		// size and position menu
+		ul.show();
+		this._resizeMenu();
+		ul.position( $.extend({
+			of: this.element
+		}, this.options.position ));
+
+		if ( this.options.autoFocus ) {
+			this.menu.next();
+		}
+	},
+
+	_resizeMenu: function() {
+		var ul = this.menu.element;
+		ul.outerWidth( Math.max(
+			// Firefox wraps long text (possibly a rounding bug)
+			// so we add 1px to avoid the wrapping (#7513)
+			ul.width( "" ).outerWidth() + 1,
+			this.element.outerWidth()
+		) );
+	},
+
+	_renderMenu: function( ul, items ) {
+		var that = this;
+		$.each( items, function( index, item ) {
+			that._renderItemData( ul, item );
+		});
+	},
+
+	_renderItemData: function( ul, item ) {
+		return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
+	},
+
+	_renderItem: function( ul, item ) {
+		return $( "<li>" )
+			.append( $( "<a>" ).text( item.label ) )
+			.appendTo( ul );
+	},
+
+	_move: function( direction, event ) {
+		if ( !this.menu.element.is( ":visible" ) ) {
+			this.search( null, event );
+			return;
+		}
+		if ( this.menu.isFirstItem() && /^previous/.test( direction ) ||
+				this.menu.isLastItem() && /^next/.test( direction ) ) {
+			this._value( this.term );
+			this.menu.blur();
+			return;
+		}
+		this.menu[ direction ]( event );
+	},
+
+	widget: function() {
+		return this.menu.element;
+	},
+
+	_value: function() {
+		return this.valueMethod.apply( this.element, arguments );
+	},
+
+	_keyEvent: function( keyEvent, event ) {
+		if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) {
+			this._move( keyEvent, event );
+
+			// prevents moving cursor to beginning/end of the text field in some browsers
+			event.preventDefault();
+		}
+	}
+});
+
+$.extend( $.ui.autocomplete, {
+	escapeRegex: function( value ) {
+		return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
+	},
+	filter: function(array, term) {
+		var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
+		return $.grep( array, function(value) {
+			return matcher.test( value.label || value.value || value );
+		});
+	}
+});
+
+
+// live region extension, adding a `messages` option
+// NOTE: This is an experimental API. We are still investigating
+// a full solution for string manipulation and internationalization.
+$.widget( "ui.autocomplete", $.ui.autocomplete, {
+	options: {
+		messages: {
+			noResults: "No search results.",
+			results: function( amount ) {
+				return amount + ( amount > 1 ? " results are" : " result is" ) +
+					" available, use up and down arrow keys to navigate.";
+			}
+		}
+	},
+
+	__response: function( content ) {
+		var message;
+		this._superApply( arguments );
+		if ( this.options.disabled || this.cancelSearch ) {
+			return;
+		}
+		if ( content && content.length ) {
+			message = this.options.messages.results( content.length );
+		} else {
+			message = this.options.messages.noResults;
+		}
+		this.liveRegion.text( message );
+	}
+});
+
+
+}( jQuery ));
+
+(function( $, undefined ) {
+
+var lastActive, startXPos, startYPos, clickDragged,
+	baseClasses = "ui-button ui-widget ui-state-default ui-corner-all",
+	stateClasses = "ui-state-hover ui-state-active ",
+	typeClasses = "ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",
+	formResetHandler = function() {
+		var buttons = $( this ).find( ":ui-button" );
+		setTimeout(function() {
+			buttons.button( "refresh" );
+		}, 1 );
+	},
+	radioGroup = function( radio ) {
+		var name = radio.name,
+			form = radio.form,
+			radios = $( [] );
+		if ( name ) {
+			if ( form ) {
+				radios = $( form ).find( "[name='" + name + "']" );
+			} else {
+				radios = $( "[name='" + name + "']", radio.ownerDocument )
+					.filter(function() {
+						return !this.form;
+					});
+			}
+		}
+		return radios;
+	};
+
+$.widget( "ui.button", {
+	version: "1.9.2",
+	defaultElement: "<button>",
+	options: {
+		disabled: null,
+		text: true,
+		label: null,
+		icons: {
+			primary: null,
+			secondary: null
+		}
+	},
+	_create: function() {
+		this.element.closest( "form" )
+			.unbind( "reset" + this.eventNamespace )
+			.bind( "reset" + this.eventNamespace, formResetHandler );
+
+		if ( typeof this.options.disabled !== "boolean" ) {
+			this.options.disabled = !!this.element.prop( "disabled" );
+		} else {
+			this.element.prop( "disabled", this.options.disabled );
+		}
+
+		this._determineButtonType();
+		this.hasTitle = !!this.buttonElement.attr( "title" );
+
+		var that = this,
+			options = this.options,
+			toggleButton = this.type === "checkbox" || this.type === "radio",
+			activeClass = !toggleButton ? "ui-state-active" : "",
+			focusClass = "ui-state-focus";
+
+		if ( options.label === null ) {
+			options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html());
+		}
+
+		this._hoverable( this.buttonElement );
+
+		this.buttonElement
+			.addClass( baseClasses )
+			.attr( "role", "button" )
+			.bind( "mouseenter" + this.eventNamespace, function() {
+				if ( options.disabled ) {
+					return;
+				}
+				if ( this === lastActive ) {
+					$( this ).addClass( "ui-state-active" );
+				}
+			})
+			.bind( "mouseleave" + this.eventNamespace, function() {
+				if ( options.disabled ) {
+					return;
+				}
+				$( this ).removeClass( activeClass );
+			})
+			.bind( "click" + this.eventNamespace, function( event ) {
+				if ( options.disabled ) {
+					event.preventDefault();
+					event.stopImmediatePropagation();
+				}
+			});
+
+		this.element
+			.bind( "focus" + this.eventNamespace, function() {
+				// no need to check disabled, focus won't be triggered anyway
+				that.buttonElement.addClass( focusClass );
+			})
+			.bind( "blur" + this.eventNamespace, function() {
+				that.buttonElement.removeClass( focusClass );
+			});
+
+		if ( toggleButton ) {
+			this.element.bind( "change" + this.eventNamespace, function() {
+				if ( clickDragged ) {
+					return;
+				}
+				that.refresh();
+			});
+			// if mouse moves between mousedown and mouseup (drag) set clickDragged flag
+			// prevents issue where button state changes but checkbox/radio checked state
+			// does not in Firefox (see ticket #6970)
+			this.buttonElement
+				.bind( "mousedown" + this.eventNamespace, function( event ) {
+					if ( options.disabled ) {
+						return;
+					}
+					clickDragged = false;
+					startXPos = event.pageX;
+					startYPos = event.pageY;
+				})
+				.bind( "mouseup" + this.eventNamespace, function( event ) {
+					if ( options.disabled ) {
+						return;
+					}
+					if ( startXPos !== event.pageX || startYPos !== event.pageY ) {
+						clickDragged = true;
+					}
+			});
+		}
+
+		if ( this.type === "checkbox" ) {
+			this.buttonElement.bind( "click" + this.eventNamespace, function() {
+				if ( options.disabled || clickDragged ) {
+					return false;
+				}
+				$( this ).toggleClass( "ui-state-active" );
+				that.buttonElement.attr( "aria-pressed", that.element[0].checked );
+			});
+		} else if ( this.type === "radio" ) {
+			this.buttonElement.bind( "click" + this.eventNamespace, function() {
+				if ( options.disabled || clickDragged ) {
+					return false;
+				}
+				$( this ).addClass( "ui-state-active" );
+				that.buttonElement.attr( "aria-pressed", "true" );
+
+				var radio = that.element[ 0 ];
+				radioGroup( radio )
+					.not( radio )
+					.map(function() {
+						return $( this ).button( "widget" )[ 0 ];
+					})
+					.removeClass( "ui-state-active" )
+					.attr( "aria-pressed", "false" );
+			});
+		} else {
+			this.buttonElement
+				.bind( "mousedown" + this.eventNamespace, function() {
+					if ( options.disabled ) {
+						return false;
+					}
+					$( this ).addClass( "ui-state-active" );
+					lastActive = this;
+					that.document.one( "mouseup", function() {
+						lastActive = null;
+					});
+				})
+				.bind( "mouseup" + this.eventNamespace, function() {
+					if ( options.disabled ) {
+						return false;
+					}
+					$( this ).removeClass( "ui-state-active" );
+				})
+				.bind( "keydown" + this.eventNamespace, function(event) {
+					if ( options.disabled ) {
+						return false;
+					}
+					if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) {
+						$( this ).addClass( "ui-state-active" );
+					}
+				})
+				.bind( "keyup" + this.eventNamespace, function() {
+					$( this ).removeClass( "ui-state-active" );
+				});
+
+			if ( this.buttonElement.is("a") ) {
+				this.buttonElement.keyup(function(event) {
+					if ( event.keyCode === $.ui.keyCode.SPACE ) {
+						// TODO pass through original event correctly (just as 2nd argument doesn't work)
+						$( this ).click();
+					}
+				});
+			}
+		}
+
+		// TODO: pull out $.Widget's handling for the disabled option into
+		// $.Widget.prototype._setOptionDisabled so it's easy to proxy and can
+		// be overridden by individual plugins
+		this._setOption( "disabled", options.disabled );
+		this._resetButton();
+	},
+
+	_determineButtonType: function() {
+		var ancestor, labelSelector, checked;
+
+		if ( this.element.is("[type=checkbox]") ) {
+			this.type = "checkbox";
+		} else if ( this.element.is("[type=radio]") ) {
+			this.type = "radio";
+		} else if ( this.element.is("input") ) {
+			this.type = "input";
+		} else {
+			this.type = "button";
+		}
+
+		if ( this.type === "checkbox" || this.type === "radio" ) {
+			// we don't search against the document in case the element
+			// is disconnected from the DOM
+			ancestor = this.element.parents().last();
+			labelSelector = "label[for='" + this.element.attr("id") + "']";
+			this.buttonElement = ancestor.find( labelSelector );
+			if ( !this.buttonElement.length ) {
+				ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings();
+				this.buttonElement = ancestor.filter( labelSelector );
+				if ( !this.buttonElement.length ) {
+					this.buttonElement = ancestor.find( labelSelector );
+				}
+			}
+			this.element.addClass( "ui-helper-hidden-accessible" );
+
+			checked = this.element.is( ":checked" );
+			if ( checked ) {
+				this.buttonElement.addClass( "ui-state-active" );
+			}
+			this.buttonElement.prop( "aria-pressed", checked );
+		} else {
+			this.buttonElement = this.element;
+		}
+	},
+
+	widget: function() {
+		return this.buttonElement;
+	},
+
+	_destroy: function() {
+		this.element
+			.removeClass( "ui-helper-hidden-accessible" );
+		this.buttonElement
+			.removeClass( baseClasses + " " + stateClasses + " " + typeClasses )
+			.removeAttr( "role" )
+			.removeAttr( "aria-pressed" )
+			.html( this.buttonElement.find(".ui-button-text").html() );
+
+		if ( !this.hasTitle ) {
+			this.buttonElement.removeAttr( "title" );
+		}
+	},
+
+	_setOption: function( key, value ) {
+		this._super( key, value );
+		if ( key === "disabled" ) {
+			if ( value ) {
+				this.element.prop( "disabled", true );
+			} else {
+				this.element.prop( "disabled", false );
+			}
+			return;
+		}
+		this._resetButton();
+	},
+
+	refresh: function() {
+		//See #8237 & #8828
+		var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "ui-button-disabled" );
+
+		if ( isDisabled !== this.options.disabled ) {
+			this._setOption( "disabled", isDisabled );
+		}
+		if ( this.type === "radio" ) {
+			radioGroup( this.element[0] ).each(function() {
+				if ( $( this ).is( ":checked" ) ) {
+					$( this ).button( "widget" )
+						.addClass( "ui-state-active" )
+						.attr( "aria-pressed", "true" );
+				} else {
+					$( this ).button( "widget" )
+						.removeClass( "ui-state-active" )
+						.attr( "aria-pressed", "false" );
+				}
+			});
+		} else if ( this.type === "checkbox" ) {
+			if ( this.element.is( ":checked" ) ) {
+				this.buttonElement
+					.addClass( "ui-state-active" )
+					.attr( "aria-pressed", "true" );
+			} else {
+				this.buttonElement
+					.removeClass( "ui-state-active" )
+					.attr( "aria-pressed", "false" );
+			}
+		}
+	},
+
+	_resetButton: function() {
+		if ( this.type === "input" ) {
+			if ( this.options.label ) {
+				this.element.val( this.options.label );
+			}
+			return;
+		}
+		var buttonElement = this.buttonElement.removeClass( typeClasses ),
+			buttonText = $( "<span></span>", this.document[0] )
+				.addClass( "ui-button-text" )
+				.html( this.options.label )
+				.appendTo( buttonElement.empty() )
+				.text(),
+			icons = this.options.icons,
+			multipleIcons = icons.primary && icons.secondary,
+			buttonClasses = [];
+
+		if ( icons.primary || icons.secondary ) {
+			if ( this.options.text ) {
+				buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) );
+			}
+
+			if ( icons.primary ) {
+				buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" );
+			}
+
+			if ( icons.secondary ) {
+				buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" );
+			}
+
+			if ( !this.options.text ) {
+				buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" );
+
+				if ( !this.hasTitle ) {
+					buttonElement.attr( "title", $.trim( buttonText ) );
+				}
+			}
+		} else {
+			buttonClasses.push( "ui-button-text-only" );
+		}
+		buttonElement.addClass( buttonClasses.join( " " ) );
+	}
+});
+
+$.widget( "ui.buttonset", {
+	version: "1.9.2",
+	options: {
+		items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(button)"
+	},
+
+	_create: function() {
+		this.element.addClass( "ui-buttonset" );
+	},
+
+	_init: function() {
+		this.refresh();
+	},
+
+	_setOption: function( key, value ) {
+		if ( key === "disabled" ) {
+			this.buttons.button( "option", key, value );
+		}
+
+		this._super( key, value );
+	},
+
+	refresh: function() {
+		var rtl = this.element.css( "direction" ) === "rtl";
+
+		this.buttons = this.element.find( this.options.items )
+			.filter( ":ui-button" )
+				.button( "refresh" )
+			.end()
+			.not( ":ui-button" )
+				.button()
+			.end()
+			.map(function() {
+				return $( this ).button( "widget" )[ 0 ];
+			})
+				.removeClass( "ui-corner-all ui-corner-left ui-corner-right" )
+				.filter( ":first" )
+					.addClass( rtl ? "ui-corner-right" : "ui-corner-left" )
+				.end()
+				.filter( ":last" )
+					.addClass( rtl ? "ui-corner-left" : "ui-corner-right" )
+				.end()
+			.end();
+	},
+
+	_destroy: function() {
+		this.element.removeClass( "ui-buttonset" );
+		this.buttons
+			.map(function() {
+				return $( this ).button( "widget" )[ 0 ];
+			})
+				.removeClass( "ui-corner-left ui-corner-right" )
+			.end()
+			.button( "destroy" );
+	}
+});
+
+}( jQuery ) );
+
+(function( $, undefined ) {
+
+$.extend($.ui, { datepicker: { version: "1.9.2" } });
+
+var PROP_NAME = 'datepicker';
+var dpuuid = new Date().getTime();
+var instActive;
+
+/* Date picker manager.
+   Use the singleton instance of this class, $.datepicker, to interact with the date picker.
+   Settings for (groups of) date pickers are maintained in an instance object,
+   allowing multiple different settings on the same page. */
+
+function Datepicker() {
+	this.debug = false; // Change this to true to start debugging
+	this._curInst = null; // The current instance in use
+	this._keyEvent = false; // If the last event was a key event
+	this._disabledInputs = []; // List of date picker inputs that have been disabled
+	this._datepickerShowing = false; // True if the popup picker is showing , false if not
+	this._inDialog = false; // True if showing within a "dialog", false if not
+	this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division
+	this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class
+	this._appendClass = 'ui-datepicker-append'; // The name of the append marker class
+	this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class
+	this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class
+	this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class
+	this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class
+	this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class
+	this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class
+	this.regional = []; // Available regional settings, indexed by language code
+	this.regional[''] = { // Default regional settings
+		closeText: 'Done', // Display text for close link
+		prevText: 'Prev', // Display text for previous month link
+		nextText: 'Next', // Display text for next month link
+		currentText: 'Today', // Display text for current month link
+		monthNames: ['January','February','March','April','May','June',
+			'July','August','September','October','November','December'], // Names of months for drop-down and formatting
+		monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting
+		dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting
+		dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting
+		dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday
+		weekHeader: 'Wk', // Column header for week of the year
+		dateFormat: 'mm/dd/yy', // See format options on parseDate
+		firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
+		isRTL: false, // True if right-to-left language, false if left-to-right
+		showMonthAfterYear: false, // True if the year select precedes month, false for month then year
+		yearSuffix: '' // Additional text to append to the year in the month headers
+	};
+	this._defaults = { // Global defaults for all the date picker instances
+		showOn: 'focus', // 'focus' for popup on focus,
+			// 'button' for trigger button, or 'both' for either
+		showAnim: 'fadeIn', // Name of jQuery animation for popup
+		showOptions: {}, // Options for enhanced animations
+		defaultDate: null, // Used when field is blank: actual date,
+			// +/-number for offset from today, null for today
+		appendText: '', // Display text following the input box, e.g. showing the format
+		buttonText: '...', // Text for trigger button
+		buttonImage: '', // URL for trigger button image
+		buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
+		hideIfNoPrevNext: false, // True to hide next/previous month links
+			// if not applicable, false to just disable them
+		navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
+		gotoCurrent: false, // True if today link goes back to current selection instead
+		changeMonth: false, // True if month can be selected directly, false if only prev/next
+		changeYear: false, // True if year can be selected directly, false if only prev/next
+		yearRange: 'c-10:c+10', // Range of years to display in drop-down,
+			// either relative to today's year (-nn:+nn), relative to currently displayed year
+			// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
+		showOtherMonths: false, // True to show dates in other months, false to leave blank
+		selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
+		showWeek: false, // True to show week of the year, false to not show it
+		calculateWeek: this.iso8601Week, // How to calculate the week of the year,
+			// takes a Date and returns the number of the week for it
+		shortYearCutoff: '+10', // Short year values < this are in the current century,
+			// > this are in the previous century,
+			// string value starting with '+' for current year + value
+		minDate: null, // The earliest selectable date, or null for no limit
+		maxDate: null, // The latest selectable date, or null for no limit
+		duration: 'fast', // Duration of display/closure
+		beforeShowDay: null, // Function that takes a date and returns an array with
+			// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '',
+			// [2] = cell title (optional), e.g. $.datepicker.noWeekends
+		beforeShow: null, // Function that takes an input field and
+			// returns a set of custom settings for the date picker
+		onSelect: null, // Define a callback function when a date is selected
+		onChangeMonthYear: null, // Define a callback function when the month or year is changed
+		onClose: null, // Define a callback function when the datepicker is closed
+		numberOfMonths: 1, // Number of months to show at a time
+		showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
+		stepMonths: 1, // Number of months to step back/forward
+		stepBigMonths: 12, // Number of months to step back/forward for the big links
+		altField: '', // Selector for an alternate field to store selected dates into
+		altFormat: '', // The date format to use for the alternate field
+		constrainInput: true, // The input is constrained by the current date format
+		showButtonPanel: false, // True to show button panel, false to not show it
+		autoSize: false, // True to size the input for the date format, false to leave as is
+		disabled: false // The initial disabled state
+	};
+	$.extend(this._defaults, this.regional['']);
+	this.dpDiv = bindHover($('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'));
+}
+
+$.extend(Datepicker.prototype, {
+	/* Class name added to elements to indicate already configured with a date picker. */
+	markerClassName: 'hasDatepicker',
+
+	//Keep track of the maximum number of rows displayed (see #7043)
+	maxRows: 4,
+
+	/* Debug logging (if enabled). */
+	log: function () {
+		if (this.debug)
+			console.log.apply('', arguments);
+	},
+
+	// TODO rename to "widget" when switching to widget factory
+	_widgetDatepicker: function() {
+		return this.dpDiv;
+	},
+
+	/* Override the default settings for all instances of the date picker.
+	   @param  settings  object - the new settings to use as defaults (anonymous object)
+	   @return the manager object */
+	setDefaults: function(settings) {
+		extendRemove(this._defaults, settings || {});
+		return this;
+	},
+
+	/* Attach the date picker to a jQuery selection.
+	   @param  target    element - the target input field or division or span
+	   @param  settings  object - the new settings to use for this date picker instance (anonymous) */
+	_attachDatepicker: function(target, settings) {
+		// check for settings on the control itself - in namespace 'date:'
+		var inlineSettings = null;
+		for (var attrName in this._defaults) {
+			var attrValue = target.getAttribute('date:' + attrName);
+			if (attrValue) {
+				inlineSettings = inlineSettings || {};
+				try {
+					inlineSettings[attrName] = eval(attrValue);
+				} catch (err) {
+					inlineSettings[attrName] = attrValue;
+				}
+			}
+		}
+		var nodeName = target.nodeName.toLowerCase();
+		var inline = (nodeName == 'div' || nodeName == 'span');
+		if (!target.id) {
+			this.uuid += 1;
+			target.id = 'dp' + this.uuid;
+		}
+		var inst = this._newInst($(target), inline);
+		inst.settings = $.extend({}, settings || {}, inlineSettings || {});
+		if (nodeName == 'input') {
+			this._connectDatepicker(target, inst);
+		} else if (inline) {
+			this._inlineDatepicker(target, inst);
+		}
+	},
+
+	/* Create a new instance object. */
+	_newInst: function(target, inline) {
+		var id = target[0].id.replace(/([^A-Za-z0-9_-])/g, '\\\\$1'); // escape jQuery meta chars
+		return {id: id, input: target, // associated target
+			selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
+			drawMonth: 0, drawYear: 0, // month being drawn
+			inline: inline, // is datepicker inline or not
+			dpDiv: (!inline ? this.dpDiv : // presentation div
+			bindHover($('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')))};
+	},
+
+	/* Attach the date picker to an input field. */
+	_connectDatepicker: function(target, inst) {
+		var input = $(target);
+		inst.append = $([]);
+		inst.trigger = $([]);
+		if (input.hasClass(this.markerClassName))
+			return;
+		this._attachments(input, inst);
+		input.addClass(this.markerClassName).keydown(this._doKeyDown).
+			keypress(this._doKeyPress).keyup(this._doKeyUp).
+			bind("setData.datepicker", function(event, key, value) {
+				inst.settings[key] = value;
+			}).bind("getData.datepicker", function(event, key) {
+				return this._get(inst, key);
+			});
+		this._autoSize(inst);
+		$.data(target, PROP_NAME, inst);
+		//If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
+		if( inst.settings.disabled ) {
+			this._disableDatepicker( target );
+		}
+	},
+
+	/* Make attachments based on settings. */
+	_attachments: function(input, inst) {
+		var appendText = this._get(inst, 'appendText');
+		var isRTL = this._get(inst, 'isRTL');
+		if (inst.append)
+			inst.append.remove();
+		if (appendText) {
+			inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>');
+			input[isRTL ? 'before' : 'after'](inst.append);
+		}
+		input.unbind('focus', this._showDatepicker);
+		if (inst.trigger)
+			inst.trigger.remove();
+		var showOn = this._get(inst, 'showOn');
+		if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field
+			input.focus(this._showDatepicker);
+		if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked
+			var buttonText = this._get(inst, 'buttonText');
+			var buttonImage = this._get(inst, 'buttonImage');
+			inst.trigger = $(this._get(inst, 'buttonImageOnly') ?
+				$('<img/>').addClass(this._triggerClass).
+					attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
+				$('<button type="button"></button>').addClass(this._triggerClass).
+					html(buttonImage == '' ? buttonText : $('<img/>').attr(
+					{ src:buttonImage, alt:buttonText, title:buttonText })));
+			input[isRTL ? 'before' : 'after'](inst.trigger);
+			inst.trigger.click(function() {
+				if ($.datepicker._datepickerShowing && $.datepicker._lastInput == input[0])
+					$.datepicker._hideDatepicker();
+				else if ($.datepicker._datepickerShowing && $.datepicker._lastInput != input[0]) {
+					$.datepicker._hideDatepicker();
+					$.datepicker._showDatepicker(input[0]);
+				} else
+					$.datepicker._showDatepicker(input[0]);
+				return false;
+			});
+		}
+	},
+
+	/* Apply the maximum length for the date format. */
+	_autoSize: function(inst) {
+		if (this._get(inst, 'autoSize') && !inst.inline) {
+			var date = new Date(2009, 12 - 1, 20); // Ensure double digits
+			var dateFormat = this._get(inst, 'dateFormat');
+			if (dateFormat.match(/[DM]/)) {
+				var findMax = function(names) {
+					var max = 0;
+					var maxI = 0;
+					for (var i = 0; i < names.length; i++) {
+						if (names[i].length > max) {
+							max = names[i].length;
+							maxI = i;
+						}
+					}
+					return maxI;
+				};
+				date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
+					'monthNames' : 'monthNamesShort'))));
+				date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
+					'dayNames' : 'dayNamesShort'))) + 20 - date.getDay());
+			}
+			inst.input.attr('size', this._formatDate(inst, date).length);
+		}
+	},
+
+	/* Attach an inline date picker to a div. */
+	_inlineDatepicker: function(target, inst) {
+		var divSpan = $(target);
+		if (divSpan.hasClass(this.markerClassName))
+			return;
+		divSpan.addClass(this.markerClassName).append(inst.dpDiv).
+			bind("setData.datepicker", function(event, key, value){
+				inst.settings[key] = value;
+			}).bind("getData.datepicker", function(event, key){
+				return this._get(inst, key);
+			});
+		$.data(target, PROP_NAME, inst);
+		this._setDate(inst, this._getDefaultDate(inst), true);
+		this._updateDatepicker(inst);
+		this._updateAlternate(inst);
+		//If disabled option is true, disable the datepicker before showing it (see ticket #5665)
+		if( inst.settings.disabled ) {
+			this._disableDatepicker( target );
+		}
+		// Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
+		// http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
+		inst.dpDiv.css( "display", "block" );
+	},
+
+	/* Pop-up the date picker in a "dialog" box.
+	   @param  input     element - ignored
+	   @param  date      string or Date - the initial date to display
+	   @param  onSelect  function - the function to call when a date is selected
+	   @param  settings  object - update the dialog date picker instance's settings (anonymous object)
+	   @param  pos       int[2] - coordinates for the dialog's position within the screen or
+	                     event - with x/y coordinates or
+	                     leave empty for default (screen centre)
+	   @return the manager object */
+	_dialogDatepicker: function(input, date, onSelect, settings, pos) {
+		var inst = this._dialogInst; // internal instance
+		if (!inst) {
+			this.uuid += 1;
+			var id = 'dp' + this.uuid;
+			this._dialogInput = $('<input type="text" id="' + id +
+				'" style="position: absolute; top: -100px; width: 0px;"/>');
+			this._dialogInput.keydown(this._doKeyDown);
+			$('body').append(this._dialogInput);
+			inst = this._dialogInst = this._newInst(this._dialogInput, false);
+			inst.settings = {};
+			$.data(this._dialogInput[0], PROP_NAME, inst);
+		}
+		extendRemove(inst.settings, settings || {});
+		date = (date && date.constructor == Date ? this._formatDate(inst, date) : date);
+		this._dialogInput.val(date);
+
+		this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
+		if (!this._pos) {
+			var browserWidth = document.documentElement.clientWidth;
+			var browserHeight = document.documentElement.clientHeight;
+			var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
+			var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
+			this._pos = // should use actual width/height below
+				[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
+		}
+
+		// move input on screen for focus, but hidden behind dialog
+		this._dialogInput.css('left', (this._pos[0] + 20) + 'px').css('top', this._pos[1] + 'px');
+		inst.settings.onSelect = onSelect;
+		this._inDialog = true;
+		this.dpDiv.addClass(this._dialogClass);
+		this._showDatepicker(this._dialogInput[0]);
+		if ($.blockUI)
+			$.blockUI(this.dpDiv);
+		$.data(this._dialogInput[0], PROP_NAME, inst);
+		return this;
+	},
+
+	/* Detach a datepicker from its control.
+	   @param  target    element - the target input field or division or span */
+	_destroyDatepicker: function(target) {
+		var $target = $(target);
+		var inst = $.data(target, PROP_NAME);
+		if (!$target.hasClass(this.markerClassName)) {
+			return;
+		}
+		var nodeName = target.nodeName.toLowerCase();
+		$.removeData(target, PROP_NAME);
+		if (nodeName == 'input') {
+			inst.append.remove();
+			inst.trigger.remove();
+			$target.removeClass(this.markerClassName).
+				unbind('focus', this._showDatepicker).
+				unbind('keydown', this._doKeyDown).
+				unbind('keypress', this._doKeyPress).
+				unbind('keyup', this._doKeyUp);
+		} else if (nodeName == 'div' || nodeName == 'span')
+			$target.removeClass(this.markerClassName).empty();
+	},
+
+	/* Enable the date picker to a jQuery selection.
+	   @param  target    element - the target input field or division or span */
+	_enableDatepicker: function(target) {
+		var $target = $(target);
+		var inst = $.data(target, PROP_NAME);
+		if (!$target.hasClass(this.markerClassName)) {
+			return;
+		}
+		var nodeName = target.nodeName.toLowerCase();
+		if (nodeName == 'input') {
+			target.disabled = false;
+			inst.trigger.filter('button').
+				each(function() { this.disabled = false; }).end().
+				filter('img').css({opacity: '1.0', cursor: ''});
+		}
+		else if (nodeName == 'div' || nodeName == 'span') {
+			var inline = $target.children('.' + this._inlineClass);
+			inline.children().removeClass('ui-state-disabled');
+			inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
+				prop("disabled", false);
+		}
+		this._disabledInputs = $.map(this._disabledInputs,
+			function(value) { return (value == target ? null : value); }); // delete entry
+	},
+
+	/* Disable the date picker to a jQuery selection.
+	   @param  target    element - the target input field or division or span */
+	_disableDatepicker: function(target) {
+		var $target = $(target);
+		var inst = $.data(target, PROP_NAME);
+		if (!$target.hasClass(this.markerClassName)) {
+			return;
+		}
+		var nodeName = target.nodeName.toLowerCase();
+		if (nodeName == 'input') {
+			target.disabled = true;
+			inst.trigger.filter('button').
+				each(function() { this.disabled = true; }).end().
+				filter('img').css({opacity: '0.5', cursor: 'default'});
+		}
+		else if (nodeName == 'div' || nodeName == 'span') {
+			var inline = $target.children('.' + this._inlineClass);
+			inline.children().addClass('ui-state-disabled');
+			inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
+				prop("disabled", true);
+		}
+		this._disabledInputs = $.map(this._disabledInputs,
+			function(value) { return (value == target ? null : value); }); // delete entry
+		this._disabledInputs[this._disabledInputs.length] = target;
+	},
+
+	/* Is the first field in a jQuery collection disabled as a datepicker?
+	   @param  target    element - the target input field or division or span
+	   @return boolean - true if disabled, false if enabled */
+	_isDisabledDatepicker: function(target) {
+		if (!target) {
+			return false;
+		}
+		for (var i = 0; i < this._disabledInputs.length; i++) {
+			if (this._disabledInputs[i] == target)
+				return true;
+		}
+		return false;
+	},
+
+	/* Retrieve the instance data for the target control.
+	   @param  target  element - the target input field or division or span
+	   @return  object - the associated instance data
+	   @throws  error if a jQuery problem getting data */
+	_getInst: function(target) {
+		try {
+			return $.data(target, PROP_NAME);
+		}
+		catch (err) {
+			throw 'Missing instance data for this datepicker';
+		}
+	},
+
+	/* Update or retrieve the settings for a date picker attached to an input field or division.
+	   @param  target  element - the target input field or division or span
+	   @param  name    object - the new settings to update or
+	                   string - the name of the setting to change or retrieve,
+	                   when retrieving also 'all' for all instance settings or
+	                   'defaults' for all global defaults
+	   @param  value   any - the new value for the setting
+	                   (omit if above is an object or to retrieve a value) */
+	_optionDatepicker: function(target, name, value) {
+		var inst = this._getInst(target);
+		if (arguments.length == 2 && typeof name == 'string') {
+			return (name == 'defaults' ? $.extend({}, $.datepicker._defaults) :
+				(inst ? (name == 'all' ? $.extend({}, inst.settings) :
+				this._get(inst, name)) : null));
+		}
+		var settings = name || {};
+		if (typeof name == 'string') {
+			settings = {};
+			settings[name] = value;
+		}
+		if (inst) {
+			if (this._curInst == inst) {
+				this._hideDatepicker();
+			}
+			var date = this._getDateDatepicker(target, true);
+			var minDate = this._getMinMaxDate(inst, 'min');
+			var maxDate = this._getMinMaxDate(inst, 'max');
+			extendRemove(inst.settings, settings);
+			// reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
+			if (minDate !== null && settings['dateFormat'] !== undefined && settings['minDate'] === undefined)
+				inst.settings.minDate = this._formatDate(inst, minDate);
+			if (maxDate !== null && settings['dateFormat'] !== undefined && settings['maxDate'] === undefined)
+				inst.settings.maxDate = this._formatDate(inst, maxDate);
+			this._attachments($(target), inst);
+			this._autoSize(inst);
+			this._setDate(inst, date);
+			this._updateAlternate(inst);
+			this._updateDatepicker(inst);
+		}
+	},
+
+	// change method deprecated
+	_changeDatepicker: function(target, name, value) {
+		this._optionDatepicker(target, name, value);
+	},
+
+	/* Redraw the date picker attached to an input field or division.
+	   @param  target  element - the target input field or division or span */
+	_refreshDatepicker: function(target) {
+		var inst = this._getInst(target);
+		if (inst) {
+			this._updateDatepicker(inst);
+		}
+	},
+
+	/* Set the dates for a jQuery selection.
+	   @param  target   element - the target input field or division or span
+	   @param  date     Date - the new date */
+	_setDateDatepicker: function(target, date) {
+		var inst = this._getInst(target);
+		if (inst) {
+			this._setDate(inst, date);
+			this._updateDatepicker(inst);
+			this._updateAlternate(inst);
+		}
+	},
+
+	/* Get the date(s) for the first entry in a jQuery selection.
+	   @param  target     element - the target input field or division or span
+	   @param  noDefault  boolean - true if no default date is to be used
+	   @return Date - the current date */
+	_getDateDatepicker: function(target, noDefault) {
+		var inst = this._getInst(target);
+		if (inst && !inst.inline)
+			this._setDateFromField(inst, noDefault);
+		return (inst ? this._getDate(inst) : null);
+	},
+
+	/* Handle keystrokes. */
+	_doKeyDown: function(event) {
+		var inst = $.datepicker._getInst(event.target);
+		var handled = true;
+		var isRTL = inst.dpDiv.is('.ui-datepicker-rtl');
+		inst._keyEvent = true;
+		if ($.datepicker._datepickerShowing)
+			switch (event.keyCode) {
+				case 9: $.datepicker._hideDatepicker();
+						handled = false;
+						break; // hide on tab out
+				case 13: var sel = $('td.' + $.datepicker._dayOverClass + ':not(.' +
+									$.datepicker._currentClass + ')', inst.dpDiv);
+						if (sel[0])
+							$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
+							var onSelect = $.datepicker._get(inst, 'onSelect');
+							if (onSelect) {
+								var dateStr = $.datepicker._formatDate(inst);
+
+								// trigger custom callback
+								onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
+							}
+						else
+							$.datepicker._hideDatepicker();
+						return false; // don't submit the form
+						break; // select the value on enter
+				case 27: $.datepicker._hideDatepicker();
+						break; // hide on escape
+				case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+							-$.datepicker._get(inst, 'stepBigMonths') :
+							-$.datepicker._get(inst, 'stepMonths')), 'M');
+						break; // previous month/year on page up/+ ctrl
+				case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+							+$.datepicker._get(inst, 'stepBigMonths') :
+							+$.datepicker._get(inst, 'stepMonths')), 'M');
+						break; // next month/year on page down/+ ctrl
+				case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target);
+						handled = event.ctrlKey || event.metaKey;
+						break; // clear on ctrl or command +end
+				case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target);
+						handled = event.ctrlKey || event.metaKey;
+						break; // current on ctrl or command +home
+				case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D');
+						handled = event.ctrlKey || event.metaKey;
+						// -1 day on ctrl or command +left
+						if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+									-$.datepicker._get(inst, 'stepBigMonths') :
+									-$.datepicker._get(inst, 'stepMonths')), 'M');
+						// next month/year on alt +left on Mac
+						break;
+				case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D');
+						handled = event.ctrlKey || event.metaKey;
+						break; // -1 week on ctrl or command +up
+				case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D');
+						handled = event.ctrlKey || event.metaKey;
+						// +1 day on ctrl or command +right
+						if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+									+$.datepicker._get(inst, 'stepBigMonths') :
+									+$.datepicker._get(inst, 'stepMonths')), 'M');
+						// next month/year on alt +right
+						break;
+				case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D');
+						handled = event.ctrlKey || event.metaKey;
+						break; // +1 week on ctrl or command +down
+				default: handled = false;
+			}
+		else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home
+			$.datepicker._showDatepicker(this);
+		else {
+			handled = false;
+		}
+		if (handled) {
+			event.preventDefault();
+			event.stopPropagation();
+		}
+	},
+
+	/* Filter entered characters - based on date format. */
+	_doKeyPress: function(event) {
+		var inst = $.datepicker._getInst(event.target);
+		if ($.datepicker._get(inst, 'constrainInput')) {
+			var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat'));
+			var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode);
+			return event.ctrlKey || event.metaKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1);
+		}
+	},
+
+	/* Synchronise manual entry and field/alternate field. */
+	_doKeyUp: function(event) {
+		var inst = $.datepicker._getInst(event.target);
+		if (inst.input.val() != inst.lastVal) {
+			try {
+				var date = $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'),
+					(inst.input ? inst.input.val() : null),
+					$.datepicker._getFormatConfig(inst));
+				if (date) { // only if valid
+					$.datepicker._setDateFromField(inst);
+					$.datepicker._updateAlternate(inst);
+					$.datepicker._updateDatepicker(inst);
+				}
+			}
+			catch (err) {
+				$.datepicker.log(err);
+			}
+		}
+		return true;
+	},
+
+	/* Pop-up the date picker for a given input field.
+	   If false returned from beforeShow event handler do not show.
+	   @param  input  element - the input field attached to the date picker or
+	                  event - if triggered by focus */
+	_showDatepicker: function(input) {
+		input = input.target || input;
+		if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger
+			input = $('input', input.parentNode)[0];
+		if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here
+			return;
+		var inst = $.datepicker._getInst(input);
+		if ($.datepicker._curInst && $.datepicker._curInst != inst) {
+			$.datepicker._curInst.dpDiv.stop(true, true);
+			if ( inst && $.datepicker._datepickerShowing ) {
+				$.datepicker._hideDatepicker( $.datepicker._curInst.input[0] );
+			}
+		}
+		var beforeShow = $.datepicker._get(inst, 'beforeShow');
+		var beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {};
+		if(beforeShowSettings === false){
+			//false
+			return;
+		}
+		extendRemove(inst.settings, beforeShowSettings);
+		inst.lastVal = null;
+		$.datepicker._lastInput = input;
+		$.datepicker._setDateFromField(inst);
+		if ($.datepicker._inDialog) // hide cursor
+			input.value = '';
+		if (!$.datepicker._pos) { // position below input
+			$.datepicker._pos = $.datepicker._findPos(input);
+			$.datepicker._pos[1] += input.offsetHeight; // add the height
+		}
+		var isFixed = false;
+		$(input).parents().each(function() {
+			isFixed |= $(this).css('position') == 'fixed';
+			return !isFixed;
+		});
+		var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
+		$.datepicker._pos = null;
+		//to avoid flashes on Firefox
+		inst.dpDiv.empty();
+		// determine sizing offscreen
+		inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'});
+		$.datepicker._updateDatepicker(inst);
+		// fix width for dynamic number of date pickers
+		// and adjust position before showing
+		offset = $.datepicker._checkOffset(inst, offset, isFixed);
+		inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
+			'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
+			left: offset.left + 'px', top: offset.top + 'px'});
+		if (!inst.inline) {
+			var showAnim = $.datepicker._get(inst, 'showAnim');
+			var duration = $.datepicker._get(inst, 'duration');
+			var postProcess = function() {
+				var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only
+				if( !! cover.length ){
+					var borders = $.datepicker._getBorders(inst.dpDiv);
+					cover.css({left: -borders[0], top: -borders[1],
+						width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()});
+				}
+			};
+			inst.dpDiv.zIndex($(input).zIndex()+1);
+			$.datepicker._datepickerShowing = true;
+
+			// DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
+			if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) )
+				inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
+			else
+				inst.dpDiv[showAnim || 'show']((showAnim ? duration : null), postProcess);
+			if (!showAnim || !duration)
+				postProcess();
+			if (inst.input.is(':visible') && !inst.input.is(':disabled'))
+				inst.input.focus();
+			$.datepicker._curInst = inst;
+		}
+	},
+
+	/* Generate the date picker content. */
+	_updateDatepicker: function(inst) {
+		this.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
+		var borders = $.datepicker._getBorders(inst.dpDiv);
+		instActive = inst; // for delegate hover events
+		inst.dpDiv.empty().append(this._generateHTML(inst));
+		this._attachHandlers(inst);
+		var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only
+		if( !!cover.length ){ //avoid call to outerXXXX() when not in IE6
+			cover.css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()})
+		}
+		inst.dpDiv.find('.' + this._dayOverClass + ' a').mouseover();
+		var numMonths = this._getNumberOfMonths(inst);
+		var cols = numMonths[1];
+		var width = 17;
+		inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width('');
+		if (cols > 1)
+			inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em');
+		inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') +
+			'Class']('ui-datepicker-multi');
+		inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') +
+			'Class']('ui-datepicker-rtl');
+		if (inst == $.datepicker._curInst && $.datepicker._datepickerShowing && inst.input &&
+				// #6694 - don't focus the input if it's already focused
+				// this breaks the change event in IE
+				inst.input.is(':visible') && !inst.input.is(':disabled') && inst.input[0] != document.activeElement)
+			inst.input.focus();
+		// deffered render of the years select (to avoid flashes on Firefox)
+		if( inst.yearshtml ){
+			var origyearshtml = inst.yearshtml;
+			setTimeout(function(){
+				//assure that inst.yearshtml didn't change.
+				if( origyearshtml === inst.yearshtml && inst.yearshtml ){
+					inst.dpDiv.find('select.ui-datepicker-year:first').replaceWith(inst.yearshtml);
+				}
+				origyearshtml = inst.yearshtml = null;
+			}, 0);
+		}
+	},
+
+	/* Retrieve the size of left and top borders for an element.
+	   @param  elem  (jQuery object) the element of interest
+	   @return  (number[2]) the left and top borders */
+	_getBorders: function(elem) {
+		var convert = function(value) {
+			return {thin: 1, medium: 2, thick: 3}[value] || value;
+		};
+		return [parseFloat(convert(elem.css('border-left-width'))),
+			parseFloat(convert(elem.css('border-top-width')))];
+	},
+
+	/* Check positioning to remain on screen. */
+	_checkOffset: function(inst, offset, isFixed) {
+		var dpWidth = inst.dpDiv.outerWidth();
+		var dpHeight = inst.dpDiv.outerHeight();
+		var inputWidth = inst.input ? inst.input.outerWidth() : 0;
+		var inputHeight = inst.input ? inst.input.outerHeight() : 0;
+		var viewWidth = document.documentElement.clientWidth + (isFixed ? 0 : $(document).scrollLeft());
+		var viewHeight = document.documentElement.clientHeight + (isFixed ? 0 : $(document).scrollTop());
+
+		offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0);
+		offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0;
+		offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
+
+		// now check if datepicker is showing outside window viewport - move to a better place if so.
+		offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
+			Math.abs(offset.left + dpWidth - viewWidth) : 0);
+		offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
+			Math.abs(dpHeight + inputHeight) : 0);
+
+		return offset;
+	},
+
+	/* Find an object's position on the screen. */
+	_findPos: function(obj) {
+		var inst = this._getInst(obj);
+		var isRTL = this._get(inst, 'isRTL');
+		while (obj && (obj.type == 'hidden' || obj.nodeType != 1 || $.expr.filters.hidden(obj))) {
+			obj = obj[isRTL ? 'previousSibling' : 'nextSibling'];
+		}
+		var position = $(obj).offset();
+		return [position.left, position.top];
+	},
+
+	/* Hide the date picker from view.
+	   @param  input  element - the input field attached to the date picker */
+	_hideDatepicker: function(input) {
+		var inst = this._curInst;
+		if (!inst || (input && inst != $.data(input, PROP_NAME)))
+			return;
+		if (this._datepickerShowing) {
+			var showAnim = this._get(inst, 'showAnim');
+			var duration = this._get(inst, 'duration');
+			var postProcess = function() {
+				$.datepicker._tidyDialog(inst);
+			};
+
+			// DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed
+			if ( $.effects && ( $.effects.effect[ showAnim ] || $.effects[ showAnim ] ) )
+				inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
+			else
+				inst.dpDiv[(showAnim == 'slideDown' ? 'slideUp' :
+					(showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))]((showAnim ? duration : null), postProcess);
+			if (!showAnim)
+				postProcess();
+			this._datepickerShowing = false;
+			var onClose = this._get(inst, 'onClose');
+			if (onClose)
+				onClose.apply((inst.input ? inst.input[0] : null),
+					[(inst.input ? inst.input.val() : ''), inst]);
+			this._lastInput = null;
+			if (this._inDialog) {
+				this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
+				if ($.blockUI) {
+					$.unblockUI();
+					$('body').append(this.dpDiv);
+				}
+			}
+			this._inDialog = false;
+		}
+	},
+
+	/* Tidy up after a dialog display. */
+	_tidyDialog: function(inst) {
+		inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar');
+	},
+
+	/* Close date picker if clicked elsewhere. */
+	_checkExternalClick: function(event) {
+		if (!$.datepicker._curInst)
+			return;
+
+		var $target = $(event.target),
+			inst = $.datepicker._getInst($target[0]);
+
+		if ( ( ( $target[0].id != $.datepicker._mainDivId &&
+				$target.parents('#' + $.datepicker._mainDivId).length == 0 &&
+				!$target.hasClass($.datepicker.markerClassName) &&
+				!$target.closest("." + $.datepicker._triggerClass).length &&
+				$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) ||
+			( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst != inst ) )
+			$.datepicker._hideDatepicker();
+	},
+
+	/* Adjust one of the date sub-fields. */
+	_adjustDate: function(id, offset, period) {
+		var target = $(id);
+		var inst = this._getInst(target[0]);
+		if (this._isDisabledDatepicker(target[0])) {
+			return;
+		}
+		this._adjustInstDate(inst, offset +
+			(period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning
+			period);
+		this._updateDatepicker(inst);
+	},
+
+	/* Action for current link. */
+	_gotoToday: function(id) {
+		var target = $(id);
+		var inst = this._getInst(target[0]);
+		if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
+			inst.selectedDay = inst.currentDay;
+			inst.drawMonth = inst.selectedMonth = inst.currentMonth;
+			inst.drawYear = inst.selectedYear = inst.currentYear;
+		}
+		else {
+			var date = new Date();
+			inst.selectedDay = date.getDate();
+			inst.drawMonth = inst.selectedMonth = date.getMonth();
+			inst.drawYear = inst.selectedYear = date.getFullYear();
+		}
+		this._notifyChange(inst);
+		this._adjustDate(target);
+	},
+
+	/* Action for selecting a new month/year. */
+	_selectMonthYear: function(id, select, period) {
+		var target = $(id);
+		var inst = this._getInst(target[0]);
+		inst['selected' + (period == 'M' ? 'Month' : 'Year')] =
+		inst['draw' + (period == 'M' ? 'Month' : 'Year')] =
+			parseInt(select.options[select.selectedIndex].value,10);
+		this._notifyChange(inst);
+		this._adjustDate(target);
+	},
+
+	/* Action for selecting a day. */
+	_selectDay: function(id, month, year, td) {
+		var target = $(id);
+		if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
+			return;
+		}
+		var inst = this._getInst(target[0]);
+		inst.selectedDay = inst.currentDay = $('a', td).html();
+		inst.selectedMonth = inst.currentMonth = month;
+		inst.selectedYear = inst.currentYear = year;
+		this._selectDate(id, this._formatDate(inst,
+			inst.currentDay, inst.currentMonth, inst.currentYear));
+	},
+
+	/* Erase the input field and hide the date picker. */
+	_clearDate: function(id) {
+		var target = $(id);
+		var inst = this._getInst(target[0]);
+		this._selectDate(target, '');
+	},
+
+	/* Update the input field with the selected date. */
+	_selectDate: function(id, dateStr) {
+		var target = $(id);
+		var inst = this._getInst(target[0]);
+		dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
+		if (inst.input)
+			inst.input.val(dateStr);
+		this._updateAlternate(inst);
+		var onSelect = this._get(inst, 'onSelect');
+		if (onSelect)
+			onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);  // trigger custom callback
+		else if (inst.input)
+			inst.input.trigger('change'); // fire the change event
+		if (inst.inline)
+			this._updateDatepicker(inst);
+		else {
+			this._hideDatepicker();
+			this._lastInput = inst.input[0];
+			if (typeof(inst.input[0]) != 'object')
+				inst.input.focus(); // restore focus
+			this._lastInput = null;
+		}
+	},
+
+	/* Update any alternate field to synchronise with the main field. */
+	_updateAlternate: function(inst) {
+		var altField = this._get(inst, 'altField');
+		if (altField) { // update alternate field too
+			var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat');
+			var date = this._getDate(inst);
+			var dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
+			$(altField).each(function() { $(this).val(dateStr); });
+		}
+	},
+
+	/* Set as beforeShowDay function to prevent selection of weekends.
+	   @param  date  Date - the date to customise
+	   @return [boolean, string] - is this date selectable?, what is its CSS class? */
+	noWeekends: function(date) {
+		var day = date.getDay();
+		return [(day > 0 && day < 6), ''];
+	},
+
+	/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
+	   @param  date  Date - the date to get the week for
+	   @return  number - the number of the week within the year that contains this date */
+	iso8601Week: function(date) {
+		var checkDate = new Date(date.getTime());
+		// Find Thursday of this week starting on Monday
+		checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
+		var time = checkDate.getTime();
+		checkDate.setMonth(0); // Compare with Jan 1
+		checkDate.setDate(1);
+		return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
+	},
+
+	/* Parse a string value into a date object.
+	   See formatDate below for the possible formats.
+
+	   @param  format    string - the expected format of the date
+	   @param  value     string - the date in the above format
+	   @param  settings  Object - attributes include:
+	                     shortYearCutoff  number - the cutoff year for determining the century (optional)
+	                     dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
+	                     dayNames         string[7] - names of the days from Sunday (optional)
+	                     monthNamesShort  string[12] - abbreviated names of the months (optional)
+	                     monthNames       string[12] - names of the months (optional)
+	   @return  Date - the extracted date value or null if value is blank */
+	parseDate: function (format, value, settings) {
+		if (format == null || value == null)
+			throw 'Invalid arguments';
+		value = (typeof value == 'object' ? value.toString() : value + '');
+		if (value == '')
+			return null;
+		var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff;
+		shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
+				new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
+		var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
+		var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
+		var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
+		var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
+		var year = -1;
+		var month = -1;
+		var day = -1;
+		var doy = -1;
+		var literal = false;
+		// Check whether a format character is doubled
+		var lookAhead = function(match) {
+			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
+			if (matches)
+				iFormat++;
+			return matches;
+		};
+		// Extract a number from the string value
+		var getNumber = function(match) {
+			var isDoubled = lookAhead(match);
+			var size = (match == '@' ? 14 : (match == '!' ? 20 :
+				(match == 'y' && isDoubled ? 4 : (match == 'o' ? 3 : 2))));
+			var digits = new RegExp('^\\d{1,' + size + '}');
+			var num = value.substring(iValue).match(digits);
+			if (!num)
+				throw 'Missing number at position ' + iValue;
+			iValue += num[0].length;
+			return parseInt(num[0], 10);
+		};
+		// Extract a name from the string value and convert to an index
+		var getName = function(match, shortNames, longNames) {
+			var names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) {
+				return [ [k, v] ];
+			}).sort(function (a, b) {
+				return -(a[1].length - b[1].length);
+			});
+			var index = -1;
+			$.each(names, function (i, pair) {
+				var name = pair[1];
+				if (value.substr(iValue, name.length).toLowerCase() == name.toLowerCase()) {
+					index = pair[0];
+					iValue += name.length;
+					return false;
+				}
+			});
+			if (index != -1)
+				return index + 1;
+			else
+				throw 'Unknown name at position ' + iValue;
+		};
+		// Confirm that a literal character matches the string value
+		var checkLiteral = function() {
+			if (value.charAt(iValue) != format.charAt(iFormat))
+				throw 'Unexpected literal at position ' + iValue;
+			iValue++;
+		};
+		var iValue = 0;
+		for (var iFormat = 0; iFormat < format.length; iFormat++) {
+			if (literal)
+				if (format.charAt(iFormat) == "'" && !lookAhead("'"))
+					literal = false;
+				else
+					checkLiteral();
+			else
+				switch (format.charAt(iFormat)) {
+					case 'd':
+						day = getNumber('d');
+						break;
+					case 'D':
+						getName('D', dayNamesShort, dayNames);
+						break;
+					case 'o':
+						doy = getNumber('o');
+						break;
+					case 'm':
+						month = getNumber('m');
+						break;
+					case 'M':
+						month = getName('M', monthNamesShort, monthNames);
+						break;
+					case 'y':
+						year = getNumber('y');
+						break;
+					case '@':
+						var date = new Date(getNumber('@'));
+						year = date.getFullYear();
+						month = date.getMonth() + 1;
+						day = date.getDate();
+						break;
+					case '!':
+						var date = new Date((getNumber('!') - this._ticksTo1970) / 10000);
+						year = date.getFullYear();
+						month = date.getMonth() + 1;
+						day = date.getDate();
+						break;
+					case "'":
+						if (lookAhead("'"))
+							checkLiteral();
+						else
+							literal = true;
+						break;
+					default:
+						checkLiteral();
+				}
+		}
+		if (iValue < value.length){
+			var extra = value.substr(iValue);
+			if (!/^\s+/.test(extra)) {
+				throw "Extra/unparsed characters found in date: " + extra;
+			}
+		}
+		if (year == -1)
+			year = new Date().getFullYear();
+		else if (year < 100)
+			year += new Date().getFullYear() - new Date().getFullYear() % 100 +
+				(year <= shortYearCutoff ? 0 : -100);
+		if (doy > -1) {
+			month = 1;
+			day = doy;
+			do {
+				var dim = this._getDaysInMonth(year, month - 1);
+				if (day <= dim)
+					break;
+				month++;
+				day -= dim;
+			} while (true);
+		}
+		var date = this._daylightSavingAdjust(new Date(year, month - 1, day));
+		if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day)
+			throw 'Invalid date'; // E.g. 31/02/00
+		return date;
+	},
+
+	/* Standard date formats. */
+	ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601)
+	COOKIE: 'D, dd M yy',
+	ISO_8601: 'yy-mm-dd',
+	RFC_822: 'D, d M y',
+	RFC_850: 'DD, dd-M-y',
+	RFC_1036: 'D, d M y',
+	RFC_1123: 'D, d M yy',
+	RFC_2822: 'D, d M yy',
+	RSS: 'D, d M y', // RFC 822
+	TICKS: '!',
+	TIMESTAMP: '@',
+	W3C: 'yy-mm-dd', // ISO 8601
+
+	_ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
+		Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),
+
+	/* Format a date object into a string value.
+	   The format can be combinations of the following:
+	   d  - day of month (no leading zero)
+	   dd - day of month (two digit)
+	   o  - day of year (no leading zeros)
+	   oo - day of year (three digit)
+	   D  - day name short
+	   DD - day name long
+	   m  - month of year (no leading zero)
+	   mm - month of year (two digit)
+	   M  - month name short
+	   MM - month name long
+	   y  - year (two digit)
+	   yy - year (four digit)
+	   @ - Unix timestamp (ms since 01/01/1970)
+	   ! - Windows ticks (100ns since 01/01/0001)
+	   '...' - literal text
+	   '' - single quote
+
+	   @param  format    string - the desired format of the date
+	   @param  date      Date - the date value to format
+	   @param  settings  Object - attributes include:
+	                     dayNamesShort    string[7] - abbreviated names of the days from Sunday (optional)
+	                     dayNames         string[7] - names of the days from Sunday (optional)
+	                     monthNamesShort  string[12] - abbreviated names of the months (optional)
+	                     monthNames       string[12] - names of the months (optional)
+	   @return  string - the date in the above format */
+	formatDate: function (format, date, settings) {
+		if (!date)
+			return '';
+		var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
+		var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
+		var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
+		var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
+		// Check whether a format character is doubled
+		var lookAhead = function(match) {
+			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
+			if (matches)
+				iFormat++;
+			return matches;
+		};
+		// Format a number, with leading zero if necessary
+		var formatNumber = function(match, value, len) {
+			var num = '' + value;
+			if (lookAhead(match))
+				while (num.length < len)
+					num = '0' + num;
+			return num;
+		};
+		// Format a name, short or long as requested
+		var formatName = function(match, value, shortNames, longNames) {
+			return (lookAhead(match) ? longNames[value] : shortNames[value]);
+		};
+		var output = '';
+		var literal = false;
+		if (date)
+			for (var iFormat = 0; iFormat < format.length; iFormat++) {
+				if (literal)
+					if (format.charAt(iFormat) == "'" && !lookAhead("'"))
+						literal = false;
+					else
+						output += format.charAt(iFormat);
+				else
+					switch (format.charAt(iFormat)) {
+						case 'd':
+							output += formatNumber('d', date.getDate(), 2);
+							break;
+						case 'D':
+							output += formatName('D', date.getDay(), dayNamesShort, dayNames);
+							break;
+						case 'o':
+							output += formatNumber('o',
+								Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
+							break;
+						case 'm':
+							output += formatNumber('m', date.getMonth() + 1, 2);
+							break;
+						case 'M':
+							output += formatName('M', date.getMonth(), monthNamesShort, monthNames);
+							break;
+						case 'y':
+							output += (lookAhead('y') ? date.getFullYear() :
+								(date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100);
+							break;
+						case '@':
+							output += date.getTime();
+							break;
+						case '!':
+							output += date.getTime() * 10000 + this._ticksTo1970;
+							break;
+						case "'":
+							if (lookAhead("'"))
+								output += "'";
+							else
+								literal = true;
+							break;
+						default:
+							output += format.charAt(iFormat);
+					}
+			}
+		return output;
+	},
+
+	/* Extract all possible characters from the date format. */
+	_possibleChars: function (format) {
+		var chars = '';
+		var literal = false;
+		// Check whether a format character is doubled
+		var lookAhead = function(match) {
+			var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
+			if (matches)
+				iFormat++;
+			return matches;
+		};
+		for (var iFormat = 0; iFormat < format.length; iFormat++)
+			if (literal)
+				if (format.charAt(iFormat) == "'" && !lookAhead("'"))
+					literal = false;
+				else
+					chars += format.charAt(iFormat);
+			else
+				switch (format.charAt(iFormat)) {
+					case 'd': case 'm': case 'y': case '@':
+						chars += '0123456789';
+						break;
+					case 'D': case 'M':
+						return null; // Accept anything
+					case "'":
+						if (lookAhead("'"))
+							chars += "'";
+						else
+							literal = true;
+						break;
+					default:
+						chars += format.charAt(iFormat);
+				}
+		return chars;
+	},
+
+	/* Get a setting value, defaulting if necessary. */
+	_get: function(inst, name) {
+		return inst.settings[name] !== undefined ?
+			inst.settings[name] : this._defaults[name];
+	},
+
+	/* Parse existing date and initialise date picker. */
+	_setDateFromField: function(inst, noDefault) {
+		if (inst.input.val() == inst.lastVal) {
+			return;
+		}
+		var dateFormat = this._get(inst, 'dateFormat');
+		var dates = inst.lastVal = inst.input ? inst.input.val() : null;
+		var date, defaultDate;
+		date = defaultDate = this._getDefaultDate(inst);
+		var settings = this._getFormatConfig(inst);
+		try {
+			date = this.parseDate(dateFormat, dates, settings) || defaultDate;
+		} catch (event) {
+			this.log(event);
+			dates = (noDefault ? '' : dates);
+		}
+		inst.selectedDay = date.getDate();
+		inst.drawMonth = inst.selectedMonth = date.getMonth();
+		inst.drawYear = inst.selectedYear = date.getFullYear();
+		inst.currentDay = (dates ? date.getDate() : 0);
+		inst.currentMonth = (dates ? date.getMonth() : 0);
+		inst.currentYear = (dates ? date.getFullYear() : 0);
+		this._adjustInstDate(inst);
+	},
+
+	/* Retrieve the default date shown on opening. */
+	_getDefaultDate: function(inst) {
+		return this._restrictMinMax(inst,
+			this._determineDate(inst, this._get(inst, 'defaultDate'), new Date()));
+	},
+
+	/* A date may be specified as an exact value or a relative one. */
+	_determineDate: function(inst, date, defaultDate) {
+		var offsetNumeric = function(offset) {
+			var date = new Date();
+			date.setDate(date.getDate() + offset);
+			return date;
+		};
+		var offsetString = function(offset) {
+			try {
+				return $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'),
+					offset, $.datepicker._getFormatConfig(inst));
+			}
+			catch (e) {
+				// Ignore
+			}
+			var date = (offset.toLowerCase().match(/^c/) ?
+				$.datepicker._getDate(inst) : null) || new Date();
+			var year = date.getFullYear();
+			var month = date.getMonth();
+			var day = date.getDate();
+			var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;
+			var matches = pattern.exec(offset);
+			while (matches) {
+				switch (matches[2] || 'd') {
+					case 'd' : case 'D' :
+						day += parseInt(matches[1],10); break;
+					case 'w' : case 'W' :
+						day += parseInt(matches[1],10) * 7; break;
+					case 'm' : case 'M' :
+						month += parseInt(matches[1],10);
+						day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
+						break;
+					case 'y': case 'Y' :
+						year += parseInt(matches[1],10);
+						day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
+						break;
+				}
+				matches = pattern.exec(offset);
+			}
+			return new Date(year, month, day);
+		};
+		var newDate = (date == null || date === '' ? defaultDate : (typeof date == 'string' ? offsetString(date) :
+			(typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));
+		newDate = (newDate && newDate.toString() == 'Invalid Date' ? defaultDate : newDate);
+		if (newDate) {
+			newDate.setHours(0);
+			newDate.setMinutes(0);
+			newDate.setSeconds(0);
+			newDate.setMilliseconds(0);
+		}
+		return this._daylightSavingAdjust(newDate);
+	},
+
+	/* Handle switch to/from daylight saving.
+	   Hours may be non-zero on daylight saving cut-over:
+	   > 12 when midnight changeover, but then cannot generate
+	   midnight datetime, so jump to 1AM, otherwise reset.
+	   @param  date  (Date) the date to check
+	   @return  (Date) the corrected date */
+	_daylightSavingAdjust: function(date) {
+		if (!date) return null;
+		date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
+		return date;
+	},
+
+	/* Set the date(s) directly. */
+	_setDate: function(inst, date, noChange) {
+		var clear = !date;
+		var origMonth = inst.selectedMonth;
+		var origYear = inst.selectedYear;
+		var newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));
+		inst.selectedDay = inst.currentDay = newDate.getDate();
+		inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
+		inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
+		if ((origMonth != inst.selectedMonth || origYear != inst.selectedYear) && !noChange)
+			this._notifyChange(inst);
+		this._adjustInstDate(inst);
+		if (inst.input) {
+			inst.input.val(clear ? '' : this._formatDate(inst));
+		}
+	},
+
+	/* Retrieve the date(s) directly. */
+	_getDate: function(inst) {
+		var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null :
+			this._daylightSavingAdjust(new Date(
+			inst.currentYear, inst.currentMonth, inst.currentDay)));
+			return startDate;
+	},
+
+	/* Attach the onxxx handlers.  These are declared statically so
+	 * they work with static code transformers like Caja.
+	 */
+	_attachHandlers: function(inst) {
+		var stepMonths = this._get(inst, 'stepMonths');
+		var id = '#' + inst.id.replace( /\\\\/g, "\\" );
+		inst.dpDiv.find('[data-handler]').map(function () {
+			var handler = {
+				prev: function () {
+					window['DP_jQuery_' + dpuuid].datepicker._adjustDate(id, -stepMonths, 'M');
+				},
+				next: function () {
+					window['DP_jQuery_' + dpuuid].datepicker._adjustDate(id, +stepMonths, 'M');
+				},
+				hide: function () {
+					window['DP_jQuery_' + dpuuid].datepicker._hideDatepicker();
+				},
+				today: function () {
+					window['DP_jQuery_' + dpuuid].datepicker._gotoToday(id);
+				},
+				selectDay: function () {
+					window['DP_jQuery_' + dpuuid].datepicker._selectDay(id, +this.getAttribute('data-month'), +this.getAttribute('data-year'), this);
+					return false;
+				},
+				selectMonth: function () {
+					window['DP_jQuery_' + dpuuid].datepicker._selectMonthYear(id, this, 'M');
+					return false;
+				},
+				selectYear: function () {
+					window['DP_jQuery_' + dpuuid].datepicker._selectMonthYear(id, this, 'Y');
+					return false;
+				}
+			};
+			$(this).bind(this.getAttribute('data-event'), handler[this.getAttribute('data-handler')]);
+		});
+	},
+
+	/* Generate the HTML for the current state of the date picker. */
+	_generateHTML: function(inst) {
+		var today = new Date();
+		today = this._daylightSavingAdjust(
+			new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time
+		var isRTL = this._get(inst, 'isRTL');
+		var showButtonPanel = this._get(inst, 'showButtonPanel');
+		var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext');
+		var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat');
+		var numMonths = this._getNumberOfMonths(inst);
+		var showCurrentAtPos = this._get(inst, 'showCurrentAtPos');
+		var stepMonths = this._get(inst, 'stepMonths');
+		var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
+		var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
+			new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
+		var minDate = this._getMinMaxDate(inst, 'min');
+		var maxDate = this._getMinMaxDate(inst, 'max');
+		var drawMonth = inst.drawMonth - showCurrentAtPos;
+		var drawYear = inst.drawYear;
+		if (drawMonth < 0) {
+			drawMonth += 12;
+			drawYear--;
+		}
+		if (maxDate) {
+			var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
+				maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
+			maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
+			while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
+				drawMonth--;
+				if (drawMonth < 0) {
+					drawMonth = 11;
+					drawYear--;
+				}
+			}
+		}
+		inst.drawMonth = drawMonth;
+		inst.drawYear = drawYear;
+		var prevText = this._get(inst, 'prevText');
+		prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
+			this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
+			this._getFormatConfig(inst)));
+		var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
+			'<a class="ui-datepicker-prev ui-corner-all" data-handler="prev" data-event="click"' +
+			' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' :
+			(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>'));
+		var nextText = this._get(inst, 'nextText');
+		nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
+			this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
+			this._getFormatConfig(inst)));
+		var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
+			'<a class="ui-datepicker-next ui-corner-all" data-handler="next" data-event="click"' +
+			' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' :
+			(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>'));
+		var currentText = this._get(inst, 'currentText');
+		var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today);
+		currentText = (!navigationAsDateFormat ? currentText :
+			this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
+		var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">' +
+			this._get(inst, 'closeText') + '</button>' : '');
+		var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') +
+			(this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" data-handler="today" data-event="click"' +
+			'>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : '';
+		var firstDay = parseInt(this._get(inst, 'firstDay'),10);
+		firstDay = (isNaN(firstDay) ? 0 : firstDay);
+		var showWeek = this._get(inst, 'showWeek');
+		var dayNames = this._get(inst, 'dayNames');
+		var dayNamesShort = this._get(inst, 'dayNamesShort');
+		var dayNamesMin = this._get(inst, 'dayNamesMin');
+		var monthNames = this._get(inst, 'monthNames');
+		var monthNamesShort = this._get(inst, 'monthNamesShort');
+		var beforeShowDay = this._get(inst, 'beforeShowDay');
+		var showOtherMonths = this._get(inst, 'showOtherMonths');
+		var selectOtherMonths = this._get(inst, 'selectOtherMonths');
+		var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week;
+		var defaultDate = this._getDefaultDate(inst);
+		var html = '';
+		for (var row = 0; row < numMonths[0]; row++) {
+			var group = '';
+			this.maxRows = 4;
+			for (var col = 0; col < numMonths[1]; col++) {
+				var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
+				var cornerClass = ' ui-corner-all';
+				var calender = '';
+				if (isMultiMonth) {
+					calender += '<div class="ui-datepicker-group';
+					if (numMonths[1] > 1)
+						switch (col) {
+							case 0: calender += ' ui-datepicker-group-first';
+								cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break;
+							case numMonths[1]-1: calender += ' ui-datepicker-group-last';
+								cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break;
+							default: calender += ' ui-datepicker-group-middle'; cornerClass = ''; break;
+						}
+					calender += '">';
+				}
+				calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' +
+					(/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') +
+					(/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') +
+					this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
+					row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
+					'</div><table class="ui-datepicker-calendar"><thead>' +
+					'<tr>';
+				var thead = (showWeek ? '<th class="ui-datepicker-week-col">' + this._get(inst, 'weekHeader') + '</th>' : '');
+				for (var dow = 0; dow < 7; dow++) { // days of the week
+					var day = (dow + firstDay) % 7;
+					thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' +
+						'<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>';
+				}
+				calender += thead + '</tr></thead><tbody>';
+				var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
+				if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth)
+					inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
+				var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
+				var curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate
+				var numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043)
+				this.maxRows = numRows;
+				var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
+				for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
+					calender += '<tr>';
+					var tbody = (!showWeek ? '' : '<td class="ui-datepicker-week-col">' +
+						this._get(inst, 'calculateWeek')(printDate) + '</td>');
+					for (var dow = 0; dow < 7; dow++) { // create date picker days
+						var daySettings = (beforeShowDay ?
+							beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']);
+						var otherMonth = (printDate.getMonth() != drawMonth);
+						var unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
+							(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
+						tbody += '<td class="' +
+							((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends
+							(otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months
+							((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key
+							(defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ?
+							// or defaultDate is current printedDate and defaultDate is selectedDate
+							' ' + this._dayOverClass : '') + // highlight selected day
+							(unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') +  // highlight unselectable days
+							(otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
+							(printDate.getTime() == currentDate.getTime() ? ' ' + this._currentClass : '') + // highlight selected day
+							(printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different)
+							((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title
+							(unselectable ? '' : ' data-handler="selectDay" data-event="click" data-month="' + printDate.getMonth() + '" data-year="' + printDate.getFullYear() + '"') + '>' + // actions
+							(otherMonth && !showOtherMonths ? '&#xa0;' : // display for other months
+							(unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' +
+							(printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') +
+							(printDate.getTime() == currentDate.getTime() ? ' ui-state-active' : '') + // highlight selected day
+							(otherMonth ? ' ui-priority-secondary' : '') + // distinguish dates from other months
+							'" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display selectable date
+						printDate.setDate(printDate.getDate() + 1);
+						printDate = this._daylightSavingAdjust(printDate);
+					}
+					calender += tbody + '</tr>';
+				}
+				drawMonth++;
+				if (drawMonth > 11) {
+					drawMonth = 0;
+					drawYear++;
+				}
+				calender += '</tbody></table>' + (isMultiMonth ? '</div>' +
+							((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : '');
+				group += calender;
+			}
+			html += group;
+		}
+		html += buttonPanel + ($.ui.ie6 && !inst.inline ?
+			'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : '');
+		inst._keyEvent = false;
+		return html;
+	},
+
+	/* Generate the month and year header. */
+	_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
+			secondary, monthNames, monthNamesShort) {
+		var changeMonth = this._get(inst, 'changeMonth');
+		var changeYear = this._get(inst, 'changeYear');
+		var showMonthAfterYear = this._get(inst, 'showMonthAfterYear');
+		var html = '<div class="ui-datepicker-title">';
+		var monthHtml = '';
+		// month selection
+		if (secondary || !changeMonth)
+			monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span>';
+		else {
+			var inMinYear = (minDate && minDate.getFullYear() == drawYear);
+			var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear);
+			monthHtml += '<select class="ui-datepicker-month" data-handler="selectMonth" data-event="change">';
+			for (var month = 0; month < 12; month++) {
+				if ((!inMinYear || month >= minDate.getMonth()) &&
+						(!inMaxYear || month <= maxDate.getMonth()))
+					monthHtml += '<option value="' + month + '"' +
+						(month == drawMonth ? ' selected="selected"' : '') +
+						'>' + monthNamesShort[month] + '</option>';
+			}
+			monthHtml += '</select>';
+		}
+		if (!showMonthAfterYear)
+			html += monthHtml + (secondary || !(changeMonth && changeYear) ? '&#xa0;' : '');
+		// year selection
+		if ( !inst.yearshtml ) {
+			inst.yearshtml = '';
+			if (secondary || !changeYear)
+				html += '<span class="ui-datepicker-year">' + drawYear + '</span>';
+			else {
+				// determine range of years to display
+				var years = this._get(inst, 'yearRange').split(':');
+				var thisYear = new Date().getFullYear();
+				var determineYear = function(value) {
+					var year = (value.match(/c[+-].*/) ? drawYear + parseInt(value.substring(1), 10) :
+						(value.match(/[+-].*/) ? thisYear + parseInt(value, 10) :
+						parseInt(value, 10)));
+					return (isNaN(year) ? thisYear : year);
+				};
+				var year = determineYear(years[0]);
+				var endYear = Math.max(year, determineYear(years[1] || ''));
+				year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
+				endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
+				inst.yearshtml += '<select class="ui-datepicker-year" data-handler="selectYear" data-event="change">';
+				for (; year <= endYear; year++) {
+					inst.yearshtml += '<option value="' + year + '"' +
+						(year == drawYear ? ' selected="selected"' : '') +
+						'>' + year + '</option>';
+				}
+				inst.yearshtml += '</select>';
+
+				html += inst.yearshtml;
+				inst.yearshtml = null;
+			}
+		}
+		html += this._get(inst, 'yearSuffix');
+		if (showMonthAfterYear)
+			html += (secondary || !(changeMonth && changeYear) ? '&#xa0;' : '') + monthHtml;
+		html += '</div>'; // Close datepicker_header
+		return html;
+	},
+
+	/* Adjust one of the date sub-fields. */
+	_adjustInstDate: function(inst, offset, period) {
+		var year = inst.drawYear + (period == 'Y' ? offset : 0);
+		var month = inst.drawMonth + (period == 'M' ? offset : 0);
+		var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) +
+			(period == 'D' ? offset : 0);
+		var date = this._restrictMinMax(inst,
+			this._daylightSavingAdjust(new Date(year, month, day)));
+		inst.selectedDay = date.getDate();
+		inst.drawMonth = inst.selectedMonth = date.getMonth();
+		inst.drawYear = inst.selectedYear = date.getFullYear();
+		if (period == 'M' || period == 'Y')
+			this._notifyChange(inst);
+	},
+
+	/* Ensure a date is within any min/max bounds. */
+	_restrictMinMax: function(inst, date) {
+		var minDate = this._getMinMaxDate(inst, 'min');
+		var maxDate = this._getMinMaxDate(inst, 'max');
+		var newDate = (minDate && date < minDate ? minDate : date);
+		newDate = (maxDate && newDate > maxDate ? maxDate : newDate);
+		return newDate;
+	},
+
+	/* Notify change of month/year. */
+	_notifyChange: function(inst) {
+		var onChange = this._get(inst, 'onChangeMonthYear');
+		if (onChange)
+			onChange.apply((inst.input ? inst.input[0] : null),
+				[inst.selectedYear, inst.selectedMonth + 1, inst]);
+	},
+
+	/* Determine the number of months to show. */
+	_getNumberOfMonths: function(inst) {
+		var numMonths = this._get(inst, 'numberOfMonths');
+		return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths));
+	},
+
+	/* Determine the current maximum date - ensure no time components are set. */
+	_getMinMaxDate: function(inst, minMax) {
+		return this._determineDate(inst, this._get(inst, minMax + 'Date'), null);
+	},
+
+	/* Find the number of days in a given month. */
+	_getDaysInMonth: function(year, month) {
+		return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate();
+	},
+
+	/* Find the day of the week of the first of a month. */
+	_getFirstDayOfMonth: function(year, month) {
+		return new Date(year, month, 1).getDay();
+	},
+
+	/* Determines if we should allow a "next/prev" month display change. */
+	_canAdjustMonth: function(inst, offset, curYear, curMonth) {
+		var numMonths = this._getNumberOfMonths(inst);
+		var date = this._daylightSavingAdjust(new Date(curYear,
+			curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));
+		if (offset < 0)
+			date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
+		return this._isInRange(inst, date);
+	},
+
+	/* Is the given date in the accepted range? */
+	_isInRange: function(inst, date) {
+		var minDate = this._getMinMaxDate(inst, 'min');
+		var maxDate = this._getMinMaxDate(inst, 'max');
+		return ((!minDate || date.getTime() >= minDate.getTime()) &&
+			(!maxDate || date.getTime() <= maxDate.getTime()));
+	},
+
+	/* Provide the configuration settings for formatting/parsing. */
+	_getFormatConfig: function(inst) {
+		var shortYearCutoff = this._get(inst, 'shortYearCutoff');
+		shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
+			new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
+		return {shortYearCutoff: shortYearCutoff,
+			dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'),
+			monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')};
+	},
+
+	/* Format the given date for display. */
+	_formatDate: function(inst, day, month, year) {
+		if (!day) {
+			inst.currentDay = inst.selectedDay;
+			inst.currentMonth = inst.selectedMonth;
+			inst.currentYear = inst.selectedYear;
+		}
+		var date = (day ? (typeof day == 'object' ? day :
+			this._daylightSavingAdjust(new Date(year, month, day))) :
+			this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
+		return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst));
+	}
+});
+
+/*
+ * Bind hover events for datepicker elements.
+ * Done via delegate so the binding only occurs once in the lifetime of the parent div.
+ * Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
+ */
+function bindHover(dpDiv) {
+	var selector = 'button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a';
+	return dpDiv.delegate(selector, 'mouseout', function() {
+			$(this).removeClass('ui-state-hover');
+			if (this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover');
+			if (this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover');
+		})
+		.delegate(selector, 'mouseover', function(){
+			if (!$.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : instActive.input[0])) {
+				$(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover');
+				$(this).addClass('ui-state-hover');
+				if (this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover');
+				if (this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover');
+			}
+		});
+}
+
+/* jQuery extend now ignores nulls! */
+function extendRemove(target, props) {
+	$.extend(target, props);
+	for (var name in props)
+		if (props[name] == null || props[name] == undefined)
+			target[name] = props[name];
+	return target;
+};
+
+/* Invoke the datepicker functionality.
+   @param  options  string - a command, optionally followed by additional parameters or
+	                Object - settings for attaching new datepicker functionality
+   @return  jQuery object */
+$.fn.datepicker = function(options){
+
+	/* Verify an empty collection wasn't passed - Fixes #6976 */
+	if ( !this.length ) {
+		return this;
+	}
+
+	/* Initialise the date picker. */
+	if (!$.datepicker.initialized) {
+		$(document).mousedown($.datepicker._checkExternalClick).
+			find(document.body).append($.datepicker.dpDiv);
+		$.datepicker.initialized = true;
+	}
+
+	var otherArgs = Array.prototype.slice.call(arguments, 1);
+	if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate' || options == 'widget'))
+		return $.datepicker['_' + options + 'Datepicker'].
+			apply($.datepicker, [this[0]].concat(otherArgs));
+	if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string')
+		return $.datepicker['_' + options + 'Datepicker'].
+			apply($.datepicker, [this[0]].concat(otherArgs));
+	return this.each(function() {
+		typeof options == 'string' ?
+			$.datepicker['_' + options + 'Datepicker'].
+				apply($.datepicker, [this].concat(otherArgs)) :
+			$.datepicker._attachDatepicker(this, options);
+	});
+};
+
+$.datepicker = new Datepicker(); // singleton instance
+$.datepicker.initialized = false;
+$.datepicker.uuid = new Date().getTime();
+$.datepicker.version = "1.9.2";
+
+// Workaround for #4055
+// Add another global to avoid noConflict issues with inline event handlers
+window['DP_jQuery_' + dpuuid] = $;
+
+})(jQuery);
+
+(function( $, undefined ) {
+
+var uiDialogClasses = "ui-dialog ui-widget ui-widget-content ui-corner-all ",
+	sizeRelatedOptions = {
+		buttons: true,
+		height: true,
+		maxHeight: true,
+		maxWidth: true,
+		minHeight: true,
+		minWidth: true,
+		width: true
+	},
+	resizableRelatedOptions = {
+		maxHeight: true,
+		maxWidth: true,
+		minHeight: true,
+		minWidth: true
+	};
+
+$.widget("ui.dialog", {
+	version: "1.9.2",
+	options: {
+		autoOpen: true,
+		buttons: {},
+		closeOnEscape: true,
+		closeText: "close",
+		dialogClass: "",
+		draggable: true,
+		hide: null,
+		height: "auto",
+		maxHeight: false,
+		maxWidth: false,
+		minHeight: 150,
+		minWidth: 150,
+		modal: false,
+		position: {
+			my: "center",
+			at: "center",
+			of: window,
+			collision: "fit",
+			// ensure that the titlebar is never outside the document
+			using: function( pos ) {
+				var topOffset = $( this ).css( pos ).offset().top;
+				if ( topOffset < 0 ) {
+					$( this ).css( "top", pos.top - topOffset );
+				}
+			}
+		},
+		resizable: true,
+		show: null,
+		stack: true,
+		title: "",
+		width: 300,
+		zIndex: 1000
+	},
+
+	_create: function() {
+		this.originalTitle = this.element.attr( "title" );
+		// #5742 - .attr() might return a DOMElement
+		if ( typeof this.originalTitle !== "string" ) {
+			this.originalTitle = "";
+		}
+		this.oldPosition = {
+			parent: this.element.parent(),
+			index: this.element.parent().children().index( this.element )
+		};
+		this.options.title = this.options.title || this.originalTitle;
+		var that = this,
+			options = this.options,
+
+			title = options.title || "&#160;",
+			uiDialog,
+			uiDialogTitlebar,
+			uiDialogTitlebarClose,
+			uiDialogTitle,
+			uiDialogButtonPane;
+
+			uiDialog = ( this.uiDialog = $( "<div>" ) )
+				.addClass( uiDialogClasses + options.dialogClass )
+				.css({
+					display: "none",
+					outline: 0, // TODO: move to stylesheet
+					zIndex: options.zIndex
+				})
+				// setting tabIndex makes the div focusable
+				.attr( "tabIndex", -1)
+				.keydown(function( event ) {
+					if ( options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode &&
+							event.keyCode === $.ui.keyCode.ESCAPE ) {
+						that.close( event );
+						event.preventDefault();
+					}
+				})
+				.mousedown(function( event ) {
+					that.moveToTop( false, event );
+				})
+				.appendTo( "body" );
+
+			this.element
+				.show()
+				.removeAttr( "title" )
+				.addClass( "ui-dialog-content ui-widget-content" )
+				.appendTo( uiDialog );
+
+			uiDialogTitlebar = ( this.uiDialogTitlebar = $( "<div>" ) )
+				.addClass( "ui-dialog-titlebar  ui-widget-header  " +
+					"ui-corner-all  ui-helper-clearfix" )
+				.bind( "mousedown", function() {
+					// Dialog isn't getting focus when dragging (#8063)
+					uiDialog.focus();
+				})
+				.prependTo( uiDialog );
+
+			uiDialogTitlebarClose = $( "<a href='#'></a>" )
+				.addClass( "ui-dialog-titlebar-close  ui-corner-all" )
+				.attr( "role", "button" )
+				.click(function( event ) {
+					event.preventDefault();
+					that.close( event );
+				})
+				.appendTo( uiDialogTitlebar );
+
+			( this.uiDialogTitlebarCloseText = $( "<span>" ) )
+				.addClass( "ui-icon ui-icon-closethick" )
+				.text( options.closeText )
+				.appendTo( uiDialogTitlebarClose );
+
+			uiDialogTitle = $( "<span>" )
+				.uniqueId()
+				.addClass( "ui-dialog-title" )
+				.html( title )
+				.prependTo( uiDialogTitlebar );
+
+			uiDialogButtonPane = ( this.uiDialogButtonPane = $( "<div>" ) )
+				.addClass( "ui-dialog-buttonpane ui-widget-content ui-helper-clearfix" );
+
+			( this.uiButtonSet = $( "<div>" ) )
+				.addClass( "ui-dialog-buttonset" )
+				.appendTo( uiDialogButtonPane );
+
+		uiDialog.attr({
+			role: "dialog",
+			"aria-labelledby": uiDialogTitle.attr( "id" )
+		});
+
+		uiDialogTitlebar.find( "*" ).add( uiDialogTitlebar ).disableSelection();
+		this._hoverable( uiDialogTitlebarClose );
+		this._focusable( uiDialogTitlebarClose );
+
+		if ( options.draggable && $.fn.draggable ) {
+			this._makeDraggable();
+		}
+		if ( options.resizable && $.fn.resizable ) {
+			this._makeResizable();
+		}
+
+		this._createButtons( options.buttons );
+		this._isOpen = false;
+
+		if ( $.fn.bgiframe ) {
+			uiDialog.bgiframe();
+		}
+
+		// prevent tabbing out of modal dialogs
+		this._on( uiDialog, { keydown: function( event ) {
+			if ( !options.modal || event.keyCode !== $.ui.keyCode.TAB ) {
+				return;
+			}
+
+			var tabbables = $( ":tabbable", uiDialog ),
+				first = tabbables.filter( ":first" ),
+				last  = tabbables.filter( ":last" );
+
+			if ( event.target === last[0] && !event.shiftKey ) {
+				first.focus( 1 );
+				return false;
+			} else if ( event.target === first[0] && event.shiftKey ) {
+				last.focus( 1 );
+				return false;
+			}
+		}});
+	},
+
+	_init: function() {
+		if ( this.options.autoOpen ) {
+			this.open();
+		}
+	},
+
+	_destroy: function() {
+		var next,
+			oldPosition = this.oldPosition;
+
+		if ( this.overlay ) {
+			this.overlay.destroy();
+		}
+		this.uiDialog.hide();
+		this.element
+			.removeClass( "ui-dialog-content ui-widget-content" )
+			.hide()
+			.appendTo( "body" );
+		this.uiDialog.remove();
+
+		if ( this.originalTitle ) {
+			this.element.attr( "title", this.originalTitle );
+		}
+
+		next = oldPosition.parent.children().eq( oldPosition.index );
+		// Don't try to place the dialog next to itself (#8613)
+		if ( next.length && next[ 0 ] !== this.element[ 0 ] ) {
+			next.before( this.element );
+		} else {
+			oldPosition.parent.append( this.element );
+		}
+	},
+
+	widget: function() {
+		return this.uiDialog;
+	},
+
+	close: function( event ) {
+		var that = this,
+			maxZ, thisZ;
+
+		if ( !this._isOpen ) {
+			return;
+		}
+
+		if ( false === this._trigger( "beforeClose", event ) ) {
+			return;
+		}
+
+		this._isOpen = false;
+
+		if ( this.overlay ) {
+			this.overlay.destroy();
+		}
+
+		if ( this.options.hide ) {
+			this._hide( this.uiDialog, this.options.hide, function() {
+				that._trigger( "close", event );
+			});
+		} else {
+			this.uiDialog.hide();
+			this._trigger( "close", event );
+		}
+
+		$.ui.dialog.overlay.resize();
+
+		// adjust the maxZ to allow other modal dialogs to continue to work (see #4309)
+		if ( this.options.modal ) {
+			maxZ = 0;
+			$( ".ui-dialog" ).each(function() {
+				if ( this !== that.uiDialog[0] ) {
+					thisZ = $( this ).css( "z-index" );
+					if ( !isNaN( thisZ ) ) {
+						maxZ = Math.max( maxZ, thisZ );
+					}
+				}
+			});
+			$.ui.dialog.maxZ = maxZ;
+		}
+
+		return this;
+	},
+
+	isOpen: function() {
+		return this._isOpen;
+	},
+
+	// the force parameter allows us to move modal dialogs to their correct
+	// position on open
+	moveToTop: function( force, event ) {
+		var options = this.options,
+			saveScroll;
+
+		if ( ( options.modal && !force ) ||
+				( !options.stack && !options.modal ) ) {
+			return this._trigger( "focus", event );
+		}
+
+		if ( options.zIndex > $.ui.dialog.maxZ ) {
+			$.ui.dialog.maxZ = options.zIndex;
+		}
+		if ( this.overlay ) {
+			$.ui.dialog.maxZ += 1;
+			$.ui.dialog.overlay.maxZ = $.ui.dialog.maxZ;
+			this.overlay.$el.css( "z-index", $.ui.dialog.overlay.maxZ );
+		}
+
+		// Save and then restore scroll
+		// Opera 9.5+ resets when parent z-index is changed.
+		// http://bugs.jqueryui.com/ticket/3193
+		saveScroll = {
+			scrollTop: this.element.scrollTop(),
+			scrollLeft: this.element.scrollLeft()
+		};
+		$.ui.dialog.maxZ += 1;
+		this.uiDialog.css( "z-index", $.ui.dialog.maxZ );
+		this.element.attr( saveScroll );
+		this._trigger( "focus", event );
+
+		return this;
+	},
+
+	open: function() {
+		if ( this._isOpen ) {
+			return;
+		}
+
+		var hasFocus,
+			options = this.options,
+			uiDialog = this.uiDialog;
+
+		this._size();
+		this._position( options.position );
+		uiDialog.show( options.show );
+		this.overlay = options.modal ? new $.ui.dialog.overlay( this ) : null;
+		this.moveToTop( true );
+
+		// set focus to the first tabbable element in the content area or the first button
+		// if there are no tabbable elements, set focus on the dialog itself
+		hasFocus = this.element.find( ":tabbable" );
+		if ( !hasFocus.length ) {
+			hasFocus = this.uiDialogButtonPane.find( ":tabbable" );
+			if ( !hasFocus.length ) {
+				hasFocus = uiDialog;
+			}
+		}
+		hasFocus.eq( 0 ).focus();
+
+		this._isOpen = true;
+		this._trigger( "open" );
+
+		return this;
+	},
+
+	_createButtons: function( buttons ) {
+		var that = this,
+			hasButtons = false;
+
+		// if we already have a button pane, remove it
+		this.uiDialogButtonPane.remove();
+		this.uiButtonSet.empty();
+
+		if ( typeof buttons === "object" && buttons !== null ) {
+			$.each( buttons, function() {
+				return !(hasButtons = true);
+			});
+		}
+		if ( hasButtons ) {
+			$.each( buttons, function( name, props ) {
+				var button, click;
+				props = $.isFunction( props ) ?
+					{ click: props, text: name } :
+					props;
+				// Default to a non-submitting button
+				props = $.extend( { type: "button" }, props );
+				// Change the context for the click callback to be the main element
+				click = props.click;
+				props.click = function() {
+					click.apply( that.element[0], arguments );
+				};
+				button = $( "<button></button>", props )
+					.appendTo( that.uiButtonSet );
+				if ( $.fn.button ) {
+					button.button();
+				}
+			});
+			this.uiDialog.addClass( "ui-dialog-buttons" );
+			this.uiDialogButtonPane.appendTo( this.uiDialog );
+		} else {
+			this.uiDialog.removeClass( "ui-dialog-buttons" );
+		}
+	},
+
+	_makeDraggable: function() {
+		var that = this,
+			options = this.options;
+
+		function filteredUi( ui ) {
+			return {
+				position: ui.position,
+				offset: ui.offset
+			};
+		}
+
+		this.uiDialog.draggable({
+			cancel: ".ui-dialog-content, .ui-dialog-titlebar-close",
+			handle: ".ui-dialog-titlebar",
+			containment: "document",
+			start: function( event, ui ) {
+				$( this )
+					.addClass( "ui-dialog-dragging" );
+				that._trigger( "dragStart", event, filteredUi( ui ) );
+			},
+			drag: function( event, ui ) {
+				that._trigger( "drag", event, filteredUi( ui ) );
+			},
+			stop: function( event, ui ) {
+				options.position = [
+					ui.position.left - that.document.scrollLeft(),
+					ui.position.top - that.document.scrollTop()
+				];
+				$( this )
+					.removeClass( "ui-dialog-dragging" );
+				that._trigger( "dragStop", event, filteredUi( ui ) );
+				$.ui.dialog.overlay.resize();
+			}
+		});
+	},
+
+	_makeResizable: function( handles ) {
+		handles = (handles === undefined ? this.options.resizable : handles);
+		var that = this,
+			options = this.options,
+			// .ui-resizable has position: relative defined in the stylesheet
+			// but dialogs have to use absolute or fixed positioning
+			position = this.uiDialog.css( "position" ),
+			resizeHandles = typeof handles === 'string' ?
+				handles	:
+				"n,e,s,w,se,sw,ne,nw";
+
+		function filteredUi( ui ) {
+			return {
+				originalPosition: ui.originalPosition,
+				originalSize: ui.originalSize,
+				position: ui.position,
+				size: ui.size
+			};
+		}
+
+		this.uiDialog.resizable({
+			cancel: ".ui-dialog-content",
+			containment: "document",
+			alsoResize: this.element,
+			maxWidth: options.maxWidth,
+			maxHeight: options.maxHeight,
+			minWidth: options.minWidth,
+			minHeight: this._minHeight(),
+			handles: resizeHandles,
+			start: function( event, ui ) {
+				$( this ).addClass( "ui-dialog-resizing" );
+				that._trigger( "resizeStart", event, filteredUi( ui ) );
+			},
+			resize: function( event, ui ) {
+				that._trigger( "resize", event, filteredUi( ui ) );
+			},
+			stop: function( event, ui ) {
+				$( this ).removeClass( "ui-dialog-resizing" );
+				options.height = $( this ).height();
+				options.width = $( this ).width();
+				that._trigger( "resizeStop", event, filteredUi( ui ) );
+				$.ui.dialog.overlay.resize();
+			}
+		})
+		.css( "position", position )
+		.find( ".ui-resizable-se" )
+			.addClass( "ui-icon ui-icon-grip-diagonal-se" );
+	},
+
+	_minHeight: function() {
+		var options = this.options;
+
+		if ( options.height === "auto" ) {
+			return options.minHeight;
+		} else {
+			return Math.min( options.minHeight, options.height );
+		}
+	},
+
+	_position: function( position ) {
+		var myAt = [],
+			offset = [ 0, 0 ],
+			isVisible;
+
+		if ( position ) {
+			// deep extending converts arrays to objects in jQuery <= 1.3.2 :-(
+	//		if (typeof position == 'string' || $.isArray(position)) {
+	//			myAt = $.isArray(position) ? position : position.split(' ');
+
+			if ( typeof position === "string" || (typeof position === "object" && "0" in position ) ) {
+				myAt = position.split ? position.split( " " ) : [ position[ 0 ], position[ 1 ] ];
+				if ( myAt.length === 1 ) {
+					myAt[ 1 ] = myAt[ 0 ];
+				}
+
+				$.each( [ "left", "top" ], function( i, offsetPosition ) {
+					if ( +myAt[ i ] === myAt[ i ] ) {
+						offset[ i ] = myAt[ i ];
+						myAt[ i ] = offsetPosition;
+					}
+				});
+
+				position = {
+					my: myAt[0] + (offset[0] < 0 ? offset[0] : "+" + offset[0]) + " " +
+						myAt[1] + (offset[1] < 0 ? offset[1] : "+" + offset[1]),
+					at: myAt.join( " " )
+				};
+			}
+
+			position = $.extend( {}, $.ui.dialog.prototype.options.position, position );
+		} else {
+			position = $.ui.dialog.prototype.options.position;
+		}
+
+		// need to show the dialog to get the actual offset in the position plugin
+		isVisible = this.uiDialog.is( ":visible" );
+		if ( !isVisible ) {
+			this.uiDialog.show();
+		}
+		this.uiDialog.position( position );
+		if ( !isVisible ) {
+			this.uiDialog.hide();
+		}
+	},
+
+	_setOptions: function( options ) {
+		var that = this,
+			resizableOptions = {},
+			resize = false;
+
+		$.each( options, function( key, value ) {
+			that._setOption( key, value );
+
+			if ( key in sizeRelatedOptions ) {
+				resize = true;
+			}
+			if ( key in resizableRelatedOptions ) {
+				resizableOptions[ key ] = value;
+			}
+		});
+
+		if ( resize ) {
+			this._size();
+		}
+		if ( this.uiDialog.is( ":data(resizable)" ) ) {
+			this.uiDialog.resizable( "option", resizableOptions );
+		}
+	},
+
+	_setOption: function( key, value ) {
+		var isDraggable, isResizable,
+			uiDialog = this.uiDialog;
+
+		switch ( key ) {
+			case "buttons":
+				this._createButtons( value );
+				break;
+			case "closeText":
+				// ensure that we always pass a string
+				this.uiDialogTitlebarCloseText.text( "" + value );
+				break;
+			case "dialogClass":
+				uiDialog
+					.removeClass( this.options.dialogClass )
+					.addClass( uiDialogClasses + value );
+				break;
+			case "disabled":
+				if ( value ) {
+					uiDialog.addClass( "ui-dialog-disabled" );
+				} else {
+					uiDialog.removeClass( "ui-dialog-disabled" );
+				}
+				break;
+			case "draggable":
+				isDraggable = uiDialog.is( ":data(draggable)" );
+				if ( isDraggable && !value ) {
+					uiDialog.draggable( "destroy" );
+				}
+
+				if ( !isDraggable && value ) {
+					this._makeDraggable();
+				}
+				break;
+			case "position":
+				this._position( value );
+				break;
+			case "resizable":
+				// currently resizable, becoming non-resizable
+				isResizable = uiDialog.is( ":data(resizable)" );
+				if ( isResizable && !value ) {
+					uiDialog.resizable( "destroy" );
+				}
+
+				// currently resizable, changing handles
+				if ( isResizable && typeof value === "string" ) {
+					uiDialog.resizable( "option", "handles", value );
+				}
+
+				// currently non-resizable, becoming resizable
+				if ( !isResizable && value !== false ) {
+					this._makeResizable( value );
+				}
+				break;
+			case "title":
+				// convert whatever was passed in o a string, for html() to not throw up
+				$( ".ui-dialog-title", this.uiDialogTitlebar )
+					.html( "" + ( value || "&#160;" ) );
+				break;
+		}
+
+		this._super( key, value );
+	},
+
+	_size: function() {
+		/* If the user has resized the dialog, the .ui-dialog and .ui-dialog-content
+		 * divs will both have width and height set, so we need to reset them
+		 */
+		var nonContentHeight, minContentHeight, autoHeight,
+			options = this.options,
+			isVisible = this.uiDialog.is( ":visible" );
+
+		// reset content sizing
+		this.element.show().css({
+			width: "auto",
+			minHeight: 0,
+			height: 0
+		});
+
+		if ( options.minWidth > options.width ) {
+			options.width = options.minWidth;
+		}
+
+		// reset wrapper sizing
+		// determine the height of all the non-content elements
+		nonContentHeight = this.uiDialog.css({
+				height: "auto",
+				width: options.width
+			})
+			.outerHeight();
+		minContentHeight = Math.max( 0, options.minHeight - nonContentHeight );
+
+		if ( options.height === "auto" ) {
+			// only needed for IE6 support
+			if ( $.support.minHeight ) {
+				this.element.css({
+					minHeight: minContentHeight,
+					height: "auto"
+				});
+			} else {
+				this.uiDialog.show();
+				autoHeight = this.element.css( "height", "auto" ).height();
+				if ( !isVisible ) {
+					this.uiDialog.hide();
+				}
+				this.element.height( Math.max( autoHeight, minContentHeight ) );
+			}
+		} else {
+			this.element.height( Math.max( options.height - nonContentHeight, 0 ) );
+		}
+
+		if (this.uiDialog.is( ":data(resizable)" ) ) {
+			this.uiDialog.resizable( "option", "minHeight", this._minHeight() );
+		}
+	}
+});
+
+$.extend($.ui.dialog, {
+	uuid: 0,
+	maxZ: 0,
+
+	getTitleId: function($el) {
+		var id = $el.attr( "id" );
+		if ( !id ) {
+			this.uuid += 1;
+			id = this.uuid;
+		}
+		return "ui-dialog-title-" + id;
+	},
+
+	overlay: function( dialog ) {
+		this.$el = $.ui.dialog.overlay.create( dialog );
+	}
+});
+
+$.extend( $.ui.dialog.overlay, {
+	instances: [],
+	// reuse old instances due to IE memory leak with alpha transparency (see #5185)
+	oldInstances: [],
+	maxZ: 0,
+	events: $.map(
+		"focus,mousedown,mouseup,keydown,keypress,click".split( "," ),
+		function( event ) {
+			return event + ".dialog-overlay";
+		}
+	).join( " " ),
+	create: function( dialog ) {
+		if ( this.instances.length === 0 ) {
+			// prevent use of anchors and inputs
+			// we use a setTimeout in case the overlay is created from an
+			// event that we're going to be cancelling (see #2804)
+			setTimeout(function() {
+				// handle $(el).dialog().dialog('close') (see #4065)
+				if ( $.ui.dialog.overlay.instances.length ) {
+					$( document ).bind( $.ui.dialog.overlay.events, function( event ) {
+						// stop events if the z-index of the target is < the z-index of the overlay
+						// we cannot return true when we don't want to cancel the event (#3523)
+						if ( $( event.target ).zIndex() < $.ui.dialog.overlay.maxZ ) {
+							return false;
+						}
+					});
+				}
+			}, 1 );
+
+			// handle window resize
+			$( window ).bind( "resize.dialog-overlay", $.ui.dialog.overlay.resize );
+		}
+
+		var $el = ( this.oldInstances.pop() || $( "<div>" ).addClass( "ui-widget-overlay" ) );
+
+		// allow closing by pressing the escape key
+		$( document ).bind( "keydown.dialog-overlay", function( event ) {
+			var instances = $.ui.dialog.overlay.instances;
+			// only react to the event if we're the top overlay
+			if ( instances.length !== 0 && instances[ instances.length - 1 ] === $el &&
+				dialog.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode &&
+				event.keyCode === $.ui.keyCode.ESCAPE ) {
+
+				dialog.close( event );
+				event.preventDefault();
+			}
+		});
+
+		$el.appendTo( document.body ).css({
+			width: this.width(),
+			height: this.height()
+		});
+
+		if ( $.fn.bgiframe ) {
+			$el.bgiframe();
+		}
+
+		this.instances.push( $el );
+		return $el;
+	},
+
+	destroy: function( $el ) {
+		var indexOf = $.inArray( $el, this.instances ),
+			maxZ = 0;
+
+		if ( indexOf !== -1 ) {
+			this.oldInstances.push( this.instances.splice( indexOf, 1 )[ 0 ] );
+		}
+
+		if ( this.instances.length === 0 ) {
+			$( [ document, window ] ).unbind( ".dialog-overlay" );
+		}
+
+		$el.height( 0 ).width( 0 ).remove();
+
+		// adjust the maxZ to allow other modal dialogs to continue to work (see #4309)
+		$.each( this.instances, function() {
+			maxZ = Math.max( maxZ, this.css( "z-index" ) );
+		});
+		this.maxZ = maxZ;
+	},
+
+	height: function() {
+		var scrollHeight,
+			offsetHeight;
+		// handle IE
+		if ( $.ui.ie ) {
+			scrollHeight = Math.max(
+				document.documentElement.scrollHeight,
+				document.body.scrollHeight
+			);
+			offsetHeight = Math.max(
+				document.documentElement.offsetHeight,
+				document.body.offsetHeight
+			);
+
+			if ( scrollHeight < offsetHeight ) {
+				return $( window ).height() + "px";
+			} else {
+				return scrollHeight + "px";
+			}
+		// handle "good" browsers
+		} else {
+			return $( document ).height() + "px";
+		}
+	},
+
+	width: function() {
+		var scrollWidth,
+			offsetWidth;
+		// handle IE
+		if ( $.ui.ie ) {
+			scrollWidth = Math.max(
+				document.documentElement.scrollWidth,
+				document.body.scrollWidth
+			);
+			offsetWidth = Math.max(
+				document.documentElement.offsetWidth,
+				document.body.offsetWidth
+			);
+
+			if ( scrollWidth < offsetWidth ) {
+				return $( window ).width() + "px";
+			} else {
+				return scrollWidth + "px";
+			}
+		// handle "good" browsers
+		} else {
+			return $( document ).width() + "px";
+		}
+	},
+
+	resize: function() {
+		/* If the dialog is draggable and the user drags it past the
+		 * right edge of the window, the document becomes wider so we
+		 * need to stretch the overlay. If the user then drags the
+		 * dialog back to the left, the document will become narrower,
+		 * so we need to shrink the overlay to the appropriate size.
+		 * This is handled by shrinking the overlay before setting it
+		 * to the full document size.
+		 */
+		var $overlays = $( [] );
+		$.each( $.ui.dialog.overlay.instances, function() {
+			$overlays = $overlays.add( this );
+		});
+
+		$overlays.css({
+			width: 0,
+			height: 0
+		}).css({
+			width: $.ui.dialog.overlay.width(),
+			height: $.ui.dialog.overlay.height()
+		});
+	}
+});
+
+$.extend( $.ui.dialog.overlay.prototype, {
+	destroy: function() {
+		$.ui.dialog.overlay.destroy( this.$el );
+	}
+});
+
+}( jQuery ) );
+
+(function( $, undefined ) {
+
+var rvertical = /up|down|vertical/,
+	rpositivemotion = /up|left|vertical|horizontal/;
+
+$.effects.effect.blind = function( o, done ) {
+	// Create element
+	var el = $( this ),
+		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
+		mode = $.effects.setMode( el, o.mode || "hide" ),
+		direction = o.direction || "up",
+		vertical = rvertical.test( direction ),
+		ref = vertical ? "height" : "width",
+		ref2 = vertical ? "top" : "left",
+		motion = rpositivemotion.test( direction ),
+		animation = {},
+		show = mode === "show",
+		wrapper, distance, margin;
+
+	// if already wrapped, the wrapper's properties are my property. #6245
+	if ( el.parent().is( ".ui-effects-wrapper" ) ) {
+		$.effects.save( el.parent(), props );
+	} else {
+		$.effects.save( el, props );
+	}
+	el.show();
+	wrapper = $.effects.createWrapper( el ).css({
+		overflow: "hidden"
+	});
+
+	distance = wrapper[ ref ]();
+	margin = parseFloat( wrapper.css( ref2 ) ) || 0;
+
+	animation[ ref ] = show ? distance : 0;
+	if ( !motion ) {
+		el
+			.css( vertical ? "bottom" : "right", 0 )
+			.css( vertical ? "top" : "left", "auto" )
+			.css({ position: "absolute" });
+
+		animation[ ref2 ] = show ? margin : distance + margin;
+	}
+
+	// start at 0 if we are showing
+	if ( show ) {
+		wrapper.css( ref, 0 );
+		if ( ! motion ) {
+			wrapper.css( ref2, margin + distance );
+		}
+	}
+
+	// Animate
+	wrapper.animate( animation, {
+		duration: o.duration,
+		easing: o.easing,
+		queue: false,
+		complete: function() {
+			if ( mode === "hide" ) {
+				el.hide();
+			}
+			$.effects.restore( el, props );
+			$.effects.removeWrapper( el );
+			done();
+		}
+	});
+
+};
+
+})(jQuery);
+
+(function( $, undefined ) {
+
+$.effects.effect.bounce = function( o, done ) {
+	var el = $( this ),
+		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
+
+		// defaults:
+		mode = $.effects.setMode( el, o.mode || "effect" ),
+		hide = mode === "hide",
+		show = mode === "show",
+		direction = o.direction || "up",
+		distance = o.distance,
+		times = o.times || 5,
+
+		// number of internal animations
+		anims = times * 2 + ( show || hide ? 1 : 0 ),
+		speed = o.duration / anims,
+		easing = o.easing,
+
+		// utility:
+		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
+		motion = ( direction === "up" || direction === "left" ),
+		i,
+		upAnim,
+		downAnim,
+
+		// we will need to re-assemble the queue to stack our animations in place
+		queue = el.queue(),
+		queuelen = queue.length;
+
+	// Avoid touching opacity to prevent clearType and PNG issues in IE
+	if ( show || hide ) {
+		props.push( "opacity" );
+	}
+
+	$.effects.save( el, props );
+	el.show();
+	$.effects.createWrapper( el ); // Create Wrapper
+
+	// default distance for the BIGGEST bounce is the outer Distance / 3
+	if ( !distance ) {
+		distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3;
+	}
+
+	if ( show ) {
+		downAnim = { opacity: 1 };
+		downAnim[ ref ] = 0;
+
+		// if we are showing, force opacity 0 and set the initial position
+		// then do the "first" animation
+		el.css( "opacity", 0 )
+			.css( ref, motion ? -distance * 2 : distance * 2 )
+			.animate( downAnim, speed, easing );
+	}
+
+	// start at the smallest distance if we are hiding
+	if ( hide ) {
+		distance = distance / Math.pow( 2, times - 1 );
+	}
+
+	downAnim = {};
+	downAnim[ ref ] = 0;
+	// Bounces up/down/left/right then back to 0 -- times * 2 animations happen here
+	for ( i = 0; i < times; i++ ) {
+		upAnim = {};
+		upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;
+
+		el.animate( upAnim, speed, easing )
+			.animate( downAnim, speed, easing );
+
+		distance = hide ? distance * 2 : distance / 2;
+	}
+
+	// Last Bounce when Hiding
+	if ( hide ) {
+		upAnim = { opacity: 0 };
+		upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance;
+
+		el.animate( upAnim, speed, easing );
+	}
+
+	el.queue(function() {
+		if ( hide ) {
+			el.hide();
+		}
+		$.effects.restore( el, props );
+		$.effects.removeWrapper( el );
+		done();
+	});
+
+	// inject all the animations we just queued to be first in line (after "inprogress")
+	if ( queuelen > 1) {
+		queue.splice.apply( queue,
+			[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
+	}
+	el.dequeue();
+
+};
+
+})(jQuery);
+
+(function( $, undefined ) {
+
+$.effects.effect.clip = function( o, done ) {
+	// Create element
+	var el = $( this ),
+		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
+		mode = $.effects.setMode( el, o.mode || "hide" ),
+		show = mode === "show",
+		direction = o.direction || "vertical",
+		vert = direction === "vertical",
+		size = vert ? "height" : "width",
+		position = vert ? "top" : "left",
+		animation = {},
+		wrapper, animate, distance;
+
+	// Save & Show
+	$.effects.save( el, props );
+	el.show();
+
+	// Create Wrapper
+	wrapper = $.effects.createWrapper( el ).css({
+		overflow: "hidden"
+	});
+	animate = ( el[0].tagName === "IMG" ) ? wrapper : el;
+	distance = animate[ size ]();
+
+	// Shift
+	if ( show ) {
+		animate.css( size, 0 );
+		animate.css( position, distance / 2 );
+	}
+
+	// Create Animation Object:
+	animation[ size ] = show ? distance : 0;
+	animation[ position ] = show ? 0 : distance / 2;
+
+	// Animate
+	animate.animate( animation, {
+		queue: false,
+		duration: o.duration,
+		easing: o.easing,
+		complete: function() {
+			if ( !show ) {
+				el.hide();
+			}
+			$.effects.restore( el, props );
+			$.effects.removeWrapper( el );
+			done();
+		}
+	});
+
+};
+
+})(jQuery);
+
+(function( $, undefined ) {
+
+$.effects.effect.drop = function( o, done ) {
+
+	var el = $( this ),
+		props = [ "position", "top", "bottom", "left", "right", "opacity", "height", "width" ],
+		mode = $.effects.setMode( el, o.mode || "hide" ),
+		show = mode === "show",
+		direction = o.direction || "left",
+		ref = ( direction === "up" || direction === "down" ) ? "top" : "left",
+		motion = ( direction === "up" || direction === "left" ) ? "pos" : "neg",
+		animation = {
+			opacity: show ? 1 : 0
+		},
+		distance;
+
+	// Adjust
+	$.effects.save( el, props );
+	el.show();
+	$.effects.createWrapper( el );
+
+	distance = o.distance || el[ ref === "top" ? "outerHeight": "outerWidth" ]( true ) / 2;
+
+	if ( show ) {
+		el
+			.css( "opacity", 0 )
+			.css( ref, motion === "pos" ? -distance : distance );
+	}
+
+	// Animation
+	animation[ ref ] = ( show ?
+		( motion === "pos" ? "+=" : "-=" ) :
+		( motion === "pos" ? "-=" : "+=" ) ) +
+		distance;
+
+	// Animate
+	el.animate( animation, {
+		queue: false,
+		duration: o.duration,
+		easing: o.easing,
+		complete: function() {
+			if ( mode === "hide" ) {
+				el.hide();
+			}
+			$.effects.restore( el, props );
+			$.effects.removeWrapper( el );
+			done();
+		}
+	});
+};
+
+})(jQuery);
+
+(function( $, undefined ) {
+
+$.effects.effect.explode = function( o, done ) {
+
+	var rows = o.pieces ? Math.round( Math.sqrt( o.pieces ) ) : 3,
+		cells = rows,
+		el = $( this ),
+		mode = $.effects.setMode( el, o.mode || "hide" ),
+		show = mode === "show",
+
+		// show and then visibility:hidden the element before calculating offset
+		offset = el.show().css( "visibility", "hidden" ).offset(),
+
+		// width and height of a piece
+		width = Math.ceil( el.outerWidth() / cells ),
+		height = Math.ceil( el.outerHeight() / rows ),
+		pieces = [],
+
+		// loop
+		i, j, left, top, mx, my;
+
+	// children animate complete:
+	function childComplete() {
+		pieces.push( this );
+		if ( pieces.length === rows * cells ) {
+			animComplete();
+		}
+	}
+
+	// clone the element for each row and cell.
+	for( i = 0; i < rows ; i++ ) { // ===>
+		top = offset.top + i * height;
+		my = i - ( rows - 1 ) / 2 ;
+
+		for( j = 0; j < cells ; j++ ) { // |||
+			left = offset.left + j * width;
+			mx = j - ( cells - 1 ) / 2 ;
+
+			// Create a clone of the now hidden main element that will be absolute positioned
+			// within a wrapper div off the -left and -top equal to size of our pieces
+			el
+				.clone()
+				.appendTo( "body" )
+				.wrap( "<div></div>" )
+				.css({
+					position: "absolute",
+					visibility: "visible",
+					left: -j * width,
+					top: -i * height
+				})
+
+			// select the wrapper - make it overflow: hidden and absolute positioned based on
+			// where the original was located +left and +top equal to the size of pieces
+				.parent()
+				.addClass( "ui-effects-explode" )
+				.css({
+					position: "absolute",
+					overflow: "hidden",
+					width: width,
+					height: height,
+					left: left + ( show ? mx * width : 0 ),
+					top: top + ( show ? my * height : 0 ),
+					opacity: show ? 0 : 1
+				}).animate({
+					left: left + ( show ? 0 : mx * width ),
+					top: top + ( show ? 0 : my * height ),
+					opacity: show ? 1 : 0
+				}, o.duration || 500, o.easing, childComplete );
+		}
+	}
+
+	function animComplete() {
+		el.css({
+			visibility: "visible"
+		});
+		$( pieces ).remove();
+		if ( !show ) {
+			el.hide();
+		}
+		done();
+	}
+};
+
+})(jQuery);
+
+(function( $, undefined ) {
+
+$.effects.effect.fade = function( o, done ) {
+	var el = $( this ),
+		mode = $.effects.setMode( el, o.mode || "toggle" );
+
+	el.animate({
+		opacity: mode
+	}, {
+		queue: false,
+		duration: o.duration,
+		easing: o.easing,
+		complete: done
+	});
+};
+
+})( jQuery );
+
+(function( $, undefined ) {
+
+$.effects.effect.fold = function( o, done ) {
+
+	// Create element
+	var el = $( this ),
+		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
+		mode = $.effects.setMode( el, o.mode || "hide" ),
+		show = mode === "show",
+		hide = mode === "hide",
+		size = o.size || 15,
+		percent = /([0-9]+)%/.exec( size ),
+		horizFirst = !!o.horizFirst,
+		widthFirst = show !== horizFirst,
+		ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ],
+		duration = o.duration / 2,
+		wrapper, distance,
+		animation1 = {},
+		animation2 = {};
+
+	$.effects.save( el, props );
+	el.show();
+
+	// Create Wrapper
+	wrapper = $.effects.createWrapper( el ).css({
+		overflow: "hidden"
+	});
+	distance = widthFirst ?
+		[ wrapper.width(), wrapper.height() ] :
+		[ wrapper.height(), wrapper.width() ];
+
+	if ( percent ) {
+		size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ];
+	}
+	if ( show ) {
+		wrapper.css( horizFirst ? {
+			height: 0,
+			width: size
+		} : {
+			height: size,
+			width: 0
+		});
+	}
+
+	// Animation
+	animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size;
+	animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0;
+
+	// Animate
+	wrapper
+		.animate( animation1, duration, o.easing )
+		.animate( animation2, duration, o.easing, function() {
+			if ( hide ) {
+				el.hide();
+			}
+			$.effects.restore( el, props );
+			$.effects.removeWrapper( el );
+			done();
+		});
+
+};
+
+})(jQuery);
+
+(function( $, undefined ) {
+
+$.effects.effect.highlight = function( o, done ) {
+	var elem = $( this ),
+		props = [ "backgroundImage", "backgroundColor", "opacity" ],
+		mode = $.effects.setMode( elem, o.mode || "show" ),
+		animation = {
+			backgroundColor: elem.css( "backgroundColor" )
+		};
+
+	if (mode === "hide") {
+		animation.opacity = 0;
+	}
+
+	$.effects.save( elem, props );
+
+	elem
+		.show()
+		.css({
+			backgroundImage: "none",
+			backgroundColor: o.color || "#ffff99"
+		})
+		.animate( animation, {
+			queue: false,
+			duration: o.duration,
+			easing: o.easing,
+			complete: function() {
+				if ( mode === "hide" ) {
+					elem.hide();
+				}
+				$.effects.restore( elem, props );
+				done();
+			}
+		});
+};
+
+})(jQuery);
+
+(function( $, undefined ) {
+
+$.effects.effect.pulsate = function( o, done ) {
+	var elem = $( this ),
+		mode = $.effects.setMode( elem, o.mode || "show" ),
+		show = mode === "show",
+		hide = mode === "hide",
+		showhide = ( show || mode === "hide" ),
+
+		// showing or hiding leaves of the "last" animation
+		anims = ( ( o.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ),
+		duration = o.duration / anims,
+		animateTo = 0,
+		queue = elem.queue(),
+		queuelen = queue.length,
+		i;
+
+	if ( show || !elem.is(":visible")) {
+		elem.css( "opacity", 0 ).show();
+		animateTo = 1;
+	}
+
+	// anims - 1 opacity "toggles"
+	for ( i = 1; i < anims; i++ ) {
+		elem.animate({
+			opacity: animateTo
+		}, duration, o.easing );
+		animateTo = 1 - animateTo;
+	}
+
+	elem.animate({
+		opacity: animateTo
+	}, duration, o.easing);
+
+	elem.queue(function() {
+		if ( hide ) {
+			elem.hide();
+		}
+		done();
+	});
+
+	// We just queued up "anims" animations, we need to put them next in the queue
+	if ( queuelen > 1 ) {
+		queue.splice.apply( queue,
+			[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
+	}
+	elem.dequeue();
+};
+
+})(jQuery);
+
+(function( $, undefined ) {
+
+$.effects.effect.puff = function( o, done ) {
+	var elem = $( this ),
+		mode = $.effects.setMode( elem, o.mode || "hide" ),
+		hide = mode === "hide",
+		percent = parseInt( o.percent, 10 ) || 150,
+		factor = percent / 100,
+		original = {
+			height: elem.height(),
+			width: elem.width(),
+			outerHeight: elem.outerHeight(),
+			outerWidth: elem.outerWidth()
+		};
+
+	$.extend( o, {
+		effect: "scale",
+		queue: false,
+		fade: true,
+		mode: mode,
+		complete: done,
+		percent: hide ? percent : 100,
+		from: hide ?
+			original :
+			{
+				height: original.height * factor,
+				width: original.width * factor,
+				outerHeight: original.outerHeight * factor,
+				outerWidth: original.outerWidth * factor
+			}
+	});
+
+	elem.effect( o );
+};
+
+$.effects.effect.scale = function( o, done ) {
+
+	// Create element
+	var el = $( this ),
+		options = $.extend( true, {}, o ),
+		mode = $.effects.setMode( el, o.mode || "effect" ),
+		percent = parseInt( o.percent, 10 ) ||
+			( parseInt( o.percent, 10 ) === 0 ? 0 : ( mode === "hide" ? 0 : 100 ) ),
+		direction = o.direction || "both",
+		origin = o.origin,
+		original = {
+			height: el.height(),
+			width: el.width(),
+			outerHeight: el.outerHeight(),
+			outerWidth: el.outerWidth()
+		},
+		factor = {
+			y: direction !== "horizontal" ? (percent / 100) : 1,
+			x: direction !== "vertical" ? (percent / 100) : 1
+		};
+
+	// We are going to pass this effect to the size effect:
+	options.effect = "size";
+	options.queue = false;
+	options.complete = done;
+
+	// Set default origin and restore for show/hide
+	if ( mode !== "effect" ) {
+		options.origin = origin || ["middle","center"];
+		options.restore = true;
+	}
+
+	options.from = o.from || ( mode === "show" ? {
+		height: 0,
+		width: 0,
+		outerHeight: 0,
+		outerWidth: 0
+	} : original );
+	options.to = {
+		height: original.height * factor.y,
+		width: original.width * factor.x,
+		outerHeight: original.outerHeight * factor.y,
+		outerWidth: original.outerWidth * factor.x
+	};
+
+	// Fade option to support puff
+	if ( options.fade ) {
+		if ( mode === "show" ) {
+			options.from.opacity = 0;
+			options.to.opacity = 1;
+		}
+		if ( mode === "hide" ) {
+			options.from.opacity = 1;
+			options.to.opacity = 0;
+		}
+	}
+
+	// Animate
+	el.effect( options );
+
+};
+
+$.effects.effect.size = function( o, done ) {
+
+	// Create element
+	var original, baseline, factor,
+		el = $( this ),
+		props0 = [ "position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity" ],
+
+		// Always restore
+		props1 = [ "position", "top", "bottom", "left", "right", "overflow", "opacity" ],
+
+		// Copy for children
+		props2 = [ "width", "height", "overflow" ],
+		cProps = [ "fontSize" ],
+		vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ],
+		hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ],
+
+		// Set options
+		mode = $.effects.setMode( el, o.mode || "effect" ),
+		restore = o.restore || mode !== "effect",
+		scale = o.scale || "both",
+		origin = o.origin || [ "middle", "center" ],
+		position = el.css( "position" ),
+		props = restore ? props0 : props1,
+		zero = {
+			height: 0,
+			width: 0,
+			outerHeight: 0,
+			outerWidth: 0
+		};
+
+	if ( mode === "show" ) {
+		el.show();
+	}
+	original = {
+		height: el.height(),
+		width: el.width(),
+		outerHeight: el.outerHeight(),
+		outerWidth: el.outerWidth()
+	};
+
+	if ( o.mode === "toggle" && mode === "show" ) {
+		el.from = o.to || zero;
+		el.to = o.from || original;
+	} else {
+		el.from = o.from || ( mode === "show" ? zero : original );
+		el.to = o.to || ( mode === "hide" ? zero : original );
+	}
+
+	// Set scaling factor
+	factor = {
+		from: {
+			y: el.from.height / original.height,
+			x: el.from.width / original.width
+		},
+		to: {
+			y: el.to.height / original.height,
+			x: el.to.width / original.width
+		}
+	};
+
+	// Scale the css box
+	if ( scale === "box" || scale === "both" ) {
+
+		// Vertical props scaling
+		if ( factor.from.y !== factor.to.y ) {
+			props = props.concat( vProps );
+			el.from = $.effects.setTransition( el, vProps, factor.from.y, el.from );
+			el.to = $.effects.setTransition( el, vProps, factor.to.y, el.to );
+		}
+
+		// Horizontal props scaling
+		if ( factor.from.x !== factor.to.x ) {
+			props = props.concat( hProps );
+			el.from = $.effects.setTransition( el, hProps, factor.from.x, el.from );
+			el.to = $.effects.setTransition( el, hProps, factor.to.x, el.to );
+		}
+	}
+
+	// Scale the content
+	if ( scale === "content" || scale === "both" ) {
+
+		// Vertical props scaling
+		if ( factor.from.y !== factor.to.y ) {
+			props = props.concat( cProps ).concat( props2 );
+			el.from = $.effects.setTransition( el, cProps, factor.from.y, el.from );
+			el.to = $.effects.setTransition( el, cProps, factor.to.y, el.to );
+		}
+	}
+
+	$.effects.save( el, props );
+	el.show();
+	$.effects.createWrapper( el );
+	el.css( "overflow", "hidden" ).css( el.from );
+
+	// Adjust
+	if (origin) { // Calculate baseline shifts
+		baseline = $.effects.getBaseline( origin, original );
+		el.from.top = ( original.outerHeight - el.outerHeight() ) * baseline.y;
+		el.from.left = ( original.outerWidth - el.outerWidth() ) * baseline.x;
+		el.to.top = ( original.outerHeight - el.to.outerHeight ) * baseline.y;
+		el.to.left = ( original.outerWidth - el.to.outerWidth ) * baseline.x;
+	}
+	el.css( el.from ); // set top & left
+
+	// Animate
+	if ( scale === "content" || scale === "both" ) { // Scale the children
+
+		// Add margins/font-size
+		vProps = vProps.concat([ "marginTop", "marginBottom" ]).concat(cProps);
+		hProps = hProps.concat([ "marginLeft", "marginRight" ]);
+		props2 = props0.concat(vProps).concat(hProps);
+
+		el.find( "*[width]" ).each( function(){
+			var child = $( this ),
+				c_original = {
+					height: child.height(),
+					width: child.width(),
+					outerHeight: child.outerHeight(),
+					outerWidth: child.outerWidth()
+				};
+			if (restore) {
+				$.effects.save(child, props2);
+			}
+
+			child.from = {
+				height: c_original.height * factor.from.y,
+				width: c_original.width * factor.from.x,
+				outerHeight: c_original.outerHeight * factor.from.y,
+				outerWidth: c_original.outerWidth * factor.from.x
+			};
+			child.to = {
+				height: c_original.height * factor.to.y,
+				width: c_original.width * factor.to.x,
+				outerHeight: c_original.height * factor.to.y,
+				outerWidth: c_original.width * factor.to.x
+			};
+
+			// Vertical props scaling
+			if ( factor.from.y !== factor.to.y ) {
+				child.from = $.effects.setTransition( child, vProps, factor.from.y, child.from );
+				child.to = $.effects.setTransition( child, vProps, factor.to.y, child.to );
+			}
+
+			// Horizontal props scaling
+			if ( factor.from.x !== factor.to.x ) {
+				child.from = $.effects.setTransition( child, hProps, factor.from.x, child.from );
+				child.to = $.effects.setTransition( child, hProps, factor.to.x, child.to );
+			}
+
+			// Animate children
+			child.css( child.from );
+			child.animate( child.to, o.duration, o.easing, function() {
+
+				// Restore children
+				if ( restore ) {
+					$.effects.restore( child, props2 );
+				}
+			});
+		});
+	}
+
+	// Animate
+	el.animate( el.to, {
+		queue: false,
+		duration: o.duration,
+		easing: o.easing,
+		complete: function() {
+			if ( el.to.opacity === 0 ) {
+				el.css( "opacity", el.from.opacity );
+			}
+			if( mode === "hide" ) {
+				el.hide();
+			}
+			$.effects.restore( el, props );
+			if ( !restore ) {
+
+				// we need to calculate our new positioning based on the scaling
+				if ( position === "static" ) {
+					el.css({
+						position: "relative",
+						top: el.to.top,
+						left: el.to.left
+					});
+				} else {
+					$.each([ "top", "left" ], function( idx, pos ) {
+						el.css( pos, function( _, str ) {
+							var val = parseInt( str, 10 ),
+								toRef = idx ? el.to.left : el.to.top;
+
+							// if original was "auto", recalculate the new value from wrapper
+							if ( str === "auto" ) {
+								return toRef + "px";
+							}
+
+							return val + toRef + "px";
+						});
+					});
+				}
+			}
+
+			$.effects.removeWrapper( el );
+			done();
+		}
+	});
+
+};
+
+})(jQuery);
+
+(function( $, undefined ) {
+
+$.effects.effect.shake = function( o, done ) {
+
+	var el = $( this ),
+		props = [ "position", "top", "bottom", "left", "right", "height", "width" ],
+		mode = $.effects.setMode( el, o.mode || "effect" ),
+		direction = o.direction || "left",
+		distance = o.distance || 20,
+		times = o.times || 3,
+		anims = times * 2 + 1,
+		speed = Math.round(o.duration/anims),
+		ref = (direction === "up" || direction === "down") ? "top" : "left",
+		positiveMotion = (direction === "up" || direction === "left"),
+		animation = {},
+		animation1 = {},
+		animation2 = {},
+		i,
+
+		// we will need to re-assemble the queue to stack our animations in place
+		queue = el.queue(),
+		queuelen = queue.length;
+
+	$.effects.save( el, props );
+	el.show();
+	$.effects.createWrapper( el );
+
+	// Animation
+	animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance;
+	animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2;
+	animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2;
+
+	// Animate
+	el.animate( animation, speed, o.easing );
+
+	// Shakes
+	for ( i = 1; i < times; i++ ) {
+		el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing );
+	}
+	el
+		.animate( animation1, speed, o.easing )
+		.animate( animation, speed / 2, o.easing )
+		.queue(function() {
+			if ( mode === "hide" ) {
+				el.hide();
+			}
+			$.effects.restore( el, props );
+			$.effects.removeWrapper( el );
+			done();
+		});
+
+	// inject all the animations we just queued to be first in line (after "inprogress")
+	if ( queuelen > 1) {
+		queue.splice.apply( queue,
+			[ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) );
+	}
+	el.dequeue();
+
+};
+
+})(jQuery);
+
+(function( $, undefined ) {
+
+$.effects.effect.slide = function( o, done ) {
+
+	// Create element
+	var el = $( this ),
+		props = [ "position", "top", "bottom", "left", "right", "width", "height" ],
+		mode = $.effects.setMode( el, o.mode || "show" ),
+		show = mode === "show",
+		direction = o.direction || "left",
+		ref = (direction === "up" || direction === "down") ? "top" : "left",
+		positiveMotion = (direction === "up" || direction === "left"),
+		distance,
+		animation = {};
+
+	// Adjust
+	$.effects.save( el, props );
+	el.show();
+	distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true );
+
+	$.effects.createWrapper( el ).css({
+		overflow: "hidden"
+	});
+
+	if ( show ) {
+		el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance );
+	}
+
+	// Animation
+	animation[ ref ] = ( show ?
+		( positiveMotion ? "+=" : "-=") :
+		( positiveMotion ? "-=" : "+=")) +
+		distance;
+
+	// Animate
+	el.animate( animation, {
+		queue: false,
+		duration: o.duration,
+		easing: o.easing,
+		complete: function() {
+			if ( mode === "hide" ) {
+				el.hide();
+			}
+			$.effects.restore( el, props );
+			$.effects.removeWrapper( el );
+			done();
+		}
+	});
+};
+
+})(jQuery);
+
+(function( $, undefined ) {
+
+$.effects.effect.transfer = function( o, done ) {
+	var elem = $( this ),
+		target = $( o.to ),
+		targetFixed = target.css( "position" ) === "fixed",
+		body = $("body"),
+		fixTop = targetFixed ? body.scrollTop() : 0,
+		fixLeft = targetFixed ? body.scrollLeft() : 0,
+		endPosition = target.offset(),
+		animation = {
+			top: endPosition.top - fixTop ,
+			left: endPosition.left - fixLeft ,
+			height: target.innerHeight(),
+			width: target.innerWidth()
+		},
+		startPosition = elem.offset(),
+		transfer = $( '<div class="ui-effects-transfer"></div>' )
+			.appendTo( document.body )
+			.addClass( o.className )
+			.css({
+				top: startPosition.top - fixTop ,
+				left: startPosition.left - fixLeft ,
+				height: elem.innerHeight(),
+				width: elem.innerWidth(),
+				position: targetFixed ? "fixed" : "absolute"
+			})
+			.animate( animation, o.duration, o.easing, function() {
+				transfer.remove();
+				done();
+			});
+};
+
+})(jQuery);
+
+(function( $, undefined ) {
+
+var mouseHandled = false;
+
+$.widget( "ui.menu", {
+	version: "1.9.2",
+	defaultElement: "<ul>",
+	delay: 300,
+	options: {
+		icons: {
+			submenu: "ui-icon-carat-1-e"
+		},
+		menus: "ul",
+		position: {
+			my: "left top",
+			at: "right top"
+		},
+		role: "menu",
+
+		// callbacks
+		blur: null,
+		focus: null,
+		select: null
+	},
+
+	_create: function() {
+		this.activeMenu = this.element;
+		this.element
+			.uniqueId()
+			.addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
+			.toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length )
+			.attr({
+				role: this.options.role,
+				tabIndex: 0
+			})
+			// need to catch all clicks on disabled menu
+			// not possible through _on
+			.bind( "click" + this.eventNamespace, $.proxy(function( event ) {
+				if ( this.options.disabled ) {
+					event.preventDefault();
+				}
+			}, this ));
+
+		if ( this.options.disabled ) {
+			this.element
+				.addClass( "ui-state-disabled" )
+				.attr( "aria-disabled", "true" );
+		}
+
+		this._on({
+			// Prevent focus from sticking to links inside menu after clicking
+			// them (focus should always stay on UL during navigation).
+			"mousedown .ui-menu-item > a": function( event ) {
+				event.preventDefault();
+			},
+			"click .ui-state-disabled > a": function( event ) {
+				event.preventDefault();
+			},
+			"click .ui-menu-item:has(a)": function( event ) {
+				var target = $( event.target ).closest( ".ui-menu-item" );
+				if ( !mouseHandled && target.not( ".ui-state-disabled" ).length ) {
+					mouseHandled = true;
+
+					this.select( event );
+					// Open submenu on click
+					if ( target.has( ".ui-menu" ).length ) {
+						this.expand( event );
+					} else if ( !this.element.is( ":focus" ) ) {
+						// Redirect focus to the menu
+						this.element.trigger( "focus", [ true ] );
+
+						// If the active item is on the top level, let it stay active.
+						// Otherwise, blur the active item since it is no longer visible.
+						if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) {
+							clearTimeout( this.timer );
+						}
+					}
+				}
+			},
+			"mouseenter .ui-menu-item": function( event ) {
+				var target = $( event.currentTarget );
+				// Remove ui-state-active class from siblings of the newly focused menu item
+				// to avoid a jump caused by adjacent elements both having a class with a border
+				target.siblings().children( ".ui-state-active" ).removeClass( "ui-state-active" );
+				this.focus( event, target );
+			},
+			mouseleave: "collapseAll",
+			"mouseleave .ui-menu": "collapseAll",
+			focus: function( event, keepActiveItem ) {
+				// If there's already an active item, keep it active
+				// If not, activate the first item
+				var item = this.active || this.element.children( ".ui-menu-item" ).eq( 0 );
+
+				if ( !keepActiveItem ) {
+					this.focus( event, item );
+				}
+			},
+			blur: function( event ) {
+				this._delay(function() {
+					if ( !$.contains( this.element[0], this.document[0].activeElement ) ) {
+						this.collapseAll( event );
+					}
+				});
+			},
+			keydown: "_keydown"
+		});
+
+		this.refresh();
+
+		// Clicks outside of a menu collapse any open menus
+		this._on( this.document, {
+			click: function( event ) {
+				if ( !$( event.target ).closest( ".ui-menu" ).length ) {
+					this.collapseAll( event );
+				}
+
+				// Reset the mouseHandled flag
+				mouseHandled = false;
+			}
+		});
+	},
+
+	_destroy: function() {
+		// Destroy (sub)menus
+		this.element
+			.removeAttr( "aria-activedescendant" )
+			.find( ".ui-menu" ).andSelf()
+				.removeClass( "ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons" )
+				.removeAttr( "role" )
+				.removeAttr( "tabIndex" )
+				.removeAttr( "aria-labelledby" )
+				.removeAttr( "aria-expanded" )
+				.removeAttr( "aria-hidden" )
+				.removeAttr( "aria-disabled" )
+				.removeUniqueId()
+				.show();
+
+		// Destroy menu items
+		this.element.find( ".ui-menu-item" )
+			.removeClass( "ui-menu-item" )
+			.removeAttr( "role" )
+			.removeAttr( "aria-disabled" )
+			.children( "a" )
+				.removeUniqueId()
+				.removeClass( "ui-corner-all ui-state-hover" )
+				.removeAttr( "tabIndex" )
+				.removeAttr( "role" )
+				.removeAttr( "aria-haspopup" )
+				.children().each( function() {
+					var elem = $( this );
+					if ( elem.data( "ui-menu-submenu-carat" ) ) {
+						elem.remove();
+					}
+				});
+
+		// Destroy menu dividers
+		this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" );
+	},
+
+	_keydown: function( event ) {
+		var match, prev, character, skip, regex,
+			preventDefault = true;
+
+		function escape( value ) {
+			return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" );
+		}
+
+		switch ( event.keyCode ) {
+		case $.ui.keyCode.PAGE_UP:
+			this.previousPage( event );
+			break;
+		case $.ui.keyCode.PAGE_DOWN:
+			this.nextPage( event );
+			break;
+		case $.ui.keyCode.HOME:
+			this._move( "first", "first", event );
+			break;
+		case $.ui.keyCode.END:
+			this._move( "last", "last", event );
+			break;
+		case $.ui.keyCode.UP:
+			this.previous( event );
+			break;
+		case $.ui.keyCode.DOWN:
+			this.next( event );
+			break;
+		case $.ui.keyCode.LEFT:
+			this.collapse( event );
+			break;
+		case $.ui.keyCode.RIGHT:
+			if ( this.active && !this.active.is( ".ui-state-disabled" ) ) {
+				this.expand( event );
+			}
+			break;
+		case $.ui.keyCode.ENTER:
+		case $.ui.keyCode.SPACE:
+			this._activate( event );
+			break;
+		case $.ui.keyCode.ESCAPE:
+			this.collapse( event );
+			break;
+		default:
+			preventDefault = false;
+			prev = this.previousFilter || "";
+			character = String.fromCharCode( event.keyCode );
+			skip = false;
+
+			clearTimeout( this.filterTimer );
+
+			if ( character === prev ) {
+				skip = true;
+			} else {
+				character = prev + character;
+			}
+
+			regex = new RegExp( "^" + escape( character ), "i" );
+			match = this.activeMenu.children( ".ui-menu-item" ).filter(function() {
+				return regex.test( $( this ).children( "a" ).text() );
+			});
+			match = skip && match.index( this.active.next() ) !== -1 ?
+				this.active.nextAll( ".ui-menu-item" ) :
+				match;
+
+			// If no matches on the current filter, reset to the last character pressed
+			// to move down the menu to the first item that starts with that character
+			if ( !match.length ) {
+				character = String.fromCharCode( event.keyCode );
+				regex = new RegExp( "^" + escape( character ), "i" );
+				match = this.activeMenu.children( ".ui-menu-item" ).filter(function() {
+					return regex.test( $( this ).children( "a" ).text() );
+				});
+			}
+
+			if ( match.length ) {
+				this.focus( event, match );
+				if ( match.length > 1 ) {
+					this.previousFilter = character;
+					this.filterTimer = this._delay(function() {
+						delete this.previousFilter;
+					}, 1000 );
+				} else {
+					delete this.previousFilter;
+				}
+			} else {
+				delete this.previousFilter;
+			}
+		}
+
+		if ( preventDefault ) {
+			event.preventDefault();
+		}
+	},
+
+	_activate: function( event ) {
+		if ( !this.active.is( ".ui-state-disabled" ) ) {
+			if ( this.active.children( "a[aria-haspopup='true']" ).length ) {
+				this.expand( event );
+			} else {
+				this.select( event );
+			}
+		}
+	},
+
+	refresh: function() {
+		var menus,
+			icon = this.options.icons.submenu,
+			submenus = this.element.find( this.options.menus );
+
+		// Initialize nested menus
+		submenus.filter( ":not(.ui-menu)" )
+			.addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
+			.hide()
+			.attr({
+				role: this.options.role,
+				"aria-hidden": "true",
+				"aria-expanded": "false"
+			})
+			.each(function() {
+				var menu = $( this ),
+					item = menu.prev( "a" ),
+					submenuCarat = $( "<span>" )
+						.addClass( "ui-menu-icon ui-icon " + icon )
+						.data( "ui-menu-submenu-carat", true );
+
+				item
+					.attr( "aria-haspopup", "true" )
+					.prepend( submenuCarat );
+				menu.attr( "aria-labelledby", item.attr( "id" ) );
+			});
+
+		menus = submenus.add( this.element );
+
+		// Don't refresh list items that are already adapted
+		menus.children( ":not(.ui-menu-item):has(a)" )
+			.addClass( "ui-menu-item" )
+			.attr( "role", "presentation" )
+			.children( "a" )
+				.uniqueId()
+				.addClass( "ui-corner-all" )
+				.attr({
+					tabIndex: -1,
+					role: this._itemRole()
+				});
+
+		// Initialize unlinked menu-items containing spaces and/or dashes only as dividers
+		menus.children( ":not(.ui-menu-item)" ).each(function() {
+			var item = $( this );
+			// hyphen, em dash, en dash
+			if ( !/[^\-—–\s]/.test( item.text() ) ) {
+				item.addClass( "ui-widget-content ui-menu-divider" );
+			}
+		});
+
+		// Add aria-disabled attribute to any disabled menu item
+		menus.children( ".ui-state-disabled" ).attr( "aria-disabled", "true" );
+
+		// If the active item has been removed, blur the menu
+		if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) {
+			this.blur();
+		}
+	},
+
+	_itemRole: function() {
+		return {
+			menu: "menuitem",
+			listbox: "option"
+		}[ this.options.role ];
+	},
+
+	focus: function( event, item ) {
+		var nested, focused;
+		this.blur( event, event && event.type === "focus" );
+
+		this._scrollIntoView( item );
+
+		this.active = item.first();
+		focused = this.active.children( "a" ).addClass( "ui-state-focus" );
+		// Only update aria-activedescendant if there's a role
+		// otherwise we assume focus is managed elsewhere
+		if ( this.options.role ) {
+			this.element.attr( "aria-activedescendant", focused.attr( "id" ) );
+		}
+
+		// Highlight active parent menu item, if any
+		this.active
+			.parent()
+			.closest( ".ui-menu-item" )
+			.children( "a:first" )
+			.addClass( "ui-state-active" );
+
+		if ( event && event.type === "keydown" ) {
+			this._close();
+		} else {
+			this.timer = this._delay(function() {
+				this._close();
+			}, this.delay );
+		}
+
+		nested = item.children( ".ui-menu" );
+		if ( nested.length && ( /^mouse/.test( event.type ) ) ) {
+			this._startOpening(nested);
+		}
+		this.activeMenu = item.parent();
+
+		this._trigger( "focus", event, { item: item } );
+	},
+
+	_scrollIntoView: function( item ) {
+		var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
+		if ( this._hasScroll() ) {
+			borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0;
+			paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0;
+			offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
+			scroll = this.activeMenu.scrollTop();
+			elementHeight = this.activeMenu.height();
+			itemHeight = item.height();
+
+			if ( offset < 0 ) {
+				this.activeMenu.scrollTop( scroll + offset );
+			} else if ( offset + itemHeight > elementHeight ) {
+				this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
+			}
+		}
+	},
+
+	blur: function( event, fromFocus ) {
+		if ( !fromFocus ) {
+			clearTimeout( this.timer );
+		}
+
+		if ( !this.active ) {
+			return;
+		}
+
+		this.active.children( "a" ).removeClass( "ui-state-focus" );
+		this.active = null;
+
+		this._trigger( "blur", event, { item: this.active } );
+	},
+
+	_startOpening: function( submenu ) {
+		clearTimeout( this.timer );
+
+		// Don't open if already open fixes a Firefox bug that caused a .5 pixel
+		// shift in the submenu position when mousing over the carat icon
+		if ( submenu.attr( "aria-hidden" ) !== "true" ) {
+			return;
+		}
+
+		this.timer = this._delay(function() {
+			this._close();
+			this._open( submenu );
+		}, this.delay );
+	},
+
+	_open: function( submenu ) {
+		var position = $.extend({
+			of: this.active
+		}, this.options.position );
+
+		clearTimeout( this.timer );
+		this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) )
+			.hide()
+			.attr( "aria-hidden", "true" );
+
+		submenu
+			.show()
+			.removeAttr( "aria-hidden" )
+			.attr( "aria-expanded", "true" )
+			.position( position );
+	},
+
+	collapseAll: function( event, all ) {
+		clearTimeout( this.timer );
+		this.timer = this._delay(function() {
+			// If we were passed an event, look for the submenu that contains the event
+			var currentMenu = all ? this.element :
+				$( event && event.target ).closest( this.element.find( ".ui-menu" ) );
+
+			// If we found no valid submenu ancestor, use the main menu to close all sub menus anyway
+			if ( !currentMenu.length ) {
+				currentMenu = this.element;
+			}
+
+			this._close( currentMenu );
+
+			this.blur( event );
+			this.activeMenu = currentMenu;
+		}, this.delay );
+	},
+
+	// With no arguments, closes the currently active menu - if nothing is active
+	// it closes all menus.  If passed an argument, it will search for menus BELOW
+	_close: function( startMenu ) {
+		if ( !startMenu ) {
+			startMenu = this.active ? this.active.parent() : this.element;
+		}
+
+		startMenu
+			.find( ".ui-menu" )
+				.hide()
+				.attr( "aria-hidden", "true" )
+				.attr( "aria-expanded", "false" )
+			.end()
+			.find( "a.ui-state-active" )
+				.removeClass( "ui-state-active" );
+	},
+
+	collapse: function( event ) {
+		var newItem = this.active &&
+			this.active.parent().closest( ".ui-menu-item", this.element );
+		if ( newItem && newItem.length ) {
+			this._close();
+			this.focus( event, newItem );
+		}
+	},
+
+	expand: function( event ) {
+		var newItem = this.active &&
+			this.active
+				.children( ".ui-menu " )
+				.children( ".ui-menu-item" )
+				.first();
+
+		if ( newItem && newItem.length ) {
+			this._open( newItem.parent() );
+
+			// Delay so Firefox will not hide activedescendant change in expanding submenu from AT
+			this._delay(function() {
+				this.focus( event, newItem );
+			});
+		}
+	},
+
+	next: function( event ) {
+		this._move( "next", "first", event );
+	},
+
+	previous: function( event ) {
+		this._move( "prev", "last", event );
+	},
+
+	isFirstItem: function() {
+		return this.active && !this.active.prevAll( ".ui-menu-item" ).length;
+	},
+
+	isLastItem: function() {
+		return this.active && !this.active.nextAll( ".ui-menu-item" ).length;
+	},
+
+	_move: function( direction, filter, event ) {
+		var next;
+		if ( this.active ) {
+			if ( direction === "first" || direction === "last" ) {
+				next = this.active
+					[ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" )
+					.eq( -1 );
+			} else {
+				next = this.active
+					[ direction + "All" ]( ".ui-menu-item" )
+					.eq( 0 );
+			}
+		}
+		if ( !next || !next.length || !this.active ) {
+			next = this.activeMenu.children( ".ui-menu-item" )[ filter ]();
+		}
+
+		this.focus( event, next );
+	},
+
+	nextPage: function( event ) {
+		var item, base, height;
+
+		if ( !this.active ) {
+			this.next( event );
+			return;
+		}
+		if ( this.isLastItem() ) {
+			return;
+		}
+		if ( this._hasScroll() ) {
+			base = this.active.offset().top;
+			height = this.element.height();
+			this.active.nextAll( ".ui-menu-item" ).each(function() {
+				item = $( this );
+				return item.offset().top - base - height < 0;
+			});
+
+			this.focus( event, item );
+		} else {
+			this.focus( event, this.activeMenu.children( ".ui-menu-item" )
+				[ !this.active ? "first" : "last" ]() );
+		}
+	},
+
+	previousPage: function( event ) {
+		var item, base, height;
+		if ( !this.active ) {
+			this.next( event );
+			return;
+		}
+		if ( this.isFirstItem() ) {
+			return;
+		}
+		if ( this._hasScroll() ) {
+			base = this.active.offset().top;
+			height = this.element.height();
+			this.active.prevAll( ".ui-menu-item" ).each(function() {
+				item = $( this );
+				return item.offset().top - base + height > 0;
+			});
+
+			this.focus( event, item );
+		} else {
+			this.focus( event, this.activeMenu.children( ".ui-menu-item" ).first() );
+		}
+	},
+
+	_hasScroll: function() {
+		return this.element.outerHeight() < this.element.prop( "scrollHeight" );
+	},
+
+	select: function( event ) {
+		// TODO: It should never be possible to not have an active item at this
+		// point, but the tests don't trigger mouseenter before click.
+		this.active = this.active || $( event.target ).closest( ".ui-menu-item" );
+		var ui = { item: this.active };
+		if ( !this.active.has( ".ui-menu" ).length ) {
+			this.collapseAll( event, true );
+		}
+		this._trigger( "select", event, ui );
+	}
+});
+
+}( jQuery ));
+
+(function( $, undefined ) {
+
+$.ui = $.ui || {};
+
+var cachedScrollbarWidth,
+	max = Math.max,
+	abs = Math.abs,
+	round = Math.round,
+	rhorizontal = /left|center|right/,
+	rvertical = /top|center|bottom/,
+	roffset = /[\+\-]\d+%?/,
+	rposition = /^\w+/,
+	rpercent = /%$/,
+	_position = $.fn.position;
+
+function getOffsets( offsets, width, height ) {
+	return [
+		parseInt( offsets[ 0 ], 10 ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ),
+		parseInt( offsets[ 1 ], 10 ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 )
+	];
+}
+function parseCss( element, property ) {
+	return parseInt( $.css( element, property ), 10 ) || 0;
+}
+
+$.position = {
+	scrollbarWidth: function() {
+		if ( cachedScrollbarWidth !== undefined ) {
+			return cachedScrollbarWidth;
+		}
+		var w1, w2,
+			div = $( "<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ),
+			innerDiv = div.children()[0];
+
+		$( "body" ).append( div );
+		w1 = innerDiv.offsetWidth;
+		div.css( "overflow", "scroll" );
+
+		w2 = innerDiv.offsetWidth;
+
+		if ( w1 === w2 ) {
+			w2 = div[0].clientWidth;
+		}
+
+		div.remove();
+
+		return (cachedScrollbarWidth = w1 - w2);
+	},
+	getScrollInfo: function( within ) {
+		var overflowX = within.isWindow ? "" : within.element.css( "overflow-x" ),
+			overflowY = within.isWindow ? "" : within.element.css( "overflow-y" ),
+			hasOverflowX = overflowX === "scroll" ||
+				( overflowX === "auto" && within.width < within.element[0].scrollWidth ),
+			hasOverflowY = overflowY === "scroll" ||
+				( overflowY === "auto" && within.height < within.element[0].scrollHeight );
+		return {
+			width: hasOverflowX ? $.position.scrollbarWidth() : 0,
+			height: hasOverflowY ? $.position.scrollbarWidth() : 0
+		};
+	},
+	getWithinInfo: function( element ) {
+		var withinElement = $( element || window ),
+			isWindow = $.isWindow( withinElement[0] );
+		return {
+			element: withinElement,
+			isWindow: isWindow,
+			offset: withinElement.offset() || { left: 0, top: 0 },
+			scrollLeft: withinElement.scrollLeft(),
+			scrollTop: withinElement.scrollTop(),
+			width: isWindow ? withinElement.width() : withinElement.outerWidth(),
+			height: isWindow ? withinElement.height() : withinElement.outerHeight()
+		};
+	}
+};
+
+$.fn.position = function( options ) {
+	if ( !options || !options.of ) {
+		return _position.apply( this, arguments );
+	}
+
+	// make a copy, we don't want to modify arguments
+	options = $.extend( {}, options );
+
+	var atOffset, targetWidth, targetHeight, targetOffset, basePosition,
+		target = $( options.of ),
+		within = $.position.getWithinInfo( options.within ),
+		scrollInfo = $.position.getScrollInfo( within ),
+		targetElem = target[0],
+		collision = ( options.collision || "flip" ).split( " " ),
+		offsets = {};
+
+	if ( targetElem.nodeType === 9 ) {
+		targetWidth = target.width();
+		targetHeight = target.height();
+		targetOffset = { top: 0, left: 0 };
+	} else if ( $.isWindow( targetElem ) ) {
+		targetWidth = target.width();
+		targetHeight = target.height();
+		targetOffset = { top: target.scrollTop(), left: target.scrollLeft() };
+	} else if ( targetElem.preventDefault ) {
+		// force left top to allow flipping
+		options.at = "left top";
+		targetWidth = targetHeight = 0;
+		targetOffset = { top: targetElem.pageY, left: targetElem.pageX };
+	} else {
+		targetWidth = target.outerWidth();
+		targetHeight = target.outerHeight();
+		targetOffset = target.offset();
+	}
+	// clone to reuse original targetOffset later
+	basePosition = $.extend( {}, targetOffset );
+
+	// force my and at to have valid horizontal and vertical positions
+	// if a value is missing or invalid, it will be converted to center
+	$.each( [ "my", "at" ], function() {
+		var pos = ( options[ this ] || "" ).split( " " ),
+			horizontalOffset,
+			verticalOffset;
+
+		if ( pos.length === 1) {
+			pos = rhorizontal.test( pos[ 0 ] ) ?
+				pos.concat( [ "center" ] ) :
+				rvertical.test( pos[ 0 ] ) ?
+					[ "center" ].concat( pos ) :
+					[ "center", "center" ];
+		}
+		pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center";
+		pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center";
+
+		// calculate offsets
+		horizontalOffset = roffset.exec( pos[ 0 ] );
+		verticalOffset = roffset.exec( pos[ 1 ] );
+		offsets[ this ] = [
+			horizontalOffset ? horizontalOffset[ 0 ] : 0,
+			verticalOffset ? verticalOffset[ 0 ] : 0
+		];
+
+		// reduce to just the positions without the offsets
+		options[ this ] = [
+			rposition.exec( pos[ 0 ] )[ 0 ],
+			rposition.exec( pos[ 1 ] )[ 0 ]
+		];
+	});
+
+	// normalize collision option
+	if ( collision.length === 1 ) {
+		collision[ 1 ] = collision[ 0 ];
+	}
+
+	if ( options.at[ 0 ] === "right" ) {
+		basePosition.left += targetWidth;
+	} else if ( options.at[ 0 ] === "center" ) {
+		basePosition.left += targetWidth / 2;
+	}
+
+	if ( options.at[ 1 ] === "bottom" ) {
+		basePosition.top += targetHeight;
+	} else if ( options.at[ 1 ] === "center" ) {
+		basePosition.top += targetHeight / 2;
+	}
+
+	atOffset = getOffsets( offsets.at, targetWidth, targetHeight );
+	basePosition.left += atOffset[ 0 ];
+	basePosition.top += atOffset[ 1 ];
+
+	return this.each(function() {
+		var collisionPosition, using,
+			elem = $( this ),
+			elemWidth = elem.outerWidth(),
+			elemHeight = elem.outerHeight(),
+			marginLeft = parseCss( this, "marginLeft" ),
+			marginTop = parseCss( this, "marginTop" ),
+			collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width,
+			collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height,
+			position = $.extend( {}, basePosition ),
+			myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() );
+
+		if ( options.my[ 0 ] === "right" ) {
+			position.left -= elemWidth;
+		} else if ( options.my[ 0 ] === "center" ) {
+			position.left -= elemWidth / 2;
+		}
+
+		if ( options.my[ 1 ] === "bottom" ) {
+			position.top -= elemHeight;
+		} else if ( options.my[ 1 ] === "center" ) {
+			position.top -= elemHeight / 2;
+		}
+
+		position.left += myOffset[ 0 ];
+		position.top += myOffset[ 1 ];
+
+		// if the browser doesn't support fractions, then round for consistent results
+		if ( !$.support.offsetFractions ) {
+			position.left = round( position.left );
+			position.top = round( position.top );
+		}
+
+		collisionPosition = {
+			marginLeft: marginLeft,
+			marginTop: marginTop
+		};
+
+		$.each( [ "left", "top" ], function( i, dir ) {
+			if ( $.ui.position[ collision[ i ] ] ) {
+				$.ui.position[ collision[ i ] ][ dir ]( position, {
+					targetWidth: targetWidth,
+					targetHeight: targetHeight,
+					elemWidth: elemWidth,
+					elemHeight: elemHeight,
+					collisionPosition: collisionPosition,
+					collisionWidth: collisionWidth,
+					collisionHeight: collisionHeight,
+					offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ],
+					my: options.my,
+					at: options.at,
+					within: within,
+					elem : elem
+				});
+			}
+		});
+
+		if ( $.fn.bgiframe ) {
+			elem.bgiframe();
+		}
+
+		if ( options.using ) {
+			// adds feedback as second argument to using callback, if present
+			using = function( props ) {
+				var left = targetOffset.left - position.left,
+					right = left + targetWidth - elemWidth,
+					top = targetOffset.top - position.top,
+					bottom = top + targetHeight - elemHeight,
+					feedback = {
+						target: {
+							element: target,
+							left: targetOffset.left,
+							top: targetOffset.top,
+							width: targetWidth,
+							height: targetHeight
+						},
+						element: {
+							element: elem,
+							left: position.left,
+							top: position.top,
+							width: elemWidth,
+							height: elemHeight
+						},
+						horizontal: right < 0 ? "left" : left > 0 ? "right" : "center",
+						vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle"
+					};
+				if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) {
+					feedback.horizontal = "center";
+				}
+				if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) {
+					feedback.vertical = "middle";
+				}
+				if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) {
+					feedback.important = "horizontal";
+				} else {
+					feedback.important = "vertical";
+				}
+				options.using.call( this, props, feedback );
+			};
+		}
+
+		elem.offset( $.extend( position, { using: using } ) );
+	});
+};
+
+$.ui.position = {
+	fit: {
+		left: function( position, data ) {
+			var within = data.within,
+				withinOffset = within.isWindow ? within.scrollLeft : within.offset.left,
+				outerWidth = within.width,
+				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
+				overLeft = withinOffset - collisionPosLeft,
+				overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset,
+				newOverRight;
+
+			// element is wider than within
+			if ( data.collisionWidth > outerWidth ) {
+				// element is initially over the left side of within
+				if ( overLeft > 0 && overRight <= 0 ) {
+					newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset;
+					position.left += overLeft - newOverRight;
+				// element is initially over right side of within
+				} else if ( overRight > 0 && overLeft <= 0 ) {
+					position.left = withinOffset;
+				// element is initially over both left and right sides of within
+				} else {
+					if ( overLeft > overRight ) {
+						position.left = withinOffset + outerWidth - data.collisionWidth;
+					} else {
+						position.left = withinOffset;
+					}
+				}
+			// too far left -> align with left edge
+			} else if ( overLeft > 0 ) {
+				position.left += overLeft;
+			// too far right -> align with right edge
+			} else if ( overRight > 0 ) {
+				position.left -= overRight;
+			// adjust based on position and margin
+			} else {
+				position.left = max( position.left - collisionPosLeft, position.left );
+			}
+		},
+		top: function( position, data ) {
+			var within = data.within,
+				withinOffset = within.isWindow ? within.scrollTop : within.offset.top,
+				outerHeight = data.within.height,
+				collisionPosTop = position.top - data.collisionPosition.marginTop,
+				overTop = withinOffset - collisionPosTop,
+				overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset,
+				newOverBottom;
+
+			// element is taller than within
+			if ( data.collisionHeight > outerHeight ) {
+				// element is initially over the top of within
+				if ( overTop > 0 && overBottom <= 0 ) {
+					newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset;
+					position.top += overTop - newOverBottom;
+				// element is initially over bottom of within
+				} else if ( overBottom > 0 && overTop <= 0 ) {
+					position.top = withinOffset;
+				// element is initially over both top and bottom of within
+				} else {
+					if ( overTop > overBottom ) {
+						position.top = withinOffset + outerHeight - data.collisionHeight;
+					} else {
+						position.top = withinOffset;
+					}
+				}
+			// too far up -> align with top
+			} else if ( overTop > 0 ) {
+				position.top += overTop;
+			// too far down -> align with bottom edge
+			} else if ( overBottom > 0 ) {
+				position.top -= overBottom;
+			// adjust based on position and margin
+			} else {
+				position.top = max( position.top - collisionPosTop, position.top );
+			}
+		}
+	},
+	flip: {
+		left: function( position, data ) {
+			var within = data.within,
+				withinOffset = within.offset.left + within.scrollLeft,
+				outerWidth = within.width,
+				offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left,
+				collisionPosLeft = position.left - data.collisionPosition.marginLeft,
+				overLeft = collisionPosLeft - offsetLeft,
+				overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft,
+				myOffset = data.my[ 0 ] === "left" ?
+					-data.elemWidth :
+					data.my[ 0 ] === "right" ?
+						data.elemWidth :
+						0,
+				atOffset = data.at[ 0 ] === "left" ?
+					data.targetWidth :
+					data.at[ 0 ] === "right" ?
+						-data.targetWidth :
+						0,
+				offset = -2 * data.offset[ 0 ],
+				newOverRight,
+				newOverLeft;
+
+			if ( overLeft < 0 ) {
+				newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset;
+				if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) {
+					position.left += myOffset + atOffset + offset;
+				}
+			}
+			else if ( overRight > 0 ) {
+				newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft;
+				if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) {
+					position.left += myOffset + atOffset + offset;
+				}
+			}
+		},
+		top: function( position, data ) {
+			var within = data.within,
+				withinOffset = within.offset.top + within.scrollTop,
+				outerHeight = within.height,
+				offsetTop = within.isWindow ? within.scrollTop : within.offset.top,
+				collisionPosTop = position.top - data.collisionPosition.marginTop,
+				overTop = collisionPosTop - offsetTop,
+				overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop,
+				top = data.my[ 1 ] === "top",
+				myOffset = top ?
+					-data.elemHeight :
+					data.my[ 1 ] === "bottom" ?
+						data.elemHeight :
+						0,
+				atOffset = data.at[ 1 ] === "top" ?
+					data.targetHeight :
+					data.at[ 1 ] === "bottom" ?
+						-data.targetHeight :
+						0,
+				offset = -2 * data.offset[ 1 ],
+				newOverTop,
+				newOverBottom;
+			if ( overTop < 0 ) {
+				newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset;
+				if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) {
+					position.top += myOffset + atOffset + offset;
+				}
+			}
+			else if ( overBottom > 0 ) {
+				newOverTop = position.top -  data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop;
+				if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) {
+					position.top += myOffset + atOffset + offset;
+				}
+			}
+		}
+	},
+	flipfit: {
+		left: function() {
+			$.ui.position.flip.left.apply( this, arguments );
+			$.ui.position.fit.left.apply( this, arguments );
+		},
+		top: function() {
+			$.ui.position.flip.top.apply( this, arguments );
+			$.ui.position.fit.top.apply( this, arguments );
+		}
+	}
+};
+
+// fraction support test
+(function () {
+	var testElement, testElementParent, testElementStyle, offsetLeft, i,
+		body = document.getElementsByTagName( "body" )[ 0 ],
+		div = document.createElement( "div" );
+
+	//Create a "fake body" for testing based on method used in jQuery.support
+	testElement = document.createElement( body ? "div" : "body" );
+	testElementStyle = {
+		visibility: "hidden",
+		width: 0,
+		height: 0,
+		border: 0,
+		margin: 0,
+		background: "none"
+	};
+	if ( body ) {
+		$.extend( testElementStyle, {
+			position: "absolute",
+			left: "-1000px",
+			top: "-1000px"
+		});
+	}
+	for ( i in testElementStyle ) {
+		testElement.style[ i ] = testElementStyle[ i ];
+	}
+	testElement.appendChild( div );
+	testElementParent = body || document.documentElement;
+	testElementParent.insertBefore( testElement, testElementParent.firstChild );
+
+	div.style.cssText = "position: absolute; left: 10.7432222px;";
+
+	offsetLeft = $( div ).offset().left;
+	$.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11;
+
+	testElement.innerHTML = "";
+	testElementParent.removeChild( testElement );
+})();
+
+// DEPRECATED
+if ( $.uiBackCompat !== false ) {
+	// offset option
+	(function( $ ) {
+		var _position = $.fn.position;
+		$.fn.position = function( options ) {
+			if ( !options || !options.offset ) {
+				return _position.call( this, options );
+			}
+			var offset = options.offset.split( " " ),
+				at = options.at.split( " " );
+			if ( offset.length === 1 ) {
+				offset[ 1 ] = offset[ 0 ];
+			}
+			if ( /^\d/.test( offset[ 0 ] ) ) {
+				offset[ 0 ] = "+" + offset[ 0 ];
+			}
+			if ( /^\d/.test( offset[ 1 ] ) ) {
+				offset[ 1 ] = "+" + offset[ 1 ];
+			}
+			if ( at.length === 1 ) {
+				if ( /left|center|right/.test( at[ 0 ] ) ) {
+					at[ 1 ] = "center";
+				} else {
+					at[ 1 ] = at[ 0 ];
+					at[ 0 ] = "center";
+				}
+			}
+			return _position.call( this, $.extend( options, {
+				at: at[ 0 ] + offset[ 0 ] + " " + at[ 1 ] + offset[ 1 ],
+				offset: undefined
+			} ) );
+		};
+	}( jQuery ) );
+}
+
+}( jQuery ) );
+
+(function( $, undefined ) {
+
+$.widget( "ui.progressbar", {
+	version: "1.9.2",
+	options: {
+		value: 0,
+		max: 100
+	},
+
+	min: 0,
+
+	_create: function() {
+		this.element
+			.addClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
+			.attr({
+				role: "progressbar",
+				"aria-valuemin": this.min,
+				"aria-valuemax": this.options.max,
+				"aria-valuenow": this._value()
+			});
+
+		this.valueDiv = $( "<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>" )
+			.appendTo( this.element );
+
+		this.oldValue = this._value();
+		this._refreshValue();
+	},
+
+	_destroy: function() {
+		this.element
+			.removeClass( "ui-progressbar ui-widget ui-widget-content ui-corner-all" )
+			.removeAttr( "role" )
+			.removeAttr( "aria-valuemin" )
+			.removeAttr( "aria-valuemax" )
+			.removeAttr( "aria-valuenow" );
+
+		this.valueDiv.remove();
+	},
+
+	value: function( newValue ) {
+		if ( newValue === undefined ) {
+			return this._value();
+		}
+
+		this._setOption( "value", newValue );
+		return this;
+	},
+
+	_setOption: function( key, value ) {
+		if ( key === "value" ) {
+			this.options.value = value;
+			this._refreshValue();
+			if ( this._value() === this.options.max ) {
+				this._trigger( "complete" );
+			}
+		}
+
+		this._super( key, value );
+	},
+
+	_value: function() {
+		var val = this.options.value;
+		// normalize invalid value
+		if ( typeof val !== "number" ) {
+			val = 0;
+		}
+		return Math.min( this.options.max, Math.max( this.min, val ) );
+	},
+
+	_percentage: function() {
+		return 100 * this._value() / this.options.max;
+	},
+
+	_refreshValue: function() {
+		var value = this.value(),
+			percentage = this._percentage();
+
+		if ( this.oldValue !== value ) {
+			this.oldValue = value;
+			this._trigger( "change" );
+		}
+
+		this.valueDiv
+			.toggle( value > this.min )
+			.toggleClass( "ui-corner-right", value === this.options.max )
+			.width( percentage.toFixed(0) + "%" );
+		this.element.attr( "aria-valuenow", value );
+	}
+});
+
+})( jQuery );
+
+(function( $, undefined ) {
+
+// number of pages in a slider
+// (how many times can you page up/down to go through the whole range)
+var numPages = 5;
+
+$.widget( "ui.slider", $.ui.mouse, {
+	version: "1.9.2",
+	widgetEventPrefix: "slide",
+
+	options: {
+		animate: false,
+		distance: 0,
+		max: 100,
+		min: 0,
+		orientation: "horizontal",
+		range: false,
+		step: 1,
+		value: 0,
+		values: null
+	},
+
+	_create: function() {
+		var i, handleCount,
+			o = this.options,
+			existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ),
+			handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",
+			handles = [];
+
+		this._keySliding = false;
+		this._mouseSliding = false;
+		this._animateOff = true;
+		this._handleIndex = null;
+		this._detectOrientation();
+		this._mouseInit();
+
+		this.element
+			.addClass( "ui-slider" +
+				" ui-slider-" + this.orientation +
+				" ui-widget" +
+				" ui-widget-content" +
+				" ui-corner-all" +
+				( o.disabled ? " ui-slider-disabled ui-disabled" : "" ) );
+
+		this.range = $([]);
+
+		if ( o.range ) {
+			if ( o.range === true ) {
+				if ( !o.values ) {
+					o.values = [ this._valueMin(), this._valueMin() ];
+				}
+				if ( o.values.length && o.values.length !== 2 ) {
+					o.values = [ o.values[0], o.values[0] ];
+				}
+			}
+
+			this.range = $( "<div></div>" )
+				.appendTo( this.element )
+				.addClass( "ui-slider-range" +
+				// note: this isn't the most fittingly semantic framework class for this element,
+				// but worked best visually with a variety of themes
+				" ui-widget-header" +
+				( ( o.range === "min" || o.range === "max" ) ? " ui-slider-range-" + o.range : "" ) );
+		}
+
+		handleCount = ( o.values && o.values.length ) || 1;
+
+		for ( i = existingHandles.length; i < handleCount; i++ ) {
+			handles.push( handle );
+		}
+
+		this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) );
+
+		this.handle = this.handles.eq( 0 );
+
+		this.handles.add( this.range ).filter( "a" )
+			.click(function( event ) {
+				event.preventDefault();
+			})
+			.mouseenter(function() {
+				if ( !o.disabled ) {
+					$( this ).addClass( "ui-state-hover" );
+				}
+			})
+			.mouseleave(function() {
+				$( this ).removeClass( "ui-state-hover" );
+			})
+			.focus(function() {
+				if ( !o.disabled ) {
+					$( ".ui-slider .ui-state-focus" ).removeClass( "ui-state-focus" );
+					$( this ).addClass( "ui-state-focus" );
+				} else {
+					$( this ).blur();
+				}
+			})
+			.blur(function() {
+				$( this ).removeClass( "ui-state-focus" );
+			});
+
+		this.handles.each(function( i ) {
+			$( this ).data( "ui-slider-handle-index", i );
+		});
+
+		this._on( this.handles, {
+			keydown: function( event ) {
+				var allowed, curVal, newVal, step,
+					index = $( event.target ).data( "ui-slider-handle-index" );
+
+				switch ( event.keyCode ) {
+					case $.ui.keyCode.HOME:
+					case $.ui.keyCode.END:
+					case $.ui.keyCode.PAGE_UP:
+					case $.ui.keyCode.PAGE_DOWN:
+					case $.ui.keyCode.UP:
+					case $.ui.keyCode.RIGHT:
+					case $.ui.keyCode.DOWN:
+					case $.ui.keyCode.LEFT:
+						event.preventDefault();
+						if ( !this._keySliding ) {
+							this._keySliding = true;
+							$( event.target ).addClass( "ui-state-active" );
+							allowed = this._start( event, index );
+							if ( allowed === false ) {
+								return;
+							}
+						}
+						break;
+				}
+
+				step = this.options.step;
+				if ( this.options.values && this.options.values.length ) {
+					curVal = newVal = this.values( index );
+				} else {
+					curVal = newVal = this.value();
+				}
+
+				switch ( event.keyCode ) {
+					case $.ui.keyCode.HOME:
+						newVal = this._valueMin();
+						break;
+					case $.ui.keyCode.END:
+						newVal = this._valueMax();
+						break;
+					case $.ui.keyCode.PAGE_UP:
+						newVal = this._trimAlignValue( curVal + ( (this._valueMax() - this._valueMin()) / numPages ) );
+						break;
+					case $.ui.keyCode.PAGE_DOWN:
+						newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / numPages ) );
+						break;
+					case $.ui.keyCode.UP:
+					case $.ui.keyCode.RIGHT:
+						if ( curVal === this._valueMax() ) {
+							return;
+						}
+						newVal = this._trimAlignValue( curVal + step );
+						break;
+					case $.ui.keyCode.DOWN:
+					case $.ui.keyCode.LEFT:
+						if ( curVal === this._valueMin() ) {
+							return;
+						}
+						newVal = this._trimAlignValue( curVal - step );
+						break;
+				}
+
+				this._slide( event, index, newVal );
+			},
+			keyup: function( event ) {
+				var index = $( event.target ).data( "ui-slider-handle-index" );
+
+				if ( this._keySliding ) {
+					this._keySliding = false;
+					this._stop( event, index );
+					this._change( event, index );
+					$( event.target ).removeClass( "ui-state-active" );
+				}
+			}
+		});
+
+		this._refreshValue();
+
+		this._animateOff = false;
+	},
+
+	_destroy: function() {
+		this.handles.remove();
+		this.range.remove();
+
+		this.element
+			.removeClass( "ui-slider" +
+				" ui-slider-horizontal" +
+				" ui-slider-vertical" +
+				" ui-slider-disabled" +
+				" ui-widget" +
+				" ui-widget-content" +
+				" ui-corner-all" );
+
+		this._mouseDestroy();
+	},
+
+	_mouseCapture: function( event ) {
+		var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle,
+			that = this,
+			o = this.options;
+
+		if ( o.disabled ) {
+			return false;
+		}
+
+		this.elementSize = {
+			width: this.element.outerWidth(),
+			height: this.element.outerHeight()
+		};
+		this.elementOffset = this.element.offset();
+
+		position = { x: event.pageX, y: event.pageY };
+		normValue = this._normValueFromMouse( position );
+		distance = this._valueMax() - this._valueMin() + 1;
+		this.handles.each(function( i ) {
+			var thisDistance = Math.abs( normValue - that.values(i) );
+			if ( distance > thisDistance ) {
+				distance = thisDistance;
+				closestHandle = $( this );
+				index = i;
+			}
+		});
+
+		// workaround for bug #3736 (if both handles of a range are at 0,
+		// the first is always used as the one with least distance,
+		// and moving it is obviously prevented by preventing negative ranges)
+		if( o.range === true && this.values(1) === o.min ) {
+			index += 1;
+			closestHandle = $( this.handles[index] );
+		}
+
+		allowed = this._start( event, index );
+		if ( allowed === false ) {
+			return false;
+		}
+		this._mouseSliding = true;
+
+		this._handleIndex = index;
+
+		closestHandle
+			.addClass( "ui-state-active" )
+			.focus();
+
+		offset = closestHandle.offset();
+		mouseOverHandle = !$( event.target ).parents().andSelf().is( ".ui-slider-handle" );
+		this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : {
+			left: event.pageX - offset.left - ( closestHandle.width() / 2 ),
+			top: event.pageY - offset.top -
+				( closestHandle.height() / 2 ) -
+				( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) -
+				( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) +
+				( parseInt( closestHandle.css("marginTop"), 10 ) || 0)
+		};
+
+		if ( !this.handles.hasClass( "ui-state-hover" ) ) {
+			this._slide( event, index, normValue );
+		}
+		this._animateOff = true;
+		return true;
+	},
+
+	_mouseStart: function() {
+		return true;
+	},
+
+	_mouseDrag: function( event ) {
+		var position = { x: event.pageX, y: event.pageY },
+			normValue = this._normValueFromMouse( position );
+
+		this._slide( event, this._handleIndex, normValue );
+
+		return false;
+	},
+
+	_mouseStop: function( event ) {
+		this.handles.removeClass( "ui-state-active" );
+		this._mouseSliding = false;
+
+		this._stop( event, this._handleIndex );
+		this._change( event, this._handleIndex );
+
+		this._handleIndex = null;
+		this._clickOffset = null;
+		this._animateOff = false;
+
+		return false;
+	},
+
+	_detectOrientation: function() {
+		this.orientation = ( this.options.orientation === "vertical" ) ? "vertical" : "horizontal";
+	},
+
+	_normValueFromMouse: function( position ) {
+		var pixelTotal,
+			pixelMouse,
+			percentMouse,
+			valueTotal,
+			valueMouse;
+
+		if ( this.orientation === "horizontal" ) {
+			pixelTotal = this.elementSize.width;
+			pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 );
+		} else {
+			pixelTotal = this.elementSize.height;
+			pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 );
+		}
+
+		percentMouse = ( pixelMouse / pixelTotal );
+		if ( percentMouse > 1 ) {
+			percentMouse = 1;
+		}
+		if ( percentMouse < 0 ) {
+			percentMouse = 0;
+		}
+		if ( this.orientation === "vertical" ) {
+			percentMouse = 1 - percentMouse;
+		}
+
+		valueTotal = this._valueMax() - this._valueMin();
+		valueMouse = this._valueMin() + percentMouse * valueTotal;
+
+		return this._trimAlignValue( valueMouse );
+	},
+
+	_start: function( event, index ) {
+		var uiHash = {
+			handle: this.handles[ index ],
+			value: this.value()
+		};
+		if ( this.options.values && this.options.values.length ) {
+			uiHash.value = this.values( index );
+			uiHash.values = this.values();
+		}
+		return this._trigger( "start", event, uiHash );
+	},
+
+	_slide: function( event, index, newVal ) {
+		var otherVal,
+			newValues,
+			allowed;
+
+		if ( this.options.values && this.options.values.length ) {
+			otherVal = this.values( index ? 0 : 1 );
+
+			if ( ( this.options.values.length === 2 && this.options.range === true ) &&
+					( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) )
+				) {
+				newVal = otherVal;
+			}
+
+			if ( newVal !== this.values( index ) ) {
+				newValues = this.values();
+				newValues[ index ] = newVal;
+				// A slide can be canceled by returning false from the slide callback
+				allowed = this._trigger( "slide", event, {
+					handle: this.handles[ index ],
+					value: newVal,
+					values: newValues
+				} );
+				otherVal = this.values( index ? 0 : 1 );
+				if ( allowed !== false ) {
+					this.values( index, newVal, true );
+				}
+			}
+		} else {
+			if ( newVal !== this.value() ) {
+				// A slide can be canceled by returning false from the slide callback
+				allowed = this._trigger( "slide", event, {
+					handle: this.handles[ index ],
+					value: newVal
+				} );
+				if ( allowed !== false ) {
+					this.value( newVal );
+				}
+			}
+		}
+	},
+
+	_stop: function( event, index ) {
+		var uiHash = {
+			handle: this.handles[ index ],
+			value: this.value()
+		};
+		if ( this.options.values && this.options.values.length ) {
+			uiHash.value = this.values( index );
+			uiHash.values = this.values();
+		}
+
+		this._trigger( "stop", event, uiHash );
+	},
+
+	_change: function( event, index ) {
+		if ( !this._keySliding && !this._mouseSliding ) {
+			var uiHash = {
+				handle: this.handles[ index ],
+				value: this.value()
+			};
+			if ( this.options.values && this.options.values.length ) {
+				uiHash.value = this.values( index );
+				uiHash.values = this.values();
+			}
+
+			this._trigger( "change", event, uiHash );
+		}
+	},
+
+	value: function( newValue ) {
+		if ( arguments.length ) {
+			this.options.value = this._trimAlignValue( newValue );
+			this._refreshValue();
+			this._change( null, 0 );
+			return;
+		}
+
+		return this._value();
+	},
+
+	values: function( index, newValue ) {
+		var vals,
+			newValues,
+			i;
+
+		if ( arguments.length > 1 ) {
+			this.options.values[ index ] = this._trimAlignValue( newValue );
+			this._refreshValue();
+			this._change( null, index );
+			return;
+		}
+
+		if ( arguments.length ) {
+			if ( $.isArray( arguments[ 0 ] ) ) {
+				vals = this.options.values;
+				newValues = arguments[ 0 ];
+				for ( i = 0; i < vals.length; i += 1 ) {
+					vals[ i ] = this._trimAlignValue( newValues[ i ] );
+					this._change( null, i );
+				}
+				this._refreshValue();
+			} else {
+				if ( this.options.values && this.options.values.length ) {
+					return this._values( index );
+				} else {
+					return this.value();
+				}
+			}
+		} else {
+			return this._values();
+		}
+	},
+
+	_setOption: function( key, value ) {
+		var i,
+			valsLength = 0;
+
+		if ( $.isArray( this.options.values ) ) {
+			valsLength = this.options.values.length;
+		}
+
+		$.Widget.prototype._setOption.apply( this, arguments );
+
+		switch ( key ) {
+			case "disabled":
+				if ( value ) {
+					this.handles.filter( ".ui-state-focus" ).blur();
+					this.handles.removeClass( "ui-state-hover" );
+					this.handles.prop( "disabled", true );
+					this.element.addClass( "ui-disabled" );
+				} else {
+					this.handles.prop( "disabled", false );
+					this.element.removeClass( "ui-disabled" );
+				}
+				break;
+			case "orientation":
+				this._detectOrientation();
+				this.element
+					.removeClass( "ui-slider-horizontal ui-slider-vertical" )
+					.addClass( "ui-slider-" + this.orientation );
+				this._refreshValue();
+				break;
+			case "value":
+				this._animateOff = true;
+				this._refreshValue();
+				this._change( null, 0 );
+				this._animateOff = false;
+				break;
+			case "values":
+				this._animateOff = true;
+				this._refreshValue();
+				for ( i = 0; i < valsLength; i += 1 ) {
+					this._change( null, i );
+				}
+				this._animateOff = false;
+				break;
+			case "min":
+			case "max":
+				this._animateOff = true;
+				this._refreshValue();
+				this._animateOff = false;
+				break;
+		}
+	},
+
+	//internal value getter
+	// _value() returns value trimmed by min and max, aligned by step
+	_value: function() {
+		var val = this.options.value;
+		val = this._trimAlignValue( val );
+
+		return val;
+	},
+
+	//internal values getter
+	// _values() returns array of values trimmed by min and max, aligned by step
+	// _values( index ) returns single value trimmed by min and max, aligned by step
+	_values: function( index ) {
+		var val,
+			vals,
+			i;
+
+		if ( arguments.length ) {
+			val = this.options.values[ index ];
+			val = this._trimAlignValue( val );
+
+			return val;
+		} else {
+			// .slice() creates a copy of the array
+			// this copy gets trimmed by min and max and then returned
+			vals = this.options.values.slice();
+			for ( i = 0; i < vals.length; i+= 1) {
+				vals[ i ] = this._trimAlignValue( vals[ i ] );
+			}
+
+			return vals;
+		}
+	},
+
+	// returns the step-aligned value that val is closest to, between (inclusive) min and max
+	_trimAlignValue: function( val ) {
+		if ( val <= this._valueMin() ) {
+			return this._valueMin();
+		}
+		if ( val >= this._valueMax() ) {
+			return this._valueMax();
+		}
+		var step = ( this.options.step > 0 ) ? this.options.step : 1,
+			valModStep = (val - this._valueMin()) % step,
+			alignValue = val - valModStep;
+
+		if ( Math.abs(valModStep) * 2 >= step ) {
+			alignValue += ( valModStep > 0 ) ? step : ( -step );
+		}
+
+		// Since JavaScript has problems with large floats, round
+		// the final value to 5 digits after the decimal point (see #4124)
+		return parseFloat( alignValue.toFixed(5) );
+	},
+
+	_valueMin: function() {
+		return this.options.min;
+	},
+
+	_valueMax: function() {
+		return this.options.max;
+	},
+
+	_refreshValue: function() {
+		var lastValPercent, valPercent, value, valueMin, valueMax,
+			oRange = this.options.range,
+			o = this.options,
+			that = this,
+			animate = ( !this._animateOff ) ? o.animate : false,
+			_set = {};
+
+		if ( this.options.values && this.options.values.length ) {
+			this.handles.each(function( i ) {
+				valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100;
+				_set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
+				$( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
+				if ( that.options.range === true ) {
+					if ( that.orientation === "horizontal" ) {
+						if ( i === 0 ) {
+							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate );
+						}
+						if ( i === 1 ) {
+							that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
+						}
+					} else {
+						if ( i === 0 ) {
+							that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate );
+						}
+						if ( i === 1 ) {
+							that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } );
+						}
+					}
+				}
+				lastValPercent = valPercent;
+			});
+		} else {
+			value = this.value();
+			valueMin = this._valueMin();
+			valueMax = this._valueMax();
+			valPercent = ( valueMax !== valueMin ) ?
+					( value - valueMin ) / ( valueMax - valueMin ) * 100 :
+					0;
+			_set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%";
+			this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate );
+
+			if ( oRange === "min" && this.orientation === "horizontal" ) {
+				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate );
+			}
+			if ( oRange === "max" && this.orientation === "horizontal" ) {
+				this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
+			}
+			if ( oRange === "min" && this.orientation === "vertical" ) {
+				this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate );
+			}
+			if ( oRange === "max" && this.orientation === "vertical" ) {
+				this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } );
+			}
+		}
+	}
+
+});
+
+}(jQuery));
+
+(function( $ ) {
+
+function modifier( fn ) {
+	return function() {
+		var previous = this.element.val();
+		fn.apply( this, arguments );
+		this._refresh();
+		if ( previous !== this.element.val() ) {
+			this._trigger( "change" );
+		}
+	};
+}
+
+$.widget( "ui.spinner", {
+	version: "1.9.2",
+	defaultElement: "<input>",
+	widgetEventPrefix: "spin",
+	options: {
+		culture: null,
+		icons: {
+			down: "ui-icon-triangle-1-s",
+			up: "ui-icon-triangle-1-n"
+		},
+		incremental: true,
+		max: null,
+		min: null,
+		numberFormat: null,
+		page: 10,
+		step: 1,
+
+		change: null,
+		spin: null,
+		start: null,
+		stop: null
+	},
+
+	_create: function() {
+		// handle string values that need to be parsed
+		this._setOption( "max", this.options.max );
+		this._setOption( "min", this.options.min );
+		this._setOption( "step", this.options.step );
+
+		// format the value, but don't constrain
+		this._value( this.element.val(), true );
+
+		this._draw();
+		this._on( this._events );
+		this._refresh();
+
+		// turning off autocomplete prevents the browser from remembering the
+		// value when navigating through history, so we re-enable autocomplete
+		// if the page is unloaded before the widget is destroyed. #7790
+		this._on( this.window, {
+			beforeunload: function() {
+				this.element.removeAttr( "autocomplete" );
+			}
+		});
+	},
+
+	_getCreateOptions: function() {
+		var options = {},
+			element = this.element;
+
+		$.each( [ "min", "max", "step" ], function( i, option ) {
+			var value = element.attr( option );
+			if ( value !== undefined && value.length ) {
+				options[ option ] = value;
+			}
+		});
+
+		return options;
+	},
+
+	_events: {
+		keydown: function( event ) {
+			if ( this._start( event ) && this._keydown( event ) ) {
+				event.preventDefault();
+			}
+		},
+		keyup: "_stop",
+		focus: function() {
+			this.previous = this.element.val();
+		},
+		blur: function( event ) {
+			if ( this.cancelBlur ) {
+				delete this.cancelBlur;
+				return;
+			}
+
+			this._refresh();
+			if ( this.previous !== this.element.val() ) {
+				this._trigger( "change", event );
+			}
+		},
+		mousewheel: function( event, delta ) {
+			if ( !delta ) {
+				return;
+			}
+			if ( !this.spinning && !this._start( event ) ) {
+				return false;
+			}
+
+			this._spin( (delta > 0 ? 1 : -1) * this.options.step, event );
+			clearTimeout( this.mousewheelTimer );
+			this.mousewheelTimer = this._delay(function() {
+				if ( this.spinning ) {
+					this._stop( event );
+				}
+			}, 100 );
+			event.preventDefault();
+		},
+		"mousedown .ui-spinner-button": function( event ) {
+			var previous;
+
+			// We never want the buttons to have focus; whenever the user is
+			// interacting with the spinner, the focus should be on the input.
+			// If the input is focused then this.previous is properly set from
+			// when the input first received focus. If the input is not focused
+			// then we need to set this.previous based on the value before spinning.
+			previous = this.element[0] === this.document[0].activeElement ?
+				this.previous : this.element.val();
+			function checkFocus() {
+				var isActive = this.element[0] === this.document[0].activeElement;
+				if ( !isActive ) {
+					this.element.focus();
+					this.previous = previous;
+					// support: IE
+					// IE sets focus asynchronously, so we need to check if focus
+					// moved off of the input because the user clicked on the button.
+					this._delay(function() {
+						this.previous = previous;
+					});
+				}
+			}
+
+			// ensure focus is on (or stays on) the text field
+			event.preventDefault();
+			checkFocus.call( this );
+
+			// support: IE
+			// IE doesn't prevent moving focus even with event.preventDefault()
+			// so we set a flag to know when we should ignore the blur event
+			// and check (again) if focus moved off of the input.
+			this.cancelBlur = true;
+			this._delay(function() {
+				delete this.cancelBlur;
+				checkFocus.call( this );
+			});
+
+			if ( this._start( event ) === false ) {
+				return;
+			}
+
+			this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
+		},
+		"mouseup .ui-spinner-button": "_stop",
+		"mouseenter .ui-spinner-button": function( event ) {
+			// button will add ui-state-active if mouse was down while mouseleave and kept down
+			if ( !$( event.currentTarget ).hasClass( "ui-state-active" ) ) {
+				return;
+			}
+
+			if ( this._start( event ) === false ) {
+				return false;
+			}
+			this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event );
+		},
+		// TODO: do we really want to consider this a stop?
+		// shouldn't we just stop the repeater and wait until mouseup before
+		// we trigger the stop event?
+		"mouseleave .ui-spinner-button": "_stop"
+	},
+
+	_draw: function() {
+		var uiSpinner = this.uiSpinner = this.element
+			.addClass( "ui-spinner-input" )
+			.attr( "autocomplete", "off" )
+			.wrap( this._uiSpinnerHtml() )
+			.parent()
+				// add buttons
+				.append( this._buttonHtml() );
+
+		this.element.attr( "role", "spinbutton" );
+
+		// button bindings
+		this.buttons = uiSpinner.find( ".ui-spinner-button" )
+			.attr( "tabIndex", -1 )
+			.button()
+			.removeClass( "ui-corner-all" );
+
+		// IE 6 doesn't understand height: 50% for the buttons
+		// unless the wrapper has an explicit height
+		if ( this.buttons.height() > Math.ceil( uiSpinner.height() * 0.5 ) &&
+				uiSpinner.height() > 0 ) {
+			uiSpinner.height( uiSpinner.height() );
+		}
+
+		// disable spinner if element was already disabled
+		if ( this.options.disabled ) {
+			this.disable();
+		}
+	},
+
+	_keydown: function( event ) {
+		var options = this.options,
+			keyCode = $.ui.keyCode;
+
+		switch ( event.keyCode ) {
+		case keyCode.UP:
+			this._repeat( null, 1, event );
+			return true;
+		case keyCode.DOWN:
+			this._repeat( null, -1, event );
+			return true;
+		case keyCode.PAGE_UP:
+			this._repeat( null, options.page, event );
+			return true;
+		case keyCode.PAGE_DOWN:
+			this._repeat( null, -options.page, event );
+			return true;
+		}
+
+		return false;
+	},
+
+	_uiSpinnerHtml: function() {
+		return "<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>";
+	},
+
+	_buttonHtml: function() {
+		return "" +
+			"<a class='ui-spinner-button ui-spinner-up ui-corner-tr'>" +
+				"<span class='ui-icon " + this.options.icons.up + "'>&#9650;</span>" +
+			"</a>" +
+			"<a class='ui-spinner-button ui-spinner-down ui-corner-br'>" +
+				"<span class='ui-icon " + this.options.icons.down + "'>&#9660;</span>" +
+			"</a>";
+	},
+
+	_start: function( event ) {
+		if ( !this.spinning && this._trigger( "start", event ) === false ) {
+			return false;
+		}
+
+		if ( !this.counter ) {
+			this.counter = 1;
+		}
+		this.spinning = true;
+		return true;
+	},
+
+	_repeat: function( i, steps, event ) {
+		i = i || 500;
+
+		clearTimeout( this.timer );
+		this.timer = this._delay(function() {
+			this._repeat( 40, steps, event );
+		}, i );
+
+		this._spin( steps * this.options.step, event );
+	},
+
+	_spin: function( step, event ) {
+		var value = this.value() || 0;
+
+		if ( !this.counter ) {
+			this.counter = 1;
+		}
+
+		value = this._adjustValue( value + step * this._increment( this.counter ) );
+
+		if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false) {
+			this._value( value );
+			this.counter++;
+		}
+	},
+
+	_increment: function( i ) {
+		var incremental = this.options.incremental;
+
+		if ( incremental ) {
+			return $.isFunction( incremental ) ?
+				incremental( i ) :
+				Math.floor( i*i*i/50000 - i*i/500 + 17*i/200 + 1 );
+		}
+
+		return 1;
+	},
+
+	_precision: function() {
+		var precision = this._precisionOf( this.options.step );
+		if ( this.options.min !== null ) {
+			precision = Math.max( precision, this._precisionOf( this.options.min ) );
+		}
+		return precision;
+	},
+
+	_precisionOf: function( num ) {
+		var str = num.toString(),
+			decimal = str.indexOf( "." );
+		return decimal === -1 ? 0 : str.length - decimal - 1;
+	},
+
+	_adjustValue: function( value ) {
+		var base, aboveMin,
+			options = this.options;
+
+		// make sure we're at a valid step
+		// - find out where we are relative to the base (min or 0)
+		base = options.min !== null ? options.min : 0;
+		aboveMin = value - base;
+		// - round to the nearest step
+		aboveMin = Math.round(aboveMin / options.step) * options.step;
+		// - rounding is based on 0, so adjust back to our base
+		value = base + aboveMin;
+
+		// fix precision from bad JS floating point math
+		value = parseFloat( value.toFixed( this._precision() ) );
+
+		// clamp the value
+		if ( options.max !== null && value > options.max) {
+			return options.max;
+		}
+		if ( options.min !== null && value < options.min ) {
+			return options.min;
+		}
+
+		return value;
+	},
+
+	_stop: function( event ) {
+		if ( !this.spinning ) {
+			return;
+		}
+
+		clearTimeout( this.timer );
+		clearTimeout( this.mousewheelTimer );
+		this.counter = 0;
+		this.spinning = false;
+		this._trigger( "stop", event );
+	},
+
+	_setOption: function( key, value ) {
+		if ( key === "culture" || key === "numberFormat" ) {
+			var prevValue = this._parse( this.element.val() );
+			this.options[ key ] = value;
+			this.element.val( this._format( prevValue ) );
+			return;
+		}
+
+		if ( key === "max" || key === "min" || key === "step" ) {
+			if ( typeof value === "string" ) {
+				value = this._parse( value );
+			}
+		}
+
+		this._super( key, value );
+
+		if ( key === "disabled" ) {
+			if ( value ) {
+				this.element.prop( "disabled", true );
+				this.buttons.button( "disable" );
+			} else {
+				this.element.prop( "disabled", false );
+				this.buttons.button( "enable" );
+			}
+		}
+	},
+
+	_setOptions: modifier(function( options ) {
+		this._super( options );
+		this._value( this.element.val() );
+	}),
+
+	_parse: function( val ) {
+		if ( typeof val === "string" && val !== "" ) {
+			val = window.Globalize && this.options.numberFormat ?
+				Globalize.parseFloat( val, 10, this.options.culture ) : +val;
+		}
+		return val === "" || isNaN( val ) ? null : val;
+	},
+
+	_format: function( value ) {
+		if ( value === "" ) {
+			return "";
+		}
+		return window.Globalize && this.options.numberFormat ?
+			Globalize.format( value, this.options.numberFormat, this.options.culture ) :
+			value;
+	},
+
+	_refresh: function() {
+		this.element.attr({
+			"aria-valuemin": this.options.min,
+			"aria-valuemax": this.options.max,
+			// TODO: what should we do with values that can't be parsed?
+			"aria-valuenow": this._parse( this.element.val() )
+		});
+	},
+
+	// update the value without triggering change
+	_value: function( value, allowAny ) {
+		var parsed;
+		if ( value !== "" ) {
+			parsed = this._parse( value );
+			if ( parsed !== null ) {
+				if ( !allowAny ) {
+					parsed = this._adjustValue( parsed );
+				}
+				value = this._format( parsed );
+			}
+		}
+		this.element.val( value );
+		this._refresh();
+	},
+
+	_destroy: function() {
+		this.element
+			.removeClass( "ui-spinner-input" )
+			.prop( "disabled", false )
+			.removeAttr( "autocomplete" )
+			.removeAttr( "role" )
+			.removeAttr( "aria-valuemin" )
+			.removeAttr( "aria-valuemax" )
+			.removeAttr( "aria-valuenow" );
+		this.uiSpinner.replaceWith( this.element );
+	},
+
+	stepUp: modifier(function( steps ) {
+		this._stepUp( steps );
+	}),
+	_stepUp: function( steps ) {
+		this._spin( (steps || 1) * this.options.step );
+	},
+
+	stepDown: modifier(function( steps ) {
+		this._stepDown( steps );
+	}),
+	_stepDown: function( steps ) {
+		this._spin( (steps || 1) * -this.options.step );
+	},
+
+	pageUp: modifier(function( pages ) {
+		this._stepUp( (pages || 1) * this.options.page );
+	}),
+
+	pageDown: modifier(function( pages ) {
+		this._stepDown( (pages || 1) * this.options.page );
+	}),
+
+	value: function( newVal ) {
+		if ( !arguments.length ) {
+			return this._parse( this.element.val() );
+		}
+		modifier( this._value ).call( this, newVal );
+	},
+
+	widget: function() {
+		return this.uiSpinner;
+	}
+});
+
+}( jQuery ) );
+
+(function( $, undefined ) {
+
+var tabId = 0,
+	rhash = /#.*$/;
+
+function getNextTabId() {
+	return ++tabId;
+}
+
+function isLocal( anchor ) {
+	return anchor.hash.length > 1 &&
+		anchor.href.replace( rhash, "" ) ===
+			location.href.replace( rhash, "" )
+				// support: Safari 5.1
+				// Safari 5.1 doesn't encode spaces in window.location
+				// but it does encode spaces from anchors (#8777)
+				.replace( /\s/g, "%20" );
+}
+
+$.widget( "ui.tabs", {
+	version: "1.9.2",
+	delay: 300,
+	options: {
+		active: null,
+		collapsible: false,
+		event: "click",
+		heightStyle: "content",
+		hide: null,
+		show: null,
+
+		// callbacks
+		activate: null,
+		beforeActivate: null,
+		beforeLoad: null,
+		load: null
+	},
+
+	_create: function() {
+		var that = this,
+			options = this.options,
+			active = options.active,
+			locationHash = location.hash.substring( 1 );
+
+		this.running = false;
+
+		this.element
+			.addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" )
+			.toggleClass( "ui-tabs-collapsible", options.collapsible )
+			// Prevent users from focusing disabled tabs via click
+			.delegate( ".ui-tabs-nav > li", "mousedown" + this.eventNamespace, function( event ) {
+				if ( $( this ).is( ".ui-state-disabled" ) ) {
+					event.preventDefault();
+				}
+			})
+			// support: IE <9
+			// Preventing the default action in mousedown doesn't prevent IE
+			// from focusing the element, so if the anchor gets focused, blur.
+			// We don't have to worry about focusing the previously focused
+			// element since clicking on a non-focusable element should focus
+			// the body anyway.
+			.delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() {
+				if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) {
+					this.blur();
+				}
+			});
+
+		this._processTabs();
+
+		if ( active === null ) {
+			// check the fragment identifier in the URL
+			if ( locationHash ) {
+				this.tabs.each(function( i, tab ) {
+					if ( $( tab ).attr( "aria-controls" ) === locationHash ) {
+						active = i;
+						return false;
+					}
+				});
+			}
+
+			// check for a tab marked active via a class
+			if ( active === null ) {
+				active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) );
+			}
+
+			// no active tab, set to false
+			if ( active === null || active === -1 ) {
+				active = this.tabs.length ? 0 : false;
+			}
+		}
+
+		// handle numbers: negative, out of range
+		if ( active !== false ) {
+			active = this.tabs.index( this.tabs.eq( active ) );
+			if ( active === -1 ) {
+				active = options.collapsible ? false : 0;
+			}
+		}
+		options.active = active;
+
+		// don't allow collapsible: false and active: false
+		if ( !options.collapsible && options.active === false && this.anchors.length ) {
+			options.active = 0;
+		}
+
+		// Take disabling tabs via class attribute from HTML
+		// into account and update option properly.
+		if ( $.isArray( options.disabled ) ) {
+			options.disabled = $.unique( options.disabled.concat(
+				$.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) {
+					return that.tabs.index( li );
+				})
+			) ).sort();
+		}
+
+		// check for length avoids error when initializing empty list
+		if ( this.options.active !== false && this.anchors.length ) {
+			this.active = this._findActive( this.options.active );
+		} else {
+			this.active = $();
+		}
+
+		this._refresh();
+
+		if ( this.active.length ) {
+			this.load( options.active );
+		}
+	},
+
+	_getCreateEventData: function() {
+		return {
+			tab: this.active,
+			panel: !this.active.length ? $() : this._getPanelForTab( this.active )
+		};
+	},
+
+	_tabKeydown: function( event ) {
+		var focusedTab = $( this.document[0].activeElement ).closest( "li" ),
+			selectedIndex = this.tabs.index( focusedTab ),
+			goingForward = true;
+
+		if ( this._handlePageNav( event ) ) {
+			return;
+		}
+
+		switch ( event.keyCode ) {
+			case $.ui.keyCode.RIGHT:
+			case $.ui.keyCode.DOWN:
+				selectedIndex++;
+				break;
+			case $.ui.keyCode.UP:
+			case $.ui.keyCode.LEFT:
+				goingForward = false;
+				selectedIndex--;
+				break;
+			case $.ui.keyCode.END:
+				selectedIndex = this.anchors.length - 1;
+				break;
+			case $.ui.keyCode.HOME:
+				selectedIndex = 0;
+				break;
+			case $.ui.keyCode.SPACE:
+				// Activate only, no collapsing
+				event.preventDefault();
+				clearTimeout( this.activating );
+				this._activate( selectedIndex );
+				return;
+			case $.ui.keyCode.ENTER:
+				// Toggle (cancel delayed activation, allow collapsing)
+				event.preventDefault();
+				clearTimeout( this.activating );
+				// Determine if we should collapse or activate
+				this._activate( selectedIndex === this.options.active ? false : selectedIndex );
+				return;
+			default:
+				return;
+		}
+
+		// Focus the appropriate tab, based on which key was pressed
+		event.preventDefault();
+		clearTimeout( this.activating );
+		selectedIndex = this._focusNextTab( selectedIndex, goingForward );
+
+		// Navigating with control key will prevent automatic activation
+		if ( !event.ctrlKey ) {
+			// Update aria-selected immediately so that AT think the tab is already selected.
+			// Otherwise AT may confuse the user by stating that they need to activate the tab,
+			// but the tab will already be activated by the time the announcement finishes.
+			focusedTab.attr( "aria-selected", "false" );
+			this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" );
+
+			this.activating = this._delay(function() {
+				this.option( "active", selectedIndex );
+			}, this.delay );
+		}
+	},
+
+	_panelKeydown: function( event ) {
+		if ( this._handlePageNav( event ) ) {
+			return;
+		}
+
+		// Ctrl+up moves focus to the current tab
+		if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) {
+			event.preventDefault();
+			this.active.focus();
+		}
+	},
+
+	// Alt+page up/down moves focus to the previous/next tab (and activates)
+	_handlePageNav: function( event ) {
+		if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) {
+			this._activate( this._focusNextTab( this.options.active - 1, false ) );
+			return true;
+		}
+		if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) {
+			this._activate( this._focusNextTab( this.options.active + 1, true ) );
+			return true;
+		}
+	},
+
+	_findNextTab: function( index, goingForward ) {
+		var lastTabIndex = this.tabs.length - 1;
+
+		function constrain() {
+			if ( index > lastTabIndex ) {
+				index = 0;
+			}
+			if ( index < 0 ) {
+				index = lastTabIndex;
+			}
+			return index;
+		}
+
+		while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) {
+			index = goingForward ? index + 1 : index - 1;
+		}
+
+		return index;
+	},
+
+	_focusNextTab: function( index, goingForward ) {
+		index = this._findNextTab( index, goingForward );
+		this.tabs.eq( index ).focus();
+		return index;
+	},
+
+	_setOption: function( key, value ) {
+		if ( key === "active" ) {
+			// _activate() will handle invalid values and update this.options
+			this._activate( value );
+			return;
+		}
+
+		if ( key === "disabled" ) {
+			// don't use the widget factory's disabled handling
+			this._setupDisabled( value );
+			return;
+		}
+
+		this._super( key, value);
+
+		if ( key === "collapsible" ) {
+			this.element.toggleClass( "ui-tabs-collapsible", value );
+			// Setting collapsible: false while collapsed; open first panel
+			if ( !value && this.options.active === false ) {
+				this._activate( 0 );
+			}
+		}
+
+		if ( key === "event" ) {
+			this._setupEvents( value );
+		}
+
+		if ( key === "heightStyle" ) {
+			this._setupHeightStyle( value );
+		}
+	},
+
+	_tabId: function( tab ) {
+		return tab.attr( "aria-controls" ) || "ui-tabs-" + getNextTabId();
+	},
+
+	_sanitizeSelector: function( hash ) {
+		return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : "";
+	},
+
+	refresh: function() {
+		var options = this.options,
+			lis = this.tablist.children( ":has(a[href])" );
+
+		// get disabled tabs from class attribute from HTML
+		// this will get converted to a boolean if needed in _refresh()
+		options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) {
+			return lis.index( tab );
+		});
+
+		this._processTabs();
+
+		// was collapsed or no tabs
+		if ( options.active === false || !this.anchors.length ) {
+			options.active = false;
+			this.active = $();
+		// was active, but active tab is gone
+		} else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) {
+			// all remaining tabs are disabled
+			if ( this.tabs.length === options.disabled.length ) {
+				options.active = false;
+				this.active = $();
+			// activate previous tab
+			} else {
+				this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) );
+			}
+		// was active, active tab still exists
+		} else {
+			// make sure active index is correct
+			options.active = this.tabs.index( this.active );
+		}
+
+		this._refresh();
+	},
+
+	_refresh: function() {
+		this._setupDisabled( this.options.disabled );
+		this._setupEvents( this.options.event );
+		this._setupHeightStyle( this.options.heightStyle );
+
+		this.tabs.not( this.active ).attr({
+			"aria-selected": "false",
+			tabIndex: -1
+		});
+		this.panels.not( this._getPanelForTab( this.active ) )
+			.hide()
+			.attr({
+				"aria-expanded": "false",
+				"aria-hidden": "true"
+			});
+
+		// Make sure one tab is in the tab order
+		if ( !this.active.length ) {
+			this.tabs.eq( 0 ).attr( "tabIndex", 0 );
+		} else {
+			this.active
+				.addClass( "ui-tabs-active ui-state-active" )
+				.attr({
+					"aria-selected": "true",
+					tabIndex: 0
+				});
+			this._getPanelForTab( this.active )
+				.show()
+				.attr({
+					"aria-expanded": "true",
+					"aria-hidden": "false"
+				});
+		}
+	},
+
+	_processTabs: function() {
+		var that = this;
+
+		this.tablist = this._getList()
+			.addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" )
+			.attr( "role", "tablist" );
+
+		this.tabs = this.tablist.find( "> li:has(a[href])" )
+			.addClass( "ui-state-default ui-corner-top" )
+			.attr({
+				role: "tab",
+				tabIndex: -1
+			});
+
+		this.anchors = this.tabs.map(function() {
+				return $( "a", this )[ 0 ];
+			})
+			.addClass( "ui-tabs-anchor" )
+			.attr({
+				role: "presentation",
+				tabIndex: -1
+			});
+
+		this.panels = $();
+
+		this.anchors.each(function( i, anchor ) {
+			var selector, panel, panelId,
+				anchorId = $( anchor ).uniqueId().attr( "id" ),
+				tab = $( anchor ).closest( "li" ),
+				originalAriaControls = tab.attr( "aria-controls" );
+
+			// inline tab
+			if ( isLocal( anchor ) ) {
+				selector = anchor.hash;
+				panel = that.element.find( that._sanitizeSelector( selector ) );
+			// remote tab
+			} else {
+				panelId = that._tabId( tab );
+				selector = "#" + panelId;
+				panel = that.element.find( selector );
+				if ( !panel.length ) {
+					panel = that._createPanel( panelId );
+					panel.insertAfter( that.panels[ i - 1 ] || that.tablist );
+				}
+				panel.attr( "aria-live", "polite" );
+			}
+
+			if ( panel.length) {
+				that.panels = that.panels.add( panel );
+			}
+			if ( originalAriaControls ) {
+				tab.data( "ui-tabs-aria-controls", originalAriaControls );
+			}
+			tab.attr({
+				"aria-controls": selector.substring( 1 ),
+				"aria-labelledby": anchorId
+			});
+			panel.attr( "aria-labelledby", anchorId );
+		});
+
+		this.panels
+			.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
+			.attr( "role", "tabpanel" );
+	},
+
+	// allow overriding how to find the list for rare usage scenarios (#7715)
+	_getList: function() {
+		return this.element.find( "ol,ul" ).eq( 0 );
+	},
+
+	_createPanel: function( id ) {
+		return $( "<div>" )
+			.attr( "id", id )
+			.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
+			.data( "ui-tabs-destroy", true );
+	},
+
+	_setupDisabled: function( disabled ) {
+		if ( $.isArray( disabled ) ) {
+			if ( !disabled.length ) {
+				disabled = false;
+			} else if ( disabled.length === this.anchors.length ) {
+				disabled = true;
+			}
+		}
+
+		// disable tabs
+		for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) {
+			if ( disabled === true || $.inArray( i, disabled ) !== -1 ) {
+				$( li )
+					.addClass( "ui-state-disabled" )
+					.attr( "aria-disabled", "true" );
+			} else {
+				$( li )
+					.removeClass( "ui-state-disabled" )
+					.removeAttr( "aria-disabled" );
+			}
+		}
+
+		this.options.disabled = disabled;
+	},
+
+	_setupEvents: function( event ) {
+		var events = {
+			click: function( event ) {
+				event.preventDefault();
+			}
+		};
+		if ( event ) {
+			$.each( event.split(" "), function( index, eventName ) {
+				events[ eventName ] = "_eventHandler";
+			});
+		}
+
+		this._off( this.anchors.add( this.tabs ).add( this.panels ) );
+		this._on( this.anchors, events );
+		this._on( this.tabs, { keydown: "_tabKeydown" } );
+		this._on( this.panels, { keydown: "_panelKeydown" } );
+
+		this._focusable( this.tabs );
+		this._hoverable( this.tabs );
+	},
+
+	_setupHeightStyle: function( heightStyle ) {
+		var maxHeight, overflow,
+			parent = this.element.parent();
+
+		if ( heightStyle === "fill" ) {
+			// IE 6 treats height like minHeight, so we need to turn off overflow
+			// in order to get a reliable height
+			// we use the minHeight support test because we assume that only
+			// browsers that don't support minHeight will treat height as minHeight
+			if ( !$.support.minHeight ) {
+				overflow = parent.css( "overflow" );
+				parent.css( "overflow", "hidden");
+			}
+			maxHeight = parent.height();
+			this.element.siblings( ":visible" ).each(function() {
+				var elem = $( this ),
+					position = elem.css( "position" );
+
+				if ( position === "absolute" || position === "fixed" ) {
+					return;
+				}
+				maxHeight -= elem.outerHeight( true );
+			});
+			if ( overflow ) {
+				parent.css( "overflow", overflow );
+			}
+
+			this.element.children().not( this.panels ).each(function() {
+				maxHeight -= $( this ).outerHeight( true );
+			});
+
+			this.panels.each(function() {
+				$( this ).height( Math.max( 0, maxHeight -
+					$( this ).innerHeight() + $( this ).height() ) );
+			})
+			.css( "overflow", "auto" );
+		} else if ( heightStyle === "auto" ) {
+			maxHeight = 0;
+			this.panels.each(function() {
+				maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() );
+			}).height( maxHeight );
+		}
+	},
+
+	_eventHandler: function( event ) {
+		var options = this.options,
+			active = this.active,
+			anchor = $( event.currentTarget ),
+			tab = anchor.closest( "li" ),
+			clickedIsActive = tab[ 0 ] === active[ 0 ],
+			collapsing = clickedIsActive && options.collapsible,
+			toShow = collapsing ? $() : this._getPanelForTab( tab ),
+			toHide = !active.length ? $() : this._getPanelForTab( active ),
+			eventData = {
+				oldTab: active,
+				oldPanel: toHide,
+				newTab: collapsing ? $() : tab,
+				newPanel: toShow
+			};
+
+		event.preventDefault();
+
+		if ( tab.hasClass( "ui-state-disabled" ) ||
+				// tab is already loading
+				tab.hasClass( "ui-tabs-loading" ) ||
+				// can't switch durning an animation
+				this.running ||
+				// click on active header, but not collapsible
+				( clickedIsActive && !options.collapsible ) ||
+				// allow canceling activation
+				( this._trigger( "beforeActivate", event, eventData ) === false ) ) {
+			return;
+		}
+
+		options.active = collapsing ? false : this.tabs.index( tab );
+
+		this.active = clickedIsActive ? $() : tab;
+		if ( this.xhr ) {
+			this.xhr.abort();
+		}
+
+		if ( !toHide.length && !toShow.length ) {
+			$.error( "jQuery UI Tabs: Mismatching fragment identifier." );
+		}
+
+		if ( toShow.length ) {
+			this.load( this.tabs.index( tab ), event );
+		}
+		this._toggle( event, eventData );
+	},
+
+	// handles show/hide for selecting tabs
+	_toggle: function( event, eventData ) {
+		var that = this,
+			toShow = eventData.newPanel,
+			toHide = eventData.oldPanel;
+
+		this.running = true;
+
+		function complete() {
+			that.running = false;
+			that._trigger( "activate", event, eventData );
+		}
+
+		function show() {
+			eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" );
+
+			if ( toShow.length && that.options.show ) {
+				that._show( toShow, that.options.show, complete );
+			} else {
+				toShow.show();
+				complete();
+			}
+		}
+
+		// start out by hiding, then showing, then completing
+		if ( toHide.length && this.options.hide ) {
+			this._hide( toHide, this.options.hide, function() {
+				eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
+				show();
+			});
+		} else {
+			eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
+			toHide.hide();
+			show();
+		}
+
+		toHide.attr({
+			"aria-expanded": "false",
+			"aria-hidden": "true"
+		});
+		eventData.oldTab.attr( "aria-selected", "false" );
+		// If we're switching tabs, remove the old tab from the tab order.
+		// If we're opening from collapsed state, remove the previous tab from the tab order.
+		// If we're collapsing, then keep the collapsing tab in the tab order.
+		if ( toShow.length && toHide.length ) {
+			eventData.oldTab.attr( "tabIndex", -1 );
+		} else if ( toShow.length ) {
+			this.tabs.filter(function() {
+				return $( this ).attr( "tabIndex" ) === 0;
+			})
+			.attr( "tabIndex", -1 );
+		}
+
+		toShow.attr({
+			"aria-expanded": "true",
+			"aria-hidden": "false"
+		});
+		eventData.newTab.attr({
+			"aria-selected": "true",
+			tabIndex: 0
+		});
+	},
+
+	_activate: function( index ) {
+		var anchor,
+			active = this._findActive( index );
+
+		// trying to activate the already active panel
+		if ( active[ 0 ] === this.active[ 0 ] ) {
+			return;
+		}
+
+		// trying to collapse, simulate a click on the current active header
+		if ( !active.length ) {
+			active = this.active;
+		}
+
+		anchor = active.find( ".ui-tabs-anchor" )[ 0 ];
+		this._eventHandler({
+			target: anchor,
+			currentTarget: anchor,
+			preventDefault: $.noop
+		});
+	},
+
+	_findActive: function( index ) {
+		return index === false ? $() : this.tabs.eq( index );
+	},
+
+	_getIndex: function( index ) {
+		// meta-function to give users option to provide a href string instead of a numerical index.
+		if ( typeof index === "string" ) {
+			index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) );
+		}
+
+		return index;
+	},
+
+	_destroy: function() {
+		if ( this.xhr ) {
+			this.xhr.abort();
+		}
+
+		this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" );
+
+		this.tablist
+			.removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" )
+			.removeAttr( "role" );
+
+		this.anchors
+			.removeClass( "ui-tabs-anchor" )
+			.removeAttr( "role" )
+			.removeAttr( "tabIndex" )
+			.removeData( "href.tabs" )
+			.removeData( "load.tabs" )
+			.removeUniqueId();
+
+		this.tabs.add( this.panels ).each(function() {
+			if ( $.data( this, "ui-tabs-destroy" ) ) {
+				$( this ).remove();
+			} else {
+				$( this )
+					.removeClass( "ui-state-default ui-state-active ui-state-disabled " +
+						"ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" )
+					.removeAttr( "tabIndex" )
+					.removeAttr( "aria-live" )
+					.removeAttr( "aria-busy" )
+					.removeAttr( "aria-selected" )
+					.removeAttr( "aria-labelledby" )
+					.removeAttr( "aria-hidden" )
+					.removeAttr( "aria-expanded" )
+					.removeAttr( "role" );
+			}
+		});
+
+		this.tabs.each(function() {
+			var li = $( this ),
+				prev = li.data( "ui-tabs-aria-controls" );
+			if ( prev ) {
+				li.attr( "aria-controls", prev );
+			} else {
+				li.removeAttr( "aria-controls" );
+			}
+		});
+
+		this.panels.show();
+
+		if ( this.options.heightStyle !== "content" ) {
+			this.panels.css( "height", "" );
+		}
+	},
+
+	enable: function( index ) {
+		var disabled = this.options.disabled;
+		if ( disabled === false ) {
+			return;
+		}
+
+		if ( index === undefined ) {
+			disabled = false;
+		} else {
+			index = this._getIndex( index );
+			if ( $.isArray( disabled ) ) {
+				disabled = $.map( disabled, function( num ) {
+					return num !== index ? num : null;
+				});
+			} else {
+				disabled = $.map( this.tabs, function( li, num ) {
+					return num !== index ? num : null;
+				});
+			}
+		}
+		this._setupDisabled( disabled );
+	},
+
+	disable: function( index ) {
+		var disabled = this.options.disabled;
+		if ( disabled === true ) {
+			return;
+		}
+
+		if ( index === undefined ) {
+			disabled = true;
+		} else {
+			index = this._getIndex( index );
+			if ( $.inArray( index, disabled ) !== -1 ) {
+				return;
+			}
+			if ( $.isArray( disabled ) ) {
+				disabled = $.merge( [ index ], disabled ).sort();
+			} else {
+				disabled = [ index ];
+			}
+		}
+		this._setupDisabled( disabled );
+	},
+
+	load: function( index, event ) {
+		index = this._getIndex( index );
+		var that = this,
+			tab = this.tabs.eq( index ),
+			anchor = tab.find( ".ui-tabs-anchor" ),
+			panel = this._getPanelForTab( tab ),
+			eventData = {
+				tab: tab,
+				panel: panel
+			};
+
+		// not remote
+		if ( isLocal( anchor[ 0 ] ) ) {
+			return;
+		}
+
+		this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) );
+
+		// support: jQuery <1.8
+		// jQuery <1.8 returns false if the request is canceled in beforeSend,
+		// but as of 1.8, $.ajax() always returns a jqXHR object.
+		if ( this.xhr && this.xhr.statusText !== "canceled" ) {
+			tab.addClass( "ui-tabs-loading" );
+			panel.attr( "aria-busy", "true" );
+
+			this.xhr
+				.success(function( response ) {
+					// support: jQuery <1.8
+					// http://bugs.jquery.com/ticket/11778
+					setTimeout(function() {
+						panel.html( response );
+						that._trigger( "load", event, eventData );
+					}, 1 );
+				})
+				.complete(function( jqXHR, status ) {
+					// support: jQuery <1.8
+					// http://bugs.jquery.com/ticket/11778
+					setTimeout(function() {
+						if ( status === "abort" ) {
+							that.panels.stop( false, true );
+						}
+
+						tab.removeClass( "ui-tabs-loading" );
+						panel.removeAttr( "aria-busy" );
+
+						if ( jqXHR === that.xhr ) {
+							delete that.xhr;
+						}
+					}, 1 );
+				});
+		}
+	},
+
+	// TODO: Remove this function in 1.10 when ajaxOptions is removed
+	_ajaxSettings: function( anchor, event, eventData ) {
+		var that = this;
+		return {
+			url: anchor.attr( "href" ),
+			beforeSend: function( jqXHR, settings ) {
+				return that._trigger( "beforeLoad", event,
+					$.extend( { jqXHR : jqXHR, ajaxSettings: settings }, eventData ) );
+			}
+		};
+	},
+
+	_getPanelForTab: function( tab ) {
+		var id = $( tab ).attr( "aria-controls" );
+		return this.element.find( this._sanitizeSelector( "#" + id ) );
+	}
+});
+
+// DEPRECATED
+if ( $.uiBackCompat !== false ) {
+
+	// helper method for a lot of the back compat extensions
+	$.ui.tabs.prototype._ui = function( tab, panel ) {
+		return {
+			tab: tab,
+			panel: panel,
+			index: this.anchors.index( tab )
+		};
+	};
+
+	// url method
+	$.widget( "ui.tabs", $.ui.tabs, {
+		url: function( index, url ) {
+			this.anchors.eq( index ).attr( "href", url );
+		}
+	});
+
+	// TODO: Remove _ajaxSettings() method when removing this extension
+	// ajaxOptions and cache options
+	$.widget( "ui.tabs", $.ui.tabs, {
+		options: {
+			ajaxOptions: null,
+			cache: false
+		},
+
+		_create: function() {
+			this._super();
+
+			var that = this;
+
+			this._on({ tabsbeforeload: function( event, ui ) {
+				// tab is already cached
+				if ( $.data( ui.tab[ 0 ], "cache.tabs" ) ) {
+					event.preventDefault();
+					return;
+				}
+
+				ui.jqXHR.success(function() {
+					if ( that.options.cache ) {
+						$.data( ui.tab[ 0 ], "cache.tabs", true );
+					}
+				});
+			}});
+		},
+
+		_ajaxSettings: function( anchor, event, ui ) {
+			var ajaxOptions = this.options.ajaxOptions;
+			return $.extend( {}, ajaxOptions, {
+				error: function( xhr, status ) {
+					try {
+						// Passing index avoid a race condition when this method is
+						// called after the user has selected another tab.
+						// Pass the anchor that initiated this request allows
+						// loadError to manipulate the tab content panel via $(a.hash)
+						ajaxOptions.error(
+							xhr, status, ui.tab.closest( "li" ).index(), ui.tab[ 0 ] );
+					}
+					catch ( error ) {}
+				}
+			}, this._superApply( arguments ) );
+		},
+
+		_setOption: function( key, value ) {
+			// reset cache if switching from cached to not cached
+			if ( key === "cache" && value === false ) {
+				this.anchors.removeData( "cache.tabs" );
+			}
+			this._super( key, value );
+		},
+
+		_destroy: function() {
+			this.anchors.removeData( "cache.tabs" );
+			this._super();
+		},
+
+		url: function( index ){
+			this.anchors.eq( index ).removeData( "cache.tabs" );
+			this._superApply( arguments );
+		}
+	});
+
+	// abort method
+	$.widget( "ui.tabs", $.ui.tabs, {
+		abort: function() {
+			if ( this.xhr ) {
+				this.xhr.abort();
+			}
+		}
+	});
+
+	// spinner
+	$.widget( "ui.tabs", $.ui.tabs, {
+		options: {
+			spinner: "<em>Loading&#8230;</em>"
+		},
+		_create: function() {
+			this._super();
+			this._on({
+				tabsbeforeload: function( event, ui ) {
+					// Don't react to nested tabs or tabs that don't use a spinner
+					if ( event.target !== this.element[ 0 ] ||
+							!this.options.spinner ) {
+						return;
+					}
+
+					var span = ui.tab.find( "span" ),
+						html = span.html();
+					span.html( this.options.spinner );
+					ui.jqXHR.complete(function() {
+						span.html( html );
+					});
+				}
+			});
+		}
+	});
+
+	// enable/disable events
+	$.widget( "ui.tabs", $.ui.tabs, {
+		options: {
+			enable: null,
+			disable: null
+		},
+
+		enable: function( index ) {
+			var options = this.options,
+				trigger;
+
+			if ( index && options.disabled === true ||
+					( $.isArray( options.disabled ) && $.inArray( index, options.disabled ) !== -1 ) ) {
+				trigger = true;
+			}
+
+			this._superApply( arguments );
+
+			if ( trigger ) {
+				this._trigger( "enable", null, this._ui( this.anchors[ index ], this.panels[ index ] ) );
+			}
+		},
+
+		disable: function( index ) {
+			var options = this.options,
+				trigger;
+
+			if ( index && options.disabled === false ||
+					( $.isArray( options.disabled ) && $.inArray( index, options.disabled ) === -1 ) ) {
+				trigger = true;
+			}
+
+			this._superApply( arguments );
+
+			if ( trigger ) {
+				this._trigger( "disable", null, this._ui( this.anchors[ index ], this.panels[ index ] ) );
+			}
+		}
+	});
+
+	// add/remove methods and events
+	$.widget( "ui.tabs", $.ui.tabs, {
+		options: {
+			add: null,
+			remove: null,
+			tabTemplate: "<li><a href='#{href}'><span>#{label}</span></a></li>"
+		},
+
+		add: function( url, label, index ) {
+			if ( index === undefined ) {
+				index = this.anchors.length;
+			}
+
+			var doInsertAfter, panel,
+				options = this.options,
+				li = $( options.tabTemplate
+					.replace( /#\{href\}/g, url )
+					.replace( /#\{label\}/g, label ) ),
+				id = !url.indexOf( "#" ) ?
+					url.replace( "#", "" ) :
+					this._tabId( li );
+
+			li.addClass( "ui-state-default ui-corner-top" ).data( "ui-tabs-destroy", true );
+			li.attr( "aria-controls", id );
+
+			doInsertAfter = index >= this.tabs.length;
+
+			// try to find an existing element before creating a new one
+			panel = this.element.find( "#" + id );
+			if ( !panel.length ) {
+				panel = this._createPanel( id );
+				if ( doInsertAfter ) {
+					if ( index > 0 ) {
+						panel.insertAfter( this.panels.eq( -1 ) );
+					} else {
+						panel.appendTo( this.element );
+					}
+				} else {
+					panel.insertBefore( this.panels[ index ] );
+				}
+			}
+			panel.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ).hide();
+
+			if ( doInsertAfter ) {
+				li.appendTo( this.tablist );
+			} else {
+				li.insertBefore( this.tabs[ index ] );
+			}
+
+			options.disabled = $.map( options.disabled, function( n ) {
+				return n >= index ? ++n : n;
+			});
+
+			this.refresh();
+			if ( this.tabs.length === 1 && options.active === false ) {
+				this.option( "active", 0 );
+			}
+
+			this._trigger( "add", null, this._ui( this.anchors[ index ], this.panels[ index ] ) );
+			return this;
+		},
+
+		remove: function( index ) {
+			index = this._getIndex( index );
+			var options = this.options,
+				tab = this.tabs.eq( index ).remove(),
+				panel = this._getPanelForTab( tab ).remove();
+
+			// If selected tab was removed focus tab to the right or
+			// in case the last tab was removed the tab to the left.
+			// We check for more than 2 tabs, because if there are only 2,
+			// then when we remove this tab, there will only be one tab left
+			// so we don't need to detect which tab to activate.
+			if ( tab.hasClass( "ui-tabs-active" ) && this.anchors.length > 2 ) {
+				this._activate( index + ( index + 1 < this.anchors.length ? 1 : -1 ) );
+			}
+
+			options.disabled = $.map(
+				$.grep( options.disabled, function( n ) {
+					return n !== index;
+				}),
+				function( n ) {
+					return n >= index ? --n : n;
+				});
+
+			this.refresh();
+
+			this._trigger( "remove", null, this._ui( tab.find( "a" )[ 0 ], panel[ 0 ] ) );
+			return this;
+		}
+	});
+
+	// length method
+	$.widget( "ui.tabs", $.ui.tabs, {
+		length: function() {
+			return this.anchors.length;
+		}
+	});
+
+	// panel ids (idPrefix option + title attribute)
+	$.widget( "ui.tabs", $.ui.tabs, {
+		options: {
+			idPrefix: "ui-tabs-"
+		},
+
+		_tabId: function( tab ) {
+			var a = tab.is( "li" ) ? tab.find( "a[href]" ) : tab;
+			a = a[0];
+			return $( a ).closest( "li" ).attr( "aria-controls" ) ||
+				a.title && a.title.replace( /\s/g, "_" ).replace( /[^\w\u00c0-\uFFFF\-]/g, "" ) ||
+				this.options.idPrefix + getNextTabId();
+		}
+	});
+
+	// _createPanel method
+	$.widget( "ui.tabs", $.ui.tabs, {
+		options: {
+			panelTemplate: "<div></div>"
+		},
+
+		_createPanel: function( id ) {
+			return $( this.options.panelTemplate )
+				.attr( "id", id )
+				.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" )
+				.data( "ui-tabs-destroy", true );
+		}
+	});
+
+	// selected option
+	$.widget( "ui.tabs", $.ui.tabs, {
+		_create: function() {
+			var options = this.options;
+			if ( options.active === null && options.selected !== undefined ) {
+				options.active = options.selected === -1 ? false : options.selected;
+			}
+			this._super();
+			options.selected = options.active;
+			if ( options.selected === false ) {
+				options.selected = -1;
+			}
+		},
+
+		_setOption: function( key, value ) {
+			if ( key !== "selected" ) {
+				return this._super( key, value );
+			}
+
+			var options = this.options;
+			this._super( "active", value === -1 ? false : value );
+			options.selected = options.active;
+			if ( options.selected === false ) {
+				options.selected = -1;
+			}
+		},
+
+		_eventHandler: function() {
+			this._superApply( arguments );
+			this.options.selected = this.options.active;
+			if ( this.options.selected === false ) {
+				this.options.selected = -1;
+			}
+		}
+	});
+
+	// show and select event
+	$.widget( "ui.tabs", $.ui.tabs, {
+		options: {
+			show: null,
+			select: null
+		},
+		_create: function() {
+			this._super();
+			if ( this.options.active !== false ) {
+				this._trigger( "show", null, this._ui(
+					this.active.find( ".ui-tabs-anchor" )[ 0 ],
+					this._getPanelForTab( this.active )[ 0 ] ) );
+			}
+		},
+		_trigger: function( type, event, data ) {
+			var tab, panel,
+				ret = this._superApply( arguments );
+
+			if ( !ret ) {
+				return false;
+			}
+
+			if ( type === "beforeActivate" ) {
+				tab = data.newTab.length ? data.newTab : data.oldTab;
+				panel = data.newPanel.length ? data.newPanel : data.oldPanel;
+				ret = this._super( "select", event, {
+					tab: tab.find( ".ui-tabs-anchor" )[ 0],
+					panel: panel[ 0 ],
+					index: tab.closest( "li" ).index()
+				});
+			} else if ( type === "activate" && data.newTab.length ) {
+				ret = this._super( "show", event, {
+					tab: data.newTab.find( ".ui-tabs-anchor" )[ 0 ],
+					panel: data.newPanel[ 0 ],
+					index: data.newTab.closest( "li" ).index()
+				});
+			}
+			return ret;
+		}
+	});
+
+	// select method
+	$.widget( "ui.tabs", $.ui.tabs, {
+		select: function( index ) {
+			index = this._getIndex( index );
+			if ( index === -1 ) {
+				if ( this.options.collapsible && this.options.selected !== -1 ) {
+					index = this.options.selected;
+				} else {
+					return;
+				}
+			}
+			this.anchors.eq( index ).trigger( this.options.event + this.eventNamespace );
+		}
+	});
+
+	// cookie option
+	(function() {
+
+	var listId = 0;
+
+	$.widget( "ui.tabs", $.ui.tabs, {
+		options: {
+			cookie: null // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true }
+		},
+		_create: function() {
+			var options = this.options,
+				active;
+			if ( options.active == null && options.cookie ) {
+				active = parseInt( this._cookie(), 10 );
+				if ( active === -1 ) {
+					active = false;
+				}
+				options.active = active;
+			}
+			this._super();
+		},
+		_cookie: function( active ) {
+			var cookie = [ this.cookie ||
+				( this.cookie = this.options.cookie.name || "ui-tabs-" + (++listId) ) ];
+			if ( arguments.length ) {
+				cookie.push( active === false ? -1 : active );
+				cookie.push( this.options.cookie );
+			}
+			return $.cookie.apply( null, cookie );
+		},
+		_refresh: function() {
+			this._super();
+			if ( this.options.cookie ) {
+				this._cookie( this.options.active, this.options.cookie );
+			}
+		},
+		_eventHandler: function() {
+			this._superApply( arguments );
+			if ( this.options.cookie ) {
+				this._cookie( this.options.active, this.options.cookie );
+			}
+		},
+		_destroy: function() {
+			this._super();
+			if ( this.options.cookie ) {
+				this._cookie( null, this.options.cookie );
+			}
+		}
+	});
+
+	})();
+
+	// load event
+	$.widget( "ui.tabs", $.ui.tabs, {
+		_trigger: function( type, event, data ) {
+			var _data = $.extend( {}, data );
+			if ( type === "load" ) {
+				_data.panel = _data.panel[ 0 ];
+				_data.tab = _data.tab.find( ".ui-tabs-anchor" )[ 0 ];
+			}
+			return this._super( type, event, _data );
+		}
+	});
+
+	// fx option
+	// The new animation options (show, hide) conflict with the old show callback.
+	// The old fx option wins over show/hide anyway (always favor back-compat).
+	// If a user wants to use the new animation API, they must give up the old API.
+	$.widget( "ui.tabs", $.ui.tabs, {
+		options: {
+			fx: null // e.g. { height: "toggle", opacity: "toggle", duration: 200 }
+		},
+
+		_getFx: function() {
+			var hide, show,
+				fx = this.options.fx;
+
+			if ( fx ) {
+				if ( $.isArray( fx ) ) {
+					hide = fx[ 0 ];
+					show = fx[ 1 ];
+				} else {
+					hide = show = fx;
+				}
+			}
+
+			return fx ? { show: show, hide: hide } : null;
+		},
+
+		_toggle: function( event, eventData ) {
+			var that = this,
+				toShow = eventData.newPanel,
+				toHide = eventData.oldPanel,
+				fx = this._getFx();
+
+			if ( !fx ) {
+				return this._super( event, eventData );
+			}
+
+			that.running = true;
+
+			function complete() {
+				that.running = false;
+				that._trigger( "activate", event, eventData );
+			}
+
+			function show() {
+				eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" );
+
+				if ( toShow.length && fx.show ) {
+					toShow
+						.animate( fx.show, fx.show.duration, function() {
+							complete();
+						});
+				} else {
+					toShow.show();
+					complete();
+				}
+			}
+
+			// start out by hiding, then showing, then completing
+			if ( toHide.length && fx.hide ) {
+				toHide.animate( fx.hide, fx.hide.duration, function() {
+					eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
+					show();
+				});
+			} else {
+				eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" );
+				toHide.hide();
+				show();
+			}
+		}
+	});
+}
+
+})( jQuery );
+
+(function( $ ) {
+
+var increments = 0;
+
+function addDescribedBy( elem, id ) {
+	var describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ );
+	describedby.push( id );
+	elem
+		.data( "ui-tooltip-id", id )
+		.attr( "aria-describedby", $.trim( describedby.join( " " ) ) );
+}
+
+function removeDescribedBy( elem ) {
+	var id = elem.data( "ui-tooltip-id" ),
+		describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ),
+		index = $.inArray( id, describedby );
+	if ( index !== -1 ) {
+		describedby.splice( index, 1 );
+	}
+
+	elem.removeData( "ui-tooltip-id" );
+	describedby = $.trim( describedby.join( " " ) );
+	if ( describedby ) {
+		elem.attr( "aria-describedby", describedby );
+	} else {
+		elem.removeAttr( "aria-describedby" );
+	}
+}
+
+$.widget( "ui.tooltip", {
+	version: "1.9.2",
+	options: {
+		content: function() {
+			return $( this ).attr( "title" );
+		},
+		hide: true,
+		// Disabled elements have inconsistent behavior across browsers (#8661)
+		items: "[title]:not([disabled])",
+		position: {
+			my: "left top+15",
+			at: "left bottom",
+			collision: "flipfit flip"
+		},
+		show: true,
+		tooltipClass: null,
+		track: false,
+
+		// callbacks
+		close: null,
+		open: null
+	},
+
+	_create: function() {
+		this._on({
+			mouseover: "open",
+			focusin: "open"
+		});
+
+		// IDs of generated tooltips, needed for destroy
+		this.tooltips = {};
+		// IDs of parent tooltips where we removed the title attribute
+		this.parents = {};
+
+		if ( this.options.disabled ) {
+			this._disable();
+		}
+	},
+
+	_setOption: function( key, value ) {
+		var that = this;
+
+		if ( key === "disabled" ) {
+			this[ value ? "_disable" : "_enable" ]();
+			this.options[ key ] = value;
+			// disable element style changes
+			return;
+		}
+
+		this._super( key, value );
+
+		if ( key === "content" ) {
+			$.each( this.tooltips, function( id, element ) {
+				that._updateContent( element );
+			});
+		}
+	},
+
+	_disable: function() {
+		var that = this;
+
+		// close open tooltips
+		$.each( this.tooltips, function( id, element ) {
+			var event = $.Event( "blur" );
+			event.target = event.currentTarget = element[0];
+			that.close( event, true );
+		});
+
+		// remove title attributes to prevent native tooltips
+		this.element.find( this.options.items ).andSelf().each(function() {
+			var element = $( this );
+			if ( element.is( "[title]" ) ) {
+				element
+					.data( "ui-tooltip-title", element.attr( "title" ) )
+					.attr( "title", "" );
+			}
+		});
+	},
+
+	_enable: function() {
+		// restore title attributes
+		this.element.find( this.options.items ).andSelf().each(function() {
+			var element = $( this );
+			if ( element.data( "ui-tooltip-title" ) ) {
+				element.attr( "title", element.data( "ui-tooltip-title" ) );
+			}
+		});
+	},
+
+	open: function( event ) {
+		var that = this,
+			target = $( event ? event.target : this.element )
+				// we need closest here due to mouseover bubbling,
+				// but always pointing at the same event target
+				.closest( this.options.items );
+
+		// No element to show a tooltip for or the tooltip is already open
+		if ( !target.length || target.data( "ui-tooltip-id" ) ) {
+			return;
+		}
+
+		if ( target.attr( "title" ) ) {
+			target.data( "ui-tooltip-title", target.attr( "title" ) );
+		}
+
+		target.data( "ui-tooltip-open", true );
+
+		// kill parent tooltips, custom or native, for hover
+		if ( event && event.type === "mouseover" ) {
+			target.parents().each(function() {
+				var parent = $( this ),
+					blurEvent;
+				if ( parent.data( "ui-tooltip-open" ) ) {
+					blurEvent = $.Event( "blur" );
+					blurEvent.target = blurEvent.currentTarget = this;
+					that.close( blurEvent, true );
+				}
+				if ( parent.attr( "title" ) ) {
+					parent.uniqueId();
+					that.parents[ this.id ] = {
+						element: this,
+						title: parent.attr( "title" )
+					};
+					parent.attr( "title", "" );
+				}
+			});
+		}
+
+		this._updateContent( target, event );
+	},
+
+	_updateContent: function( target, event ) {
+		var content,
+			contentOption = this.options.content,
+			that = this,
+			eventType = event ? event.type : null;
+
+		if ( typeof contentOption === "string" ) {
+			return this._open( event, target, contentOption );
+		}
+
+		content = contentOption.call( target[0], function( response ) {
+			// ignore async response if tooltip was closed already
+			if ( !target.data( "ui-tooltip-open" ) ) {
+				return;
+			}
+			// IE may instantly serve a cached response for ajax requests
+			// delay this call to _open so the other call to _open runs first
+			that._delay(function() {
+				// jQuery creates a special event for focusin when it doesn't
+				// exist natively. To improve performance, the native event
+				// object is reused and the type is changed. Therefore, we can't
+				// rely on the type being correct after the event finished
+				// bubbling, so we set it back to the previous value. (#8740)
+				if ( event ) {
+					event.type = eventType;
+				}
+				this._open( event, target, response );
+			});
+		});
+		if ( content ) {
+			this._open( event, target, content );
+		}
+	},
+
+	_open: function( event, target, content ) {
+		var tooltip, events, delayedShow,
+			positionOption = $.extend( {}, this.options.position );
+
+		if ( !content ) {
+			return;
+		}
+
+		// Content can be updated multiple times. If the tooltip already
+		// exists, then just update the content and bail.
+		tooltip = this._find( target );
+		if ( tooltip.length ) {
+			tooltip.find( ".ui-tooltip-content" ).html( content );
+			return;
+		}
+
+		// if we have a title, clear it to prevent the native tooltip
+		// we have to check first to avoid defining a title if none exists
+		// (we don't want to cause an element to start matching [title])
+		//
+		// We use removeAttr only for key events, to allow IE to export the correct
+		// accessible attributes. For mouse events, set to empty string to avoid
+		// native tooltip showing up (happens only when removing inside mouseover).
+		if ( target.is( "[title]" ) ) {
+			if ( event && event.type === "mouseover" ) {
+				target.attr( "title", "" );
+			} else {
+				target.removeAttr( "title" );
+			}
+		}
+
+		tooltip = this._tooltip( target );
+		addDescribedBy( target, tooltip.attr( "id" ) );
+		tooltip.find( ".ui-tooltip-content" ).html( content );
+
+		function position( event ) {
+			positionOption.of = event;
+			if ( tooltip.is( ":hidden" ) ) {
+				return;
+			}
+			tooltip.position( positionOption );
+		}
+		if ( this.options.track && event && /^mouse/.test( event.type ) ) {
+			this._on( this.document, {
+				mousemove: position
+			});
+			// trigger once to override element-relative positioning
+			position( event );
+		} else {
+			tooltip.position( $.extend({
+				of: target
+			}, this.options.position ) );
+		}
+
+		tooltip.hide();
+
+		this._show( tooltip, this.options.show );
+		// Handle tracking tooltips that are shown with a delay (#8644). As soon
+		// as the tooltip is visible, position the tooltip using the most recent
+		// event.
+		if ( this.options.show && this.options.show.delay ) {
+			delayedShow = setInterval(function() {
+				if ( tooltip.is( ":visible" ) ) {
+					position( positionOption.of );
+					clearInterval( delayedShow );
+				}
+			}, $.fx.interval );
+		}
+
+		this._trigger( "open", event, { tooltip: tooltip } );
+
+		events = {
+			keyup: function( event ) {
+				if ( event.keyCode === $.ui.keyCode.ESCAPE ) {
+					var fakeEvent = $.Event(event);
+					fakeEvent.currentTarget = target[0];
+					this.close( fakeEvent, true );
+				}
+			},
+			remove: function() {
+				this._removeTooltip( tooltip );
+			}
+		};
+		if ( !event || event.type === "mouseover" ) {
+			events.mouseleave = "close";
+		}
+		if ( !event || event.type === "focusin" ) {
+			events.focusout = "close";
+		}
+		this._on( true, target, events );
+	},
+
+	close: function( event ) {
+		var that = this,
+			target = $( event ? event.currentTarget : this.element ),
+			tooltip = this._find( target );
+
+		// disabling closes the tooltip, so we need to track when we're closing
+		// to avoid an infinite loop in case the tooltip becomes disabled on close
+		if ( this.closing ) {
+			return;
+		}
+
+		// only set title if we had one before (see comment in _open())
+		if ( target.data( "ui-tooltip-title" ) ) {
+			target.attr( "title", target.data( "ui-tooltip-title" ) );
+		}
+
+		removeDescribedBy( target );
+
+		tooltip.stop( true );
+		this._hide( tooltip, this.options.hide, function() {
+			that._removeTooltip( $( this ) );
+		});
+
+		target.removeData( "ui-tooltip-open" );
+		this._off( target, "mouseleave focusout keyup" );
+		// Remove 'remove' binding only on delegated targets
+		if ( target[0] !== this.element[0] ) {
+			this._off( target, "remove" );
+		}
+		this._off( this.document, "mousemove" );
+
+		if ( event && event.type === "mouseleave" ) {
+			$.each( this.parents, function( id, parent ) {
+				$( parent.element ).attr( "title", parent.title );
+				delete that.parents[ id ];
+			});
+		}
+
+		this.closing = true;
+		this._trigger( "close", event, { tooltip: tooltip } );
+		this.closing = false;
+	},
+
+	_tooltip: function( element ) {
+		var id = "ui-tooltip-" + increments++,
+			tooltip = $( "<div>" )
+				.attr({
+					id: id,
+					role: "tooltip"
+				})
+				.addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content " +
+					( this.options.tooltipClass || "" ) );
+		$( "<div>" )
+			.addClass( "ui-tooltip-content" )
+			.appendTo( tooltip );
+		tooltip.appendTo( this.document[0].body );
+		if ( $.fn.bgiframe ) {
+			tooltip.bgiframe();
+		}
+		this.tooltips[ id ] = element;
+		return tooltip;
+	},
+
+	_find: function( target ) {
+		var id = target.data( "ui-tooltip-id" );
+		return id ? $( "#" + id ) : $();
+	},
+
+	_removeTooltip: function( tooltip ) {
+		tooltip.remove();
+		delete this.tooltips[ tooltip.attr( "id" ) ];
+	},
+
+	_destroy: function() {
+		var that = this;
+
+		// close open tooltips
+		$.each( this.tooltips, function( id, element ) {
+			// Delegate to close method to handle common cleanup
+			var event = $.Event( "blur" );
+			event.target = event.currentTarget = element[0];
+			that.close( event, true );
+
+			// Remove immediately; destroying an open tooltip doesn't use the
+			// hide animation
+			$( "#" + id ).remove();
+
+			// Restore the title
+			if ( element.data( "ui-tooltip-title" ) ) {
+				element.attr( "title", element.data( "ui-tooltip-title" ) );
+				element.removeData( "ui-tooltip-title" );
+			}
+		});
+	}
+});
+
+}( jQuery ) );
diff --git a/pub/lib/jquery/jquery.tabs.js b/pub/lib/jquery/jquery.tabs.js
index 92a3793838478b8a5bd7900caed3c3a5736a7d54..e02dbd1a1746922bbaf67c99a53afde77ea8ccbd 100644
--- a/pub/lib/jquery/jquery.tabs.js
+++ b/pub/lib/jquery/jquery.tabs.js
@@ -291,4 +291,4 @@
     })
   })
 
-}(window.jQuery);
\ No newline at end of file
+}(window.jQuery);
diff --git a/pub/lib/jquery/jstree/themes/default/style.css b/pub/lib/jquery/jstree/themes/default/style.css
index 7ef6a04308050b5ed3fc10b3c102a71f716f1084..c8bbd01311599e378e1ab34eb1f253a3ac74add7 100644
--- a/pub/lib/jquery/jstree/themes/default/style.css
+++ b/pub/lib/jquery/jstree/themes/default/style.css
@@ -12,12 +12,12 @@
 .jstree-default .jstree-closed > ins { background-position:-54px 0; }
 .jstree-default .jstree-leaf > ins { background-position:-36px 0; }
 
-.jstree-default .jstree-hovered { background:#e7f4f9; border:1px solid #d8f0fa; padding:0 2px 0 1px; }
-.jstree-default .jstree-clicked { background:#beebff; border:1px solid #99defd; padding:0 2px 0 1px; }
+.jstree-default .jstree-hovered { background:#f1f8fc; }
+.jstree-default .jstree-clicked { background:#cdecf6; }
 .jstree-default a .jstree-icon { background-position:-56px -19px; }
 .jstree-default a.jstree-loading .jstree-icon { background:url("throbber.gif") center center no-repeat !important; }
 
-.jstree-default.jstree-focused { background:#ffffee; }
+.jstree-default.jstree-focused { background:#fff; }
 
 .jstree-default .jstree-no-dots li, 
 .jstree-default .jstree-no-dots .jstree-leaf > ins { background:transparent; }
diff --git a/pub/lib/mage/backend/multisuggest.js b/pub/lib/mage/backend/multisuggest.js
deleted file mode 100644
index cb6bcfcb29e6f92234c9aecabb2e75ed9fc07a6a..0000000000000000000000000000000000000000
--- a/pub/lib/mage/backend/multisuggest.js
+++ /dev/null
@@ -1,166 +0,0 @@
-/**
- * Magento
- *
- * NOTICE OF LICENSE
- *
- * This source file is subject to the Academic Free License (AFL 3.0)
- * that is bundled with this package in the file LICENSE_AFL.txt.
- * It is also available through the world-wide-web at this URL:
- * http://opensource.org/licenses/afl-3.0.php
- * If you did not receive a copy of the license and are unable to
- * obtain it through the world-wide-web, please send an email
- * to license@magentocommerce.com so we can send you a copy immediately.
- *
- * DISCLAIMER
- *
- * Do not edit or add to this file if you wish to upgrade Magento to newer
- * versions in the future. If you wish to customize Magento for your
- * needs please refer to http://www.magentocommerce.com for more information.
- *
- * @category    mage
- * @package     mage
- * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
- * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
- */
-/*jshint jquery:true browser:true*/
-(function($) {
-    'use strict';
-    $.widget('mage.suggest', $.mage.suggest, {
-        /**
-         * @override
-         */
-        _create: function() {
-            this._super();
-            if (this.options.multiselect) {
-                this.valueField.hide();
-            }
-        },
-
-        /**
-         * @override
-         */
-        _prepareValueField: function() {
-            this._super();
-            if (this.options.multiselect && !this.options.valueField && this.options.selectedItems) {
-                $.each(this.options.selectedItems, $.proxy(function(i, item) {
-                    this._addOption(item);
-                }, this));
-            }
-        },
-
-        /**
-         * @override
-         */
-        _createValueField: function() {
-            if (this.options.multiselect) {
-                return $('<select/>', {
-                    type: 'hidden',
-                    multiple: 'multiple'
-                });
-            } else {
-                return this._super();
-            }
-        },
-
-        /**
-         * @override
-         */
-        _selectItem: function() {
-            if (this.options.multiselect) {
-                if (this.isDropdownShown() && this._focused) {
-                    this._selectedItem = this._readItemData(this._focused);
-                    if (this.valueField.find('option[value=' + this._selectedItem.id + ']').length) {
-                        this._selectedItem = this._nonSelectedItem;
-                    }
-                    if (this._selectedItem !== this._nonSelectedItem) {
-                        this._term = '';
-                        this._addOption(this._selectedItem);
-                    }
-                }
-            } else {
-                this._super();
-            }
-        },
-
-        /**
-         * Add selected item in to select options
-         * @param item
-         * @private
-         */
-        _addOption: function(item) {
-            this.valueField.append(
-                '<option value="' + item.id + '" selected="selected">' + item.label + '</option>'
-            );
-        },
-
-        /**
-         * Remove item from select options
-         * @param item
-         * @private
-         */
-        _removeOption: function(item) {
-            this.valueField.find('option[value=' + item.id + ']').remove();
-        },
-
-        /**
-         * @override
-         */
-        _hideDropdown: function() {
-            this._super();
-            if (this.options.multiselect) {
-                this.element.val('');
-            }
-        }
-    });
-
-    $.widget('mage.suggest', $.mage.suggest, {
-        options: {
-            multiSuggestWrapper: '<ul class="category-selector-choices">' +
-                '<li class="category-selector-search-field"></li></ul>',
-            choiceTemplate: '<li class="category-selector-search-choice button"><div>${text}</div>' +
-                '<span class="category-selector-search-choice-close" tabindex="-1" ' +
-                'data-mage-init="{&quot;actionLink&quot;:{&quot;event&quot;:&quot;removeOption&quot;}}"></span></li>'
-        },
-
-        /**
-         * @override
-         */
-        _render: function() {
-            this._super();
-            if (this.options.multiselect) {
-                this.element.wrap(this.options.multiSuggestWrapper);
-                this.elementWrapper = this.element.parent();
-                this.valueField.find('option').each($.proxy(function(i, option) {
-                    option = $(option);
-                    this._renderOption({id: option.val(), label: option.text()});
-                }, this));
-            }
-        },
-
-        /**
-         * @override
-         */
-        _selectItem: function() {
-            this._superApply(arguments);
-            if (this.options.multiselect && this._selectedItem !== this._nonSelectedItem) {
-                this._renderOption(this._selectedItem);
-            }
-        },
-
-        /**
-         * Render visual element of selected item
-         * @param {Object} item - selected item
-         * @private
-         */
-        _renderOption: function(item) {
-            $.tmpl(this.options.choiceTemplate, {text: item.label})
-                .data(item)
-                .insertBefore(this.elementWrapper)
-                .trigger('contentUpdated')
-                .on('removeOption', $.proxy(function(e) {
-                    this._removeOption($(e.currentTarget).data());
-                    $(e.currentTarget).remove();
-                }, this));
-        }
-    });
-})(jQuery);
diff --git a/pub/lib/mage/backend/notification.js b/pub/lib/mage/backend/notification.js
index 5097fb479dbe1f302046a59db0c0c81fb66b1054..ca7be4f881832da73b9fca47922ca13fb7d34337 100644
--- a/pub/lib/mage/backend/notification.js
+++ b/pub/lib/mage/backend/notification.js
@@ -52,7 +52,7 @@
         _add: function(event, jqXHR) {
             try {
                 var response = $.parseJSON(jqXHR.responseText);
-                if (response && response.error) {
+                if (response && response.error && response.message) {
                     this.element.append($.tmpl('globalNotification', response));
                 }
             } catch(e) {}
diff --git a/pub/lib/mage/backend/suggest.js b/pub/lib/mage/backend/suggest.js
index 79ddbe558b5436ea3da49112057be2bf7ee453e7..a909f2e99c779a2c51c21f929b4eca92caca7200 100644
--- a/pub/lib/mage/backend/suggest.js
+++ b/pub/lib/mage/backend/suggest.js
@@ -71,7 +71,7 @@
         },
 
         /**
-         * Render base elemments for suggest component
+         * Render base elements for suggest component
          * @private
          */
         _render: function() {
@@ -339,8 +339,9 @@
          */
         _setTemplate: function() {
             this.templateName = 'suggest' + Math.random().toString(36).substr(2);
-            if ($(this.options.template).length && $(this.options.template).prop('type')=== 'text/x-jquery-tmpl') {
-                $(this.options.template).template(this.templateName);
+            var template = $(this.options.template);
+            if (template.length && template.prop('type')=== 'text/x-jquery-tmpl') {
+                template.template(this.templateName);
             } else {
                 $.template(this.templateName, this.options.template);
             }
@@ -395,7 +396,8 @@
                 items: this._items,
                 term: this._term,
                 optionData: function(item) {
-                    return 'data-suggest-option="' + JSON.stringify(item).replace(/"/g, '&quot;') + '"';
+                    return 'data-suggest-option="' +
+                        $('<div>').text(JSON.stringify(item)).html().replace(/"/g, '&quot;') + '"';
                 }
             });
         },
@@ -419,26 +421,32 @@
         },
 
         /**
-         * Implement search process via spesific source
+         * Implement search process via specific source
          * @param {string} term - search phrase
          * @param {Function} renderer - search results handler, display search result
          * @private
          */
         _source: function(term, renderer) {
-            if ($.isArray(this.options.source)) {
-                renderer(this.filter(this.options.source, term));
-
-            } else if ($.type(this.options.source) === 'string') {
+            var o = this.options;
+            if ($.isArray(o.source)) {
+                renderer(this.filter(o.source, term));
+            } else if ($.type(o.source) === 'string') {
                 if (this._xhr) {
                     this._xhr.abort();
                 }
                 this._xhr = $.ajax($.extend({
-                    url: this.options.source,
+                    url: o.source,
                     type: 'POST',
                     dataType: 'json',
-                    data: {name_part: term},
-                    success: renderer
-                }, this.options.ajaxOptions || {}));
+                    data: $.extend({label_part: term}, o.ajaxData || {}),
+                    /* @todo refactor this to use 'response' event instead of o.response */
+                    success: function(data) {
+                        if ($.type(o.response) === 'function') {
+                            data = o.response(data);
+                        }
+                        renderer(data);
+                    }
+                }, o.ajaxOptions || {}));
             }
         },
 
@@ -456,7 +464,7 @@
          * @return {Object}
          */
         filter: function(items, term) {
-            var matcher = new RegExp(term, 'i');
+            var matcher = new RegExp(term.replace(/[\-\/\\\^$*+?.()|\[\]{}]/g, '\\$&'), 'i');
             return $.grep(items, function(value) {
                 return matcher.test(value.label || value.id || value);
             });
@@ -568,7 +576,7 @@
         },
 
         /**
-         * Add selected item of search result into storage of recents
+         * Add selected item of search result into storage of recent items
          * @param {Object} item - label+id object
          * @private
          */
@@ -636,4 +644,155 @@
             });
         }
     });
+
+    /**
+     * Implement multi suggest functionality
+     */
+    $.widget('mage.suggest', $.mage.suggest, {
+        /**
+         * @override
+         */
+        _create: function() {
+            this._super();
+            if (this.options.multiselect) {
+                this.valueField.hide();
+            }
+        },
+
+        /**
+         * @override
+         */
+        _prepareValueField: function() {
+            this._super();
+            if (this.options.multiselect && !this.options.valueField && this.options.selectedItems) {
+                $.each(this.options.selectedItems, $.proxy(function(i, item) {
+                    this._addOption(item);
+                }, this));
+            }
+        },
+
+        /**
+         * @override
+         */
+        _createValueField: function() {
+            if (this.options.multiselect) {
+                return $('<select/>', {
+                    type: 'hidden',
+                    multiple: 'multiple'
+                });
+            } else {
+                return this._super();
+            }
+        },
+
+        /**
+         * @override
+         */
+        _selectItem: function() {
+            if (this.options.multiselect) {
+                if (this.isDropdownShown() && this._focused) {
+                    this._selectedItem = this._readItemData(this._focused);
+                    if (this.valueField.find('option[value=' + this._selectedItem.id + ']').length) {
+                        this._selectedItem = this._nonSelectedItem;
+                    }
+                    if (this._selectedItem !== this._nonSelectedItem) {
+                        this._term = '';
+                        this._addOption(this._selectedItem);
+                    }
+                }
+            } else {
+                this._super();
+            }
+        },
+
+        /**
+         * Add selected item in to select options
+         * @param item
+         * @private
+         */
+        _addOption: function(item) {
+            this.valueField.append($('<option>', {value: item.id, selected: true}).text(item.label));             
+        },
+
+        /**
+         * Remove item from select options
+         * @param item
+         * @private
+         */
+        _removeOption: function(item) {
+            this.valueField.find('option[value=' + item.id + ']').remove();
+        },
+
+        /**
+         * @override
+         */
+        _hideDropdown: function() {
+            this._super();
+            if (this.options.multiselect) {
+                this.element.val('');
+            }
+        }
+    });
+
+    $.widget('mage.suggest', $.mage.suggest, {
+        options: {
+            multiSuggestWrapper: '<ul class="category-selector-choices">' +
+                '<li class="category-selector-search-field"></li></ul>',
+            choiceTemplate: '<li class="category-selector-search-choice button"><div>${text}</div>' +
+                '<span class="category-selector-search-choice-close" tabindex="-1" ' +
+                'data-mage-init="{actionLink:{event:&quot;removeOption&quot;}}"></span></li>'
+        },
+
+        /**
+         * @override
+         */
+        _render: function() {
+            this._super();
+            if (this.options.multiselect) {
+                this.element.wrap(this.options.multiSuggestWrapper);
+                this.elementWrapper = this.element.parent();
+                this.valueField.find('option').each($.proxy(function(i, option) {
+                    option = $(option);
+                    this._renderOption({id: option.val(), label: option.text()});
+                }, this));
+            }
+        },
+
+        /**
+         * @override
+         */
+        _selectItem: function() {
+            this._superApply(arguments);
+            if (this.options.multiselect && this._selectedItem !== this._nonSelectedItem) {
+                this._renderOption(this._selectedItem);
+            }
+        },
+
+        /**
+         * Render visual element of selected item
+         * @param {Object} item - selected item
+         * @private
+         */
+        _renderOption: function(item) {
+            $.tmpl(this.options.choiceTemplate, {text: item.label})
+                .data(item)
+                .insertBefore(this.elementWrapper)
+                .trigger('contentUpdated')
+                .on('removeOption', $.proxy(function(e) {
+                this._removeOption($(e.currentTarget).data());
+                $(e.currentTarget).remove();
+            }, this));
+        },
+
+        /**
+         * Select item
+         * @todo Refactor widget to make this possible via event triggering
+         */
+        selectItem: function(item) {
+            this._term = item.label;
+            this.valueField.val(item.id);
+            this._addOption(item);
+            this._renderOption(item);
+        }
+    });
 })(jQuery);
diff --git a/pub/lib/mage/backend/tabs.js b/pub/lib/mage/backend/tabs.js
index 81063931c9aaaba10ff93fa5fefe79e106129914..1d957d5004b14e3ddb387792035ba8c42f31683c 100644
--- a/pub/lib/mage/backend/tabs.js
+++ b/pub/lib/mage/backend/tabs.js
@@ -130,7 +130,7 @@
         _movePanelsInDestination: function(panels) {
             if (this.options.destination && !panels.parents(this.options.destination).length) {
                 panels
-                    .find('script').remove();
+                    .find('script[type!="text/x-jquery-tmpl"]').remove();
                 panels.appendTo(this.options.destination)
                     .each($.proxy(function(i, panel) {
                         $(panel).trigger('move.tabs', this.anchors.eq(i));
@@ -167,7 +167,9 @@
              * @param {Object}
              */
             load: function(event, ui) {
-                $(ui.tab).prop('href', '#' + $(ui.panel).prop('id'));
+                var panel = $(ui.panel);
+                $(ui.tab).prop('href', '#' + panel.prop('id'));
+                panel.trigger('contentUpdated');
             }
         }
     });
diff --git a/pub/lib/mage/backend/validation.js b/pub/lib/mage/backend/validation.js
index 0fdc51455e51006ea8be59bc9efe596ebd9c2878..5d9ba76a8d1ced2a10abba588d402f07f76b5f62 100644
--- a/pub/lib/mage/backend/validation.js
+++ b/pub/lib/mage/backend/validation.js
@@ -55,6 +55,28 @@
         }
     });
 
+    $.extend($.fn, {
+        /**
+         * ValidationDelegate overridden for those cases where the form is located in another form,
+         *     to avoid not correct working of validate plug-in
+         * @override
+         * @param {string} delegate - selector, if event target matched against this selector,
+         *     then event will be delegated
+         * @param {string} type - event type
+         * @param {function} handler - event handler
+         * @return {Element}
+         */
+        validateDelegate: function (delegate, type, handler) {
+            return this.on(type, $.proxy(function (event) {
+                var target = $(event.target);
+                var form = target[0].form;
+                if(form && $(form).is(this) && $.data(form, "validator") && target.is(delegate)) {
+                    return handler.apply(target, arguments);
+                }
+            }, this));
+        }
+    });
+
     $.widget("mage.validation", $.mage.validation, {
         options: {
             messagesId: 'messages',
diff --git a/pub/lib/mage/common.js b/pub/lib/mage/common.js
new file mode 100644
index 0000000000000000000000000000000000000000..0585e6fbf4cb4d1b88d13c93390ad6fae57dbb92
--- /dev/null
+++ b/pub/lib/mage/common.js
@@ -0,0 +1,31 @@
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    mage
+ * @package     mage
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+/*jshint browser:true jquery:true*/
+jQuery(function ($) {
+    $(document).ready(function(){
+        /* Form with auto submit feature */
+        $('form[data-auto-submit="true"]').submit();
+    });
+});
\ No newline at end of file
diff --git a/pub/lib/mage/mage.js b/pub/lib/mage/mage.js
index bf6f6a56f73589032dec435e3c0e6d2b4dd53d15..694d7a0bd65b53d3ef4fa10ae16e027d4bcfe7e6 100644
--- a/pub/lib/mage/mage.js
+++ b/pub/lib/mage/mage.js
@@ -247,7 +247,7 @@
          *     (several components may be passed also as separate arguments)
          * @return {Object} $.mage
          */
-        load: function(component) {
+        load: function() {
             $.each(arguments, function(i, component) {
                 if (_resources[component] && _resources[component].length) {
                     _onload(_resources[component]);
@@ -258,25 +258,28 @@
     });
 })(jQuery);
 
-(function($) {
+(function($, window) {
     "use strict";
-    $.extend(true, $, {
-        mage: {
-            constant: {
-                KEY_BACKSPACE: 8,
-                KEY_TAB: 9,
-                KEY_RETURN: 13,
-                KEY_ESC: 27,
-                KEY_LEFT: 37,
-                KEY_UP: 38,
-                KEY_RIGHT: 39,
-                KEY_DOWN: 40,
-                KEY_DELETE: 46,
-                KEY_HOME: 36,
-                KEY_END: 35,
-                KEY_PAGEUP: 33,
-                KEY_PAGEDOWN: 34
+    $.extend($.mage, {
+            /**
+             * Method handling redirects and page refresh
+             * @param {String} url - redirect URL
+             * @param {(undefined|String)} type - 'assign', 'reload', 'replace'
+             * @param {(undefined|Number)} timeout - timeout in milliseconds before processing the redirect or reload
+             * @param {(undefined|Boolean)} forced - true|false used for 'reload' only
+             */
+            redirect: function(url, type, timeout, forced) {
+                forced = forced ? true : false;
+                timeout = timeout ? timeout : 0;
+                type = type ? type : "assign";
+                var _redirect = function() {
+                    window.location[type](type === 'reload' ? forced : url);
+                };
+                if (timeout) {
+                    setTimeout(_redirect, timeout);
+                } else {
+                    _redirect();
+                }
             }
-        }
     });
-})(jQuery);
+})(jQuery, window);
diff --git a/pub/lib/mage/toggle.js b/pub/lib/mage/toggle.js
new file mode 100644
index 0000000000000000000000000000000000000000..8bca9964a9c34b5368ec512d2fe8c83320d02a57
--- /dev/null
+++ b/pub/lib/mage/toggle.js
@@ -0,0 +1,198 @@
+/**
+ * Magento
+ *
+ * NOTICE OF LICENSE
+ *
+ * This source file is subject to the Academic Free License (AFL 3.0)
+ * that is bundled with this package in the file LICENSE_AFL.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://opensource.org/licenses/afl-3.0.php
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@magentocommerce.com so we can send you a copy immediately.
+ *
+ * DISCLAIMER
+ *
+ * Do not edit or add to this file if you wish to upgrade Magento to newer
+ * versions in the future. If you wish to customize Magento for your
+ * needs please refer to http://www.magentocommerce.com for more information.
+ *
+ * @category    mage
+ * @package     mage
+ * @copyright   Copyright (c) 2013 X.commerce, Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+/*jshint browser:true jquery:true*/
+(function($) {
+    "use strict";
+
+    $.widget("mage.toggleAdvanced", {
+
+        options: {
+            baseToggleClass: "active"      // Class used to be toggled on clicked element
+        },
+
+        /**
+         * Toggle creation
+         * @private
+         */
+        _create: function() {
+            this.beforeCreate();
+            this._bindCore();
+            this.afterCreate();
+        },
+
+        /**
+         *  Core bound events & setup
+         * @protected
+         */
+        _bindCore: function() {
+            var widget = this;
+            this.element.on('click', $.proxy(function(e) {
+                widget._onClick();
+                e.preventDefault();
+            }, this));
+        },
+
+        /**
+         * Binding Click event
+         *
+         * @protected
+         */
+        _onClick: function() {
+            this._prepareOptions();
+            this._toggleSelectors();
+        },
+
+        /**
+         * Method used to look for data attributes to override default options
+         *
+         * @protected
+         */
+        _prepareOptions: function() {
+            this.options.baseToggleClass = (this.element.data('base-toggle-class')) ?
+                this.element.data('base-toggle-class') :this.options.baseToggleClass;
+        },
+
+        /**
+         * Method responsible for hiding and revealing specified DOM elements
+         * Toggle the class on clicked element
+         *
+         * @protected
+         */
+        _toggleSelectors: function () {
+            this.element.toggleClass(this.options.baseToggleClass);
+        },
+
+        /**
+         * Method used to inject 3rd party functionality before create
+         * @public
+         */
+        beforeCreate: function() {},
+
+        /**
+         * Method used to inject 3rd party functionality after create
+         * @public
+         */
+        afterCreate: function() {}
+    });
+
+    // Extension for mage.toggle - Adding selectors support for other DOM elements we wish to toggle
+    $.widget('mage.toggleAdvanced', $.mage.toggleAdvanced, {
+
+        options: {
+            selectorsToggleClass: "hidden"    // Class used to be toggled on selectors DOM elements
+        },
+
+        /**
+         * Method responsible for hiding and revealing specified DOM elements
+         * If data-toggle-selectors attribute is present - toggle will be done on these selectors
+         * Otherwise we toggle the class on clicked element
+         *
+         * @protected
+         * @override
+         */
+        _toggleSelectors: function () {
+            this._super();
+            if (this.element.data('toggle-selectors')) {
+                $(this.element.data('toggle-selectors')).toggleClass(this.options.selectorsToggleClass);
+            } else {
+                this.element.toggleClass(this.options.baseToggleClass);
+            }
+        },
+
+        /**
+         * Method used to look for data attributes to override default options
+         *
+         * @protected
+         * @override
+         */
+        _prepareOptions: function() {
+            this.options.selectorsToggleClass = (this.element.data('selectors-toggle-class')) ?
+                this.element.data('selectors-toggle-class') :this.options.selectorsToggleClass;
+            this._super();
+        }
+    });
+
+    // Extension for mage.toggle - Adding label toggle
+    $.widget('mage.toggleAdvanced', $.mage.toggleAdvanced, {
+
+        options: {
+            newLabel: null,             // Text of the new label to be used on toggle
+            curLabel: null,             // Text of the old label to be used on toggle
+            currentLabelElement: null   // Current label container
+        },
+
+        /**
+         * Binding Click event
+         *
+         * @protected
+         * @override
+         */
+        _onClick: function() {
+            this._super();
+            this._toggleLabel();
+        },
+
+        /**
+         * Method responsible for replacing clicked element labels
+         * @protected
+         */
+        _toggleLabel: function() {
+            if (this.options.newLabel) {
+                var cachedLabel = this.options.newLabel,
+                    currentLabelSelector = (this.options.currentLabelElement) ?
+                        $(this.options.currentLabelElement) : this.element;
+
+                this.element.data('toggle-label', this.options.curLabel);
+                currentLabelSelector.html(this.options.newLabel);
+
+                this.options.curLabel = this.options.newLabel;
+                this.options.newLabel = cachedLabel;
+            }
+        },
+
+        /**
+         * Method used to look for data attributes to override default options
+         *
+         * @protected
+         * @override
+         */
+        _prepareOptions: function() {
+            this.options.newLabel = (this.element.data('toggle-label')) ?
+                this.element.data('toggle-label') : this.options.newLabel;
+
+            this.options.currentLabelElement = (this.element.data('current-label-el')) ?
+                this.element.data('current-label-el') : this.options.currentLabelElement;
+
+            if(!this.options.currentLabelElement) {
+                this.options.currentLabelElement = this.element;
+            }
+
+            this.options.curLabel = $(this.options.currentLabelElement).html();
+
+            this._super();
+        }
+    });
+
+})(jQuery);
diff --git a/pub/lib/mage/validation.js b/pub/lib/mage/validation.js
index 5cb77cb5a6d5fcd112e748c5a36484ca7ad146a3..7e81a3ef2cefb805f2bc0dcba1d7a6d3448e4c8f 100644
--- a/pub/lib/mage/validation.js
+++ b/pub/lib/mage/validation.js
@@ -861,6 +861,21 @@
             function() {
                 return $.mage.__('Please enter a value greater than or equal to %s').replace('%s', this.gteToVal);
             }
+        ],
+        "validate-emails": [
+            function(value) {
+                if ($.mage.isEmpty(value)) {
+                    return true;
+                }
+                var valid_regexp = /^[a-z0-9\._-]{1,30}@([a-z0-9_-]{1,30}\.){1,5}[a-z]{2,4}$/i,
+                    emails = value.split(',');
+                for (var i = 0; i < emails.length; i++) {
+                    if(!valid_regexp.test(emails[i].strip())) {
+                        return false;
+                    }
+                }
+                return true;
+            }, "Please enter a valid email addresses, separated by commas. For example johndoe@domain.com, johnsmith@domain.com."
         ]
     };
 
@@ -895,7 +910,15 @@
             onclick: false,
             ignoreTitle: true,
             errorClass: 'mage-error',
-            errorElement: 'div'
+            errorElement: 'div',
+            errorPlacement: function (error, element) {
+                // logic for date-picker error placement
+                if (element.hasClass('hasDatepicker')) {
+                    element.siblings('img').after(error);
+                } else {
+                    element.after(error);
+                }
+            }
         },
         /**
          * Validation creation
diff --git a/pub/lib/mage/validation/dob-rule.js b/pub/lib/mage/validation/dob-rule.js
index 73eeaedba1885e03080f807ceeabd4a641226634..859bcfd8107f31d959cedb0cab5700efad842e26 100644
--- a/pub/lib/mage/validation/dob-rule.js
+++ b/pub/lib/mage/validation/dob-rule.js
@@ -31,11 +31,15 @@
             $('.customer-dob').find('.' + this.settings.errorClass).removeClass(this.settings.errorClass);
             var dayVal = $(params[0]).find('input:text').val(),
                 monthVal = $(params[1]).find('input:text').val(),
-                yearVal = $(params[2]).find('input:text').val();
-            if (params[3] && dayVal.length + monthVal.length + yearVal.length === 0) {
+                yearVal = $(params[2]).find('input:text').val(),
+                dobLength = dayVal.length + monthVal.length + yearVal.length;
+            if (params[3] && dobLength === 0) {
                 this.dobErrorMessage = 'This is a required field.';
                 return false;
             }
+            if (!params[3] && dobLength === 0) {
+                return true;
+            }
             var day = parseInt(dayVal, 10) || 0,
                 month = parseInt(monthVal, 10) || 0,
                 year = parseInt(yearVal, 10) || 0,
diff --git a/pub/lib/mage/validation/validation.js b/pub/lib/mage/validation/validation.js
index f7a8aebe21abab18eba10566ddf978bc8a2e40d0..3ce4f66f84305eadcf6a60aacc8c9a685f8dab34 100644
--- a/pub/lib/mage/validation/validation.js
+++ b/pub/lib/mage/validation/validation.js
@@ -79,6 +79,25 @@
         'Please select one of the options.'
     );
 
+    $.validator.addMethod(
+        "validate-date-between",
+        function(value, element, params) {
+            var minDate = new Date(params[0]),
+                maxDate = new Date(params[1]),
+                inputDate = new Date(element.value);
+            minDate.setHours(0);
+            maxDate.setHours(0);
+            if (inputDate >= minDate && inputDate <= maxDate) {
+                return true;
+            }
+            this.dateBetweenErrorMessage = $.mage.__('Please enter a date between %min and %max.').replace('%min', minDate).replace('%max', maxDate);
+            return false;
+        },
+        function(){
+            return this.dateBetweenErrorMessage;
+        }
+    );
+
     $.widget("mage.validation", $.mage.validation, {
         /**
          * Check if form pass validation rules without submit