diff --git a/.htaccess b/.htaccess
index f553ff7fb8da6684462793d204fde0c77b9ce8da..7385a8174ec9e045cb6a3d4c02d4583a8b2d17cb 100644
--- a/.htaccess
+++ b/.htaccess
@@ -128,6 +128,12 @@
 
     RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
 
+############################################
+## TRACE and TRACK HTTP methods disabled to prevent XSS attacks
+
+    RewriteCond %{REQUEST_METHOD} ^TRAC[EK]
+    RewriteRule .* - [L,R=405]
+
 ############################################
 ## always send 404 on missing files in these folders
 
diff --git a/CHANGELOG.markdown b/CHANGELOG.markdown
new file mode 100644
index 0000000000000000000000000000000000000000..151cb4d1f9b27e5d51403ee7be71e5fd03efad24
--- /dev/null
+++ b/CHANGELOG.markdown
@@ -0,0 +1,58 @@
+Update as of 3/26/2012
+======================
+
+* Introduced concept of containers and "page types" in layout.
+  * Containers replace `Mage_Core_Block_Text_List` and `Mage_Page_Block_Html_Wrapper`
+  * Widgets now utilize page types and containers instead of "handles" and "block references"
+* Implemented first draft of visual design editor with the following capabilities
+  * highlighting and dragging blocks and containers, toggling highlighting on/off
+  * switching to arbitrary theme and skin
+  * navigating to arbitrary page types (product view, order success page, etc...), so that they would be editable with visual design editor
+* Refactored various places across the system in order to accommodate transition to containers, page types and visual design editor, which includes
+  * Output in any frontend controller action using layout only
+  * Output in any frontend controller specifies one and only one layout handle, which equals to its full action name. There can be other handles that extend it and they are determined by layout loading parameters, provided by controller.
+  * No program termination (exit) on logging in admin user
+  * Session cookie lifetime is set to 0 for frontend and backend. Session will exist until browser window is open, however backend session lifetime limitation does not depend on cookie lifetime anymore.
+* Fixes:
+  * Failures of tests in developer mode
+  * `app/etc/local.xml` affected integration tests
+* Addressed pull requests and issues from Github
+* Fetched updates from Magento 1 up to March 2 2012. Refer to [Magento 1 release notes](http://www.magentocommerce.com/download/release_notes) for details.
+
+Update as of 2/29/2012
+======================
+
+* Added jQuery to Magento 2. It has not been made a main library yet, however all new features are developed using jQuery.
+* Added support for new versions of testing tools - PHPUnit 3.6, PHPMD 1.3.0. Confirmed compatibility with latest PHPCS 1.3.2 and PHPCPD 1.3.5.
+* Improved legacy tests:
+  * Refactored Integrity_ClassesTest and Legacy_ClassesTest.
+  * Implemented a tool for migrating factory names from 1.x to 2.x. The tool scans PHP-code and replaces the most "popular" cases.
+  * Added tests for `//model` in config.xml files and `//*[@module]` in all xml files.
+  * Implemented a test that verifies the absence of relocated directories.
+  * Added a test against the obsolete Varien_Profiler.
+* Bug fixes:
+  * Fixed docblock for Mage_Core_Model_Design_Package.
+  * Fixed static code analysis failures related to case-sensitivity.
+  * Fixed several typos and minor mistakes.
+  * Fixed integration test's failures due to specifics of xpath library version.
+* Imported fresh features and bug fixes from Magento 1.x.
+
+Additional Tests and Fixes
+==========================
+
+* Various code integrity fixes in different places:
+  * Fixed obsolete references to classes
+  * Fixed broken references to template and static view files
+  * Fixed some minor occurrences of deprecated code
+  * Code style minor fixes
+* Various minor bugfixes
+* Implemented "developer mode" in integration tests
+* Added "rollback" scripts capability for data fixtures
+* Removed deprecated methods and attributes from product type class
+* Restructured code integrity tests:
+  * Moved out part of the tests from integration into static tests
+  * Introduced "Legacy" test suite in static tests. This test suite is not executed by default when running either phpunit directly or using the "batch tool"
+  * Simplified and reorganized the "Exemplar" and self-assessment tests for static code analysis
+* Covered previously made backwards-incompatible changes with legacy tests
+* Changed storage of class map from a PHP-file with array into a better-performing text file with serialized array.
+* Published dev/tests/static and dev/tests/unit
diff --git a/app/Mage.php b/app/Mage.php
index 60df8c62a14053e12a120a0375acc5f19a71ab21..3b7c61f6d2ecfdaa4d98d2f2711206e96d6a63b7 100644
--- a/app/Mage.php
+++ b/app/Mage.php
@@ -99,6 +99,22 @@ final class Mage
      */
     static private $_isInstalled;
 
+    /**
+     * Magento edition constants
+     */
+    const EDITION_COMMUNITY    = 'Community';
+    const EDITION_ENTERPRISE   = 'Enterprise';
+    const EDITION_PROFESSIONAL = 'Professional';
+    const EDITION_GO           = 'Go';
+
+    /**
+     * Current Magento edition.
+     *
+     * @var string
+     * @static
+     */
+    static private $_currentEdition = self::EDITION_COMMUNITY;
+
     /**
      * Gets the current Magento version string
      * @link http://www.magentocommerce.com/blog/new-community-edition-release-process/
@@ -130,6 +146,17 @@ final class Mage
         );
     }
 
+    /**
+     * Get current Magento edition
+     *
+     * @static
+     * @return string
+     */
+    public static function getEdition()
+    {
+       return self::$_currentEdition;
+    }
+
     /**
      * Set all my static data to defaults
      *
@@ -555,8 +582,8 @@ final class Mage
             self::$_app = new Mage_Core_Model_App();
             self::setRoot();
             self::$_events = new Varien_Event_Collection();
-            self::setIsInstalled($options);
-            self::setConfigModel($options);
+            self::_setIsInstalled($options);
+            self::_setConfigModel($options);
 
             Magento_Profiler::start('self::app::init');
             self::$_app->init($code, $type, $options);
@@ -578,8 +605,8 @@ final class Mage
         try {
             self::setRoot();
             self::$_app     = new Mage_Core_Model_App();
-            self::setIsInstalled($options);
-            self::setConfigModel($options);
+            self::_setIsInstalled($options);
+            self::_setConfigModel($options);
 
             if (!empty($modules)) {
                 self::$_app->initSpecified($code, $type, $options, $modules);
@@ -610,6 +637,9 @@ final class Mage
         try {
             Magento_Profiler::start('mage');
             self::setRoot();
+            if (isset($options['edition'])) {
+                self::$_currentEdition = $options['edition'];
+            }
             self::$_app    = new Mage_Core_Model_App();
             if (isset($options['request'])) {
                 self::$_app->setRequest($options['request']);
@@ -618,8 +648,8 @@ final class Mage
                 self::$_app->setResponse($options['response']);
             }
             self::$_events = new Varien_Event_Collection();
-            self::setIsInstalled($options);
-            self::setConfigModel($options);
+            self::_setIsInstalled($options);
+            self::_setConfigModel($options);
             self::$_app->run(array(
                 'scope_code' => $code,
                 'scope_type' => $type,
@@ -655,7 +685,7 @@ final class Mage
      *
      * @param array $options
      */
-    public static function setIsInstalled($options = array())
+    protected static function _setIsInstalled($options = array())
     {
         if (isset($options['is_installed']) && $options['is_installed']) {
             self::$_isInstalled = true;
@@ -667,7 +697,7 @@ final class Mage
      *
      * @param array $options
      */
-    public static function setConfigModel($options = array())
+    protected static function _setConfigModel($options = array())
     {
         if (isset($options['config_model']) && Magento_Autoload::getInstance()->classExists($options['config_model'])) {
             $alternativeConfigModelName = $options['config_model'];
diff --git a/app/bootstrap.php b/app/bootstrap.php
index 5f431e8380777525c981330c2a251407d323dd99..4ebb9d3cfba5df98abfb358608c1bc4445ab4b32 100644
--- a/app/bootstrap.php
+++ b/app/bootstrap.php
@@ -89,7 +89,15 @@ if (file_exists($classMapPath)) {
     Magento_Autoload::getInstance()->addFilesMap($classMapPath);
 }
 
-#Magento_Profiler::enable();
-#Magento_Profiler::registerOutput(new Magento_Profiler_Output_Html());
-#Magento_Profiler::registerOutput(new Magento_Profiler_Output_Firebug());
-#Magento_Profiler::registerOutput(new Magento_Profiler_Output_Csvfile(__DIR__ . '/var/log/profiler.csv'));
+if (isset($_SERVER['MAGE_PROFILER'])) {
+    switch ($_SERVER['MAGE_PROFILER']) {
+        case 'firebug':
+            Magento_Profiler::registerOutput(new Magento_Profiler_Output_Firebug());
+            break;
+        case 'csv':
+            Magento_Profiler::registerOutput(new Magento_Profiler_Output_Csvfile(__DIR__ . '/../var/log/profiler.csv'));
+            break;
+        default:
+            Magento_Profiler::registerOutput(new Magento_Profiler_Output_Html());
+    }
+}
diff --git a/app/code/community/Phoenix/Moneybookers/Block/Redirect.php b/app/code/community/Phoenix/Moneybookers/Block/Redirect.php
index 418f6d71140475af6b9ea153389912e466bd446d..6172f764b50e6124a549eeeefbbdee767faf0e01 100644
--- a/app/code/community/Phoenix/Moneybookers/Block/Redirect.php
+++ b/app/code/community/Phoenix/Moneybookers/Block/Redirect.php
@@ -26,11 +26,15 @@
 class Phoenix_Moneybookers_Block_Redirect extends Mage_Core_Block_Template
 {
     /**
-     * Constructor. Set template.
+     * Preparing global layout
+     *
+     * You can redefine this method in child classes for changing layout
+     *
+     * @return Mage_Core_Block_Abstract
      */
-    protected function _construct()
+    protected function _prepareLayout()
     {
-        parent::_construct();
-        $this->setTemplate('redirect.phtml');
+        $this->setRedirectUrl(Mage::registry(Phoenix_Moneybookers_ProcessingController::REGISTRY_REDIRECT_URL_KEY));
+        return parent::_prepareLayout();
     }
 }
diff --git a/app/code/community/Phoenix/Moneybookers/controllers/ProcessingController.php b/app/code/community/Phoenix/Moneybookers/controllers/ProcessingController.php
index 2bb4d8ba3d901c44fa0cc3a56e6aebbbcfc95dff..241e9266bf77c078f94a2e6942c660360c3d44ef 100644
--- a/app/code/community/Phoenix/Moneybookers/controllers/ProcessingController.php
+++ b/app/code/community/Phoenix/Moneybookers/controllers/ProcessingController.php
@@ -25,6 +25,13 @@
  */
 class Phoenix_Moneybookers_ProcessingController extends Mage_Core_Controller_Front_Action
 {
+    /**
+     * Register key name for redirect url
+     *
+     * @const string
+     */
+    const REGISTRY_REDIRECT_URL_KEY = 'phoenix_moneybookers_redirect_url';
+
     /**
      * Get singleton of Checkout Session Model
      *
@@ -141,12 +148,8 @@ class Phoenix_Moneybookers_ProcessingController extends Mage_Core_Controller_Fro
      */
     protected function _redirect($path, $arguments=array())
     {
-        $this->getResponse()->setBody(
-            $this->getLayout()
-                ->createBlock('Phoenix_Moneybookers_Block_Redirect')
-                ->setRedirectUrl(Mage::getUrl($path, $arguments))
-                ->toHtml()
-        );
+        Mage::register(self::REGISTRY_REDIRECT_URL_KEY, Mage::getUrl($path, $arguments));
+        $this->loadLayout('moneybookers_processing_redirect')->renderLayout();
         return $this;
     }
 }
diff --git a/app/code/community/Phoenix/Moneybookers/view/frontend/layout.xml b/app/code/community/Phoenix/Moneybookers/view/frontend/layout.xml
index aff28c1b59d08ca559feaa6ef698010e8cf2bf17..ce7c0fed2946930f1b1b3a764f7cf17ff7c48e40 100644
--- a/app/code/community/Phoenix/Moneybookers/view/frontend/layout.xml
+++ b/app/code/community/Phoenix/Moneybookers/view/frontend/layout.xml
@@ -27,7 +27,8 @@
 
 -->
 <layout version="0.1.0">
-    <moneybookers_processing_payment>
+    <moneybookers_processing_payment translate="label" type="page" parent="checkout_onepage_paymentmethod">
+        <label>Moneybookers Payment</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
         </reference>
@@ -36,7 +37,8 @@
         </reference>
     </moneybookers_processing_payment>
 
-    <moneybookers_processing_placeform>
+    <moneybookers_processing_placeform translate="label" type="page" parent="moneybookers_processing_payment">
+        <label>Moneybookers Place Form</label>
         <reference name="root">
             <action method="setTemplate"><template>Phoenix_Moneybookers::blank.phtml</template></action>
         </reference>
@@ -44,4 +46,9 @@
             <block type="Phoenix_Moneybookers_Block_Placeform" name="moneybookers_placeform" template="placeform.phtml" />
         </reference>
     </moneybookers_processing_placeform>
+
+    <moneybookers_processing_redirect translate="label" type="page" parent="moneybookers_processing_payment">
+        <label>Moneybookers Redirect</label>
+        <block type="Phoenix_Moneybookers_Block_Redirect" output="1" name="moneybookers_placeform" template="redirect.phtml"/>
+    </moneybookers_processing_redirect>
 </layout>
diff --git a/app/code/core/Mage/Admin/Model/Observer.php b/app/code/core/Mage/Admin/Model/Observer.php
deleted file mode 100644
index 89de6db9211af5a93ef0816f540cb57ee95a3727..0000000000000000000000000000000000000000
--- a/app/code/core/Mage/Admin/Model/Observer.php
+++ /dev/null
@@ -1,97 +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    Mage
- * @package     Mage_Admin
- * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
- * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
- */
-
-/**
- * Admin observer model
- *
- * @category    Mage
- * @package     Mage_Admin
- * @author      Magento Core Team <core@magentocommerce.com>
- */
-class Mage_Admin_Model_Observer
-{
-    const FLAG_NO_LOGIN = 'no-login';
-    /**
-     * Handler for controller_action_predispatch event
-     *
-     * @param Varien_Event_Observer $observer
-     * @return boolean
-     */
-    public function actionPreDispatchAdmin($observer)
-    {
-        $session = Mage::getSingleton('Mage_Admin_Model_Session');
-        /** @var $session Mage_Admin_Model_Session */
-        $request = Mage::app()->getRequest();
-        $user = $session->getUser();
-
-        $requestedActionName = $request->getActionName();
-        $openActions = array(
-            'forgotpassword',
-            'resetpassword',
-            'resetpasswordpost',
-            'logout',
-            'refresh' // captcha refresh
-        );
-        if (in_array($requestedActionName, $openActions)) {
-            $request->setDispatched(true);
-        } else {
-            if($user) {
-                $user->reload();
-            }
-            if (!$user || !$user->getId()) {
-                if ($request->getPost('login')) {
-                    $postLogin  = $request->getPost('login');
-                    $username   = isset($postLogin['username']) ? $postLogin['username'] : '';
-                    $password   = isset($postLogin['password']) ? $postLogin['password'] : '';
-                    $session->login($username, $password, $request);
-                    $request->setPost('login', null);
-                }
-                if (!$request->getParam('forwarded')) {
-                    if ($request->getParam('isIframe')) {
-                        $request->setParam('forwarded', true)
-                            ->setControllerName('index')
-                            ->setActionName('deniedIframe')
-                            ->setDispatched(false);
-                    } elseif($request->getParam('isAjax')) {
-                        $request->setParam('forwarded', true)
-                            ->setControllerName('index')
-                            ->setActionName('deniedJson')
-                            ->setDispatched(false);
-                    } else {
-                        $request->setParam('forwarded', true)
-                            ->setRouteName('adminhtml')
-                            ->setControllerName('index')
-                            ->setActionName('login')
-                            ->setDispatched(false);
-                    }
-                    return false;
-                }
-            }
-        }
-
-        $session->refreshAcl();
-    }
-}
diff --git a/app/code/core/Mage/Admin/Model/Session.php b/app/code/core/Mage/Admin/Model/Session.php
index 87b119e050c2a824e753bbdfcc537b2594596f8c..3c49d34c15e2f497befba8ae153e9dd7622631d5 100644
--- a/app/code/core/Mage/Admin/Model/Session.php
+++ b/app/code/core/Mage/Admin/Model/Session.php
@@ -34,6 +34,7 @@
  */
 class Mage_Admin_Model_Session extends Mage_Core_Model_Session_Abstract
 {
+    const XML_PATH_SESSION_LIFETIME = 'admin/security/session_lifetime';
 
     /**
      * Whether it is the first page after successfull login
@@ -72,52 +73,56 @@ class Mage_Admin_Model_Session extends Mage_Core_Model_Session_Abstract
     }
 
     /**
-     * Try to login user in admin
+     * Try to login user in admin. Possible results:
+     * - Mage_Admin_Model_User - user logged in and appropriate model is loaded
+     * - false - user not logged in
      *
      * @param  string $username
      * @param  string $password
-     * @param  Mage_Core_Controller_Request_Http $request
-     * @return Mage_Admin_Model_User|null
+     * @return Mage_Admin_Model_User|bool
      */
-    public function login($username, $password, $request = null)
+    public function login($username, $password)
     {
         if (empty($username) || empty($password)) {
-            return;
+            return false;
         }
 
         try {
             /** @var $user Mage_Admin_Model_User */
             $user = Mage::getModel('Mage_Admin_Model_User');
             $user->login($username, $password);
-            if ($user->getId()) {
-                $this->renewSession();
-
-                if (Mage::getSingleton('Mage_Adminhtml_Model_Url')->useSecretKey()) {
-                    Mage::getSingleton('Mage_Adminhtml_Model_Url')->renewSecretUrls();
-                }
-                $this->setIsFirstPageAfterLogin(true);
-                $this->setUser($user);
-                $this->setAcl(Mage::getResourceModel('Mage_Admin_Model_Resource_Acl')->loadAcl());
-
-                $requestUri = $this->_getRequestUri($request);
-                if ($requestUri) {
-                    Mage::dispatchEvent('admin_session_user_login_success', array('user' => $user));
-                    header('Location: ' . $requestUri);
-                    exit;
-                }
-            } else {
+            if (!$user->getId()) {
                 Mage::throwException(Mage::helper('Mage_Adminhtml_Helper_Data')->__('Invalid User Name or Password.'));
             }
+
+            $this->renewSession();
+
+            if (Mage::getSingleton('Mage_Adminhtml_Model_Url')->useSecretKey()) {
+                Mage::getSingleton('Mage_Adminhtml_Model_Url')->renewSecretUrls();
+            }
+            $this->setIsFirstPageAfterLogin(true);
+            $this->setUser($user);
+            $this->setAcl(Mage::getResourceModel('Mage_Admin_Model_Resource_Acl')->loadAcl());
+            $this->setUpdatedAt(time());
+
+            Mage::dispatchEvent('admin_session_user_login_success', array('user' => $user));
+
+            return $user;
         } catch (Mage_Core_Exception $e) {
             Mage::dispatchEvent('admin_session_user_login_failed',
                 array('user_name' => $username, 'exception' => $e));
-            if ($request && !$request->getParam('messageSent')) {
-                Mage::getSingleton('Mage_Adminhtml_Model_Session')->addError($e->getMessage());
-                $request->setParam('messageSent', true);
-            }
+            return false;
         }
+    }
 
-        return $user;
+    /**
+     * Log out the user from the admin
+     */
+    public function logout()
+    {
+        $this->unsetAll();
+        $this->getCookie()->delete($this->getSessionName());
+        Mage::dispatchEvent('admin_session_user_logout');
     }
 
     /**
@@ -184,7 +189,19 @@ class Mage_Admin_Model_Session extends Mage_Core_Model_Session_Abstract
      */
     public function isLoggedIn()
     {
-        return $this->getUser() && $this->getUser()->getId();
+        $lifetime = Mage::getStoreConfig(self::XML_PATH_SESSION_LIFETIME);
+        $currentTime = time();
+
+        /* Validate admin session lifetime that should be more than 60 seconds */
+        if ($lifetime >= 60 && ($this->getUpdatedAt() < $currentTime - $lifetime)) {
+            return false;
+        }
+
+        if ($this->getUser() && $this->getUser()->getId()) {
+            $this->setUpdatedAt($currentTime);
+            return true;
+        }
+        return false;
     }
 
     /**
@@ -211,21 +228,4 @@ class Mage_Admin_Model_Session extends Mage_Core_Model_Session_Abstract
         $this->_isFirstPageAfterLogin = (bool)$value;
         return $this->setIsFirstVisit($this->_isFirstPageAfterLogin);
     }
-
-    /**
-     * Custom REQUEST_URI logic
-     *
-     * @param Mage_Core_Controller_Request_Http $request
-     * @return string|null
-     */
-    protected function _getRequestUri($request = null)
-    {
-        if (Mage::getSingleton('Mage_Adminhtml_Model_Url')->useSecretKey()) {
-            return Mage::getSingleton('Mage_Adminhtml_Model_Url')->getUrl('*/*/*', array('_current' => true));
-        } elseif ($request) {
-            return $request->getRequestUri();
-        } else {
-            return null;
-        }
-    }
 }
diff --git a/app/code/core/Mage/Admin/Model/User.php b/app/code/core/Mage/Admin/Model/User.php
index 68f3d61bbf9ad00e53e8b299d6a22a009c5df42b..037b08f10ccfd7c92121db8cadba79fd7d46e379 100644
--- a/app/code/core/Mage/Admin/Model/User.php
+++ b/app/code/core/Mage/Admin/Model/User.php
@@ -61,7 +61,7 @@
 class Mage_Admin_Model_User extends Mage_Core_Model_Abstract
 {
     /**
-     * Configuration pathes for email templates and identities
+     * Configuration paths for email templates and identities
      */
     const XML_PATH_FORGOT_EMAIL_TEMPLATE    = 'admin/emails/forgot_email_template';
     const XML_PATH_FORGOT_EMAIL_IDENTITY    = 'admin/emails/forgot_email_identity';
diff --git a/app/code/core/Mage/Adminhtml/Block/Api/Tab/Rolesusers.php b/app/code/core/Mage/Adminhtml/Block/Api/Tab/Rolesusers.php
index b807d26da58c7db0a9eb63365bb4421f4d699fa4..00b8c17ecabe7548a606340cc1999ed3d1491f4c 100644
--- a/app/code/core/Mage/Adminhtml/Block/Api/Tab/Rolesusers.php
+++ b/app/code/core/Mage/Adminhtml/Block/Api/Tab/Rolesusers.php
@@ -54,7 +54,7 @@ class Mage_Adminhtml_Block_Api_Tab_Rolesusers extends Mage_Adminhtml_Block_Widge
 
     protected function _getJsObjectName()
     {
-        return $this->getChild('userGrid')->getJsObjectName();
+        return $this->getChildBlock('userGrid')->getJsObjectName();
     }
 
 }
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Helper/Pricestep.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Helper/Pricestep.php
index addd5efdf4df129c8374898d2d142cfa3991e1e6..fc9eba98b51239d6e153bf82a1aae900b233b15d 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Helper/Pricestep.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Category/Helper/Pricestep.php
@@ -46,6 +46,7 @@ class Mage_Adminhtml_Block_Catalog_Category_Helper_Pricestep extends Varien_Data
             $this->setData('disabled', 'disabled');
             $disabled = true;
         }
+        parent::addClass('validate-number validate-number-range number-range-0.01-1000000000');
         $html = parent::getElementHtml();
         $htmlId = 'use_config_' . $this->getHtmlId();
         $html .= '<br/><input id="'.$htmlId.'" name="use_config[]" value="' . $this->getId() . '"';
@@ -57,7 +58,9 @@ class Mage_Adminhtml_Block_Catalog_Category_Helper_Pricestep extends Varien_Data
 
         $html .= ' <label for="'.$htmlId.'" class="normal">'
             . Mage::helper('Mage_Adminhtml_Helper_Data')->__('Use Config Settings').'</label>';
-        $html .= '<script type="text/javascript">toggleValueElements($(\''.$htmlId.'\'), $(\''.$htmlId.'\').parentNode);</script>';
+        $html .= '<script type="text/javascript">'
+            . 'toggleValueElements($(\''.$htmlId.'\'), $(\''.$htmlId.'\').parentNode);'
+            . '</script>';
 
         return $html;
     }
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Helper/Form/Wysiwyg.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Helper/Form/Wysiwyg.php
index 98758aa32b9b1aa719d4f5c0aa3d4d9e45cfb7be..52d5597c02a7482a075f014f88c4f79c295439cb 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Helper/Form/Wysiwyg.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Helper/Form/Wysiwyg.php
@@ -48,7 +48,7 @@ class Mage_Adminhtml_Block_Catalog_Helper_Form_Wysiwyg extends Varien_Data_Form_
                     'label'   => Mage::helper('Mage_Catalog_Helper_Data')->__('WYSIWYG Editor'),
                     'type'    => 'button',
                     'disabled' => $disabled,
-                    'class' => ($disabled) ? 'disabled' : '',
+                    'class' => ($disabled) ? 'disabled btn-wysiwyg' : 'btn-wysiwyg',
                     'onclick' => 'catalogWysiwygEditor.open(\''
                         . Mage::helper('Mage_Adminhtml_Helper_Data')->getUrl('*/*/wysiwyg')
                         . '\', \'' . $this->getHtmlId().'\')'
@@ -65,10 +65,10 @@ class Mage_Adminhtml_Block_Catalog_Helper_Form_Wysiwyg extends Varien_Data_Form_
     public function getIsWysiwygEnabled()
     {
         if (Mage::helper('Mage_Catalog_Helper_Data')->isModuleEnabled('Mage_Cms')) {
-            return (bool)(Mage::getSingleton('Mage_Cms_Model_Wysiwyg_Config')->isEnabled() && $this->getEntityAttribute()->getIsWysiwygEnabled());
+            return (bool)(Mage::getSingleton('Mage_Cms_Model_Wysiwyg_Config')->isEnabled()
+                && $this->getEntityAttribute()->getIsWysiwygEnabled());
         }
 
         return false;
     }
 }
-
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Set/Toolbar/Add.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Set/Toolbar/Add.php
index f88d94ad344684457850b592e583533514e166c0..74a8694a194c46605e65b53414f2ad7407daf846 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Set/Toolbar/Add.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Attribute/Set/Toolbar/Add.php
@@ -83,6 +83,6 @@ class Mage_Adminhtml_Block_Catalog_Product_Attribute_Set_Toolbar_Add extends Mag
 
     protected function getFormId()
     {
-        return $this->getChild('setForm')->getForm()->getId();
+        return $this->getChildBlock('setForm')->getForm()->getId();
     }
 }
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Composite/Fieldset.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Composite/Fieldset.php
index 09707c6d161adbfe64096adfd2926037188c8599..953b1a38f0ea014faac9fbe90a83421024658965 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Composite/Fieldset.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Composite/Fieldset.php
@@ -41,16 +41,12 @@ class Mage_Adminhtml_Block_Catalog_Product_Composite_Fieldset extends Mage_Core_
      */
     protected function _toHtml()
     {
-        $children = $this->getSortedChildren();
+        $children = $this->getLayout()->getChildBlocks($this->getNameInLayout());
         $total = count($children);
         $i = 0;
         $this->setText('');
-        foreach ($children as $name) {
-            $block = $this->getLayout()->getBlock($name);
-            if (!$block) {
-                Mage::throwException(Mage::helper('Mage_Core_Helper_Data')->__('Invalid block: %s', $name));
-            }
-
+        /** @var $block Mage_Core_Block_Abstract  */
+        foreach ($children as $block) {
             $i++;
             $block->setIsLastFieldset($i == $total);
 
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 5249a57b00edb89ad842a9f79577b208e756ac55..f23247e207d50c4da1cdf27a1fb71f9d102cab9b 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
@@ -95,8 +95,11 @@ 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" onclick="toogleFieldEditMode(this, \'' . $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>';
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Option.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Option.php
index 4317e806088f6694d57c5b36beb7e572482b1cec..c2eef09497e7d856e981407627b7932aa4947020 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Option.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Option.php
@@ -145,7 +145,7 @@ class Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Options_Option extends Mage_
     {
         $buttonId = $this->getLayout()
                 ->getBlock('admin.product.options')
-                ->getChild('add_button')->getId();
+                ->getChildBlock('add_button')->getId();
         return $buttonId;
     }
 
@@ -189,19 +189,19 @@ class Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Options_Option extends Mage_
     {
         $canEditPrice = $this->getCanEditPrice();
         $canReadPrice = $this->getCanReadPrice();
-        $this->getChild('select_option_type')
+        $this->getChildBlock('select_option_type')
             ->setCanReadPrice($canReadPrice)
             ->setCanEditPrice($canEditPrice);
 
-        $this->getChild('file_option_type')
+        $this->getChildBlock('file_option_type')
             ->setCanReadPrice($canReadPrice)
             ->setCanEditPrice($canEditPrice);
 
-        $this->getChild('date_option_type')
+        $this->getChildBlock('date_option_type')
             ->setCanReadPrice($canReadPrice)
             ->setCanEditPrice($canEditPrice);
 
-        $this->getChild('text_option_type')
+        $this->getChildBlock('text_option_type')
             ->setCanReadPrice($canReadPrice)
             ->setCanEditPrice($canEditPrice);
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Type/Abstract.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Type/Abstract.php
index adc6187f6c18d25f6e467bc17184cf2ce777c3fe..24b12fa8e14b1219bd86c2e0b1e051c5fe435054 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Type/Abstract.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Type/Abstract.php
@@ -39,14 +39,14 @@ class Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Options_Type_Abstract extend
     protected function _prepareLayout()
     {
         $this->setChild('option_price_type',
-            $this->getLayout()->createBlock('Mage_Adminhtml_Block_Html_Select')
+            $this->getLayout()->addBlock('Mage_Adminhtml_Block_Html_Select', '', $this->getNameInLayout())
                 ->setData(array(
                     'id' => 'product_option_{{option_id}}_price_type',
                     'class' => 'select product-option-price-type'
                 ))
         );
 
-        $this->getChild('option_price_type')->setName('product[options][{{option_id}}][price_type]')
+        $this->getChildBlock('option_price_type')->setName('product[options][{{option_id}}][price_type]')
             ->setOptions(Mage::getSingleton('Mage_Adminhtml_Model_System_Config_Source_Product_Options_Price')
             ->toOptionArray());
 
@@ -61,7 +61,7 @@ class Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Options_Type_Abstract extend
     public function getPriceTypeSelectHtml()
     {
         if ($this->getCanEditPrice() === false) {
-            $this->getChild('option_price_type')->setExtraParams('disabled="disabled"');
+            $this->getChildBlock('option_price_type')->setExtraParams('disabled="disabled"');
         }
         return $this->getChildHtml('option_price_type');
     }
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Type/Select.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Type/Select.php
index 0b54dcafd143e7b5f83e3895ff0ae2c3cc073e95..12f4c293508048043a32eedf30cab3d4c0ff838b 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Type/Select.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Options/Type/Select.php
@@ -81,7 +81,7 @@ class Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Options_Type_Select extends
 
     public function getPriceTypeSelectHtml()
     {
-        $this->getChild('option_price_type')
+        $this->getChildBlock('option_price_type')
             ->setData('id', 'product_option_{{id}}_select_{{select_id}}_price_type')
             ->setName('product[options][{{id}}][values][{{select_id}}][price_type]');
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Config.php b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Config.php
index 12d2d5d8f6c6cfd5bb3fde93027450ea0a8076b8..c66c77ca574b1ffa2c6539ceb3b2ee656584de94 100644
--- a/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Config.php
+++ b/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Config.php
@@ -226,7 +226,7 @@ class Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Super_Config extends Mage_Ad
      */
     public function getGridJsObject()
     {
-        return $this->getChild('grid')->getJsObjectName();
+        return $this->getChildBlock('grid')->getJsObjectName();
     }
 
     /**
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 ce96be325c0ab9d6a001b95df1d44702430392fc..1aec50d3451430105732540f3e211aab7ce1d4cf 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
@@ -69,7 +69,7 @@ class Mage_Adminhtml_Block_Catalog_Product_Helper_Form_Gallery_Content extends M
      */
     public function getUploader()
     {
-        return $this->getChild('uploader');
+        return $this->getChildBlock('uploader');
     }
 
     /**
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Renderer/Region.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Renderer/Region.php
index f20ca90f20ffae729f0288187159464b30f52dce..9415a1648506b36ebc3fda5de2b44085523c05e1 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Renderer/Region.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Renderer/Region.php
@@ -29,7 +29,9 @@
  *
  * @author      Magento Core Team <core@magentocommerce.com>
  */
-class Mage_Adminhtml_Block_Customer_Edit_Renderer_Region extends Mage_Adminhtml_Block_Abstract implements Varien_Data_Form_Element_Renderer_Interface
+class Mage_Adminhtml_Block_Customer_Edit_Renderer_Region
+    extends Mage_Adminhtml_Block_Abstract
+    implements Varien_Data_Form_Element_Renderer_Interface
 {
     /**
      * Output the region element and javasctipt that makes it dependent from country element
@@ -50,22 +52,25 @@ class Mage_Adminhtml_Block_Customer_Edit_Renderer_Region extends Mage_Adminhtml_
 
         $html = '<tr>';
         $element->setClass('input-text');
-        $html.= '<td class="label">'.$element->getLabelHtml().'</td><td class="value">';
-        $html.= $element->getElementHtml();
+        $element->setRequired(true);
+        $html .= '<td class="label">' . $element->getLabelHtml() . '</td><td class="value">';
+        $html .= $element->getElementHtml();
 
         $selectName = str_replace('region', 'region_id', $element->getName());
-        $selectId   = $element->getHtmlId().'_id';
-        $html.= '<select id="'.$selectId.'" name="'.$selectName.'" class="select required-entry" style="display:none">';
-        $html.= '<option value="">'.Mage::helper('Mage_Customer_Helper_Data')->__('Please select').'</option>';
-        $html.= '</select>';
+        $selectId = $element->getHtmlId() . '_id';
+        $html .= '<select id="' . $selectId . '" name="' . $selectName
+            . '" class="select required-entry" style="display:none">';
+        $html .= '<option value="">' . Mage::helper('Mage_Customer_Helper_Data')->__('Please select') . '</option>';
+        $html .= '</select>';
 
-        $html.= '<script type="text/javascript">'."\n";
-        $html.= 'new regionUpdater("'
-            . $country->getHtmlId() . '", "' . $element->getHtmlId() . '", "' . $selectId . '", '
-            . $this->helper('Mage_Directory_Helper_Data')->getRegionJson().');'."\n";
-        $html.= '</script>'."\n";
+        $html .= '<script type="text/javascript">' . "\n";
+        $html .= '$("' . $selectId . '").setAttribute("defaultValue", "' . $regionId.'");' . "\n";
+        $html .= 'new regionUpdater("' . $country->getHtmlId() . '", "' . $element->getHtmlId()
+            . '", "' . $selectId . '", ' . $this->helper('Mage_Directory_Helper_Data')->getRegionJson() . ');' . "\n";
+        $html .= '</script>' . "\n";
+
+        $html .= '</td></tr>' . "\n";
 
-        $html.= '</td></tr>'."\n";
         return $html;
     }
 }
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 b247209c9688f42682802ac9c5a765c1d44caea6..98a40274ccf2935c1be707528a66ba58393e59ab 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
@@ -110,6 +110,17 @@ class Mage_Adminhtml_Block_Customer_Edit_Tab_Account extends Mage_Adminhtml_Bloc
                 . '</script>'
             );
         }
+        $form->getElement('website_id')->setAfterElementHtml(
+            Mage::getBlockSingleton('Mage_Adminhtml_Block_Store_Switcher')->getHintHtml()
+        );
+
+//        if (Mage::app()->isSingleStoreMode()) {
+//            $fieldset->removeField('website_id');
+//            $fieldset->addField('website_id', 'hidden', array(
+//                'name'      => 'website_id'
+//            ));
+//            $customer->setWebsiteId(Mage::app()->getStore(true)->getWebsiteId());
+//        }
 
         $customerStoreId = null;
         if ($customer->getId()) {
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 fe00e65c877d0c90b9485d4be62148565dfaa8f8..6883cf980b207265c5a6f1fb5d13da8ecd386c7d 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
@@ -135,6 +135,7 @@ class Mage_Adminhtml_Block_Customer_Edit_Tab_Addresses extends Mage_Adminhtml_Bl
         $this->_setFieldset($attributes, $fieldset);
 
         $regionElement = $form->getElement('region');
+        $regionElement->setRequired(true);
         if ($regionElement) {
             $regionElement->setRenderer(Mage::getModel('Mage_Adminhtml_Model_Customer_Renderer_Region'));
         }
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View.php
index 7d38b8c7033c2c895e38152a1444aeecbdccf601..856865e328964f0db10bfdff54609b03f9bc3ea0 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View.php
@@ -78,7 +78,7 @@ class Mage_Adminhtml_Block_Customer_Edit_Tab_View
      */
     public function getCreateDate()
     {
-        return Mage::helper('Mage_Core_Helper_Data')->formatDateRespectTimezone(
+        return Mage::helper('Mage_Core_Helper_Data')->formatDate(
             $this->getCustomer()->getCreatedAtTimestamp(),
             Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM,
             true
@@ -110,8 +110,8 @@ class Mage_Adminhtml_Block_Customer_Edit_Tab_View
     {
         $date = $this->getCustomerLog()->getLoginAtTimestamp();
         if ($date) {
-            return Mage::helper('Mage_Core_Helper_Data')->formatDateRespectTimezone(
-                Mage::app()->getLocale()->date($date),
+            return Mage::helper('Mage_Core_Helper_Data')->formatDate(
+                $date,
                 Mage_Core_Model_Locale::FORMAT_TYPE_MEDIUM,
                 true
             );
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Accordion.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Accordion.php
index 1fa39a2597fabde13f9841e9dd67b20c0bc17a9c..360537cef0785e426c3041aa23a94cc42fc59300 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Accordion.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Accordion.php
@@ -70,10 +70,8 @@ class Mage_Adminhtml_Block_Customer_Edit_Tab_View_Accordion extends Mage_Adminht
         }
 
         // count wishlist items
-        $wishlist = Mage::getModel('Mage_Wishlist_Model_Wishlist');
-        $wishlistCount = $wishlist->loadByCustomer($customer)
-            ->setSharedStoreIds($wishlist->getSharedStoreIds(false))
-            ->getItemCollection()
+        $wishlistCount = Mage::getModel('Mage_Wishlist_Model_Wishlist')->getCollection()
+            ->addCustomerIdFilter($customer->getId())
             ->addStoreData()
             ->getSize();
         // add wishlist ajax accordion
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Wishlist.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Wishlist.php
index 17c02c167a176a74bc2499f01697ca84384dfaf9..293bcf3c9a899a8699c7af61ddb1d3e7c8e1341c 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Wishlist.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/View/Wishlist.php
@@ -55,10 +55,8 @@ class Mage_Adminhtml_Block_Customer_Edit_Tab_View_Wishlist extends Mage_Adminhtm
      */
     protected function _prepareCollection()
     {
-        $wishlist = Mage::getModel('Mage_Wishlist_Model_Wishlist');
-        $collection = $wishlist->loadByCustomer(Mage::registry('current_customer'))
-            ->setSharedStoreIds($wishlist->getSharedStoreIds(false))
-            ->getItemCollection()
+        $collection = Mage::getModel('Mage_Wishlist_Model_Item')->getCollection()
+            ->addCustomerIdFilter(Mage::registry('current_customer')->getId())
             ->addDaysInWishlist()
             ->addStoreData()
             ->setInStockFilter(true);
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Wishlist.php b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Wishlist.php
index bcbb23b30803fe63d83c8b324de3ee2c2be8f249..e32ef0fdd751418c336b966cebdcbe743965cfa3 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Wishlist.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Wishlist.php
@@ -41,6 +41,7 @@ class Mage_Adminhtml_Block_Customer_Edit_Tab_Wishlist extends Mage_Adminhtml_Blo
      */
 
     protected $_defaultSort = 'added_at';
+
     /**
      * Parent template name
      *
@@ -63,7 +64,7 @@ class Mage_Adminhtml_Block_Customer_Edit_Tab_Wishlist extends Mage_Adminhtml_Blo
         $this->setId('wishlistGrid');
         $this->setUseAjax(true);
         $this->_parentTemplate = $this->getTemplate();
-        $this->setTemplate('customer/tab/wishlist.phtml');
+        $this->setTemplate('Mage_Adminhtml::customer/tab/wishlist.phtml');
         $this->setEmptyText(Mage::helper('Mage_Customer_Helper_Data')->__('No Items Found'));
         $this->addProductConfigurationHelper('default', 'Mage_Catalog_Helper_Product_Configuration');
     }
@@ -78,6 +79,16 @@ class Mage_Adminhtml_Block_Customer_Edit_Tab_Wishlist extends Mage_Adminhtml_Blo
         return Mage::registry('current_customer');
     }
 
+    /**
+     * Create customer wishlist item collection
+     *
+     * @return Mage_Wishlist_Model_Resource_Item_Collection
+     */
+    protected function _createCollection()
+    {
+        return Mage::getModel('Mage_Wishlist_Model_Item')->getCollection();
+    }
+
     /**
      * Prepare customer wishlist product collection
      *
@@ -85,14 +96,10 @@ class Mage_Adminhtml_Block_Customer_Edit_Tab_Wishlist extends Mage_Adminhtml_Blo
      */
     protected function _prepareCollection()
     {
-        $wishlist = Mage::getModel('Mage_Wishlist_Model_Wishlist');
-        $collection = $wishlist->loadByCustomer($this->_getCustomer())
-            ->setSharedStoreIds($wishlist->getSharedStoreIds(false))
-            ->getItemCollection()
+        $collection = $this->_createCollection()->addCustomerIdFilter($this->_getCustomer()->getId())
             ->resetSortOrder()
             ->addDaysInWishlist()
             ->addStoreData();
-
         $this->setCollection($collection);
 
         return parent::_prepareCollection();
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Online.php b/app/code/core/Mage/Adminhtml/Block/Customer/Online.php
index a780c57a80751f4b21caeb1ee1ab55f99a9fa2dd..11ef3105bf586ff609b8b29753674dd8fad647c9 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Online.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Online.php
@@ -57,7 +57,7 @@ class Mage_Adminhtml_Block_Customer_Online extends Mage_Adminhtml_Block_Template
 
     public function getFilterFormHtml()
     {
-        return $this->getChild('filterForm')->toHtml();
+        return $this->getChildBlock('filterForm')->toHtml();
     }
 
 }
diff --git a/app/code/core/Mage/Adminhtml/Block/Customer/Sales/Order/Address/Form/Renderer/Vat.php b/app/code/core/Mage/Adminhtml/Block/Customer/Sales/Order/Address/Form/Renderer/Vat.php
index 9847fc918dc851214a82e2fc930a011ba720aff7..d812974cc16c5367fb09167a1c42bccefe4b01c0 100644
--- a/app/code/core/Mage/Adminhtml/Block/Customer/Sales/Order/Address/Form/Renderer/Vat.php
+++ b/app/code/core/Mage/Adminhtml/Block/Customer/Sales/Order/Address/Form/Renderer/Vat.php
@@ -66,17 +66,22 @@ class Mage_Adminhtml_Block_Customer_Sales_Order_Address_Form_Renderer_Vat
             $validateUrl = Mage::getSingleton('Mage_Adminhtml_Model_Url')
                 ->getUrl('*/customer_system_config_validatevat/validateAdvanced');
 
+            $groupSuggestionMessage = Mage::helper('Mage_Customer_Helper_Data')->__('The customer is currently assigned to Customer Group %s.')
+                . ' ' . Mage::helper('Mage_Customer_Helper_Data')->__('Would you like to change the Customer Group for this order?');
+
             $vatValidateOptions = Mage::helper('Mage_Core_Helper_Data')->jsonEncode(array(
                 'vatElementId' => $vatElementId,
                 'countryElementId' => $countryElementId,
                 'groupIdHtmlId' => 'group_id',
                 'validateUrl' => $validateUrl,
                 'vatValidMessage' => Mage::helper('Mage_Customer_Helper_Data')->__('The VAT ID is valid. The current Customer Group will be used.'),
-                'vatValidAndGroupChangeMessage' => Mage::helper('Mage_Customer_Helper_Data')->__('Based on the VAT ID, the customer would belong to the Customer Group %s.') . "\n"
-                    . Mage::helper('Mage_Customer_Helper_Data')->__('The customer is currently assigned to Customer Group %s.') . ' '
-                    . Mage::helper('Mage_Customer_Helper_Data')->__('Would you like to change the Customer Group for this order?'),
-                'vatInvalidMessage' => Mage::helper('Mage_Customer_Helper_Data')->__('The VAT ID entered (%s) is not a valid VAT ID.'),
-                'vatValidationFailedMessage'    => Mage::helper('Mage_Customer_Helper_Data')->__('There was an error validating the VAT ID. Please try again later.'),
+                'vatValidAndGroupChangeMessage' => Mage::helper('Mage_Customer_Helper_Data')->__('Based on the VAT ID, the customer would belong to the Customer Group %s.')
+                    . "\n" . $groupSuggestionMessage,
+                'vatInvalidMessage' => Mage::helper('Mage_Customer_Helper_Data')->__('The VAT ID entered (%s) is not a valid VAT ID. The customer would belong to Customer Group %s.')
+                    . "\n" . $groupSuggestionMessage,
+                'vatValidationFailedMessage'    => Mage::helper('Mage_Customer_Helper_Data')->__('There was an error validating the VAT ID. The customer would belong to Customer Group %s.')
+                    . "\n" . $groupSuggestionMessage,
+                'vatErrorMessage' => Mage::helper('Mage_Customer_Helper_Data')->__('There was an error validating the VAT ID.')
             ));
 
             $optionsVarName = $this->getJsVariablePrefix() . 'VatParameters';
diff --git a/app/code/core/Mage/Adminhtml/Block/Dashboard/Graph.php b/app/code/core/Mage/Adminhtml/Block/Dashboard/Graph.php
index c57342332369b26f89df552126d9e27df3ae769b..0f94d2acecd993e79c253c232cb998b159b784b5 100644
--- a/app/code/core/Mage/Adminhtml/Block/Dashboard/Graph.php
+++ b/app/code/core/Mage/Adminhtml/Block/Dashboard/Graph.php
@@ -212,10 +212,6 @@ class Mage_Adminhtml_Block_Dashboard_Graph extends Mage_Adminhtml_Block_Dashboar
 
         while($dateStart->compare($dateEnd) < 0){
             switch ($this->getDataHelper()->getParam('period')) {
-                case '24h':
-                    $d = $dateStart->toString('yyyy-MM-dd HH:00');
-                    $dateStart->addHour(1);
-                    break;
                 case '7d':
                 case '1m':
                     $d = $dateStart->toString('yyyy-MM-dd');
@@ -226,6 +222,9 @@ class Mage_Adminhtml_Block_Dashboard_Graph extends Mage_Adminhtml_Block_Dashboar
                     $d = $dateStart->toString('yyyy-MM');
                     $dateStart->addMonth(1);
                     break;
+                default:
+                    $d = $dateStart->toString('yyyy-MM-dd HH:00');
+                    $dateStart->addHour(1);
             }
             foreach ($this->getAllSeries() as $index=>$serie) {
                 if (in_array($d, $this->_axisLabels['x'])) {
@@ -280,22 +279,15 @@ class Mage_Adminhtml_Block_Dashboard_Graph extends Mage_Adminhtml_Block_Dashboar
         }
 
         // process each string in the array, and find the max length
+        $localmaxvalue = array(0);
+        $localminvalue = array(0);
         foreach ($this->getAllSeries() as $index => $serie) {
-            $localmaxlength[$index] = sizeof($serie);
             $localmaxvalue[$index] = max($serie);
             $localminvalue[$index] = min($serie);
         }
 
-        if (is_numeric($this->_max)) {
-            $maxvalue = $this->_max;
-        } else {
-            $maxvalue = max($localmaxvalue);
-        }
-        if (is_numeric($this->_min)) {
-            $minvalue = $this->_min;
-        } else {
-            $minvalue = min($localminvalue);
-        }
+        $maxvalue = max($localmaxvalue);
+        $minvalue = min($localminvalue);
 
         // default values
         $yrange = 0;
@@ -304,7 +296,6 @@ class Mage_Adminhtml_Block_Dashboard_Graph extends Mage_Adminhtml_Block_Dashboar
         $maxy = 0;
         $yorigin = 0;
 
-        $maxlength = max($localmaxlength);
         if ($minvalue >= 0 && $maxvalue >= 0) {
             $miny = 0;
             if ($maxvalue > 10) {
diff --git a/app/code/core/Mage/Adminhtml/Block/Newsletter/Subscriber.php b/app/code/core/Mage/Adminhtml/Block/Newsletter/Subscriber.php
index ffc107093e09bb834f56d5114048df91dbb73bb7..07f5668aacbd369a99736d379fc045035ee7b56b 100644
--- a/app/code/core/Mage/Adminhtml/Block/Newsletter/Subscriber.php
+++ b/app/code/core/Mage/Adminhtml/Block/Newsletter/Subscriber.php
@@ -85,7 +85,7 @@ class Mage_Adminhtml_Block_Newsletter_Subscriber extends Mage_Adminhtml_Block_Te
 
     public function getShowQueueAdd()
     {
-        return $this->getChild('grid')->getShowQueueAdd();
+        return $this->getChildBlock('grid')->getShowQueueAdd();
     }
 
     /**
diff --git a/app/code/core/Mage/Adminhtml/Block/Notification/Security.php b/app/code/core/Mage/Adminhtml/Block/Notification/Security.php
index 7e524804d6d095a3003c7f680b4d6fe6922d01c7..9e8ac1ee15781e98dfd4673f437da2fecaabba48 100644
--- a/app/code/core/Mage/Adminhtml/Block/Notification/Security.php
+++ b/app/code/core/Mage/Adminhtml/Block/Notification/Security.php
@@ -54,7 +54,7 @@ class Mage_Adminhtml_Block_Notification_Security extends Mage_Adminhtml_Block_Te
         if ($this->_isFileAccessible()) {
             return true;
         }
-        $adminSessionLifetime = (int)Mage::getStoreConfig('admin/security/session_cookie_lifetime');
+        $adminSessionLifetime = (int)Mage::getStoreConfig('admin/security/session_lifetime');
         Mage::app()->saveCache(true, self::VERIFICATION_RESULT_CACHE_KEY, array(), $adminSessionLifetime);
         return false;
     }
diff --git a/app/code/core/Mage/Adminhtml/Block/Notification/Window.php b/app/code/core/Mage/Adminhtml/Block/Notification/Window.php
index 5673b22ecec722e04576af210c478755a8d1ae22..06f1111abcc99efc6aeab748f0d1cd40eefcc21c 100644
--- a/app/code/core/Mage/Adminhtml/Block/Notification/Window.php
+++ b/app/code/core/Mage/Adminhtml/Block/Notification/Window.php
@@ -53,17 +53,17 @@ class Mage_Adminhtml_Block_Notification_Window extends Mage_Adminhtml_Block_Noti
     {
         parent::_construct();
 
-        $this->setHeaderText(addslashes($this->__('Incoming Message')));
-        $this->setCloseText(addslashes($this->__('close')));
-        $this->setReadDetailsText(addslashes($this->__('Read details')));
-        $this->setNoticeText(addslashes($this->__('NOTICE')));
-        $this->setMinorText(addslashes($this->__('MINOR')));
-        $this->setMajorText(addslashes($this->__('MAJOR')));
-        $this->setCriticalText(addslashes($this->__('CRITICAL')));
+        $this->setHeaderText($this->escapeHtml($this->__('Incoming Message')));
+        $this->setCloseText($this->escapeHtml($this->__('close')));
+        $this->setReadDetailsText($this->escapeHtml($this->__('Read details')));
+        $this->setNoticeText($this->escapeHtml($this->__('NOTICE')));
+        $this->setMinorText($this->escapeHtml($this->__('MINOR')));
+        $this->setMajorText($this->escapeHtml($this->__('MAJOR')));
+        $this->setCriticalText($this->escapeHtml($this->__('CRITICAL')));
 
 
-        $this->setNoticeMessageText(addslashes($this->getLastNotice()->getTitle()));
-        $this->setNoticeMessageUrl(addslashes($this->getLastNotice()->getUrl()));
+        $this->setNoticeMessageText($this->escapeHtml($this->getLastNotice()->getTitle()));
+        $this->setNoticeMessageUrl($this->escapeUrl($this->getLastNotice()->getUrl()));
 
         switch ($this->getLastNotice()->getSeverity()) {
             default:
diff --git a/app/code/core/Mage/Adminhtml/Block/Page/Menu.php b/app/code/core/Mage/Adminhtml/Block/Page/Menu.php
index d4036a8c0a37b356d45e898ac602256c4ca9c219..a8de251c3e7303bbd9b2b85c2f47bec7699617d6 100644
--- a/app/code/core/Mage/Adminhtml/Block/Page/Menu.php
+++ b/app/code/core/Mage/Adminhtml/Block/Page/Menu.php
@@ -88,16 +88,6 @@ class Mage_Adminhtml_Block_Page_Menu extends Mage_Adminhtml_Block_Template
         return $cacheKeyInfo;
     }
 
-    /**
-     * Retrieve Adminhtml Menu array
-     *
-     * @return array
-     */
-    public function getMenuArray()
-    {
-        return $this->_buildMenuArray();
-    }
-
     /**
      * Retrieve Title value for menu node
      *
@@ -259,7 +249,7 @@ class Mage_Adminhtml_Block_Page_Menu extends Mage_Adminhtml_Block_Template
      */
     protected function _afterToHtml($html)
     {
-        $html = preg_replace_callback('#'.Mage_Adminhtml_Model_Url::SECRET_KEY_PARAM_NAME.'/\$([^\/].*)/([^\$].*)\$#', array($this, '_callbackSecretKey'), $html);
+        $html = preg_replace_callback('#'.Mage_Adminhtml_Model_Url::SECRET_KEY_PARAM_NAME.'/\$([^\/].*)/([^\$].*)\$#U', array($this, '_callbackSecretKey'), $html);
 
         return $html;
     }
@@ -275,4 +265,58 @@ class Mage_Adminhtml_Block_Page_Menu extends Mage_Adminhtml_Block_Template
         return Mage_Adminhtml_Model_Url::SECRET_KEY_PARAM_NAME . '/'
             . $this->_url->getSecretKey($match[1], $match[2]);
     }
+
+    /**
+     * Render HTML menu recursively starting from the specified level
+     *
+     * @param array $menu
+     * @param int $level
+     * @return string
+     */
+    protected function _renderMenuLevel(array $menu, $level = 0)
+    {
+        $result = '<ul' . (!$level ? ' id="nav"' : '') . '>';
+        foreach ($menu as $item) {
+            $hasChildren = !empty($item['children']);
+            $cssClasses = array('level' . $level);
+            if (!$level && !empty($item['active'])) {
+                $cssClasses[] = 'active';
+            }
+            if ($hasChildren) {
+                $cssClasses[] = 'parent';
+            }
+            if (!empty($level) && !empty($item['last'])) {
+                $cssClasses[] = 'last';
+            }
+            $result .= '<li'
+                . ($hasChildren ? ' onmouseover="Element.addClassName(this,\'over\')"' : '')
+                . ($hasChildren ? ' onmouseout="Element.removeClassName(this,\'over\')"' : '')
+                . ' class="' . implode(' ', $cssClasses) . '">'
+                . '<a'
+                . ' href="' . $item['url'] . '"'
+                . (!empty($item['title']) ? ' title="' . $item['title'] . '"' : '')
+                . (!empty($item['click']) ? ' onclick="' . $item['click'] . '"' : '')
+                . ($level === 0 && !empty($item['active']) ? ' class="active"' : '')
+                . '>'
+                . '<span>' . Mage::helper('Mage_Adminhtml_Helper_Data')->escapeHtml($item['label']) . '</span>'
+                . '</a>'
+            ;
+            if ($hasChildren) {
+                $result .= $this->_renderMenuLevel($item['children'], $level + 1);
+            }
+            $result .= '</li>';
+        }
+        $result .= '</ul>';
+        return $result;
+    }
+
+    /**
+     * Render HTML menu
+     *
+     * @return string
+     */
+    public function renderMenu()
+    {
+        return $this->_renderMenuLevel($this->_buildMenuArray());
+    }
 }
diff --git a/app/code/core/Mage/Adminhtml/Block/Permissions/Roles.php b/app/code/core/Mage/Adminhtml/Block/Permissions/Roles.php
index dfda51c8974cddc7ba53c4eaa04def6805889621..04f8a511cf96dc3973194d687fdd02c5ff6373b0 100644
--- a/app/code/core/Mage/Adminhtml/Block/Permissions/Roles.php
+++ b/app/code/core/Mage/Adminhtml/Block/Permissions/Roles.php
@@ -50,6 +50,6 @@ class Mage_Adminhtml_Block_Permissions_Roles extends Mage_Adminhtml_Block_Templa
      */
     public function getGridHtml()
     {
-        return $this->getChild('grid')->toHtml();
+        return $this->getChildBlock('grid')->toHtml();
     }
 }
diff --git a/app/code/core/Mage/Adminhtml/Block/Permissions/Tab/Rolesusers.php b/app/code/core/Mage/Adminhtml/Block/Permissions/Tab/Rolesusers.php
index db6289e7955ba457ece437099b092e0ca4864ec6..8d8965b61f5f2f4f7664b01031b152fc0ce0ca58 100644
--- a/app/code/core/Mage/Adminhtml/Block/Permissions/Tab/Rolesusers.php
+++ b/app/code/core/Mage/Adminhtml/Block/Permissions/Tab/Rolesusers.php
@@ -54,7 +54,7 @@ class Mage_Adminhtml_Block_Permissions_Tab_Rolesusers extends Mage_Adminhtml_Blo
 
     protected function _getJsObjectName()
     {
-        return $this->getChild('userGrid')->getJsObjectName();
+        return $this->getChildBlock('userGrid')->getJsObjectName();
     }
 
 }
diff --git a/app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Edit/Tab/Main.php b/app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Edit/Tab/Main.php
index d1df446b14a6b2c6e41b5c21cbc5b784dcd946c4..c7e99ecb936f7aa14cf1cf956f9c59a95886eabe 100644
--- a/app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Edit/Tab/Main.php
+++ b/app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Edit/Tab/Main.php
@@ -135,7 +135,8 @@ class Mage_Adminhtml_Block_Promo_Catalog_Edit_Tab_Main
                 'label'     => Mage::helper('Mage_CatalogRule_Helper_Data')->__('Websites'),
                 'title'     => Mage::helper('Mage_CatalogRule_Helper_Data')->__('Websites'),
                 'required' => true,
-                'values'   => Mage::getSingleton('Mage_Adminhtml_Model_System_Store')->getWebsiteValuesForForm()
+                'values'   => Mage::getSingleton('Mage_Adminhtml_Model_System_Store')->getWebsiteValuesForForm(),
+                'after_element_html' => Mage::getBlockSingleton('Mage_Adminhtml_Block_Store_Switcher')->getHintHtml()
             ));
         }
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Grid.php b/app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Grid.php
index 50a4e6e974a829b73379929860f39f03abf9ccc5..b8a469ac0c2462ae0baa584a6cb00832a742ca14 100644
--- a/app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Promo/Catalog/Grid.php
@@ -108,8 +108,8 @@ class Mage_Adminhtml_Block_Promo_Catalog_Grid extends Mage_Adminhtml_Block_Widge
             'index'     => 'is_active',
             'type'      => 'options',
             'options'   => array(
-                1 => 'Active',
-                0 => 'Inactive',
+                1 => Mage::helper('Mage_CatalogRule_Helper_Data')->__('Active'),
+                0 => Mage::helper('Mage_CatalogRule_Helper_Data')->__('Inactive')
             ),
         ));
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Edit/Tab/Coupons/Grid.php b/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Edit/Tab/Coupons/Grid.php
index 104f0707ed8fbe65d5d62d921b9b9f0a5a6a2f29..0cc6bf1c3cb9be23b52db78be7c57be7ab70b8a5 100644
--- a/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Edit/Tab/Coupons/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Edit/Tab/Coupons/Grid.php
@@ -94,7 +94,7 @@ class Mage_Adminhtml_Block_Promo_Quote_Edit_Tab_Coupons_Grid extends Mage_Adminh
                 Mage::helper('Mage_Adminhtml_Helper_Data')->__('No'),
                 Mage::helper('Mage_Adminhtml_Helper_Data')->__('Yes')
             ),
-            'renderer' => 'adminhtml/promo_quote_edit_tab_coupons_grid_column_renderer_used',
+            'renderer' => 'Mage_Adminhtml_Block_Promo_Quote_Edit_Tab_Coupons_Grid_Column_Renderer_Used',
             'filter_condition_callback' => array(
                 Mage::getResourceModel('Mage_SalesRule_Model_Resource_Coupon_Collection'), 'addIsUsedFilterCallback'
             )
diff --git a/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Edit/Tab/Main.php b/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Edit/Tab/Main.php
index 90c16d4e8a974f2f2bd21469ed0c9769dfc20bc5..aa95aeafeecde0e66fe32c979d13674cb547b4c1 100644
--- a/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Edit/Tab/Main.php
+++ b/app/code/core/Mage/Adminhtml/Block/Promo/Quote/Edit/Tab/Main.php
@@ -129,7 +129,8 @@ class Mage_Adminhtml_Block_Promo_Quote_Edit_Tab_Main
             $websiteId = Mage::app()->getStore(true)->getWebsiteId();
             $fieldset->addField('website_ids', 'hidden', array(
                 'name'     => 'website_ids[]',
-                'value'    => $websiteId
+                'value'    => $websiteId,
+                'after_element_html' => Mage::getBlockSingleton('Mage_Adminhtml_Block_Store_Switcher')->getHintHtml()
             ));
             $model->setWebsiteIds($websiteId);
         } else {
@@ -138,7 +139,8 @@ class Mage_Adminhtml_Block_Promo_Quote_Edit_Tab_Main
                 'label'     => Mage::helper('Mage_SalesRule_Helper_Data')->__('Websites'),
                 'title'     => Mage::helper('Mage_SalesRule_Helper_Data')->__('Websites'),
                 'required' => true,
-                'values'   => Mage::getSingleton('Mage_Adminhtml_Model_System_Store')->getWebsiteValuesForForm()
+                'values'   => Mage::getSingleton('Mage_Adminhtml_Model_System_Store')->getWebsiteValuesForForm(),
+                'after_element_html' => Mage::getBlockSingleton('Mage_Adminhtml_Block_Store_Switcher')->getHintHtml()
             ));
         }
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Rating/Edit/Tab/Form.php b/app/code/core/Mage/Adminhtml/Block/Rating/Edit/Tab/Form.php
index cb0bd8203ff8a578e82573e735c59191cc08a1d1..95cf52f36dde72025847c4a328ef3cb9636b4734 100644
--- a/app/code/core/Mage/Adminhtml/Block/Rating/Edit/Tab/Form.php
+++ b/app/code/core/Mage/Adminhtml/Block/Rating/Edit/Tab/Form.php
@@ -34,32 +34,33 @@
 
 class Mage_Adminhtml_Block_Rating_Edit_Tab_Form extends Mage_Adminhtml_Block_Widget_Form
 {
+    /**
+     * Prepare rating edit form
+     *
+     * @return Mage_Adminhtml_Block_Rating_Edit_Tab_Form
+     */
     protected function _prepareForm()
     {
         $form = new Varien_Data_Form();
         $this->setForm($form);
-        $defaultStore = Mage::app()->getStore(0);
 
         $fieldset = $form->addFieldset('rating_form', array(
             'legend'=>Mage::helper('Mage_Rating_Helper_Data')->__('Rating Title')
         ));
 
         $fieldset->addField('rating_code', 'text', array(
-            'name'      => 'rating_code',
-            'label'     => Mage::helper('Mage_Rating_Helper_Data')->__('Default Value'),
-            'class'     => 'required-entry',
-            'required'  => true,
-
+            'name' => 'rating_code',
+            'label' => Mage::helper('Mage_Rating_Helper_Data')->__('Default Value'),
+            'class' => 'required-entry',
+            'required' => true,
         ));
 
-//        if (!Mage::app()->isSingleStoreMode()) {
-            foreach(Mage::getSingleton('Mage_Adminhtml_Model_System_Store')->getStoreCollection() as $store) {
-                $fieldset->addField('rating_code_' . $store->getId(), 'text', array(
-                    'label'     => $store->getName(),
-                    'name'      => 'rating_codes['. $store->getId() .']',
-                ));
-            }
-//        }
+        foreach (Mage::getSingleton('Mage_Adminhtml_Model_System_Store')->getStoreCollection() as $store) {
+            $fieldset->addField('rating_code_' . $store->getId(), 'text', array(
+                'label' => $store->getName(),
+                'name' => 'rating_codes[' . $store->getId() . ']',
+            ));
+        }
 
         if (Mage::getSingleton('Mage_Adminhtml_Model_Session')->getRatingData()) {
             $form->setValues(Mage::getSingleton('Mage_Adminhtml_Model_Session')->getRatingData());
@@ -68,8 +69,7 @@ class Mage_Adminhtml_Block_Rating_Edit_Tab_Form extends Mage_Adminhtml_Block_Wid
                $this->_setRatingCodes($data['rating_codes']);
             }
             Mage::getSingleton('Mage_Adminhtml_Model_Session')->setRatingData(null);
-        }
-        elseif (Mage::registry('rating_data')) {
+        } elseif (Mage::registry('rating_data')) {
             $form->setValues(Mage::registry('rating_data')->getData());
             if (Mage::registry('rating_data')->getRatingCodes()) {
                $this->_setRatingCodes(Mage::registry('rating_data')->getRatingCodes());
@@ -85,46 +85,43 @@ class Mage_Adminhtml_Block_Rating_Edit_Tab_Form extends Mage_Adminhtml_Block_Wid
             $i = 1;
             foreach ($collection->getItems() as $item) {
                 $fieldset->addField('option_code_' . $item->getId() , 'hidden', array(
-                    'required'  => true,
-                    'name'      => 'option_title[' . $item->getId() . ']',
-                    'value'     => ($item->getCode()) ? $item->getCode() : $i,
+                    'required' => true,
+                    'name' => 'option_title[' . $item->getId() . ']',
+                    'value' => ($item->getCode()) ? $item->getCode() : $i,
                 ));
 
                 $i ++;
             }
-        }
-        else {
-            for ($i=1; $i<=5; $i++ ) {
+        } else {
+            for ($i = 1; $i <= 5; $i++) {
                 $fieldset->addField('option_code_' . $i, 'hidden', array(
-                    'required'  => true,
-                    'name'      => 'option_title[add_' . $i . ']',
-                    'value'     => $i,
+                    'required' => true,
+                    'name' => 'option_title[add_' . $i . ']',
+                    'value' => $i,
                 ));
             }
         }
 
-//        if (!Mage::app()->isSingleStoreMode()) {
-            $fieldset = $form->addFieldset('visibility_form', array(
-                'legend'    => Mage::helper('Mage_Rating_Helper_Data')->__('Rating Visibility'))
-            );
-            $fieldset->addField('stores', 'multiselect', array(
-                'label'     => Mage::helper('Mage_Rating_Helper_Data')->__('Visible In'),
-//                'required'  => true,
-                'name'      => 'stores[]',
-                'values'    => Mage::getSingleton('Mage_Adminhtml_Model_System_Store')->getStoreValuesForForm(),
-                'after_element_html' => Mage::getBlockSingleton('Mage_Adminhtml_Block_Store_Switcher')->getHintHtml()
-            ));
+        $fieldset = $form->addFieldset('visibility_form', array(
+            'legend' => Mage::helper('Mage_Rating_Helper_Data')->__('Rating Visibility')
+        ));
 
-            if (Mage::registry('rating_data')) {
-                $form->getElement('stores')->setValue(Mage::registry('rating_data')->getStores());
-            }
-//        }
-//        else {
-//            $fieldset->addField('stores', 'hidden', array(
-//                'name'      => 'stores[]',
-//                'value'     => Mage::app()->getStore(true)->getId()
-//            ));
-//        }
+        $fieldset->addField('stores', 'multiselect', array(
+            'label' => Mage::helper('Mage_Rating_Helper_Data')->__('Visible In'),
+            'name' => 'stores[]',
+            'values' => Mage::getSingleton('Mage_Adminhtml_Model_System_Store')->getStoreValuesForForm(),
+            'after_element_html' => Mage::getBlockSingleton('Mage_Adminhtml_Block_Store_Switcher')->getHintHtml()
+        ));
+
+        $fieldset->addField('position', 'text', array(
+            'label' => Mage::helper('Mage_Rating_Helper_Data')->__('Sort Order'),
+            'name' => 'position',
+        ));
+
+        if (Mage::registry('rating_data')) {
+            $form->getElement('position')->setValue(Mage::registry('rating_data')->getPosition());
+            $form->getElement('stores')->setValue(Mage::registry('rating_data')->getStores());
+        }
 
         return parent::_prepareForm();
     }
diff --git a/app/code/core/Mage/Adminhtml/Block/Rating/Grid.php b/app/code/core/Mage/Adminhtml/Block/Rating/Grid.php
index 5c9ff3a609bc2d8d4de4f9341ff2f6a8894f1965..6ed76c6e97b172a552c0e7ae8f78dd3ea43047ea 100644
--- a/app/code/core/Mage/Adminhtml/Block/Rating/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Rating/Grid.php
@@ -52,6 +52,11 @@ class Mage_Adminhtml_Block_Rating_Grid extends Mage_Adminhtml_Block_Widget_Grid
         return parent::_prepareCollection();
     }
 
+    /**
+     * Prepare Rating Grid colunms
+     *
+     * @return Mage_Adminhtml_Block_Rating_Grid
+     */
     protected function _prepareColumns()
     {
         $this->addColumn('rating_id', array(
@@ -63,10 +68,16 @@ class Mage_Adminhtml_Block_Rating_Grid extends Mage_Adminhtml_Block_Widget_Grid
 
         $this->addColumn('rating_code', array(
             'header'    => Mage::helper('Mage_Rating_Helper_Data')->__('Rating Name'),
-            'align'     =>'left',
             'index'     => 'rating_code',
         ));
 
+        $this->addColumn('position', array(
+            'header' => Mage::helper('Mage_Rating_Helper_Data')->__('Sort Order'),
+            'align' => 'left',
+            'width' => '100px',
+            'index' => 'position',
+        ));
+
         return parent::_prepareColumns();
     }
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Filter/Form.php b/app/code/core/Mage/Adminhtml/Block/Report/Filter/Form.php
index 48b985c245bd42e95911f26fef82a4685ce7f2a9..0ad63b8521dfba822d103c436dda0dc07a6fcec7 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Filter/Form.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Filter/Form.php
@@ -189,7 +189,13 @@ class Mage_Adminhtml_Block_Report_Filter_Form extends Mage_Adminhtml_Block_Widge
      */
     protected function _initFormValues()
     {
-        $this->getForm()->addValues($this->getFilterData()->getData());
+        $data = $this->getFilterData()->getData();
+        foreach ($data as $key => $value) {
+            if (is_array($value) && isset($value[0])) {
+                $data[$key] = explode(',', $value[0]);
+            }
+        }
+        $this->getForm()->addValues($data);
         return parent::_initFormValues();
     }
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Report/Grid/Abstract.php b/app/code/core/Mage/Adminhtml/Block/Report/Grid/Abstract.php
index 7373473d67effd1453d106e05988b9151d8fc783..6de83e6e060413ee868a4a94f984266fa5f18ac0 100644
--- a/app/code/core/Mage/Adminhtml/Block/Report/Grid/Abstract.php
+++ b/app/code/core/Mage/Adminhtml/Block/Report/Grid/Abstract.php
@@ -241,6 +241,7 @@ class Mage_Adminhtml_Block_Report_Grid_Abstract extends Mage_Adminhtml_Block_Wid
             ->isSubTotals(true);
 
         $this->_addOrderStatusFilter($subTotalsCollection, $filterData);
+        $this->_addCustomFilter($subTotalsCollection, $filterData);
 
         $this->setSubTotals($subTotalsCollection->getItems());
         return parent::getSubTotals();
diff --git a/app/code/core/Mage/Adminhtml/Block/Review/Main.php b/app/code/core/Mage/Adminhtml/Block/Review/Main.php
index 72e595e6804ae6a568c18e029d7dc4e443d8e5d5..043d1adebb18d8db61d1af617c8e4ad10e875f9a 100644
--- a/app/code/core/Mage/Adminhtml/Block/Review/Main.php
+++ b/app/code/core/Mage/Adminhtml/Block/Review/Main.php
@@ -49,6 +49,12 @@ class Mage_Adminhtml_Block_Review_Main extends Mage_Adminhtml_Block_Widget_Grid_
             $customerName = $customer->getFirstname() . ' ' . $customer->getLastname();
             $customerName = $this->escapeHtml($customerName);
         }
+        $productId = $this->getRequest()->getParam('productId', false);
+        $productName = null;
+        if ($productId) {
+            $product = Mage::getModel('Mage_Catalog_Model_Product')->load($productId);
+            $productName =  $this->escapeHtml($product->getName());
+        }
 
         if( Mage::registry('usePendingFilter') === true ) {
             if ($customerName) {
@@ -60,6 +66,8 @@ class Mage_Adminhtml_Block_Review_Main extends Mage_Adminhtml_Block_Widget_Grid_
         } else {
             if ($customerName) {
                 $this->_headerText = Mage::helper('Mage_Review_Helper_Data')->__('All Reviews of Customer `%s`', $customerName);
+            } elseif ($productName) {
+                $this->_headerText = Mage::helper('Mage_Review_Helper_Data')->__('All Reviews of Product `%s`', $productName);
             } else {
                 $this->_headerText = Mage::helper('Mage_Review_Helper_Data')->__('All Reviews');
             }
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Items/Abstract.php b/app/code/core/Mage/Adminhtml/Block/Sales/Items/Abstract.php
index d02f569b6eb2a23c22901a0c96e8368078a7a9a9..28fef2157e70f6ddcd17ca488448400fdb517525 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Items/Abstract.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Items/Abstract.php
@@ -185,7 +185,7 @@ class  Mage_Adminhtml_Block_Sales_Items_Abstract extends Mage_Adminhtml_Block_Te
      */
     public function getItemExtraInfoHtml(Varien_Object $item)
     {
-        $extraInfoBlock = $this->getChild('order_item_extra_info');
+        $extraInfoBlock = $this->getChildBlock('order_item_extra_info');
         if ($extraInfoBlock) {
             return $extraInfoBlock
                 ->setItem($item)
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Address.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Address.php
index 9d6d0f57e1eadda5ce4e34e349e23c9c67439de4..5d31e664f6f269039db42378bedd8de3a3f3585c 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Address.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Form/Address.php
@@ -166,7 +166,7 @@ class Mage_Adminhtml_Block_Sales_Order_Create_Form_Address
                 }
             }
         }
-        if (!$this->_form->getElement('country_id')->getValue()) {
+        if (is_null($this->_form->getElement('country_id')->getValue())) {
             $this->_form->getElement('country_id')->setValue(
                 Mage::helper('Mage_Core_Helper_Data')->getDefaultCountry($this->getStore())
             );
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Items/Grid.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Items/Grid.php
index 83d021a83468e6c1d939d606df60bdd7fcff3a6d..b65bb42151f335267b3d51ff8d4b19c37c850ceb 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Items/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Items/Grid.php
@@ -357,4 +357,16 @@ class Mage_Adminhtml_Block_Sales_Order_Create_Items_Grid extends Mage_Adminhtml_
     {
         return $item->getProduct()->isVisibleInSiteVisibility();
     }
+
+
+    /**
+     * Retrieve collection of customer wishlists
+     *
+     * @return Mage_Wishlist_Model_Resource_Wishlist_Collection
+     */
+    public function getCustomerWishlists()
+    {
+        return Mage::getModel('Mage_Wishlist_Model_Wishlist')->getCollection()
+            ->filterByCustomerId($this->getCustomerId());
+    }
 }
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Load.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Load.php
index b0769e4d9dcad5fa19fc5b44810593dfe15ee08b..ae003fcd8a1da2fb0443d7a3139974fb5826589b 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Load.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Create/Load.php
@@ -37,12 +37,9 @@ class Mage_Adminhtml_Block_Sales_Order_Create_Load extends Mage_Core_Block_Templ
     protected function _toHtml()
     {
         $result = array();
-        foreach ($this->getSortedChildren() as $name) {
-            if (!$block = $this->getChild($name)) {
-                $result[$name] = Mage::helper('Mage_Sales_Helper_Data')->__('Invalid block: %s.', $name);
-            } else {
-                $result[$name] = $block->toHtml();
-            }
+        $layout = $this->getLayout();
+        foreach ($this->getChildNames() as $name) {
+            $result[$name] = $layout->renderElement($name);
         }
         $resultJson = Mage::helper('Mage_Core_Helper_Data')->jsonEncode($result);
         $jsVarname = $this->getRequest()->getParam('as_js_varname');
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Packaging.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Packaging.php
index 20d93cda90039f56e9c7186a853710de437085bd..013194184185df7c99461a170ebcfbc9e8a3b888 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Packaging.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Shipment/Packaging.php
@@ -327,7 +327,8 @@ class Mage_Adminhtml_Block_Sales_Order_Shipment_Packaging extends Mage_Adminhtml
      */
     public function getCustomValueCurrencyCode()
     {
-        return Mage::app()->getStore()->getBaseCurrencyCode();
+        $orderInfo = $this->getShipment()->getOrder();
+        return $orderInfo->getBaseCurrency()->getCurrencyCode();
     }
 
     /**
@@ -341,6 +342,18 @@ class Mage_Adminhtml_Block_Sales_Order_Shipment_Packaging extends Mage_Adminhtml
         return $this->getShipment()->getOrder()->formatPriceTxt($price);
     }
 
+    /**
+     * Display formatted customs price
+     *
+     * @param float $price
+     * @return string
+     */
+    public function displayCustomsPrice($price)
+    {
+        $orderInfo = $this->getShipment()->getOrder();
+        return $orderInfo->getBaseCurrency()->formatTxt($price);
+    }
+
     /**
      * Get ordered qty of item
      *
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Status/New/Form.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Status/New/Form.php
index bc2b79a60c4b700bec65b87b6703d032e431d570..2d4c12470618c1b72075dd9b44e2468ec677b1d6 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/Status/New/Form.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/Status/New/Form.php
@@ -80,6 +80,8 @@ class Mage_Adminhtml_Block_Sales_Order_Status_New_Form extends Mage_Adminhtml_Bl
             'legend'       => Mage::helper('Mage_Sales_Helper_Data')->__('Store View Specific Labels'),
             'table_class'  => 'form-list stores-tree',
         ));
+        $renderer = $this->getLayout()->createBlock('Mage_Adminhtml_Block_Store_Switcher_Form_Renderer_Fieldset');
+        $fieldset->setRenderer($renderer);
 
         foreach (Mage::app()->getWebsites() as $website) {
             $fieldset->addField("w_{$website->getId()}_label", 'note', array(
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View.php
index ad29f707314f84d7d5ea3ccc5e96896f040fed00..2f83e257b0b5261b1b127790f3de65f107fd0964 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View.php
@@ -172,7 +172,7 @@ class Mage_Adminhtml_Block_Sales_Order_View extends Mage_Adminhtml_Block_Widget_
 
         if ($this->_isAllowedAction('reorder')
             && $this->helper('Mage_Sales_Helper_Reorder')->isAllowed($order->getStore())
-            && $order->canReorder()
+            && $order->canReorderIgnoreSalable()
         ) {
             $this->_addButton('order_reorder', array(
                 'label'     => Mage::helper('Mage_Sales_Helper_Data')->__('Reorder'),
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Giftmessage.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Giftmessage.php
index a2b4856cdd73bc06433cfd8a24c0f25acb4d1999..fcf122969d87182fc0dcf7044bad27292ceb380b 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Giftmessage.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Giftmessage.php
@@ -90,7 +90,7 @@ class Mage_Adminhtml_Block_Sales_Order_View_Giftmessage extends Mage_Adminhtml_B
      */
     public function getSaveButtonHtml()
     {
-        $this->getChild('save_button')->setOnclick(
+        $this->getChildBlock('save_button')->setOnclick(
             'giftMessagesController.saveGiftMessage(\''. $this->getHtmlId() .'\')'
         );
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Info.php b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Info.php
index c443a089af7ad2a4038af0e4e0a556533b07735f..c054d4ddb3d35f6f2d771ef4d3e6709081fe13b5 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Info.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sales/Order/View/Info.php
@@ -161,4 +161,13 @@ class Mage_Adminhtml_Block_Sales_Order_View_Info extends Mage_Adminhtml_Block_Sa
         $url = $this->getUrl('*/sales_order/address', array('address_id'=>$address->getId()));
         return '<a href="'.$url.'">' . $label . '</a>';
     }
+
+    /**
+     * Whether Customer IP address should be displayed on sales documents
+     * @return bool
+     */
+    public function shouldDisplayCustomerIp()
+    {
+        return !Mage::getStoreConfigFlag('sales/general/hide_customer_ip', $this->getOrder()->getStoreId());
+    }
 }
diff --git a/app/code/core/Mage/Adminhtml/Block/Sitemap/Edit/Form.php b/app/code/core/Mage/Adminhtml/Block/Sitemap/Edit/Form.php
index 13a7ce2773f1f4d3430ff0dc5c2f20169c672fcf..f3dd818760aeb934e1d0bedf832856a2a9686231 100644
--- a/app/code/core/Mage/Adminhtml/Block/Sitemap/Edit/Form.php
+++ b/app/code/core/Mage/Adminhtml/Block/Sitemap/Edit/Form.php
@@ -87,7 +87,8 @@ class Mage_Adminhtml_Block_Sitemap_Edit_Form extends Mage_Adminhtml_Block_Widget
                 'name'     => 'store_id',
                 'required' => true,
                 'value'    => $model->getStoreId(),
-                'values'   => Mage::getSingleton('Mage_Adminhtml_Model_System_Store')->getStoreValuesForForm()
+                'values'   => Mage::getSingleton('Mage_Adminhtml_Model_System_Store')->getStoreValuesForForm(),
+                'after_element_html' => Mage::getBlockSingleton('Mage_Adminhtml_Block_Store_Switcher')->getHintHtml()
             ));
         }
         else {
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Config/Form.php b/app/code/core/Mage/Adminhtml/Block/System/Config/Form.php
index bdd5a49a7167f5b32d33ec46a3b6b69b8213e386..1a3eaf7444573a3f1ed3b634729d41f91de0df77 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Config/Form.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Config/Form.php
@@ -228,11 +228,11 @@ class Mage_Adminhtml_Block_System_Config_Form extends Mage_Adminhtml_Block_Widge
      */
     protected function _getDependence()
     {
-        if (!$this->getChild('element_dependense')){
+        if (!$this->getChildBlock('element_dependense')){
             $this->setChild('element_dependense',
                 $this->getLayout()->createBlock('Mage_Adminhtml_Block_Widget_Form_Element_Dependence'));
         }
-        return $this->getChild('element_dependense');
+        return $this->getChildBlock('element_dependense');
     }
 
     /**
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Design/Edit/Tab/General.php b/app/code/core/Mage/Adminhtml/Block/System/Design/Edit/Tab/General.php
index 6ddf5a0a2c27b2c5ac39ce92ce315a602eef3674..c80f713912358e9c870ef227e83c797afaa1a736 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Design/Edit/Tab/General.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Design/Edit/Tab/General.php
@@ -39,6 +39,7 @@ class Mage_Adminhtml_Block_System_Design_Edit_Tab_General extends Mage_Adminhtml
                 'values'   => Mage::getSingleton('Mage_Adminhtml_Model_System_Store')->getStoreValuesForForm(),
                 'name'     => 'store_id',
                 'required' => true,
+                'after_element_html' => Mage::getBlockSingleton('Mage_Adminhtml_Block_Store_Switcher')->getHintHtml()
             ));
         } else {
             $fieldset->addField('store_id', 'hidden', array(
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Edit/Form.php b/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Edit/Form.php
index aeb14a9192e6324d33f569a13e603318843d5e6d..3dcaf3e63e9584dd63d961e5e97cd411303f831a 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Edit/Form.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Edit/Form.php
@@ -45,7 +45,7 @@ class Mage_Adminhtml_Block_System_Email_Template_Edit_Form extends Mage_Adminhtm
         if ($head = $this->getLayout()->getBlock('head')) {
             $head->addJs('prototype/window.js')
                 ->addCss('prototype/windows/themes/default.css')
-                ->addCss('prototype/windows/themes/magento.css')
+                ->addCss('Mage_Core::prototype/magento.css')
                 ->addJs('Mage_Adminhtml::variables.js');
         }
         return parent::_prepareLayout();
@@ -72,7 +72,8 @@ class Mage_Adminhtml_Block_System_Email_Template_Edit_Form extends Mage_Adminhtm
                 'container_id' => 'used_currently_for',
                 'after_element_html' =>
                     '<script type="text/javascript">' .
-                    (!$this->getEmailTemplate()->getSystemConfigPathsWhereUsedCurrently() ? '$(\'' . 'used_currently_for' . '\').hide(); ' : '') .
+                    (!$this->getEmailTemplate()->getSystemConfigPathsWhereUsedCurrently()
+                        ? '$(\'' . 'used_currently_for' . '\').hide(); ' : '') .
                     '</script>',
             ));
         }
@@ -83,7 +84,8 @@ class Mage_Adminhtml_Block_System_Email_Template_Edit_Form extends Mage_Adminhtm
                 'container_id' => 'used_default_for',
                 'after_element_html' =>
                     '<script type="text/javascript">' .
-                    (!(bool)$this->getEmailTemplate()->getOrigTemplateCode() ? '$(\'' . 'used_default_for' . '\').hide(); ' : '') .
+                    (!(bool)$this->getEmailTemplate()->getOrigTemplateCode()
+                        ? '$(\'' . 'used_default_for' . '\').hide(); ' : '') .
                     '</script>',
             ));
         }
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Preview.php b/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Preview.php
index 2ee03216e5587752fa8ef35676221b36f19d629f..3a4e919106fabe7f7862c0c983a397fece8d41a1 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Preview.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Email/Template/Preview.php
@@ -33,11 +33,17 @@
  */
 class Mage_Adminhtml_Block_System_Email_Template_Preview extends Mage_Adminhtml_Block_Widget
 {
+    /**
+     * Prepare html output
+     *
+     * @return string
+     */
     protected function _toHtml()
     {
         /** @var $template Mage_Core_Model_Email_Template */
         $template = Mage::getModel('Mage_Core_Model_Email_Template');
-        if ($id = (int)$this->getRequest()->getParam('id')) {
+        $id = (int)$this->getRequest()->getParam('id');
+        if ($id) {
             $template->load($id);
         } else {
             $template->setTemplateType($this->getRequest()->getParam('type'));
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Store/Delete.php b/app/code/core/Mage/Adminhtml/Block/System/Store/Delete.php
index 637bdbab4d5d191229a3cd513ea8659933ffa8a3..7061011f6c704961de2674ae298bc47946c9b6e2 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Store/Delete.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Store/Delete.php
@@ -68,7 +68,7 @@ class Mage_Adminhtml_Block_System_Store_Delete extends Mage_Adminhtml_Block_Widg
     public function getHeaderText()
     {
         return Mage::helper('Mage_Adminhtml_Helper_Data')->__("Delete %s '%s'", $this->getStoreTypeTitle(),
-            $this->escapeHtml($this->getChild('form')->getDataObject()->getName()));
+            $this->escapeHtml($this->getChildBlock('form')->getDataObject()->getName()));
     }
 
     /**
diff --git a/app/code/core/Mage/Adminhtml/Block/System/Store/Edit/Form.php b/app/code/core/Mage/Adminhtml/Block/System/Store/Edit/Form.php
index 7bc32a689ba201f06d52b8f9c5cc97ff0811ea14..589bc2edaf03b2b6eaf96020f769be8551054c30 100644
--- a/app/code/core/Mage/Adminhtml/Block/System/Store/Edit/Form.php
+++ b/app/code/core/Mage/Adminhtml/Block/System/Store/Edit/Form.php
@@ -110,8 +110,10 @@ class Mage_Adminhtml_Block_System_Store_Edit_Form extends Mage_Adminhtml_Block_W
 
             if (Mage::registry('store_action') == 'edit') {
                 $groups = Mage::getModel('Mage_Core_Model_Store_Group')->getCollection()
-                    ->addWebsiteFilter($websiteModel->getId())->toOptionArray();
-                //array_unshift($groups, array('label'=>'', 'value'=>0));
+                    ->addWebsiteFilter($websiteModel->getId())
+                    ->setWithoutStoreViewFilter()
+                    ->toOptionArray();
+
                 $fieldset->addField('website_default_group_id', 'select', array(
                     'name'      => 'website[default_group_id]',
                     'label'     => Mage::helper('Mage_Core_Helper_Data')->__('Default Store'),
diff --git a/app/code/core/Mage/Adminhtml/Block/Tax/Class.php b/app/code/core/Mage/Adminhtml/Block/Tax/Class.php
index 922aa393d83a120807c51babb473c7a52637825a..0bf887bbb38413dbaa13053ffd99ac6f23381aae 100644
--- a/app/code/core/Mage/Adminhtml/Block/Tax/Class.php
+++ b/app/code/core/Mage/Adminhtml/Block/Tax/Class.php
@@ -51,7 +51,7 @@ class Mage_Adminhtml_Block_Tax_Class extends Mage_Adminhtml_Block_Widget_Grid_Co
             $this->_addButtonLabel  = Mage::helper('Mage_Tax_Helper_Data')->__('Add New Class');
         }
 
-        $this->getChild('grid')->setClassType($classType);
+        $this->getChildBlock('grid')->setClassType($classType);
         $this->setData('class_type', $classType);
 
         return $this;
diff --git a/app/code/core/Mage/Adminhtml/Block/Tax/Class/Edit.php b/app/code/core/Mage/Adminhtml/Block/Tax/Class/Edit.php
index 68471b20b58394066d98f05679c2f9990c5f5c47..d9ab9a882e3facf9a42777f283bb48a967daef20 100644
--- a/app/code/core/Mage/Adminhtml/Block/Tax/Class/Edit.php
+++ b/app/code/core/Mage/Adminhtml/Block/Tax/Class/Edit.php
@@ -57,7 +57,7 @@ class Mage_Adminhtml_Block_Tax_Class_Edit extends Mage_Adminhtml_Block_Widget_Fo
 
     public function setClassType($classType)
     {
-        $this->getChild('form')->setClassType($classType);
+        $this->getChildBlock('form')->setClassType($classType);
         return $this;
     }
 }
diff --git a/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Edit.php b/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Edit.php
index 62f39cc040161022b56afc53ea8369c881f78394..3fdbca566f5d7aec117e1ede75a432a7ce355504 100644
--- a/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Edit.php
+++ b/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Edit.php
@@ -206,15 +206,18 @@ class Mage_Adminhtml_Block_Urlrewrite_Edit extends Mage_Adminhtml_Block_Widget_C
      * Since buttons are set as children, we remove them as children after generating them
      * not to duplicate them in future
      *
+     * @param null $area
      * @return string
      */
     public function getButtonsHtml($area = null)
     {
         if (null === $this->_buttonsHtml) {
             $this->_buttonsHtml = parent::getButtonsHtml();
-            foreach ($this->_children as $alias => $child) {
+            $layout = $this->getLayout();
+            foreach ($this->getChildNames() as $name) {
+                $alias = $layout->getElementAlias($name);
                 if (false !== strpos($alias, '_button')) {
-                    $this->unsetChild($alias);
+                    $layout->unsetChild($this->getNameInLayout(), $alias);
                 }
             }
         }
diff --git a/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Edit/Form.php b/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Edit/Form.php
index 2b51a48ef099e4ff6e368a564bb27b0220ff7315..89f3b7e3c945c73448ee3f0ab2fd01cc1cdda4db 100644
--- a/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Edit/Form.php
+++ b/app/code/core/Mage/Adminhtml/Block/Urlrewrite/Edit/Form.php
@@ -157,6 +157,7 @@ class Mage_Adminhtml_Block_Urlrewrite_Edit_Form extends Mage_Adminhtml_Block_Wid
                 'values'    => $stores,
                 'disabled'  => true,
                 'value'     => $formValues['store_id'],
+                'after_element_html' => Mage::getBlockSingleton('Mage_Adminhtml_Block_Store_Switcher')->getHintHtml()
             ));
             if ($noStoreError) {
                 $element->setAfterElementHtml($noStoreError);
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Button.php b/app/code/core/Mage/Adminhtml/Block/Widget/Button.php
index 5148dbeb75fe2f46d8a70b220c99eeee73436fb3..8736c7529c0ed06e907c9a6c1a561036ae30fe77 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Button.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Button.php
@@ -56,7 +56,9 @@ class Mage_Adminhtml_Block_Widget_Button extends Mage_Adminhtml_Block_Widget
         $html = $this->getBeforeHtml().'<button '
             . ($this->getId()?' id="'.$this->getId() . '"':'')
             . ($this->getElementName()?' name="'.$this->getElementName() . '"':'')
-            . ($this->getTitle()?' title="'.$this->getTitle() . '"':'')
+            . ' title="'
+            . Mage::helper('Mage_Core_Helper_Data')->quoteEscape($this->getTitle() ? $this->getTitle() : $this->getLabel())
+            . '"'
             . ' type="'.$this->getType() . '"'
             . ' class="scalable ' . $this->getClass() . ($this->getDisabled() ? ' disabled' : '') . '"'
             . ' onclick="'.$this->getOnClick().'"'
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Container.php b/app/code/core/Mage/Adminhtml/Block/Widget/Container.php
index 52f927125ed55e978a196846ba3209c4c7803894..4c2a7f25cf106fc4aeb798db553a72a8502d1913 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Container.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Container.php
@@ -140,7 +140,7 @@ class Mage_Adminhtml_Block_Widget_Container extends Mage_Adminhtml_Block_Templat
         foreach ($this->_buttons as $level => $buttons) {
             if (isset($buttons[$id])) {
                 if (!empty($key)) {
-                    if ($child = $this->getChild($id . '_button')) {
+                    if ($child = $this->getChildBlock($id . '_button')) {
                         $child->setData($key, $data);
                     }
                     if ('level' == $key) {
@@ -234,7 +234,7 @@ class Mage_Adminhtml_Block_Widget_Container extends Mage_Adminhtml_Block_Templat
                     continue;
                 }
                 $childId = $this->_prepareButtonBlockId($id);
-                $child = $this->getChild($childId);
+                $child = $this->getChildBlock($childId);
 
                 if (!$child) {
                     $child = $this->_addButtonChildBlock($childId);
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Form/Container.php b/app/code/core/Mage/Adminhtml/Block/Widget/Form/Container.php
index e02832dbbca676cce5f0a27cf3b2225f40653eeb..e8c4f3c9ce31361039ba4eb950d9f42dfe790118 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Form/Container.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Form/Container.php
@@ -132,7 +132,7 @@ class Mage_Adminhtml_Block_Widget_Form_Container extends Mage_Adminhtml_Block_Wi
 
     public function getFormHtml()
     {
-        $this->getChild('form')->setData('action', $this->getSaveUrl());
+        $this->getChildBlock('form')->setData('action', $this->getSaveUrl());
         return $this->getChildHtml('form');
     }
 
@@ -175,7 +175,7 @@ class Mage_Adminhtml_Block_Widget_Form_Container extends Mage_Adminhtml_Block_Wi
      */
     public function setDataObject($object)
     {
-        $this->getChild('form')->setDataObject($object);
+        $this->getChildBlock('form')->setDataObject($object);
         return $this->setData('data_object', $object);
     }
 
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid.php
index eeb363594240f49d4552b2c9916b4b24465ba4b5..47e4ebd5913b856d188bb4726b150bd12e1d0221 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid.php
@@ -1342,7 +1342,7 @@ class Mage_Adminhtml_Block_Widget_Grid extends Mage_Adminhtml_Block_Widget
      */
     public function getMassactionBlock()
     {
-        return $this->getChild('massaction');
+        return $this->getChildBlock('massaction');
     }
 
     public function getMassactionBlockHtml()
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Abstract.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Abstract.php
index be35373185c34d18252f49739db5d79398f85b5b..786864e37a1b6da95de0ffd8b7a69da9d0abc667 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Abstract.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Renderer/Abstract.php
@@ -105,7 +105,6 @@ abstract class Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
 
     public function renderHeader()
     {
-        $out = '';
         if (false !== $this->getColumn()->getGrid()->getSortable() && false !== $this->getColumn()->getSortable()) {
             $className = 'not-sort';
             $dir = strtolower($this->getColumn()->getDir());
@@ -116,8 +115,7 @@ abstract class Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
             $out = '<a href="#" name="' . $this->getColumn()->getId() . '" title="' . $nDir
                    . '" class="' . $className . '"><span class="sort-title">'
                    . $this->getColumn()->getHeader().'</span></a>';
-        }
-        else {
+        } else {
             $out = $this->getColumn()->getHeader();
         }
         return $out;
@@ -126,13 +124,6 @@ abstract class Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
     public function renderProperty()
     {
         $out = '';
-        /**
-         * Now we generate 2 "col" definition instead span=2
-         */
-//        if ($this->getColumn()->getEditable() && !$this->getColumn()->getEditOnly()) {
-//            $out .= ' span="2"';
-//        }
-
         $width = $this->_defaultWidth;
 
         if ($this->getColumn()->hasData('width')) {
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Massaction/Item.php b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Massaction/Item.php
index 7a640229621cb323439554cd249fe145a9b31e42..503c24ce6854eeaae7e7d4268c39c11bdf4fe6c1 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Massaction/Item.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Massaction/Item.php
@@ -100,7 +100,7 @@ class Mage_Adminhtml_Block_Widget_Grid_Massaction_Item extends Mage_Adminhtml_Bl
      */
     public function getAdditionalActionBlock()
     {
-        return $this->getChild('additional_action');
+        return $this->getChildBlock('additional_action');
     }
 
     /**
diff --git a/app/code/core/Mage/Adminhtml/Block/Widget/Tabs.php b/app/code/core/Mage/Adminhtml/Block/Widget/Tabs.php
index 2597095aacaba49ffa8670644b5488be0ba800af..c996e1f63ed77db14391d8f111d3603bf86a9bd2 100644
--- a/app/code/core/Mage/Adminhtml/Block/Widget/Tabs.php
+++ b/app/code/core/Mage/Adminhtml/Block/Widget/Tabs.php
@@ -111,8 +111,8 @@ class Mage_Adminhtml_Block_Widget_Tabs extends Mage_Adminhtml_Block_Widget
             if (strpos($tab, '_Block_')) {
                 $this->_tabs[$tabId] = $this->getLayout()->createBlock($tab);
             }
-            elseif ($this->getChild($tab)) {
-                $this->_tabs[$tabId] = $this->getChild($tab);
+            elseif ($this->getChildBlock($tab)) {
+                $this->_tabs[$tabId] = $this->getChildBlock($tab);
             }
             else {
                 $this->_tabs[$tabId] = null;
diff --git a/app/code/core/Mage/Adminhtml/Controller/Action.php b/app/code/core/Mage/Adminhtml/Controller/Action.php
index e6e3d2cbc03e89f8b559e54e813fced61a6ecc18..62e5feec695760b5183d04d2d9b05b15b0c50f3d 100644
--- a/app/code/core/Mage/Adminhtml/Controller/Action.php
+++ b/app/code/core/Mage/Adminhtml/Controller/Action.php
@@ -25,16 +25,20 @@
  */
 
 /**
- * Base adminhtml controller
- *
- * @category    Mage
- * @package     Mage_Adminhtml
- * @author      Magento Core Team <core@magentocommerce.com>
+ * Generic backend controller
  */
 class Mage_Adminhtml_Controller_Action extends Mage_Core_Controller_Varien_Action
 {
+    /**
+     * Name of "is URLs checked" flag
+     */
     const FLAG_IS_URLS_CHECKED = 'check_url_settings';
 
+    /**
+     * Session namespace to refer in other places
+     */
+    const SESSION_NAMESPACE = 'adminhtml';
+
     /**
      * Array of actions which can be processed without secret key validation
      *
@@ -59,7 +63,7 @@ class Mage_Adminhtml_Controller_Action extends Mage_Core_Controller_Varien_Actio
      *
      * @var string
      */
-    protected $_sessionNamespace = 'adminhtml';
+    protected $_sessionNamespace = self::SESSION_NAMESPACE;
 
     protected function _isAllowed()
     {
@@ -107,23 +111,44 @@ class Mage_Adminhtml_Controller_Action extends Mage_Core_Controller_Varien_Actio
     }
 
     /**
+     * @param Mage_Core_Block_Abstract $block
      * @return Mage_Adminhtml_Controller_Action
      */
     protected function _addContent(Mage_Core_Block_Abstract $block)
     {
-        $this->getLayout()->getBlock('content')->append($block);
-        return $this;
+        return $this->_moveBlockToContainer($block, 'content');
     }
 
+    /**
+     * @param Mage_Core_Block_Abstract $block
+     * @return Mage_Adminhtml_Controller_Action
+     */
     protected function _addLeft(Mage_Core_Block_Abstract $block)
     {
-        $this->getLayout()->getBlock('left')->append($block);
-        return $this;
+        return $this->_moveBlockToContainer($block, 'left');
     }
 
+    /**
+     * @param Mage_Core_Block_Abstract $block
+     * @return Mage_Adminhtml_Controller_Action
+     */
     protected function _addJs(Mage_Core_Block_Abstract $block)
     {
-        $this->getLayout()->getBlock('js')->append($block);
+        return $this->_moveBlockToContainer($block, 'js');
+    }
+
+    /**
+     * Set specified block as an anonymous child to specified container
+     *
+     * The block will be moved to the container from previous parent after all other elements
+     *
+     * @param Mage_Core_Block_Abstract $block
+     * @param string $containerName
+     * @return Mage_Adminhtml_Controller_Action
+     */
+    private function _moveBlockToContainer(Mage_Core_Block_Abstract $block, $containerName)
+    {
+        $this->getLayout()->setChild($containerName, $block->getNameInLayout(), '');
         return $this;
     }
 
@@ -134,7 +159,7 @@ class Mage_Adminhtml_Controller_Action extends Mage_Core_Controller_Varien_Actio
      */
     public function preDispatch()
     {
-        $this->getLayout()->setArea($this->_currentArea);
+        Mage::app()->setCurrentStore('admin');
         $this->_areaDesign = (string)Mage::getConfig()->getNode(
             $this->_currentArea . '/' . Mage_Core_Model_Design_Package::XML_PATH_THEME
         ) ?: 'default/default/default'; // always override frontend theme
diff --git a/app/code/core/Mage/Adminhtml/Helper/Catalog/Product/Composite.php b/app/code/core/Mage/Adminhtml/Helper/Catalog/Product/Composite.php
index 688e9e244f29585ff02daacf258c5b550c560bb5..ffe8952debb27972944e2e80747216a199c4aada 100644
--- a/app/code/core/Mage/Adminhtml/Helper/Catalog/Product/Composite.php
+++ b/app/code/core/Mage/Adminhtml/Helper/Catalog/Product/Composite.php
@@ -79,7 +79,7 @@ class Mage_Adminhtml_Helper_Catalog_Product_Composite extends Mage_Core_Helper_A
         $update = $controller->getLayout()->getUpdate();
         if ($isOk) {
             $update->addHandle('ADMINHTML_CATALOG_PRODUCT_COMPOSITE_CONFIGURE')
-                ->addHandle('PRODUCT_TYPE_' . $productType);
+                ->addHandle('catalog_product_view_type_' . $productType);
         } else {
             $update->addHandle('ADMINHTML_CATALOG_PRODUCT_COMPOSITE_CONFIGURE_ERROR');
         }
diff --git a/app/code/core/Mage/Adminhtml/Model/Observer.php b/app/code/core/Mage/Adminhtml/Model/Observer.php
index 099aa335fcd81b57ba474c4a7d0502f288339d07..09d54d442d3bbec8be0eecc03391cc0c5928cfd0 100644
--- a/app/code/core/Mage/Adminhtml/Model/Observer.php
+++ b/app/code/core/Mage/Adminhtml/Model/Observer.php
@@ -45,12 +45,6 @@ class Mage_Adminhtml_Model_Observer
         return $this;
     }
 
-    public function bindStore()
-    {
-        Mage::app()->setCurrentStore('admin');
-        return $this;
-    }
-
     /**
      * Prepare massaction separated data
      *
@@ -60,7 +54,8 @@ class Mage_Adminhtml_Model_Observer
     {
         $request = Mage::app()->getFrontController()->getRequest();
         if ($key = $request->getPost('massaction_prepare_key')) {
-            $value = is_array($request->getPost($key)) ? $request->getPost($key) : explode(',', $request->getPost($key));
+            $postData = $request->getPost($key);
+            $value = is_array($postData) ? $postData : explode(',', $postData);
             $request->setPost($key, $value ? $value : null);
         }
         return $this;
@@ -76,4 +71,130 @@ class Mage_Adminhtml_Model_Observer
         Mage::app()->removeCache(Mage_Adminhtml_Block_Notification_Security::VERIFICATION_RESULT_CACHE_KEY);
         return $this;
     }
+
+    /**
+     * Handler for controller_action_predispatch event
+     *
+     * @param Varien_Event_Observer $observer
+     */
+    public function actionPreDispatchAdmin($observer)
+    {
+        $request = Mage::app()->getRequest();
+        /** @var $controller Mage_Core_Controller_Varien_Action */
+        $controller = $observer->getEvent()->getControllerAction();
+        /** @var $session Mage_Admin_Model_Session */
+        $session = Mage::getSingleton('Mage_Admin_Model_Session');
+        /** @var $user Mage_Admin_Model_User */
+        $user = $session->getUser();
+
+        $requestedActionName = $request->getActionName();
+        $openActions = array(
+            'forgotpassword',
+            'resetpassword',
+            'resetpasswordpost',
+            'logout',
+            'refresh' // captcha refresh
+        );
+        if (in_array($requestedActionName, $openActions)) {
+            $request->setDispatched(true);
+        } else {
+            if ($user) {
+                $user->reload();
+            }
+            if (!$session->isLoggedIn()) {
+                $isRedirectNeeded = false;
+                if ($request->getPost('login')) {
+                    $this->_performLogin($controller, $isRedirectNeeded);
+                }
+                if (!$isRedirectNeeded && !$request->getParam('forwarded')) {
+                    if ($request->getParam('isIframe')) {
+                        $request->setParam('forwarded', true)
+                            ->setControllerName('index')
+                            ->setActionName('deniedIframe')
+                            ->setDispatched(false);
+                    } else if ($request->getParam('isAjax')) {
+                        $request->setParam('forwarded', true)
+                            ->setControllerName('index')
+                            ->setActionName('deniedJson')
+                            ->setDispatched(false);
+                    } else {
+                        $request->setParam('forwarded', true)
+                            ->setRouteName('adminhtml')
+                            ->setControllerName('index')
+                            ->setActionName('login')
+                            ->setDispatched(false);
+                    }
+                }
+            }
+        }
+
+        $session->refreshAcl();
+    }
+
+    /**
+     * Performs login, if user submitted login form
+     *
+     * @param Mage_Core_Controller_Varien_Action $controller
+     * @param bool $isRedirectNeeded
+     * @return bool
+     */
+    protected function _performLogin($controller, &$isRedirectNeeded)
+    {
+        $isRedirectNeeded = false;
+        /** @var $session Mage_Admin_Model_Session */
+        $session = Mage::getSingleton('Mage_Admin_Model_Session');
+        $request = $controller->getRequest();
+
+        $postLogin  = $request->getPost('login');
+        $username   = isset($postLogin['username']) ? $postLogin['username'] : '';
+        $password   = isset($postLogin['password']) ? $postLogin['password'] : '';
+        $request->setPost('login', null);
+        $result = $session->login($username, $password);
+        if ($result) {
+            $this->_redirectIfNeededAfterLogin($controller);
+        } else if (!$request->getParam('messageSent')) {
+            Mage::getSingleton('Mage_Adminhtml_Model_Session')->addError(
+                Mage::helper('Mage_Adminhtml_Helper_Data')->__('Invalid User Name or Password.')
+            );
+            $request->setParam('messageSent', true);
+        }
+        return $result;
+    }
+
+    /**
+     * Checks, whether Magento requires redirection after successful admin login, and redirects user, if needed
+     *
+     * @param Mage_Core_Controller_Varien_Action $controller
+     * @return bool
+     */
+    protected function _redirectIfNeededAfterLogin($controller)
+    {
+        $requestUri = $this->_getRequestUri($controller->getRequest());
+        if (!$requestUri) {
+            return false;
+        }
+        Mage::app()->getResponse()->setRedirect($requestUri);
+        $controller->setFlag('', Mage_Core_Controller_Varien_Action::FLAG_NO_DISPATCH, true);
+        return true;
+    }
+
+    /**
+     * Checks, whether secret key is required for admin access or request uri is explicitly set, and returns
+     * an appropriate url for redirection or null, if none
+     *
+     * @param Mage_Core_Controller_Request_Http $request
+     * @return string|null
+     */
+    protected function _getRequestUri($request)
+    {
+        /** @var $urlModel Mage_Adminhtml_Model_Url */
+        $urlModel = Mage::getSingleton('Mage_Adminhtml_Model_Url');
+        if ($urlModel->useSecretKey()) {
+            return $urlModel->getUrl('*/*/*', array('_current' => true));
+        } elseif ($request) {
+            return $request->getRequestUri();
+        } else {
+            return null;
+        }
+    }
 }
diff --git a/app/code/core/Mage/Adminhtml/Model/Sales/Order/Create.php b/app/code/core/Mage/Adminhtml/Model/Sales/Order/Create.php
index 26dc8d39a4875986419adb0722c3e6342715e9e9..a63ef4b8b3a6e2d27db543247bf5c4d19c6db81f 100644
--- a/app/code/core/Mage/Adminhtml/Model/Sales/Order/Create.php
+++ b/app/code/core/Mage/Adminhtml/Model/Sales/Order/Create.php
@@ -532,7 +532,8 @@ class Mage_Adminhtml_Model_Sales_Order_Create extends Varien_Object implements M
         $item = $this->_getQuoteItem($item);
         if ($item) {
             $removeItem = false;
-            switch ($moveTo) {
+            $moveTo = explode('_', $moveTo);
+            switch ($moveTo[0]) {
                 case 'order':
                     $info = $item->getBuyRequest();
                     $info->setOptions($this->_prepareOptionsForRequest($item))
@@ -585,8 +586,27 @@ class Mage_Adminhtml_Model_Sales_Order_Create extends Varien_Object implements M
                     }
                     break;
                 case 'wishlist':
-                    $wishlist = $this->getCustomerWishlist();
-                    if ($wishlist && $item->getProduct()->isVisibleInSiteVisibility()) {
+                    $wishlist = null;
+                    if (!isset($moveTo[1])) {
+                        $wishlist = Mage::getModel('Mage_Wishlist_Model_Wishlist')->loadByCustomer(
+                            $this->getSession()->getCustomer(),
+                            true
+                        );
+                    } else {
+                        $wishlist = Mage::getModel('Mage_Wishlist_Model_Wishlist')->load($moveTo[1]);
+                        if (!$wishlist->getId()
+                            || $wishlist->getCustomerId() != $this->getSession()->getCustomerId()
+                        ) {
+                            $wishlist = null;
+                        }
+                    }
+                    if (!$wishlist) {
+                        Mage::throwException(Mage::helper('Mage_Wishlist_Helper_Data')->__('Could not find wishlist'));
+                    }
+                    $wishlist->setStore($this->getSession()->getStore())
+                        ->setSharedStoreIds($this->getSession()->getStore()->getWebsite()->getStoreIds());
+
+                    if ($wishlist->getId() && $item->getProduct()->isVisibleInSiteVisibility()) {
                         $info = $item->getBuyRequest();
                         $info->setOptions($this->_prepareOptionsForRequest($item))
                             ->setQty($qty)
@@ -1489,6 +1509,7 @@ class Mage_Adminhtml_Model_Sales_Order_Create extends Varien_Object implements M
         $quote = $this->getQuote();
         $this->_prepareQuoteItems();
 
+        /** @var $service Mage_Sales_Model_Service_Quote */
         $service = Mage::getModel('Mage_Sales_Model_Service_Quote', $quote);
         if ($this->getSession()->getOrder()->getId()) {
             $oldOrder = $this->getSession()->getOrder();
@@ -1507,7 +1528,7 @@ class Mage_Adminhtml_Model_Sales_Order_Create extends Varien_Object implements M
             $service->setOrderData($orderData);
         }
 
-        $order = $service->submit();
+        $order = $service->submitOrder();
         if ((!$quote->getCustomer()->getId() || !$quote->getCustomer()->isInStore($this->getSession()->getStore()))
             && !$quote->getCustomerIsGuest()
         ) {
diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Custom.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Custom.php
index e7abd834904abe5ee44ee6d488f3e6bbcff49985..36c769f43ad9c1317d5cb4f848939f20255902f2 100644
--- a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Custom.php
+++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Custom.php
@@ -86,17 +86,6 @@ class Mage_Adminhtml_Model_System_Config_Backend_Admin_Custom extends Mage_Core_
                 self::CONFIG_SCOPE,
                 self::CONFIG_SCOPE_ID
             );
-        } else {
-            Mage::getConfig()->deleteConfig(
-                self::XML_PATH_SECURE_BASE_URL,
-                self::CONFIG_SCOPE,
-                self::CONFIG_SCOPE_ID
-            );
-            Mage::getConfig()->deleteConfig(
-                self::XML_PATH_UNSECURE_BASE_URL,
-                self::CONFIG_SCOPE,
-                self::CONFIG_SCOPE_ID
-            );
         }
 
         return $this;
diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Password/Link/Expirationperiod.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Password/Link/Expirationperiod.php
index 42c3fc4a1b80203af4f03fa474642ec618701d12..55d59675fef4f42d8f0208246e83ede77020810b 100644
--- a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Password/Link/Expirationperiod.php
+++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Password/Link/Expirationperiod.php
@@ -42,12 +42,12 @@ class Mage_Adminhtml_Model_System_Config_Backend_Admin_Password_Link_Expirationp
     protected function _beforeSave()
     {
         parent::_beforeSave();
-        $resetPasswordLinkExpirationPeriod = (int) $this->getValue();
-        // This value must be greater than 0
+        $resetPasswordLinkExpirationPeriod = (int)$this->getValue();
+
         if ($resetPasswordLinkExpirationPeriod < 1) {
-            $resetPasswordLinkExpirationPeriod = (int) $this->getOldValue();
+            $resetPasswordLinkExpirationPeriod = (int)$this->getOldValue();
         }
-        $this->setValue((string) $resetPasswordLinkExpirationPeriod);
+        $this->setValue((string)$resetPasswordLinkExpirationPeriod);
         return $this;
     }
 }
diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Usecustom.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Usecustom.php
index 6c3523528d4c20c3681dc92556aa3f551e925823..453b4350d9b5c290a42cd938536feac4f86b4407 100644
--- a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Usecustom.php
+++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Admin/Usecustom.php
@@ -51,4 +51,29 @@ class Mage_Adminhtml_Model_System_Config_Backend_Admin_Usecustom extends Mage_Co
 
         return $this;
     }
+
+    /**
+     * Delete custom admin url from configuration if "Use Custom Admin Url" option disabled
+     *
+     * @return Mage_Adminhtml_Model_System_Config_Backend_Admin_Usecustom
+     */
+    protected function _afterSave()
+    {
+        $value = $this->getValue();
+
+        if (!$value) {
+            Mage::getConfig()->deleteConfig(
+                Mage_Adminhtml_Model_System_Config_Backend_Admin_Custom::XML_PATH_SECURE_BASE_URL,
+                Mage_Adminhtml_Model_System_Config_Backend_Admin_Custom::CONFIG_SCOPE,
+                Mage_Adminhtml_Model_System_Config_Backend_Admin_Custom::CONFIG_SCOPE_ID
+            );
+            Mage::getConfig()->deleteConfig(
+                Mage_Adminhtml_Model_System_Config_Backend_Admin_Custom::XML_PATH_UNSECURE_BASE_URL,
+                Mage_Adminhtml_Model_System_Config_Backend_Admin_Custom::CONFIG_SCOPE,
+                Mage_Adminhtml_Model_System_Config_Backend_Admin_Custom::CONFIG_SCOPE_ID
+            );
+        }
+
+        return $this;
+    }
 }
diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Baseurl.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Baseurl.php
index 8d3df8a603e6bcb28fb5ee113763dfd230cf3caf..2bea13cd4d3292c83fce2e83fe59a50d10ad3c68 100644
--- a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Baseurl.php
+++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Baseurl.php
@@ -31,7 +31,7 @@ class Mage_Adminhtml_Model_System_Config_Backend_Baseurl extends Mage_Core_Model
     {
         $value = $this->getValue();
 
-        if (!preg_match('#^{{((un)?secure_)?base_url}}#', $value)) {
+        if (!preg_match('#^{{((un)?secure_)?(base|public)_url}}#', $value)) {
             $parsedUrl = parse_url($value);
             if (!isset($parsedUrl['scheme']) || !isset($parsedUrl['host'])) {
                 Mage::throwException(Mage::helper('Mage_Core_Helper_Data')->__('The %s you entered is invalid. Please make sure that it follows "http://domain.com/" format.', $this->getFieldConfig()->label));
diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Customer/Password/Link/Expirationperiod.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Customer/Password/Link/Expirationperiod.php
index 3e3ead27555a9cc8e31cf6896f314513b0707c07..3b07d813568b911845443ab028917be68a7e8f55 100644
--- a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Customer/Password/Link/Expirationperiod.php
+++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Customer/Password/Link/Expirationperiod.php
@@ -43,12 +43,12 @@ class Mage_Adminhtml_Model_System_Config_Backend_Customer_Password_Link_Expirati
     protected function _beforeSave()
     {
         parent::_beforeSave();
-        $resetPasswordLinkExpirationPeriod = (int) $this->getValue();
-        // This value must be greater than 0
+        $resetPasswordLinkExpirationPeriod = (int)$this->getValue();
+
         if ($resetPasswordLinkExpirationPeriod < 1) {
-            $resetPasswordLinkExpirationPeriod = (int) $this->getOldValue();
+            $resetPasswordLinkExpirationPeriod = (int)$this->getOldValue();
         }
-        $this->setValue((string) $resetPasswordLinkExpirationPeriod);
+        $this->setValue((string)$resetPasswordLinkExpirationPeriod);
         return $this;
     }
 }
diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Email/Logo.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Email/Logo.php
new file mode 100644
index 0000000000000000000000000000000000000000..a02a2f024fc0eae2152924b5ae7118fb83394dee
--- /dev/null
+++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Email/Logo.php
@@ -0,0 +1,92 @@
+<?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_Adminhtml
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+ /**
+ * Backend model for uploading transactional emails custom logo image
+ *
+ * @category   Mage
+ * @package    Mage_Adminhtml
+ * @author     Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_Adminhtml_Model_System_Config_Backend_Email_Logo extends Mage_Adminhtml_Model_System_Config_Backend_Image
+{
+    /**
+     * The tail part of directory path for uploading
+     */
+    const UPLOAD_DIR                = 'email/logo';
+
+    /**
+     * Token for the root part of directory path for uploading
+     */
+    const UPLOAD_ROOT_TOKEN         = 'system/filesystem/media';
+
+    /**
+     * Upload max file size in kilobytes
+     *
+     * @var int
+     */
+    protected $_maxFileSize         = 2048;
+
+    /**
+     * Return path to directory for upload file
+     *
+     * @return string
+     */
+    protected function _getUploadDir()
+    {
+        $uploadDir  = $this->_appendScopeInfo(self::UPLOAD_DIR);
+        $uploadRoot = $this->_getUploadRoot(self::UPLOAD_ROOT_TOKEN);
+        $uploadDir  = $uploadRoot . DS . $uploadDir;
+        return $uploadDir;
+    }
+
+    /**
+     * Makes a decision about whether to add info about the scope
+     *
+     * @return boolean
+     */
+    protected function _addWhetherScopeInfo()
+    {
+        return true;
+    }
+
+    /**
+     * Save uploaded file before saving config value
+     *
+     * Save changes and delete file if "delete" option passed
+     *
+     * @return Mage_Adminhtml_Model_System_Config_Backend_Email_logo
+     */
+    protected function _beforeSave()
+    {
+        $value = $this->getValue();
+        if (is_array($value) && !empty($value['delete'])) {
+            $io = new Varien_Io_File();
+            $io->rm($this->_getUploadRoot(self::UPLOAD_ROOT_TOKEN) . DS . self::UPLOAD_DIR . DS . $value['value']);
+        }
+        return parent::_beforeSave();
+    }
+}
diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/File.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/File.php
index bf8c5bee0e2630582837197342702dcf68fc8b4f..3a6f86e321f149316c8dd797da3294361c62735b 100644
--- a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/File.php
+++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/File.php
@@ -24,7 +24,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
 /**
  * System config file field backend model
  *
@@ -34,6 +33,12 @@
  */
 class Mage_Adminhtml_Model_System_Config_Backend_File extends Mage_Core_Model_Config_Data
 {
+    /**
+     * Upload max file size in kilobytes
+     *
+     * @var int
+     */
+    protected $_maxFileSize = 0;
 
     /**
      * Save uploaded file before saving config value
@@ -60,6 +65,7 @@ class Mage_Adminhtml_Model_System_Config_Backend_File extends Mage_Core_Model_Co
                 $uploader = new Mage_Core_Model_File_Uploader($file);
                 $uploader->setAllowedExtensions($this->_getAllowedExtensions());
                 $uploader->setAllowRenameFiles(true);
+                $uploader->addValidateCallback('size', $this, 'validateMaxSize');
                 $result = $uploader->save($uploadDir);
 
             } catch (Exception $e) {
@@ -79,6 +85,19 @@ class Mage_Adminhtml_Model_System_Config_Backend_File extends Mage_Core_Model_Co
         return $this;
     }
 
+    /**
+     * Validation callback for checking max file size
+     *
+     * @param  string $filePath Path to temporary uploaded file
+     * @throws Mage_Core_Exception
+     */
+    public function validateMaxSize($filePath)
+    {
+        if ($this->_maxFileSize > 0 && filesize($filePath) > ($this->_maxFileSize * 1024)) {
+            throw Mage::exception('Mage_Core', Mage::helper('Mage_Adminhtml_Helper_Data')->__('Uploaded file is larger than %.2f kilobytes allowed by server', $this->_maxFileSize));
+        }
+    }
+
     /**
      * Makes a decision about whether to add info about the scope.
      *
diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Image/Favicon.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Image/Favicon.php
index 89894e871d62638676c8463fb67c67a94874166f..a5621168a98f8a5c56a3f88219c8fab94ac00efc 100644
--- a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Image/Favicon.php
+++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Image/Favicon.php
@@ -77,7 +77,7 @@ class Mage_Adminhtml_Model_System_Config_Backend_Image_Favicon extends Mage_Admi
      */
     protected function _getAllowedExtensions()
     {
-        return array('ico', 'png', 'gif', 'jpeg', 'apng', 'svg');
+        return array('ico', 'png', 'gif', 'jpg', 'jpeg', 'apng', 'svg');
     }
 
     /**
diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Locale/Timezone.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Locale/Timezone.php
index 048fa75f8386d7e42d1de64f72efa00e94ef6fac..5035db8f2044633fb6312310d4de29fc1415b036 100644
--- a/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Locale/Timezone.php
+++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Locale/Timezone.php
@@ -34,9 +34,22 @@
  */
 class Mage_Adminhtml_Model_System_Config_Backend_Locale_Timezone extends Mage_Core_Model_Config_Data
 {
+    /**
+     * Const for PHP 5.3+ compatibility
+     * This value copied from DateTimeZone::ALL_WITH_BC in PHP 5.3+
+     *
+     * @constant ALL_WITH_BC
+     */
+    const ALL_WITH_BC = 4095;
+
     protected function _beforeSave()
     {
-        if (!in_array($this->getValue(), DateTimeZone::listIdentifiers())) {
+        $allWithBc = self::ALL_WITH_BC;
+        if (defined('DateTimeZone::ALL_WITH_BC')) {
+            $allWithBc = DateTimeZone::ALL_WITH_BC;
+        }
+
+        if (!in_array($this->getValue(), DateTimeZone::listIdentifiers($allWithBc))) {
             Mage::throwException(Mage::helper('Mage_Adminhtml_Helper_Data')->__('Invalid timezone'));
         }
 
diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Admin/Page.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Admin/Page.php
index fadd44c9a53dcd1114d19fe308bb9126933860bf..97818fd3ff5ae7fb4d5b843ca02dadd8b4c24a9c 100644
--- a/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Admin/Page.php
+++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Admin/Page.php
@@ -94,8 +94,9 @@ class Mage_Adminhtml_Model_System_Config_Source_Admin_Page
         $parentArr = array();
         $sortOrder = 0;
         foreach ($parent->children() as $childName=>$child) {
-
-            if ($child->depends && !$this->_checkDepends($child->depends)) {
+            if ((1 == $child->disabled)
+                || ($child->depends && !$this->_checkDepends($child->depends))
+            ) {
                 continue;
             }
 
diff --git a/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Price/Step.php b/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Price/Step.php
index 1b5691533988cf99528f6eca87ae47b597035fc4..025b1ae4ab7beeab27779287760f26e483871155 100644
--- a/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Price/Step.php
+++ b/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Price/Step.php
@@ -31,7 +31,11 @@ class Mage_Adminhtml_Model_System_Config_Source_Price_Step
         return array(
             array(
                 'value' => Mage_Catalog_Model_Layer_Filter_Price::RANGE_CALCULATION_AUTO,
-                'label' => Mage::helper('Mage_Adminhtml_Helper_Data')->__('Automatic')
+                'label' => Mage::helper('Mage_Adminhtml_Helper_Data')->__('Automatic (equalize price ranges)')
+            ),
+            array(
+                'value' => Mage_Catalog_Model_Layer_Filter_Price::RANGE_CALCULATION_IMPROVED,
+                'label' => Mage::helper('Mage_Adminhtml_Helper_Data')->__('Automatic (equalize product counts)')
             ),
             array(
                 'value' => Mage_Catalog_Model_Layer_Filter_Price::RANGE_CALCULATION_MANUAL,
diff --git a/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/Action/AttributeController.php b/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/Action/AttributeController.php
index 4d7366bace430048604fc304852ef0d4ecc89964..bda8241f1eac6a59c823c3d2dc082ee2f8137631 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/Action/AttributeController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/Action/AttributeController.php
@@ -51,6 +51,9 @@ class Mage_Adminhtml_Catalog_Product_Action_AttributeController extends Mage_Adm
         $this->renderLayout();
     }
 
+    /**
+     * Update product attributes
+     */
     public function saveAction()
     {
         if (!$this->_validateProducts()) {
@@ -95,7 +98,13 @@ class Mage_Adminhtml_Catalog_Product_Action_AttributeController extends Mage_Adm
                             $value = null;
                         }
                         $attributesData[$attributeCode] = $value;
-                    } else if ($attribute->getFrontendInput() == 'multiselect') {
+                    } elseif ($attribute->getFrontendInput() == 'multiselect') {
+                        // Check if 'Change' checkbox has been checked by admin for this attribute
+                        $isChanged = (bool)$this->getRequest()->getPost($attributeCode . '_checkbox');
+                        if (!$isChanged) {
+                            unset($attributesData[$attributeCode]);
+                            continue;
+                        }
                         if (is_array($value)) {
                             $value = implode(',', $value);
                         }
diff --git a/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/ReviewController.php b/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/ReviewController.php
index 29c540a5d0746e3a3f274513e4976c9e914f3e91..fd8d533e2e07e3513d96ae22b8b06746e94e309a 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/ReviewController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Catalog/Product/ReviewController.php
@@ -315,7 +315,9 @@ class Mage_Adminhtml_Catalog_Product_ReviewController extends Mage_Adminhtml_Con
         $session    = Mage::getSingleton('Mage_Adminhtml_Model_Session');
 
         if ($data = $this->getRequest()->getPost()) {
-            if(isset($data['select_stores'])) {
+            if (Mage::app()->isSingleStoreMode()) {
+                $data['stores'] = array(Mage::app()->getStore(true)->getId());
+            } else  if (isset($data['select_stores'])) {
                 $data['stores'] = $data['select_stores'];
             }
 
diff --git a/app/code/core/Mage/Adminhtml/controllers/Catalog/ProductController.php b/app/code/core/Mage/Adminhtml/controllers/Catalog/ProductController.php
index a305ce08b92223e6ed6adfc2b5fe225c516d73d3..3fcda6cee7b86ec15dc8af8d3b2102df9c57bb10 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Catalog/ProductController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Catalog/ProductController.php
@@ -673,6 +673,9 @@ class Mage_Adminhtml_Catalog_ProductController extends Mage_Adminhtml_Controller
         if (isset($stockData['min_qty']) && (int)$stockData['min_qty'] < 0) {
             $stockData['min_qty'] = 0;
         }
+        if (!isset($stockData['is_decimal_divided']) || $stockData['is_qty_decimal'] == 0) {
+            $stockData['is_decimal_divided'] = 0;
+        }
     }
 
     public function categoriesJsonAction()
diff --git a/app/code/core/Mage/Adminhtml/controllers/Customer/GroupController.php b/app/code/core/Mage/Adminhtml/controllers/Customer/GroupController.php
index 0d48c0a2a22fba88b232ddc2b941f04d2d28eb4d..4c2f6ea2fe48619cca1ba66a367ebc8d624dcb14 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Customer/GroupController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Customer/GroupController.php
@@ -79,9 +79,8 @@ class Mage_Adminhtml_Customer_GroupController extends Mage_Adminhtml_Controller_
 
         $this->_title($currentGroup->getId() ? $currentGroup->getCode() : $this->__('New Group'));
 
-        $this->getLayout()->getBlock('content')
-            ->append($this->getLayout()->createBlock('Mage_Adminhtml_Block_Customer_Group_Edit', 'group')
-                        ->setEditMode((bool)Mage::registry('current_group')->getId()));
+        $this->getLayout()->addBlock('Mage_Adminhtml_Block_Customer_Group_Edit', 'group', 'content')
+            ->setEditMode((bool)Mage::registry('current_group')->getId());
 
         $this->renderLayout();
     }
diff --git a/app/code/core/Mage/Adminhtml/controllers/IndexController.php b/app/code/core/Mage/Adminhtml/controllers/IndexController.php
index 043f37dea93a6f54224f656f9de02480e8fb87ea..9cd661007755b4220b76bc257af46da6e2665181 100644
--- a/app/code/core/Mage/Adminhtml/controllers/IndexController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/IndexController.php
@@ -75,9 +75,6 @@ class Mage_Adminhtml_IndexController extends Mage_Adminhtml_Controller_Action
             $this->_redirect('*');
             return;
         }
-        $loginData = $this->getRequest()->getParam('login');
-        $username = (is_array($loginData) && array_key_exists('username', $loginData)) ? $loginData['username'] : null;
-
         $this->loadLayout();
         $this->renderLayout();
     }
@@ -89,10 +86,8 @@ class Mage_Adminhtml_IndexController extends Mage_Adminhtml_Controller_Action
     {
         /** @var $adminSession Mage_Admin_Model_Session */
         $adminSession = Mage::getSingleton('Mage_Admin_Model_Session');
-        $adminSession->unsetAll();
-        $adminSession->getCookie()->delete($adminSession->getSessionName());
+        $adminSession->logout();
         $adminSession->addSuccess(Mage::helper('Mage_Adminhtml_Helper_Data')->__('You have logged out.'));
-
         $this->_redirect('*');
     }
 
diff --git a/app/code/core/Mage/Adminhtml/controllers/Permissions/RoleController.php b/app/code/core/Mage/Adminhtml/controllers/Permissions/RoleController.php
index 564499ad955cb24aac745c006451df5e898ec258..97477d50d4d429d221ebb3292bba00f316e1b2ea 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Permissions/RoleController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Permissions/RoleController.php
@@ -219,7 +219,7 @@ class Mage_Adminhtml_Permissions_RoleController extends Mage_Adminhtml_Controlle
         }
 
         //$this->getResponse()->setRedirect($this->getUrl("*/*/editrole/rid/$rid"));
-        $this->_redirect('*/*/editrole', array('rid' => $rid));
+        $this->_redirect('*/*/');
         return;
     }
 
diff --git a/app/code/core/Mage/Adminhtml/controllers/Permissions/UserController.php b/app/code/core/Mage/Adminhtml/controllers/Permissions/UserController.php
index b79561ad5cce5ed9d4fd8b48e0b94b2cd7d05742..e62c6a7db0860abfe2c366b1cb3781190a8e509d 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Permissions/UserController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Permissions/UserController.php
@@ -81,16 +81,24 @@ class Mage_Adminhtml_Permissions_UserController extends Mage_Adminhtml_Controlle
 
         Mage::register('permissions_user', $model);
 
+        if (isset($id)) {
+            $breadcrumb = $this->__('Edit User');
+        } else {
+            $breadcrumb = $this->__('New User');
+        }
         $this->_initAction()
-            ->_addBreadcrumb($id ? $this->__('Edit User') : $this->__('New User'), $id ? $this->__('Edit User') : $this->__('New User'))
-            ->_addContent($this->getLayout()
-                ->createBlock('Mage_Adminhtml_Block_Permissions_User_Edit')
-                ->setData('action', $this->getUrl('*/permissions_user/save')))
+            ->_addBreadcrumb($breadcrumb, $breadcrumb)
+            ->_addContent(
+                $this->getLayout()
+                    ->createBlock('Mage_Adminhtml_Block_Permissions_User_Edit')
+                    ->setData('action', $this->getUrl('*/permissions_user/save'))
+            )
             ->_addLeft($this->getLayout()->createBlock('Mage_Adminhtml_Block_Permissions_User_Edit_Tabs'));
 
-        $this->_addJs($this->getLayout()
-            ->createBlock('Mage_Adminhtml_Block_Template')
-            ->setTemplate('permissions/user_roles_grid_js.phtml')
+        $this->_addJs(
+            $this->getLayout()
+                ->createBlock('Mage_Adminhtml_Block_Template')
+                ->setTemplate('permissions/user_roles_grid_js.phtml')
         );
         $this->renderLayout();
     }
@@ -147,7 +155,7 @@ class Mage_Adminhtml_Permissions_UserController extends Mage_Adminhtml_Controlle
                 }
                 Mage::getSingleton('Mage_Adminhtml_Model_Session')->addSuccess($this->__('The user has been saved.'));
                 Mage::getSingleton('Mage_Adminhtml_Model_Session')->setUserData(false);
-                $this->_redirect('*/*/edit', array('user_id' => $model->getUserId()));
+                $this->_redirect('*/*/');
                 return;
             } catch (Mage_Core_Exception $e) {
                 Mage::getSingleton('Mage_Adminhtml_Model_Session')->addError($e->getMessage());
@@ -198,7 +206,9 @@ class Mage_Adminhtml_Permissions_UserController extends Mage_Adminhtml_Controlle
 
         Mage::register('permissions_user', $model);
         $this->getResponse()->setBody(
-            $this->getLayout()->createBlock('Mage_Adminhtml_Block_Permissions_User_Edit_Tab_Roles')->toHtml()
+            $this->getLayout()
+                ->createBlock('Mage_Adminhtml_Block_Permissions_User_Edit_Tab_Roles')
+                ->toHtml()
         );
     }
 
diff --git a/app/code/core/Mage/Adminhtml/controllers/Promo/CatalogController.php b/app/code/core/Mage/Adminhtml/controllers/Promo/CatalogController.php
index 64b484575313f1e358bdfc488bc85d3191670011..0dac7fdf9f87acfbb3084dd165b0db08e8166c86 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Promo/CatalogController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Promo/CatalogController.php
@@ -33,6 +33,13 @@
  */
 class Mage_Adminhtml_Promo_CatalogController extends Mage_Adminhtml_Controller_Action
 {
+    /**
+     * Dirty rules notice message
+     *
+     * @var string
+     */
+    protected $_dirtyRulesNoticeMessage;
+
     protected function _initAction()
     {
         $this->loadLayout()
@@ -48,10 +55,9 @@ class Mage_Adminhtml_Promo_CatalogController extends Mage_Adminhtml_Controller_A
     {
         $this->_title($this->__('Promotions'))->_title($this->__('Catalog Price Rules'));
 
-        if (Mage::app()->loadCache('catalog_rules_dirty')) {
-            Mage::getSingleton('Mage_Adminhtml_Model_Session')->addNotice(
-                Mage::helper('Mage_CatalogRule_Helper_Data')->__('There are rules that have been changed but were not applied. Please, click Apply Rules in order to see immediate effect in the catalog.')
-            );
+        $dirtyRules = Mage::getModel('Mage_CatalogRule_Model_Flag')->loadSelf();
+        if ($dirtyRules->getState()) {
+            Mage::getSingleton('Mage_Adminhtml_Model_Session')->addNotice($this->getDirtyRulesNoticeMessage());
         }
 
         $this->_initAction()
@@ -157,7 +163,9 @@ class Mage_Adminhtml_Promo_CatalogController extends Mage_Adminhtml_Controller_A
                     $this->getRequest()->setParam('rule_id', $model->getId());
                     $this->_forward('applyRules');
                 } else {
-                    Mage::app()->saveCache(1, 'catalog_rules_dirty');
+                    Mage::getModel('Mage_CatalogRule_Model_Flag')->loadSelf()
+                        ->setState(1)
+                        ->save();
                     if ($this->getRequest()->getParam('back')) {
                         $this->_redirect('*/*/edit', array('id' => $model->getId()));
                         return;
@@ -187,7 +195,9 @@ class Mage_Adminhtml_Promo_CatalogController extends Mage_Adminhtml_Controller_A
                 $model = Mage::getModel('Mage_CatalogRule_Model_Rule');
                 $model->load($id);
                 $model->delete();
-                Mage::app()->saveCache(1, 'catalog_rules_dirty');
+                Mage::getModel('Mage_CatalogRule_Model_Flag')->loadSelf()
+                    ->setState(1)
+                    ->save();
                 Mage::getSingleton('Mage_Adminhtml_Model_Session')->addSuccess(
                     Mage::helper('Mage_CatalogRule_Helper_Data')->__('The rule has been deleted.')
                 );
@@ -279,7 +289,9 @@ class Mage_Adminhtml_Promo_CatalogController extends Mage_Adminhtml_Controller_A
         $errorMessage = Mage::helper('Mage_CatalogRule_Helper_Data')->__('Unable to apply rules.');
         try {
             Mage::getModel('Mage_CatalogRule_Model_Rule')->applyAll();
-            Mage::app()->removeCache('catalog_rules_dirty');
+            Mage::getModel('Mage_CatalogRule_Model_Flag')->loadSelf()
+                ->setState(0)
+                ->save();
             $this->_getSession()->addSuccess(Mage::helper('Mage_CatalogRule_Helper_Data')->__('The rules have been applied.'));
         } catch (Mage_Core_Exception $e) {
             $this->_getSession()->addError($errorMessage . ' ' . $e->getMessage());
@@ -293,4 +305,25 @@ class Mage_Adminhtml_Promo_CatalogController extends Mage_Adminhtml_Controller_A
     {
         return Mage::getSingleton('Mage_Admin_Model_Session')->isAllowed('promo/catalog');
     }
+
+    /**
+     * Set dirty rules notice message
+     *
+     * @param string $dirtyRulesNoticeMessage
+     */
+    public function setDirtyRulesNoticeMessage($dirtyRulesNoticeMessage)
+    {
+        $this->_dirtyRulesNoticeMessage = $dirtyRulesNoticeMessage;
+    }
+
+    /**
+     * Get dirty rules notice message
+     *
+     * @return string
+     */
+    public function getDirtyRulesNoticeMessage()
+    {
+        $defaultMessage = Mage::helper('Mage_CatalogRule_Helper_Data')->__('There are rules that have been changed but were not applied. Please, click Apply Rules in order to see immediate effect in the catalog.');
+        return $this->_dirtyRulesNoticeMessage ? $this->_dirtyRulesNoticeMessage : $defaultMessage;
+    }
 }
diff --git a/app/code/core/Mage/Adminhtml/controllers/Promo/QuoteController.php b/app/code/core/Mage/Adminhtml/controllers/Promo/QuoteController.php
index 7de8f01ed9fd2ce5ecf590d7bdb84c751e48dd4b..d87849480cfc80fd3fa549a0f0facca0003a93f0 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Promo/QuoteController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Promo/QuoteController.php
@@ -379,7 +379,7 @@ class Mage_Adminhtml_Promo_QuoteController extends Mage_Adminhtml_Controller_Act
                     $generator->setData($data);
                     $generator->generatePool();
                     $generated = $generator->getGeneratedCount();
-                    $this->_getSession()->addSuccess(Mage::helper('Mage_SalesRule_Helper_Data')->__('%s Coupon(s) generated successfully', $generated));
+                    $this->_getSession()->addSuccess(Mage::helper('Mage_SalesRule_Helper_Data')->__('%s Coupon(s) have been generated', $generated));
                     $this->_initLayoutMessages('Mage_Adminhtml_Model_Session');
                     $result['messages']  = $this->getLayout()->getMessagesBlock()->getGroupedHtml();
                 }
diff --git a/app/code/core/Mage/Adminhtml/controllers/RatingController.php b/app/code/core/Mage/Adminhtml/controllers/RatingController.php
index 44691f3b52d4115b3b8a074d1f4473bd0e1a928c..479c6844c87754b231e56de6dc772dca82112693 100644
--- a/app/code/core/Mage/Adminhtml/controllers/RatingController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/RatingController.php
@@ -71,30 +71,35 @@ class Mage_Adminhtml_RatingController extends Mage_Adminhtml_Controller_Action
         $this->_forward('edit');
     }
 
+    /**
+     * Save rating
+     */
     public function saveAction()
     {
         $this->_initEnityId();
 
-        if ( $this->getRequest()->getPost() ) {
+        if ($this->getRequest()->getPost()) {
             try {
                 $ratingModel = Mage::getModel('Mage_Rating_Model_Rating');
 
                 $stores = $this->getRequest()->getParam('stores');
+                $position = (int)$this->getRequest()->getParam('position');
                 $stores[] = 0;
                 $ratingModel->setRatingCode($this->getRequest()->getParam('rating_code'))
-                      ->setRatingCodes($this->getRequest()->getParam('rating_codes'))
-                      ->setStores($stores)
-                      ->setId($this->getRequest()->getParam('id'))
-                      ->setEntityId(Mage::registry('entityId'))
-                      ->save();
+                    ->setRatingCodes($this->getRequest()->getParam('rating_codes'))
+                    ->setStores($stores)
+                    ->setPosition($position)
+                    ->setId($this->getRequest()->getParam('id'))
+                    ->setEntityId(Mage::registry('entityId'))
+                    ->save();
 
                 $options = $this->getRequest()->getParam('option_title');
 
-                if( is_array($options) ) {
+                if (is_array($options)) {
                     $i = 1;
-                    foreach( $options as $key => $optionCode ) {
+                    foreach ($options as $key => $optionCode) {
                         $optionModel = Mage::getModel('Mage_Rating_Model_Rating_Option');
-                        if( !preg_match("/^add_([0-9]*?)$/", $key) ) {
+                        if (!preg_match("/^add_([0-9]*?)$/", $key)) {
                             $optionModel->setId($key);
                         }
 
diff --git a/app/code/core/Mage/Adminhtml/controllers/Report/StatisticsController.php b/app/code/core/Mage/Adminhtml/controllers/Report/StatisticsController.php
index 874145813389310841184f5151793f1319457d33..00ac321177eea4b1ab5d4c4608ca18246b0ba2d7 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Report/StatisticsController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Report/StatisticsController.php
@@ -106,7 +106,7 @@ class Mage_Adminhtml_Report_StatisticsController extends Mage_Adminhtml_Controll
             'refunded'    => 'Mage_Sales_Model_Resource_Report_Refunded',
             'coupons'     => 'Mage_SalesRule_Model_Resource_Report_Rule',
             'bestsellers' => 'Mage_Sales_Model_Resource_Report_Bestsellers',
-            'viewed'      => 'Mage_Sales_Model_Resource_Report_Product_Viewed',
+            'viewed'      => 'Mage_Reports_Model_Resource_Report_Product_Viewed',
         );
         $out = array();
         foreach ($codes as $code) {
diff --git a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/CreateController.php b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/CreateController.php
index 735aa1756360aa281e90bb440a4f1eba62bce6f2..73ea214e65f06cc2245ffee061b44ec6ce2d3fae 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/CreateController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/CreateController.php
@@ -40,6 +40,9 @@ class Mage_Adminhtml_Sales_Order_CreateController extends Mage_Adminhtml_Control
     protected function _construct()
     {
         $this->setUsedModuleName('Mage_Sales');
+
+        // During order creation in the backend admin has ability to add any products to order
+        Mage::helper('Mage_Catalog_Helper_Product')->setSkipSaleableCheck(true);
     }
 
     /**
@@ -161,9 +164,10 @@ class Mage_Adminhtml_Sales_Order_CreateController extends Mage_Adminhtml_Control
          */
         if (!$this->_getOrderCreateModel()->getQuote()->isVirtual()) {
             $syncFlag = $this->getRequest()->getPost('shipping_as_billing');
+            $shippingMethod = $this->_getOrderCreateModel()->getShippingAddress()->getShippingMethod();
             if (is_null($syncFlag)
                 && $this->_getOrderCreateModel()->getShippingAddress()->getSameAsBilling()
-                && is_null($this->_getOrderCreateModel()->getShippingMethod())
+                && empty($shippingMethod)
             ) {
                 $this->_getOrderCreateModel()->setShippingAsBilling(1);
             } else {
@@ -285,10 +289,14 @@ class Mage_Adminhtml_Sales_Order_CreateController extends Mage_Adminhtml_Control
         }
 
         $data = $this->getRequest()->getPost('order');
-        if (!empty($data['coupon']['code'])) {
-            if ($this->_getQuote()->getCouponCode() !== $data['coupon']['code']) {
+        $couponCode = '';
+        if (isset($data) && isset($data['coupon']['code'])) {
+            $couponCode = trim($data['coupon']['code']);
+        }
+        if (!empty($couponCode)) {
+            if ($this->_getQuote()->getCouponCode() !== $couponCode) {
                 $this->_getSession()->addError(
-                    $this->__('"%s" coupon code is not valid.', $this->_getHelper()->escapeHtml($data['coupon']['code'])));
+                    $this->__('"%s" coupon code is not valid.', $this->_getHelper()->escapeHtml($couponCode)));
             } else {
                 $this->_getSession()->addSuccess($this->__('The coupon code has been accepted.'));
             }
@@ -402,7 +410,7 @@ class Mage_Adminhtml_Sales_Order_CreateController extends Mage_Adminhtml_Control
             }
         }
         $this->loadLayoutUpdates()->generateLayoutXml()->generateLayoutBlocks();
-        $result = $this->getLayout()->getBlock('content')->toHtml();
+        $result = $this->getLayout()->renderElement('content');
         if ($request->getParam('as_js_varname')) {
             Mage::getSingleton('Mage_Adminhtml_Model_Session')->setUpdateResult($result);
             $this->_redirect('*/*/showUpdateResult');
diff --git a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/EditController.php b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/EditController.php
index be3d5c1c783c954755521378c791e535e03dc3b1..56bcf3cd299e8993b7c268ded19fe84903fc26d6 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Sales/Order/EditController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Sales/Order/EditController.php
@@ -34,15 +34,6 @@ require_once('CreateController.php');
  */
 class Mage_Adminhtml_Sales_Order_EditController extends Mage_Adminhtml_Sales_Order_CreateController
 {
-    /**
-     * Additional initialization
-     *
-     */
-    protected function _construct()
-    {
-        $this->setUsedModuleName('Mage_Sales');
-    }
-
     /**
      * Start edit order initialization
      */
diff --git a/app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php b/app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php
index c09b76df946d82ab03a30f08f4e8a344e1782848..d0fb58f7e19a87442b1f0607e450b74579131dfd 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php
@@ -730,7 +730,7 @@ class Mage_Adminhtml_Sales_OrderController extends Mage_Adminhtml_Controller_Act
             // Do not display VAT validation button on edit order address form
             $addressFormContainer = $this->getLayout()->getBlock('sales_order_address.form.container');
             if ($addressFormContainer) {
-                $addressFormContainer->getChild('form')->setDisplayVatValidationButton(false);
+                $addressFormContainer->getChildBlock('form')->setDisplayVatValidationButton(false);
             }
 
             $this->renderLayout();
diff --git a/app/code/core/Mage/Adminhtml/controllers/System/BackupController.php b/app/code/core/Mage/Adminhtml/controllers/System/BackupController.php
index cc173fdad32fc7b1e75408920454b9321f4a3beb..d2c74ae3c7c5af70b90841cb359b430483170b01 100644
--- a/app/code/core/Mage/Adminhtml/controllers/System/BackupController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/System/BackupController.php
@@ -86,8 +86,8 @@ class Mage_Adminhtml_System_BackupController extends Mage_Adminhtml_Controller_A
             $type = $this->getRequest()->getParam('type');
 
             if ($type == Mage_Backup_Helper_Data::TYPE_SYSTEM_SNAPSHOT
-                && $this->getRequest()->getParam('exclude_media'))
-            {
+                && $this->getRequest()->getParam('exclude_media')
+            ) {
                 $type = Mage_Backup_Helper_Data::TYPE_SNAPSHOT_WITHOUT_MEDIA;
             }
 
@@ -105,8 +105,8 @@ class Mage_Adminhtml_System_BackupController extends Mage_Adminhtml_Controller_A
 
                 if (!$turnedOn) {
                     $response->setError(
-                        Mage::helper('Mage_Backup_Helper_Data')->__("Warning! System couldn't put store on the maintenance mode.") . ' '
-                        . Mage::helper('Mage_Backup_Helper_Data')->__("Please deselect the sufficient check-box, if you want to continue backup's creation")
+                        Mage::helper('Mage_Backup_Helper_Data')->__('You do not have sufficient permissions to enable Maintenance Mode during this operation.')
+                            . ' ' . Mage::helper('Mage_Backup_Helper_Data')->__('Please either unselect the "Put store on the maintenance mode" checkbox or update your permissions to proceed with the backup."')
                     );
                     $backupManager->setErrorMessage(Mage::helper('Mage_Backup_Helper_Data')->__("System couldn't put store on the maintenance mode"));
                     return $this->getResponse()->setBody($response->toJson());
@@ -233,8 +233,8 @@ class Mage_Adminhtml_System_BackupController extends Mage_Adminhtml_Controller_A
 
                 if (!$turnedOn) {
                     $response->setError(
-                        Mage::helper('Mage_Backup_Helper_Data')->__("Warning! System couldn't put store on the maintenance mode.") . ' '
-                        . Mage::helper('Mage_Backup_Helper_Data')->__("Please deselect the sufficient check-box, if you want to continue rollback processing")
+                        Mage::helper('Mage_Backup_Helper_Data')->__('You do not have sufficient permissions to enable Maintenance Mode during this operation.')
+                            . ' ' . Mage::helper('Mage_Backup_Helper_Data')->__('Please either unselect the "Put store on the maintenance mode" checkbox or update your permissions to proceed with the rollback."')
                     );
                     $backupManager->setErrorMessage(Mage::helper('Mage_Backup_Helper_Data')->__("System couldn't put store on the maintenance mode"));
                     return $this->getResponse()->setBody($response->toJson());
diff --git a/app/code/core/Mage/Adminhtml/controllers/System/ConfigController.php b/app/code/core/Mage/Adminhtml/controllers/System/ConfigController.php
index a56869bd2350adc95998e9a42c7d447c3e5ee9fc..67c37d03cd4d59f87e2ba86b175b0bfbcabb5a63 100644
--- a/app/code/core/Mage/Adminhtml/controllers/System/ConfigController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/System/ConfigController.php
@@ -95,8 +95,7 @@ class Mage_Adminhtml_System_ConfigController extends Mage_Adminhtml_Controller_A
         $this->_addBreadcrumb(Mage::helper('Mage_Adminhtml_Helper_Data')->__('System'), Mage::helper('Mage_Adminhtml_Helper_Data')->__('System'),
             $this->getUrl('*/system'));
 
-        $this->getLayout()->getBlock('left')
-            ->append($this->getLayout()->createBlock('Mage_Adminhtml_Block_System_Config_Tabs')->initTabs());
+        $this->getLayout()->addBlock('Mage_Adminhtml_Block_System_Config_Tabs', '', 'left')->initTabs();
 
         if ($this->_isSectionAllowedFlag) {
             $this->_addContent($this->getLayout()->createBlock('Mage_Adminhtml_Block_System_Config_Edit')->initForm());
diff --git a/app/code/core/Mage/Adminhtml/controllers/System/CurrencyController.php b/app/code/core/Mage/Adminhtml/controllers/System/CurrencyController.php
index 1c90bc0abbbdf7d3739a30fc660454eeb5189eb8..09e44b8a38da56f7f9d3e592ee916ce7063ac4c8 100644
--- a/app/code/core/Mage/Adminhtml/controllers/System/CurrencyController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/System/CurrencyController.php
@@ -70,7 +70,9 @@ class Mage_Adminhtml_System_CurrencyController extends Mage_Adminhtml_Controller
                 throw new Exception(Mage::helper('Mage_Adminhtml_Helper_Data')->__('Invalid Import Service Specified'));
             }
             try {
-                $importModel = Mage::getModel(Mage::getConfig()->getNode('global/currency/import/services/' . $service . '/model')->asArray());
+                $importModel = Mage::getModel(
+                    Mage::getConfig()->getNode('global/currency/import/services/' . $service . '/model')->asArray()
+                );
             } catch (Exception $e) {
                 Mage::throwException(Mage::helper('Mage_Adminhtml_Helper_Data')->__('Unable to initialize import model'));
             }
@@ -120,6 +122,6 @@ class Mage_Adminhtml_System_CurrencyController extends Mage_Adminhtml_Controller
 
     protected function _isAllowed()
     {
-        return Mage::getSingleton('Mage_Admin_Model_Session')->isAllowed('system/currency');
+        return Mage::getSingleton('Mage_Admin_Model_Session')->isAllowed('system/currency/rates');
     }
 }
diff --git a/app/code/core/Mage/Adminhtml/controllers/System/VariableController.php b/app/code/core/Mage/Adminhtml/controllers/System/VariableController.php
index 9c2b457669f6df5d6fa4ed7e10d7f25cbf807e14..1cc88c1b4630145dc9bdb682de3ba35661ffa336 100644
--- a/app/code/core/Mage/Adminhtml/controllers/System/VariableController.php
+++ b/app/code/core/Mage/Adminhtml/controllers/System/VariableController.php
@@ -102,7 +102,7 @@ class Mage_Adminhtml_System_VariableController extends Mage_Adminhtml_Controller
         $this->_initLayout()
             ->_addContent($this->getLayout()->createBlock('Mage_Adminhtml_Block_System_Variable_Edit'))
             ->_addJs($this->getLayout()->createBlock('Mage_Core_Block_Template', '', array(
-                'template' => 'system/variable/js.phtml'
+                'template' => 'Mage_Adminhtml::system/variable/js.phtml'
             )))
             ->renderLayout();
     }
diff --git a/app/code/core/Mage/Adminhtml/etc/adminhtml.xml b/app/code/core/Mage/Adminhtml/etc/adminhtml.xml
index 025cba8a08f40ee392a4c905242f63bd0bcd6500..d9f64b58e83b58e90bacfd4d82dbe75364f52229 100644
--- a/app/code/core/Mage/Adminhtml/etc/adminhtml.xml
+++ b/app/code/core/Mage/Adminhtml/etc/adminhtml.xml
@@ -48,8 +48,14 @@
                 </tools>
                 <design translate="title">
                     <title>Design</title>
-                    <action>adminhtml/system_design</action>
                     <sort_order>30</sort_order>
+                    <children>
+                        <schedule translate="title">
+                            <title>Schedule</title>
+                            <action>adminhtml/system_design</action>
+                            <sort_order>10</sort_order>
+                        </schedule>
+                    </children>
                 </design>
                 <convert translate="title">
                     <title>Import/Export</title>
@@ -150,6 +156,12 @@
                             <design translate="title">
                                 <title>Design</title>
                                 <sort_order>25</sort_order>
+                                <children>
+                                    <schedule translate="title">
+                                        <title>Schedule</title>
+                                        <sort_order>10</sort_order>
+                                    </schedule>
+                                </children>
                             </design>
                             <config translate="title">
                                 <title>Configuration</title>
diff --git a/app/code/core/Mage/Adminhtml/etc/config.xml b/app/code/core/Mage/Adminhtml/etc/config.xml
index 3656c858ad450022c8dd1d23a29ccb70525e913e..84c6011b96c58b6024bb3799b986d0abf15689e8 100644
--- a/app/code/core/Mage/Adminhtml/etc/config.xml
+++ b/app/code/core/Mage/Adminhtml/etc/config.xml
@@ -44,10 +44,6 @@
         <events>
             <adminhtml_controller_action_predispatch_start>
                 <observers>
-                    <store>
-                        <class>Mage_Adminhtml_Model_Observer</class>
-                        <method>bindStore</method>
-                    </store>
                     <massaction>
                         <class>Mage_Adminhtml_Model_Observer</class>
                         <method>massactionPrepareKey</method>
@@ -80,7 +76,7 @@
             <controller_action_predispatch>
                 <observers>
                     <auth>
-                        <class>Mage_Admin_Model_Observer</class>
+                        <class>Mage_Adminhtml_Model_Observer</class>
                         <method>actionPreDispatchAdmin</method>
                     </auth>
                 </observers>
diff --git a/app/code/core/Mage/Adminhtml/etc/translater.xml b/app/code/core/Mage/Adminhtml/etc/jstranslator.xml
similarity index 98%
rename from app/code/core/Mage/Adminhtml/etc/translater.xml
rename to app/code/core/Mage/Adminhtml/etc/jstranslator.xml
index 8454ad559c2786988b105e5c1a55cd1997a6aaa9..fe8428f8ad5b040946ab8895300c7930144a6ec7 100644
--- a/app/code/core/Mage/Adminhtml/etc/translater.xml
+++ b/app/code/core/Mage/Adminhtml/etc/jstranslator.xml
@@ -25,7 +25,7 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 -->
-<translater>
+<jstranslator>
     <!-- flexuploader.js -->
     <flexuploader-complete translate="message" module="Mage_Adminhtml">
         <message>Complete</message>
@@ -61,5 +61,5 @@
     <sales-order-create-addproducts translate="message" module="Mage_Adminhtml">
         <message>Add Products</message>
     </sales-order-create-addproducts>
-</translater>
+</jstranslator>
 
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/backup/dialogs.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/backup/dialogs.phtml
index 7b2b8635d54f961c480e65903ab1d3d37734b49f..525c16d3e646a671d5a2209ed2f484ddad07f48d 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/backup/dialogs.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/backup/dialogs.phtml
@@ -75,7 +75,7 @@
                      <tr>
                          <td style="padding-right: 8px;"><label for="backup_name" class="nobr"><?php echo $this->__('Backup Name')?></label></td>
                          <td>
-                             <input type="text" name="backup_name" id="backup_name" class="validate-alphanum-with-spaces" style="width: 343px"/>
+                             <input type="text" name="backup_name" id="backup_name" class="validate-alphanum-with-spaces validate-length maximum-length-50" style="width: 343px" maxlength="50" />
                              <p class="note"><span><?php echo $this->__('Please use only letters (a-z or A-Z), numbers (0-9) or spaces in this field.'); ?></span></p>
                          </td>
                      </tr>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog.xml b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog.xml
index 49abfdbbb1123fff6d609d5ca2aa466b9f973cc7..746892290666f9c4124a5f1da0fc6a8260c22b37 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog.xml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog.xml
@@ -73,43 +73,43 @@
     </adminhtml_catalog_product_edit>
 
     <adminhtml_catalog_product_categories>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Categories" name="catalog.product.edit.tab.categories"/>
-        </block>
+        </container>
     </adminhtml_catalog_product_categories>
-    
+
     <adminhtml_catalog_product_reviews>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Reviews" name="admin.product.reviews"/>
-        </block>
+        </container>
     </adminhtml_catalog_product_reviews>
 
     <adminhtml_catalog_product_taggrid>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Tag" name="admin.product.tags"/>
-        </block>
+        </container>
     </adminhtml_catalog_product_taggrid>
 
     <adminhtml_catalog_product_tagcustomergrid>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Tag_Customer" name="admin.product.tags.customers"/>
-        </block>
+        </container>
     </adminhtml_catalog_product_tagcustomergrid>
 
     <adminhtml_catalog_product_options>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Options" name="admin.product.options"/>
-        </block>
+        </container>
     </adminhtml_catalog_product_options>
 
     <adminhtml_catalog_product_grid>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Catalog_Product_Grid" name="admin.product.grid"/>
-        </block>
+        </container>
     </adminhtml_catalog_product_grid>
 
     <adminhtml_catalog_product_related>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Related" name="catalog.product.edit.tab.related"/>
             <block type="Mage_Adminhtml_Block_Widget_Grid_Serializer" name="related_grid_serializer">
                 <reference name="related_grid_serializer">
@@ -124,29 +124,29 @@
                     </action>
                 </reference>
             </block>
-        </block>
+        </container>
     </adminhtml_catalog_product_related>
 
     <adminhtml_catalog_product_relatedgrid>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Related" name="catalog.product.edit.tab.related"/>
-        </block>
+        </container>
     </adminhtml_catalog_product_relatedgrid>
 
     <adminhtml_catalog_product_superconfig>
-        <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Super_Config_Grid" name="admin.product.edit.tab.super.config.grid" output="toHtml" />
+        <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Super_Config_Grid" name="admin.product.edit.tab.super.config.grid" output="1" />
     </adminhtml_catalog_product_superconfig>
 
     <adminhtml_catalog_product_alertspricegrid>
-        <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Alerts_Price" name="admin.product.edit.tab.alerts.price" output="toHtml" />
+        <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Alerts_Price" name="admin.product.edit.tab.alerts.price" output="1" />
     </adminhtml_catalog_product_alertspricegrid>
 
     <adminhtml_catalog_product_alertsstockgrid>
-        <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Alerts_Stock" name="admin.product.edit.tab.alerts.stock" output="toHtml" />
+        <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Alerts_Stock" name="admin.product.edit.tab.alerts.stock" output="1" />
     </adminhtml_catalog_product_alertsstockgrid>
 
     <adminhtml_catalog_product_upsell>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Upsell" name="catalog.product.edit.tab.upsell"/>
             <block type="Mage_Adminhtml_Block_Widget_Grid_Serializer" name="upsell_grid_serializer">
                 <reference name="upsell_grid_serializer">
@@ -161,17 +161,17 @@
                     </action>
                 </reference>
             </block>
-        </block>
+        </container>
     </adminhtml_catalog_product_upsell>
 
     <adminhtml_catalog_product_upsellgrid>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Upsell" name="catalog.product.edit.tab.upsell"/>
-        </block>
+        </container>
     </adminhtml_catalog_product_upsellgrid>
 
     <adminhtml_catalog_product_crosssell>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Crosssell" name="catalog.product.edit.tab.crosssell"/>
             <block type="Mage_Adminhtml_Block_Widget_Grid_Serializer" name="crosssell_grid_serializer">
                 <reference name="crosssell_grid_serializer">
@@ -186,13 +186,13 @@
                     </action>
                 </reference>
             </block>
-        </block>
+        </container>
     </adminhtml_catalog_product_crosssell>
 
     <adminhtml_catalog_product_crosssellgrid>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Crosssell" name="catalog.product.edit.tab.crosssell"/>
-        </block>
+        </container>
     </adminhtml_catalog_product_crosssellgrid>
 <!--
 Layout handle for simple products
@@ -210,7 +210,7 @@ Layout handle for grouped products
     </adminhtml_catalog_product_grouped>
 
     <adminhtml_catalog_product_supergroup>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Super_Group" name="catalog.product.edit.tab.super.group" />
             <block type="Mage_Adminhtml_Block_Widget_Grid_Serializer" name="grouped_grid_serializer">
                 <reference name="grouped_grid_serializer">
@@ -226,13 +226,13 @@ Layout handle for grouped products
                     </action>
                 </reference>
             </block>
-        </block>
+        </container>
     </adminhtml_catalog_product_supergroup>
 
     <adminhtml_catalog_product_supergroupgridonly>
-        <block type="Mage_Core_Block_Text_List" name="root">
+        <container name="root" label="Root">
             <block type="Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Super_Group" name="catalog.product.edit.tab.super.group" />
-        </block>
+        </container>
     </adminhtml_catalog_product_supergroupgridonly>
 <!--
 Layout handle for configurable products
@@ -295,7 +295,7 @@ Layout handle for configurable products
     </adminhtml_catalog_category_edit>
 
     <ADMINHTML_CATALOG_PRODUCT_COMPOSITE_CONFIGURE>
-        <block type="Mage_Adminhtml_Block_Catalog_Product_Composite_Fieldset" name="product.composite.fieldset" output="toHtml">
+        <block type="Mage_Adminhtml_Block_Catalog_Product_Composite_Fieldset" name="product.composite.fieldset" output="1">
             <block name="product.composite.fieldset.options" type="Mage_Adminhtml_Block_Catalog_Product_Composite_Fieldset_Options" template="catalog/product/composite/fieldset/options.phtml">
                 <action method="addOptionRenderer"><type>text</type><block>Mage_Catalog_Block_Product_View_Options_Type_Text</block><template>Mage_Adminhtml::catalog/product/composite/fieldset/options/type/text.phtml</template></action>
                 <action method="addOptionRenderer"><type>file</type><block>Mage_Catalog_Block_Product_View_Options_Type_File</block><template>Mage_Adminhtml::catalog/product/composite/fieldset/options/type/file.phtml</template></action>
@@ -306,27 +306,27 @@ Layout handle for configurable products
             <block type="Mage_Adminhtml_Block_Catalog_Product_Composite_Fieldset_Qty" name="product.composite.fieldset.qty" template="catalog/product/composite/fieldset/qty.phtml"/>
         </block>
     </ADMINHTML_CATALOG_PRODUCT_COMPOSITE_CONFIGURE>
-    
+
     <ADMINHTML_CATALOG_PRODUCT_COMPOSITE_CONFIGURE_ERROR>
-        <block type="Mage_Adminhtml_Block_Catalog_Product_Composite_Error" name="product.composite.error" output="toHtml" />
+        <block type="Mage_Adminhtml_Block_Catalog_Product_Composite_Error" name="product.composite.error" output="1" />
     </ADMINHTML_CATALOG_PRODUCT_COMPOSITE_CONFIGURE_ERROR>
-    
+
     <ADMINHTML_CATALOG_PRODUCT_COMPOSITE_UPDATE_RESULT>
-        <block type="Mage_Adminhtml_Block_Catalog_Product_Composite_Update_Result" name="product.composite.update.result" output="toHtml" />
+        <block type="Mage_Adminhtml_Block_Catalog_Product_Composite_Update_Result" name="product.composite.update.result" output="1" />
     </ADMINHTML_CATALOG_PRODUCT_COMPOSITE_UPDATE_RESULT>
 <!--
 Additional block in composite_fieldset block dependant on product type
 -->
-    <PRODUCT_TYPE_configurable>
+    <catalog_product_view_type_configurable>
         <reference name="product.composite.fieldset">
             <block type="Mage_Adminhtml_Block_Catalog_Product_Composite_Fieldset_Configurable" name="product.composite.fieldset.configurable" before="product.composite.fieldset.options" template="catalog/product/composite/fieldset/configurable.phtml" />
         </reference>
-    </PRODUCT_TYPE_configurable>
-    <PRODUCT_TYPE_grouped>
+    </catalog_product_view_type_configurable>
+    <catalog_product_view_type_grouped>
         <reference name="product.composite.fieldset">
             <block type="Mage_Adminhtml_Block_Catalog_Product_Composite_Fieldset_Grouped" name="product.composite.fieldset.grouped" before="product.composite.fieldset.options" template="catalog/product/composite/fieldset/grouped.phtml"/>
             <remove name="product.composite.fieldset.qty"/>
         </reference>
-    </PRODUCT_TYPE_grouped>
+    </catalog_product_view_type_grouped>
 
 </layout>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/attribute/options.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/attribute/options.phtml
index f1b17645d38a549b550437cb9b09ed8cc12cd048..d0d09543651d2048e19988fcabb596912fb427c0 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/attribute/options.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/attribute/options.phtml
@@ -115,7 +115,7 @@ var templateText =
 <?php endforeach; ?>
             '<td><input class="input-text" type="text" name="option[order][{{id}}]" value="{{sort_order}}" <?php if ($this->getReadOnly()):?> disabled="disabled"<?php endif;?>/><\/td>'+
             '<td class="a-center"><input class="input-radio" type="{{intype}}" name="default[]" value="{{id}}" {{checked}} <?php if ($this->getReadOnly()):?> disabled="disabled"<?php endif;?>/><\/td>'+
-            '<td class="a-left">'+
+            '<td class="a-left" id="delete_button_container_{{id}}">'+
                 '<input type="hidden" class="delete-flag" name="option[delete][{{id}}]" value="" />'+
                 <?php if (!$this->getReadOnly()):?>
                     '<?php echo $this->getDeleteButtonHtml() ?>'+
@@ -129,16 +129,21 @@ var attributeOption = {
     templateText : templateText,
     itemCount : 0,
     totalItems : 0,
+    isReadOnly: <?php echo (int)$this->getReadOnly(); ?>,
     add : function(data) {
         this.template = new Template(this.templateText, this.templateSyntax);
+        var isNewOption = false;
         if(!data.id){
             data = {};
             data.id  = 'option_'+this.itemCount;
+            isNewOption = true;
         }
         if (!data.intype)
             data.intype = optionDefaultInputType;
-
         Element.insert(this.table, {after: this.template.evaluate(data)});
+        if (isNewOption && !this.isReadOnly) {
+            this.enableNewOptionDeleteButton(data.id);
+        }
         this.bindRemoveButtons();
         this.itemCount++;
         this.totalItems++;
@@ -178,6 +183,12 @@ var attributeOption = {
             $('option-count-check').value = '';
         }
     },
+    enableNewOptionDeleteButton: function(id) {
+        $$('#delete_button_container_' + id + ' button').each(function(button) {
+            button.enable();
+            button.removeClassName('disabled');
+        });
+    },
     bindRemoveButtons : function(){
         var buttons = $$('.delete-option');
         for(var i=0;i<buttons.length;i++){
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/composite/configure.js b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/composite/configure.js
index 98d5706a987383ddc46ade6fcdc5fe77d1d76dba..f3d245fc96184e2966ba4c77a605dfff509bdff3 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/composite/configure.js
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/composite/configure.js
@@ -343,8 +343,6 @@ ProductConfigure.prototype = {
      * Triggered when form was submitted and iFrame was loaded. Get response from iFrame and handle it
      */
     onLoadIFrame: function() {
-        varienLoaderHandler.handler.onComplete();
-
         this.blockFormConfirmed.select('[configure_disabled=1]').each(function (element) {
             element.disabled = element.getAttribute('configure_prev_disabled') == '1';
         });
@@ -371,6 +369,8 @@ ProductConfigure.prototype = {
 
             document.fire(this.current.listType + ':afterIFrameLoaded');
         }
+        varienLoaderHandler.handler.onComplete();
+
         this.clean('current');
     },
 
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/composite/fieldset/configurable.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/composite/fieldset/configurable.phtml
index ec879c360f8e4d31b51f437700e6b555f8ff4e79..22c39b88a1aac6f4086c15a1e43178354a44875f 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/composite/fieldset/configurable.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/composite/fieldset/configurable.phtml
@@ -28,7 +28,8 @@
 <?php /* @var $this Mage_Adminhtml_Block_Catalog_Product_Composite_Fieldset_Configurable */ ?>
 <?php $_product = $this->getProduct(); ?>
 <?php $_attributes = Mage::helper('Mage_Core_Helper_Data')->decorateArray($this->getAllowAttributes()); ?>
-<?php if ($_product->isSaleable() && count($_attributes)):?>
+<?php $_skipSaleableCheck = Mage::helper('Mage_Catalog_Helper_Product')->getSkipSaleableCheck(); ?>
+<?php if (($_product->isSaleable() || $_skipSaleableCheck) && count($_attributes)):?>
 <div id="catalog_product_composite_configure_fields_configurable" class="<?php echo $this->getIsLastFieldset() ? 'last-fieldset' : '' ?>">
     <h4><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Associated Products') ?></h4>
     <div class="product-options">
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/composite/fieldset/grouped.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/composite/fieldset/grouped.phtml
index 75d29b0725c877da234c3d28297fda857f2c4264..198721a01266767893c330644b84504090002414 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/composite/fieldset/grouped.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/composite/fieldset/grouped.phtml
@@ -25,7 +25,8 @@
  */
  ?>
 
- <?php /* @var $this Mage_Adminhtml_Block_Catalog_Product_Composite_Fieldset_Grouped */ ?>
+<?php /* @var $this Mage_Adminhtml_Block_Catalog_Product_Composite_Fieldset_Grouped */ ?>
+<?php $_skipSaleableCheck = Mage::helper('Mage_Catalog_Helper_Product')->getSkipSaleableCheck(); ?>
 <div id="catalog_product_composite_configure_fields_grouped" class="grid <?php echo $this->getIsLastFieldset() ? 'last-fieldset' : '' ?>">
     <h4><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Associated Products') ?></h4>
     <div class="product-options">
@@ -33,7 +34,7 @@
         <?php $this->setPreconfiguredValue(); ?>
         <?php $_associatedProducts = $this->getAssociatedProducts(); ?>
         <?php $_hasAssociatedProducts = count($_associatedProducts) > 0; ?>
-        <?php if (!$_product->isAvailable() || !$_hasAssociatedProducts): ?>
+        <?php if ((!$_product->isAvailable() && !$_skipSaleableCheck) || !$_hasAssociatedProducts): ?>
             <p class="availability out-of-stock"><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Availability:') ?> <span><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Out of stock') ?></span></p>
         <?php endif; ?>
         <table class="data-table grouped-items-table" id="super-product-table">
@@ -50,7 +51,7 @@
                     <?php if ($this->getCanShowProductPrice($_product)): ?>
                     <th class="a-right"><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Price') ?></th>
                     <?php endif; ?>
-                    <?php if ($_product->isSaleable()): ?>
+                    <?php if ($_product->isSaleable() || $_skipSaleableCheck): ?>
                     <th class="a-center"><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Qty') ?></th>
                     <?php endif; ?>
                 </tr>
@@ -71,9 +72,9 @@
                         <?php endif; ?>
                     </td>
                     <?php endif; ?>
-                    <?php if ($_product->isSaleable()): ?>
+                    <?php if ($_product->isSaleable() || $_skipSaleableCheck): ?>
                     <td class="a-center">
-                    <?php if ($_item->isSaleable()) : ?>
+                    <?php if ($_item->isSaleable() || $_skipSaleableCheck) : ?>
                         <input type="text" name="super_group[<?php echo $_item->getId() ?>]" id="super_group[<?php echo $_item->getId() ?>]" maxlength="12" value="<?php echo $_item->getQty()*1 ?>" title="<?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Qty') ?>" class="input-text qty" />
                         <input type="hidden" value="1" price="<?php echo $this->getCurrencyPrice($_item->getPrice()) ?>" qtyId="super_group[<?php echo $_item->getId() ?>]" />
                     <?php else: ?>
@@ -85,7 +86,7 @@
             <?php endforeach; ?>
             <?php else: ?>
                <tr>
-                   <td colspan="<?php if ($_product->isSaleable()): ?>4<?php else : ?>3<?php endif; ?>"><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('No options of this product are available.') ?></td>
+                   <td colspan="<?php if ($_product->isSaleable() || $_skipSaleableCheck): ?>4<?php else : ?>3<?php endif; ?>"><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('No options of this product are available.') ?></td>
                </tr>
             <?php endif; ?>
             </tbody>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/websites.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/websites.phtml
index 721bd19a37fa46b6d55aa7aec742dec57289528f..94bf040104c8b41c993a921b32db89b4df59e8c5 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/websites.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/catalog/product/edit/websites.phtml
@@ -38,36 +38,38 @@
             </li>
         </ul>
     <?php endif; ?>
-    <?php echo $this->getHintHtml() ?>
-    <?php foreach ($this->getWebsiteCollection() as $_website): ?>
-    <div>
-        <div class="website-name">
-            <input name="product[website_ids][]" value="<?php echo $_website->getId() ?>" <?php if ($this->isReadonly()):?> disabled="disabled"<?php endif;?> class="checkbox website-checkbox" id="product_website_<?php echo $_website->getId() ?>" type="checkbox"<?php if($this->hasWebsite($_website->getId())): ?> checked="checked"<?php endif; ?> />
-            <big><strong><label for="product_website_<?php echo $_website->getId() ?>"><?php echo $this->escapeHtml($_website->getName()) ?></label></strong></big>
-        </div>
-        <div class="webiste-groups" id="product_website_<?php echo $_website->getId() ?>_data">
-        <?php foreach ($this->getGroupCollection($_website) as $_group): ?>
-            <h4><?php echo $this->escapeHtml($_group->getName()) ?></h4>
-            <div class="group-stores">
-            <table>
-            <?php foreach ($this->getStoreCollection($_group) as $_store): ?>
-                <tr>
-                    <td><?php echo $this->escapeHtml($_store->getName()) ?></td>
-                    <td>
-                    <?php if($this->getWebsites() && !$this->hasWebsite($_website->getId())): ?>
-                        <span class="website-<?php echo $_website->getId() ?>-select" style="display:none">
-                        <?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('(Copy data from: %s)', $this->getChooseFromStoreHtml($_store)) ?>
-                        </span>
-                    <?php endif; ?>
-                    </td>
-                </tr>
+    <div class="storeScope">
+        <?php echo $this->getHintHtml() ?>
+        <div class="tree-storeScope">
+            <?php foreach ($this->getWebsiteCollection() as $_website): ?>
+            <div class="website-name">
+                <input name="product[website_ids][]" value="<?php echo $_website->getId() ?>" <?php if ($this->isReadonly()):?> disabled="disabled"<?php endif;?> class="checkbox website-checkbox" id="product_website_<?php echo $_website->getId() ?>" type="checkbox"<?php if($this->hasWebsite($_website->getId())): ?> checked="checked"<?php endif; ?> />
+                <big><strong><label for="product_website_<?php echo $_website->getId() ?>"><?php echo $this->escapeHtml($_website->getName()) ?></label></strong></big>
+            </div>
+            <div class="webiste-groups" id="product_website_<?php echo $_website->getId() ?>_data">
+            <?php foreach ($this->getGroupCollection($_website) as $_group): ?>
+                <h4><?php echo $this->escapeHtml($_group->getName()) ?></h4>
+                <div class="group-stores">
+                <table>
+                <?php foreach ($this->getStoreCollection($_group) as $_store): ?>
+                    <tr>
+                        <td><?php echo $this->escapeHtml($_store->getName()) ?></td>
+                        <td>
+                        <?php if($this->getWebsites() && !$this->hasWebsite($_website->getId())): ?>
+                            <span class="website-<?php echo $_website->getId() ?>-select" style="display:none">
+                            <?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('(Copy data from: %s)', $this->getChooseFromStoreHtml($_store)) ?>
+                            </span>
+                        <?php endif; ?>
+                        </td>
+                    </tr>
+                <?php endforeach; ?>
+                </table>
+                </div>
             <?php endforeach; ?>
-            </table>
             </div>
-        <?php endforeach; ?>
+            <?php endforeach; ?>
         </div>
     </div>
-    <?php endforeach; ?>
     </fieldset>
 </div>
 <script type="text/javascript">
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 99f450f03a5e86d18589d4285ef79fbbc56fc689..b63ff48fc29b19221847cace1d1553fe82c8e266 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
@@ -107,6 +107,15 @@
             </td>
             <td class="value scope-label"><?php echo Mage::helper('Mage_Adminhtml_Helper_Data')->__('[GLOBAL]') ?></td>
         </tr>
+        <tr>
+            <td class="label"><label for="inventory_is_decimal_divided"><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Can be Divided into Multiple Boxes for Shipping') ?></label></td>
+            <td class="value"><select id="inventory_is_decimal_divided" name="<?php echo $this->getFieldSuffix() ?>[stock_data][is_decimal_divided]" class="select" <?php echo $_readonly;?>>
+                <option value="0"><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('No') ?></option>
+                <option value="1"<?php if($this->getFieldValue('is_decimal_divided') == 1): ?> selected="selected"<?php endif; ?>><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Yes') ?></option>
+            </select>
+            </td>
+            <td class="value scope-label"><?php echo Mage::helper('Mage_Adminhtml_Helper_Data')->__('[GLOBAL]') ?></td>
+        </tr>
         <?php endif; ?>
 
         <tr>
@@ -187,8 +196,7 @@
     {
         if ($('inventory_use_config_manage_stock').checked) {
             var manageStock = $('inventory_manage_stock_default').value;
-        }
-        else {
+        } else {
             var manageStock = $('inventory_manage_stock').value;
         }
         if (el == $('inventory_manage_stock').up(1)) {
@@ -201,21 +209,16 @@
         }
         if (manageStock == 1) {
             el.show();
-        }
-        else {
+        } else {
             el.hide();
         }
         return;
     }
-    Event.observe($('inventory_manage_stock'), 'change', changeManageStockOption);
-    Event.observe($('inventory_use_config_manage_stock'), 'change', changeManageStockOption);
-    changeManageStockOption();
 
     function applyEnableQtyIncrements() {
         if ($('inventory_use_config_enable_qty_increments').checked) {
             var enableQtyIncrements = $('inventory_enable_qty_increments_default').value;
-        }
-        else {
+        } else {
             var enableQtyIncrements = $('inventory_enable_qty_increments').value;
         }
         if (enableQtyIncrements == 1) {
@@ -224,9 +227,37 @@
             $('inventory_qty_increments').up('tr').hide();
         }
     }
-    Event.observe($('inventory_enable_qty_increments'), 'change', applyEnableQtyIncrements);
-    Event.observe($('inventory_use_config_enable_qty_increments'), 'change', applyEnableQtyIncrements);
-    applyEnableQtyIncrements();
+
+    function applyEnableDecimalDivided() {
+        $('inventory_is_decimal_divided').up('tr').hide();
+        $('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) {
+            $('inventory_is_decimal_divided').up('tr').show();
+            $('inventory_qty_increments').addClassName('validate-number');
+            $('inventory_min_sale_qty').addClassName('validate-number');
+        } else {
+            $('inventory_qty_increments').addClassName('validate-digits');
+            $('inventory_min_sale_qty').addClassName('validate-digits');
+        }
+    }
+
+    Event.observe(window, 'load', function() {
+        if ($('inventory_manage_stock') && $('inventory_use_config_manage_stock')) {
+            Event.observe($('inventory_manage_stock'), 'change', changeManageStockOption);
+            Event.observe($('inventory_use_config_manage_stock'), 'change', changeManageStockOption);
+            changeManageStockOption();
+        }
+        if ($('inventory_enable_qty_increments') && $('inventory_use_config_enable_qty_increments')) {
+            Event.observe($('inventory_enable_qty_increments'), 'change', applyEnableQtyIncrements);
+            Event.observe($('inventory_use_config_enable_qty_increments'), 'change', applyEnableQtyIncrements);
+            applyEnableQtyIncrements();
+        }
+        if ($('inventory_is_qty_decimal') && $('inventory_qty_increments') && $('inventory_min_sale_qty')) {
+            Event.observe($('inventory_is_qty_decimal'), 'change', applyEnableDecimalDivided);
+            applyEnableDecimalDivided();
+        }
+    });
     //]]>
     </script>
     </fieldset>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/cms.xml b/app/code/core/Mage/Adminhtml/view/adminhtml/cms.xml
index 8b5fb088421985bc3f4a4d5710b52ec863b29e26..1c163ef1ca41f4b7bec0681013b511984b06f704 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/cms.xml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/cms.xml
@@ -89,7 +89,7 @@
     </adminhtml_cms_wysiwyg_images_index>
 
     <adminhtml_cms_wysiwyg_images_contents>
-        <block name="wysiwyg_images.files" type="Mage_Adminhtml_Block_Cms_Wysiwyg_Images_Content_Files" template="cms/browser/content/files.phtml" output="toHtml" />
+        <block name="wysiwyg_images.files" type="Mage_Adminhtml_Block_Cms_Wysiwyg_Images_Content_Files" template="cms/browser/content/files.phtml" output="1" />
     </adminhtml_cms_wysiwyg_images_contents>
 
 </layout>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/customer.xml b/app/code/core/Mage/Adminhtml/view/adminhtml/customer.xml
index 538c9f3b53b29ff461d093c22775a9b16d84a0ee..1ba7c6ef4dc124bdfe9f0a6abbccac50a2430f66 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/customer.xml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/customer.xml
@@ -55,72 +55,72 @@
         </reference>
     </adminhtml_customer_group_index>
     <adminhtml_customer_wishlist>
-        <block type="Mage_Adminhtml_Block_Customer_Edit_Tab_Wishlist" name="customer.wishlist.edit.tab" output="toHtml" />
+        <block type="Mage_Adminhtml_Block_Customer_Edit_Tab_Wishlist" name="customer.wishlist.edit.tab" output="1" />
     </adminhtml_customer_wishlist>
 
     <adminhtml_customer_orders>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Customer_Edit_Tab_Orders" name="adminhtml.customer.edit.tab.orders"/>
-        </block>
+        </container>
     </adminhtml_customer_orders>
 
     <adminhtml_customer_carts>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Customer_Edit_Tab_Carts" name="admin.customer.carts"/>
-        </block>
+        </container>
     </adminhtml_customer_carts>
 
     <adminhtml_customer_viewcart>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Customer_Edit_Tab_View_Cart" name="admin.customer.view.cart"/>
-        </block>
+        </container>
     </adminhtml_customer_viewcart>
 
     <adminhtml_customer_viewwishlist>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Customer_Edit_Tab_View_Wishlist" name="admin.customer.view.wishlist"/>
-        </block>
+        </container>
     </adminhtml_customer_viewwishlist>
 
     <adminhtml_customer_lastorders>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Customer_Edit_Tab_View_Orders" name="admin.customer.lastorders"/>
-        </block>
+        </container>
     </adminhtml_customer_lastorders>
 
     <adminhtml_customer_productreviews>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Customer_Edit_Tab_Reviews" name="admin.customer.reviews"/>
-        </block>
+        </container>
     </adminhtml_customer_productreviews>
 
     <adminhtml_customer_producttags>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Customer_Edit_Tab_Tag" name="admin.customer.tags"/>
-        </block>
+        </container>
     </adminhtml_customer_producttags>
 
     <adminhtml_customer_taggrid>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Customer_Edit_Tab_Tag" name="admin.customer.tags"/>
-        </block>
+        </container>
     </adminhtml_customer_taggrid>
 
     <adminhtml_customer_newsletter>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Customer_Edit_Tab_Newsletter_Grid" name="admin.customer.newsletter.grid"/>
-        </block>
+        </container>
     </adminhtml_customer_newsletter>
 
     <adminhtml_customer_grid>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Customer_Grid" name="admin.customer.grid"/>
-        </block>
+        </container>
     </adminhtml_customer_grid>
 
     <adminhtml_customer_cart>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Customer_Edit_Tab_Cart" name="admin.customer.view.edit.cart" />
-        </block>
+        </container>
     </adminhtml_customer_cart>
 </layout>
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 ced2f290bacbd9ff51fd6ac692449fe8ca9f7f77..f8a97cfb567c7af00803181c962697b66ea11b20 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
@@ -146,6 +146,8 @@ addressesModel.prototype = {
 
         this.loader = new varienLoader(true);
         this.regionsUrl = '<?php echo $this->getRegionsUrl() ?>';
+        this.requiredStateForCountries = <?php echo $this->helper('Mage_Directory_Helper_Data')->getCountriesWithStatesRequired(true) ?>;
+        this.showAllRegions = <?php echo (string)$this->helper('Mage_Directory_Helper_Data')->getShowNonRequiredState() ? 1 : 0; ?>;
 
         this.reloadItemList(1);
 
@@ -206,7 +208,10 @@ addressesModel.prototype = {
             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 + '">'
@@ -330,6 +335,16 @@ addressesModel.prototype = {
             //new Effect.Appear($('form_'+item.id), {duration : 0.3 });
             //$('form_'+item.id).focus();
             this.addFieldChangeObserver($('form_'+item.id));
+            var regionIdElement = $('_item' + item.id.replace(/address_item_/, '') + 'region_id');
+            var regionElement = $('_item' + item.id.replace(/address_item_/, '') + 'region');
+            this.countryEl = $('_item' + item.id.replace(/address_item_/, '') + 'country_id');
+            if (regionIdElement && regionElement) {
+                var actualId = regionElement.id;
+                if (('select' == regionIdElement.tagName.toLowerCase()) && regionIdElement) {
+                    actualId = regionIdElement.id;
+                }
+                this._checkRegionRequired([regionIdElement, regionElement], actualId);
+            }
         }
 
         this.activeItem = item;
@@ -480,6 +495,7 @@ addressesModel.prototype = {
             var regionElement  = $(countryElement.id.replace(/country_id/, 'region'));
             if(regionElement){
                 this.regionElement = regionElement;
+                this.countryEl = countryElement;
                 if (countryElement.value) {
                     var url = this.regionsUrl + 'parent/' + countryElement.value;
                     this.loader.load(url, {}, this.refreshRegionField.bind(this));
@@ -553,6 +569,61 @@ addressesModel.prototype = {
         var newInput = $(newInputId);
         Event.observe(newInput, 'change', this.onItemFormFieldChange); // Restore observing to update address info
         this.syncFormData(newInput); // Update address info now
+        var activeElementId = regionHtmlId;
+        if (('select' == $(regionIdHtmlId).tagName.toLowerCase()) && regionIdHtmlId) {
+            activeElementId = regionIdHtmlId;
+        }
+        this._checkRegionRequired([$(regionHtmlId), $(regionIdHtmlId)], activeElementId);
+    },
+
+    _checkRegionRequired: function(elements, activeElementId)
+    {
+        var label, wildCard;
+        var that = this;
+        var regionRequired = this.requiredStateForCountries.indexOf(this.countryEl.value) >= 0;
+
+        elements.each(function(currentElement) {
+            Validation.reset(currentElement);
+            label = $$('label[for="' + currentElement.id + '"]')[0];
+            if (label) {
+                wildCard = label.down('em') || label.down('span.required');
+                if (!that.showAllRegions) {
+                    if (regionRequired) {
+                        label.up('tr').show();
+                    } else {
+                        label.up('tr').hide();
+                    }
+                }
+            }
+
+            if (label && wildCard) {
+                if (!regionRequired) {
+                    wildCard.hide();
+                } else {
+                    wildCard.show();
+                }
+            }
+
+            if (!regionRequired) {
+                if (currentElement.hasClassName('required-entry')) {
+                    currentElement.removeClassName('required-entry');
+                }
+                if ('select' == currentElement.tagName.toLowerCase() &&
+                    currentElement.hasClassName('validate-select')
+                ) {
+                    currentElement.removeClassName('validate-select');
+                }
+            } else if (activeElementId == currentElement.id) {
+                if (!currentElement.hasClassName('required-entry')) {
+                    currentElement.addClassName('required-entry');
+                }
+                if ('select' == currentElement.tagName.toLowerCase() &&
+                    !currentElement.hasClassName('validate-select')
+                ) {
+                    currentElement.addClassName('validate-select');
+                }
+            }
+        });
     }
 }
 
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/customer/tab/newsletter.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/customer/tab/newsletter.phtml
index fa2b24de4bfcaa4ff8c1b8f876485842fc8e5975..543573d7fd0c88f993cba664f16e6d7d5c2e0c7e 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/customer/tab/newsletter.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/customer/tab/newsletter.phtml
@@ -25,6 +25,6 @@
  */
 ?>
 <div class="entry-edit">
-<?php echo $this->getFormObject()->getHtml() ?>
+<?php echo $this->getForm()->getHtml() ?>
 </div>
 <?php echo $this->getChildHtml('grid') ?>
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 9a61d3e3e33ef14609372df640add380d90dff7e..124c8e3cad75e3b581f290aebd7769d7af581453 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
@@ -79,4 +79,4 @@ $createDateStore    = $this->getStoreCreateDate();
         </address>
     </fieldset>
 </div>
-<?php echo $this->getChildHtml('', true, true); ?>
+<?php echo $this->getChildHtml('', true); ?>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/dashboard/index.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/dashboard/index.phtml
index 1f302d5e2cfc0a282985fd3e49f0ba72b9137ac9..59f68b28b4554438f722a81de7f23169cdd0c6e6 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/dashboard/index.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/dashboard/index.phtml
@@ -25,18 +25,18 @@
  */
 ?>
 
-<?php if (is_array($this->getChild('diagrams')->getTabsIds())) : ?>
+<?php if (is_array($this->getChildBlock('diagrams')->getTabsIds())) : ?>
 <script type="text/javascript">
 //<![CDATA[
 function changeDiagramsPeriod(periodObj) {
     periodParam = periodObj.value ? 'period/' + periodObj.value + '/' : '';
-<?php foreach ($this->getChild('diagrams')->getTabsIds() as $tabId): ?>
+<?php foreach ($this->getChildBlock('diagrams')->getTabsIds() as $tabId): ?>
     ajaxBlockParam = 'block/tab_<?php echo $tabId ?>/';
     ajaxBlockUrl = '<?php echo $this->getUrl('*/*/ajaxBlock', array('_current' => true, 'block' => '', 'period' => '')) ?>' + ajaxBlockParam + periodParam;
     new Ajax.Request(ajaxBlockUrl, {
         parameters: {isAjax: 'true', form_key: FORM_KEY},
         onSuccess: function(transport) {
-            tabContentElementId = '<?php echo $this->getChild('diagrams')->getId() ?>_<?php echo $tabId ?>_content';
+            tabContentElementId = '<?php echo $this->getChildBlock('diagrams')->getId() ?>_<?php echo $tabId ?>_content';
             try {
                 if (transport.responseText.isJSON()) {
                     var response = transport.responseText.evalJSON()
@@ -116,7 +116,7 @@ function toggleCal(id) {
             <td>
                 <div class="entry-edit" style="border:1px solid #ccc;">
                     <?php echo $this->getChildHtml('diagrams') ?>
-                    <?php if (is_array($this->getChild('diagrams')->getTabsIds())) : ?>
+                    <?php if (is_array($this->getChildBlock('diagrams')->getTabsIds())) : ?>
                         <div id="diagram_tab_content"></div>
                     <?php endif; ?>
                     <div style="margin:20px;">
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/dataflow.xml b/app/code/core/Mage/Adminhtml/view/adminhtml/dataflow.xml
index 0ea564b913a4dcd1d5deabe512d212227b512efd..547d6fc91383bb7aad0eef6de2ed72c3ec28a1de 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/dataflow.xml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/dataflow.xml
@@ -30,7 +30,7 @@
 
     <adminhtml_system_convert_gui_run>
         <remove name="root"/>
-        <block type="Mage_Adminhtml_Block_Page" name="convert_root" output="toHtml" template="admin/page.phtml">
+        <block type="Mage_Adminhtml_Block_Page" name="convert_root" output="1" template="admin/page.phtml">
             <block type="Mage_Adminhtml_Block_Page_Head" name="convert_root_head" as="head" template="page/head.phtml">
                 <action method="addJs"><file>prototype/prototype.js</file></action>
                 <action method="addJs"><file>prototype/validation.js</file></action>
@@ -38,13 +38,13 @@
                 <action method="addJs"><file>mage/translate.js</file></action>
                 <action method="addJs"><file>mage/adminhtml/tools.js</file></action>
             </block>
-            <block type="Mage_Adminhtml_Block_System_Convert_Profile_Run" name="system_convert_profile_run" template="system/convert/profile/process.phtml" output="toHtml"/>
+            <block type="Mage_Adminhtml_Block_System_Convert_Profile_Run" name="system_convert_profile_run" template="system/convert/profile/process.phtml" output="1"/>
         </block>
     </adminhtml_system_convert_gui_run>
     
     <adminhtml_system_convert_profile_run>
         <remove name="root"/>
-        <block type="Mage_Adminhtml_Block_Page" name="convert_root" output="toHtml" template="admin/page.phtml">
+        <block type="Mage_Adminhtml_Block_Page" name="convert_root" output="1" template="admin/page.phtml">
             <block type="Mage_Adminhtml_Block_Page_Head" name="convert_root_head" as="head" template="page/head.phtml">
                 <action method="addJs"><file>prototype/prototype.js</file></action>
                 <action method="addJs"><file>prototype/validation.js</file></action>
@@ -52,7 +52,7 @@
                 <action method="addJs"><file>mage/translate.js</file></action>
                 <action method="addJs"><file>mage/adminhtml/tools.js</file></action>
             </block>
-            <block type="Mage_Adminhtml_Block_System_Convert_Profile_Run" name="system_convert_profile_run" template="system/convert/profile/process.phtml" output="toHtml"/>
+            <block type="Mage_Adminhtml_Block_System_Convert_Profile_Run" name="system_convert_profile_run" template="system/convert/profile/process.phtml" output="1"/>
         </block>
     </adminhtml_system_convert_profile_run>
 
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/main.xml b/app/code/core/Mage/Adminhtml/view/adminhtml/main.xml
index 76a1a9e968cbbd619ca97c6598da18eaeecf1881..d107cc45665cc223742932034a595733d835ddfe 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/main.xml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/main.xml
@@ -52,7 +52,7 @@ Default layout, loads most of the pages
 -->
 
     <default>
-        <block type="Mage_Adminhtml_Block_Page" name="root" output="toHtml" template="admin/page.phtml">
+        <block type="Mage_Adminhtml_Block_Page" name="root" output="1" template="admin/page.phtml">
            <block type="Mage_Adminhtml_Block_Page_Head" name="head" as="head" template="page/head.phtml">
                 <action method="setTitle" translate="title"><title>Magento Admin</title></action>
                 <action method="addJs"><file>prototype/prototype.js</file></action>
@@ -102,12 +102,12 @@ Default layout, loads most of the pages
             <block type="Mage_Adminhtml_Block_Page_Notices" name="global_notices" as="global_notices" template="page/notices.phtml" />
             <block type="Mage_Adminhtml_Block_Page_Header" name="header" as="header"></block>
             <block type="Mage_Adminhtml_Block_Page_Menu" name="menu" as="menu"></block>
-            <block type="Mage_Core_Block_Text_List" name="notifications" as="notifications">
+            <container name="notifications" as="notifications" label="Notifications">
                 <block type="Mage_Adminhtml_Block_Notification_Baseurl" name="notification_baseurl" as="notification_baseurl" template="notification/baseurl.phtml"></block>
                 <block type="Mage_Adminhtml_Block_Cache_Notifications" name="cache_notifications" template="system/cache/notifications.phtml"></block>
                 <block type="Mage_Adminhtml_Block_Notification_Survey" name="notification_survey" template="notification/survey.phtml"/>
                 <block type="Mage_Adminhtml_Block_Notification_Security" name="notification_security" as="notification_security" template="notification/security.phtml"></block>
-            </block>
+            </container>
             <block type="Mage_Adminhtml_Block_Widget_Breadcrumbs" name="breadcrumbs" as="breadcrumbs"></block>
 
             <!--<update handle="formkey"/> this won't work, see the try/catch and a jammed exception in Mage_Core_Model_Layout::createBlock() -->
@@ -115,14 +115,14 @@ Default layout, loads most of the pages
 
             <!-- deprecated since 1.7.0.0 see Mage_Page_Block_Js_Translate -->
             <block type="Mage_Page_Block_Js_Translate" name="js_translate" as="js_translate" template="Mage_Adminhtml::page/js/translate.phtml"/>
-            <block type="Mage_Core_Block_Text_List" name="left" as="left"/>
-            <block type="Mage_Core_Block_Text_List" name="content" as="content"/>
+            <container name="left" as="left" label="Left Column"/>
+            <container name="content" as="content" label="Content"/>
             <block type="Mage_Core_Block_Messages" name="messages" as="messages"/>
-            <block type="Mage_Core_Block_Text_List" name="js" as="js"/>
+            <container name="js" as="js" label="JavaScript"/>
             <block type="Mage_Adminhtml_Block_Page_Footer" name="footer" as="footer">
                 <action method="setBugreportUrl"><url>http://www.magentocommerce.com/bug-tracking</url></action>
             </block>
-            <block type="Mage_Core_Block_Text_List" name="before_body_end" as="before_body_end"/>
+            <container name="before_body_end" as="before_body_end" label="Before Body End"/>
 
         </block>
     </default>
@@ -163,7 +163,7 @@ Layout for editor element
             <action method="addJs"><file>mage/adminhtml/browser.js</file></action>
             <action method="addJs"><file>prototype/window.js</file></action>
             <action method="addCss"><file>prototype/windows/themes/default.css</file></action>
-            <action method="addCss"><file>prototype/windows/themes/magento.css</file></action>
+            <action method="addCss"><file>Mage_Core::prototype/magento.css</file></action>
         </reference>
     </editor>
 
@@ -194,19 +194,19 @@ Base preview layout (?)
 -->
 
     <preview>
-        <block type="Mage_Core_Block_Template" name="root" output="toHtml" template="Mage_Adminhtml::newsletter/template/preview.phtml">
+        <block type="Mage_Core_Block_Template" name="root" output="1" template="Mage_Adminhtml::newsletter/template/preview.phtml">
             <block type="Mage_Adminhtml_Block_Newsletter_Template_Preview" name="content" as="content"></block>
         </block>
     </preview>
 
     <newsletter_template_preview>
-        <block type="Mage_Core_Block_Template" name="root" output="toHtml" template="Mage_Adminhtml::newsletter/template/preview.phtml">
+        <block type="Mage_Core_Block_Template" name="root" output="1" template="Mage_Adminhtml::newsletter/template/preview.phtml">
             <block type="Mage_Adminhtml_Block_Newsletter_Template_Preview" name="content" as="content"></block>
         </block>
     </newsletter_template_preview>
 
     <newsletter_queue_preview>
-        <block type="Mage_Core_Block_Template" name="root" output="toHtml" template="Mage_Adminhtml::newsletter/queue/preview.phtml">
+        <block type="Mage_Core_Block_Template" name="root" output="1" template="Mage_Adminhtml::newsletter/queue/preview.phtml">
             <block type="Mage_Adminhtml_Block_Newsletter_Queue_Preview" name="content" as="content"></block>
         </block>
     </newsletter_queue_preview>
@@ -216,43 +216,43 @@ Base preview layout
 -->
 
     <systemPreview>
-        <block type="Mage_Core_Block_Template" name="root" output="toHtml" template="Mage_Adminhtml::system/email/template/preview.phtml">
+        <block type="Mage_Core_Block_Template" name="root" output="1" template="Mage_Adminhtml::system/email/template/preview.phtml">
             <block type="Mage_Adminhtml_Block_System_Email_Template_Preview" name="content" as="content"></block>
         </block>
     </systemPreview>
 
     <adminhtml_dashboard_customersmost>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Dashboard_Tab_Customers_Most" name="adminhtml.dashboard.tab.customers.most"/>
-        </block>
+        </container>
     </adminhtml_dashboard_customersmost>
 
     <adminhtml_dashboard_customersnewest>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Dashboard_Tab_Customers_Newest" name="adminhtml.dashboard.tab.customers.newest"/>
-        </block>
+        </container>
     </adminhtml_dashboard_customersnewest>
 
     <adminhtml_dashboard_productsviewed>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Dashboard_Tab_Products_Viewed" name="adminhtml.dashboard.tab.products.viewed"/>
-        </block>
+        </container>
     </adminhtml_dashboard_productsviewed>
 
     <adminhtml_index_login>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Template" name="content" template="admin/login.phtml">
-                <block type="Mage_Core_Block_Text_List" name="form.additional.info" />
+                <container name="form.additional.info"  label="Form Additional Info"/>
             </block>
-        </block>
+        </container>
     </adminhtml_index_login>
 
     <adminhtml_index_forgotpassword>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Template" name="content" template="admin/forgotpassword.phtml">
-                <block type="Mage_Core_Block_Text_List" name="form.additional.info" />
+                <container name="form.additional.info" label="Form Additional Info"/>
             </block>
-        </block>
+        </container>
     </adminhtml_index_forgotpassword>
 <!--
 Empty hanle for ajax response etc.
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/newsletter/problem/list.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/newsletter/problem/list.phtml
index a8b0c3aab96622ed48199dca8608b5c467c94b49..30e6a91488331f323013632bd5f60a992cd9689f 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/newsletter/problem/list.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/newsletter/problem/list.phtml
@@ -63,7 +63,7 @@
         },
 
         unsubscribe: function () {
-            var elements = $('problemGrid').getElementsByClassName('problemCheckbox');
+            var elements = $$('input.problemCheckbox');
             var serializedElements = Form.serializeElements(elements, true);
             serializedElements._unsubscribe = '1';
             serializedElements.form_key = FORM_KEY;
@@ -76,7 +76,7 @@
         },
 
         deleteSelected: function () {
-            var elements = $('problemGrid').getElementsByClassName('problemCheckbox');
+            var elements = $$('input.problemCheckbox');
             var serializedElements = Form.serializeElements(elements, true);
             serializedElements._delete = '1';
             serializedElements.form_key = FORM_KEY;
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/page/menu.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/page/menu.phtml
index fae8bb3785a7478ed1f422ed5a016773aedc9869..5b66e85a92c989f756a04e05195f2d50e3e3a531 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/page/menu.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/page/menu.phtml
@@ -29,18 +29,7 @@
 
 <!-- menu end -->
 <div class="nav-bar">
-<?php drawMenuLevel($this->getMenuArray()); ?>
-<?php function drawMenuLevel($_menu, $_level=0) { ?>
-    <ul <?php if(!$_level): ?>id="nav"<?php endif ?>>
-        <?php foreach ($_menu as $_item): ?>
-        <li <?php if(!empty($_item['children'])): ?>onmouseover="Element.addClassName(this,'over')" onmouseout="Element.removeClassName(this,'over')"<?php endif ?> class=" <?php echo (!$_level && !empty($_item['active']))?' active':'' ?> <?php echo !empty($_item['children'])?' parent':'' ?><?php echo (!empty($_level) && !empty($_item['last']))?' last':'' ?> level<?php echo $_level ?>"> <a href="<?php echo $_item['url'] ?>" <?php if(!empty($_item['title'])): ?>title="<?php echo $_item['title'] ?>"<?php endif ?> <?php if(!empty($_item['click'])): ?>onclick="<?php echo $_item['click']; ?>"<?php endif ?> class="<?php echo ($_level===0 && !empty($_item['active']))?'active':'' ?>"><span><?php echo Mage::helper('Mage_Adminhtml_Helper_Data')->escapeHtml($_item['label']); ?><?php if(!$_level): ?><?php endif ?></span></a>
-            <?php if(!empty($_item['children'])): ?>
-                <?php drawMenuLevel($_item['children'], $_level+1); ?>
-            <?php endif; ?>
-        </li>
-        <?php endforeach; ?>
-    </ul>
-<?php }//function ?>
+<?php echo $this->renderMenu(); ?>
 
     <a id="page-help-link" href="<?php echo Mage::helper('Mage_Adminhtml_Helper_Data')->getPageHelpUrl() ?>"><?php echo $this->__('Get help for this page') ?></a>
     <script type="text/javascript">$('page-help-link').target = 'magento_page_help'</script>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/permissions/role_users_grid_js.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/permissions/role_users_grid_js.phtml
index f35308cc61aaf3f02f26566aa7e26d1a2bfd8400..f85c428294a7489189395c71e75d950240738236 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/permissions/role_users_grid_js.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/permissions/role_users_grid_js.phtml
@@ -53,17 +53,17 @@
         if (trElement) {
             var checkbox = Element.getElementsBySelector(trElement, 'input');
             if(checkbox[0]){
-                var checked = isInput ? checkbox[0].checked : !checkbox[0].checked;
+                var checked = isInput ? !checkbox[0].checked : checkbox[0].checked;
                 if (checked) {
-                    checkbox[0].checked = true;
                     if ( confirm("<?php echo $this->__('Warning!\r\nThis action will remove this user from already assigned role\r\nAre you sure?') ?>") ) {
-                        checkBoxes.set(checkbox[0].value, checked);
+                        checkbox[0].checked = false;
+                        checkBoxes.set(checkbox[0].value, false);
                         varienElementMethods.setHasChanges(checkbox[0]);
                     } else {
-                        checkbox[0].checked = false;
+                        checkbox[0].checked = true;
                     }
-                    warning = false;
                 } else {
+                    checkbox[0].checked = true;
                     checkBoxes.unset(checkbox[0].value);
                 }
 
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/promo.xml b/app/code/core/Mage/Adminhtml/view/adminhtml/promo.xml
index 0db056d5f4956c16db713e090a897c91ac86f6e5..7336db0b5d713c80c69a8a387df9b447988719d8 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/promo.xml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/promo.xml
@@ -90,8 +90,8 @@
         </reference>
     </adminhtml_promo_quote_edit>
     <adminhtml_promo_quote_couponsgrid>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Promo_Quote_Edit_Tab_Coupons_Grid" name="promo_quote_edit_tab_coupons_grid" />
-        </block>
+        </container>
     </adminhtml_promo_quote_couponsgrid>
 </layout>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/promo/salesrulejs.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/promo/salesrulejs.phtml
index ae07da53ff53c9b8309a92eb75656512c4dd746f..5f8914d8cfdd423443278cbbacd6a747da030408 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/promo/salesrulejs.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/promo/salesrulejs.phtml
@@ -57,6 +57,7 @@ function handleCouponTypeChange() {
 
 function refreshCouponCodesGrid(grid, gridMassAction, transport) {
     grid.reload();
+    gridMassAction.unselectAll();
 }
 
 function generateCouponCodes(idPrefix, generateUrl, grid) {
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/sales.xml b/app/code/core/Mage/Adminhtml/view/adminhtml/sales.xml
index a3973fc77176702a326746f5e8edf5b15c77b199..b9468ddb8202ffdffb380147e6617191d6ea78e0 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/sales.xml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/sales.xml
@@ -29,7 +29,7 @@
 <layout>
     <adminhtml_sales_order_grid>
         <update handle="formkey"/>
-        <block type="Mage_Adminhtml_Block_Sales_Order_Grid" name="sales_order.grid" output="toHtml"></block>
+        <block type="Mage_Adminhtml_Block_Sales_Order_Grid" name="sales_order.grid" output="1"></block>
     </adminhtml_sales_order_grid>
 
     <adminhtml_sales_order_index>
@@ -39,7 +39,7 @@
     </adminhtml_sales_order_index>
 
     <adminhtml_sales_order_transactions>
-        <block type="Mage_Adminhtml_Block_Sales_Transactions_Grid" name="sales_transactions.grid" output="toHtml"></block>
+        <block type="Mage_Adminhtml_Block_Sales_Transactions_Grid" name="sales_transactions.grid" output="1"></block>
     </adminhtml_sales_order_transactions>
 
     <adminhtml_sales_billing_agreement_index>
@@ -49,7 +49,7 @@
     </adminhtml_sales_billing_agreement_index>
 
     <adminhtml_sales_billing_agreement_grid>
-        <block type="Mage_Sales_Block_Adminhtml_Billing_Agreement_Grid" name="sales.billing.agreement.grid" output="toHtml"></block>
+        <block type="Mage_Sales_Block_Adminhtml_Billing_Agreement_Grid" name="sales.billing.agreement.grid" output="1"></block>
     </adminhtml_sales_billing_agreement_grid>
 
     <adminhtml_sales_billing_agreement_view>
@@ -65,11 +65,11 @@
     </adminhtml_sales_billing_agreement_view>
 
     <adminhtml_sales_billing_agreement_ordersgrid>
-        <block type="Mage_Sales_Block_Adminhtml_Billing_Agreement_View_Tab_Orders" name="related.orders.grid" output="toHtml"></block>
+        <block type="Mage_Sales_Block_Adminhtml_Billing_Agreement_View_Tab_Orders" name="related.orders.grid" output="1"></block>
     </adminhtml_sales_billing_agreement_ordersgrid>
 
     <adminhtml_sales_billing_agreement_customergrid>
-        <block type="Mage_Sales_Block_Adminhtml_Customer_Edit_Tab_Agreement" name="customer.billing.agreement.grid" output="toHtml"></block>
+        <block type="Mage_Sales_Block_Adminhtml_Customer_Edit_Tab_Agreement" name="customer.billing.agreement.grid" output="1"></block>
     </adminhtml_sales_billing_agreement_customergrid>
 
     <adminhtml_sales_order_view>
@@ -135,7 +135,7 @@
     </adminhtml_sales_order_view>
 
     <adminhtml_sales_order_addcomment>
-        <block type="Mage_Adminhtml_Block_Sales_Order_View_History" name="order_history" template="sales/order/view/history.phtml" output="toHtml"/>
+        <block type="Mage_Adminhtml_Block_Sales_Order_View_History" name="order_history" template="sales/order/view/history.phtml" output="1"/>
     </adminhtml_sales_order_addcomment>
 
     <adminhtml_sales_order_invoice_new>
@@ -149,7 +149,7 @@
                         <action method="addColumnRender"><column>qty</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Qty</block><template>sales/items/column/qty.phtml</template></action>
                         <action method="addColumnRender"><column>name</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Name</block><template>sales/items/column/name.phtml</template></action>
                         <action method="addColumnRender"><column>name</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Name_Grouped</block><template>sales/items/column/name.phtml</template><type>grouped</type></action>
-                        <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"></block>
+                        <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"/>
                         <block type="Mage_Adminhtml_Block_Sales_Order_Totalbar" name="order_totalbar" template="sales/order/totalbar.phtml"></block>
 
                         <block type="Mage_Adminhtml_Block_Sales_Order_Invoice_Totals" name="invoice_totals" template="sales/order/totals.phtml">
@@ -193,7 +193,7 @@
             <action method="addColumnRender"><column>qty</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Qty</block><template>sales/items/column/qty.phtml</template></action>
             <action method="addColumnRender"><column>name</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Name</block><template>sales/items/column/name.phtml</template></action>
             <action method="addColumnRender"><column>name</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Name_Grouped</block><template>sales/items/column/name.phtml</template><type>grouped</type></action>
-            <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"></block>
+            <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"/>
             <block type="Mage_Adminhtml_Block_Sales_Order_Totalbar" name="order_totalbar" template="sales/order/totalbar.phtml"></block>
             <block type="Mage_Adminhtml_Block_Sales_Order_Invoice_Totals" name="invoice_totals" template="sales/order/totals.phtml">
                 <block type="Mage_Adminhtml_Block_Sales_Order_Totals_Tax" name="tax" template="sales/order/totals/tax.phtml" />
@@ -245,7 +245,7 @@
                         <action method="addColumnRender"><column>qty</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Qty</block><template>sales/items/column/qty.phtml</template></action>
                         <action method="addColumnRender"><column>name</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Name</block><template>sales/items/column/name.phtml</template></action>
                         <action method="addColumnRender"><column>name</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Name_Grouped</block><template>sales/items/column/name.phtml</template><type>grouped</type></action>
-                        <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"></block>
+                        <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"/>
                     </block>
                     <block type="Mage_Adminhtml_Block_Sales_Order_Comments_View" name="order_comments" template="sales/order/comments/view.phtml">
                         <action method="setParentType"><type>invoice</type></action>
@@ -298,7 +298,7 @@
                         <action method="addItemRender"><type>default</type><block>Mage_Adminhtml_Block_Sales_Items_Renderer_Default</block><template>sales/order/shipment/create/items/renderer/default.phtml</template></action>
                         <action method="addColumnRender"><column>qty</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Qty</block><template>sales/items/column/qty.phtml</template></action>
                         <action method="addColumnRender"><column>name</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Name</block><template>sales/items/column/name.phtml</template></action>
-                        <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"></block>
+                        <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"/>
                     </block>
                     <block type="Mage_Adminhtml_Block_Sales_Order_Shipment_Packaging" name="shipment_packaging" template="sales/order/shipment/packaging/popup.phtml" />
                 </block>
@@ -334,7 +334,7 @@
                         <action method="addItemRender"><type>default</type><block>Mage_Adminhtml_Block_Sales_Items_Renderer_Default</block><template>sales/order/shipment/view/items/renderer/default.phtml</template></action>
                         <action method="addColumnRender"><column>qty</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Qty</block><template>sales/items/column/qty.phtml</template></action>
                         <action method="addColumnRender"><column>name</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Name</block><template>sales/items/column/name.phtml</template></action>
-                        <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"></block>
+                        <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"/>
                     </block>
                     <block type="Mage_Adminhtml_Block_Sales_Order_Invoice_Create_Tracking" name="invoice_tracking" template="sales/order/shipment/create/tracking.phtml"></block>
                     <block type="Mage_Adminhtml_Block_Sales_Order_Comments_View"  name="order_comments" template="sales/order/comments/view.phtml">
@@ -358,7 +358,7 @@
                         <action method="addColumnRender"><column>qty</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Qty</block><template>sales/items/column/qty.phtml</template></action>
                         <action method="addColumnRender"><column>name</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Name</block><template>sales/items/column/name.phtml</template></action>
                         <action method="addColumnRender"><column>name</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Name_Grouped</block><template>sales/items/column/name.phtml</template><type>grouped</type></action>
-                        <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"></block>
+                        <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"/>
                         <block type="Mage_Adminhtml_Block_Sales_Order_Totalbar" name="order_totalbar" template="sales/order/totalbar.phtml"></block>
 
                         <block type="Mage_Adminhtml_Block_Sales_Order_Creditmemo_Totals" name="creditmemo_totals" template="sales/order/totals.phtml">
@@ -381,8 +381,8 @@
                                 <block type="Mage_Adminhtml_Block_Sales_Order_Totals_Item" name="adjustments" template="sales/order/creditmemo/create/totals/adjustments.phtml" />
                             </block>-->
                         </block>
-                        <block type="Mage_Core_Block_Text_List" name="submit_before" />
-                        <block type="Mage_Core_Block_Text_List" name="submit_after" />
+                        <container name="submit_before" label="Submit Before"/>
+                        <container name="submit_after" label="Submit After"/>
                     </block>
                 </block>
             </block>
@@ -395,7 +395,7 @@
             <action method="addColumnRender"><column>qty</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Qty</block><template>sales/items/column/qty.phtml</template></action>
             <action method="addColumnRender"><column>name</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Name</block><template>sales/items/column/name.phtml</template></action>
             <action method="addColumnRender"><column>name</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Name_Grouped</block><template>sales/items/column/name.phtml</template><type>grouped</type></action>
-            <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"></block>
+            <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"/>
             <block type="Mage_Adminhtml_Block_Sales_Order_Totalbar" name="order_totalbar" template="sales/order/totalbar.phtml"></block>
 
             <block type="Mage_Adminhtml_Block_Sales_Order_Creditmemo_Totals" name="creditmemo_totals" template="sales/order/totals.phtml">
@@ -420,8 +420,8 @@
                 </block>-->
             </block>
 
-            <block type="Mage_Core_Block_Text_List" name="submit_before" />
-            <block type="Mage_Core_Block_Text_List" name="submit_after" />
+            <container name="submit_before" label="Submit Before"/>
+            <container name="submit_after" label="Submit After"/>
         </block>
     </adminhtml_sales_order_creditmemo_updateqty>
 
@@ -442,7 +442,7 @@
                         <action method="addColumnRender"><column>qty</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Qty</block><template>sales/items/column/qty.phtml</template></action>
                         <action method="addColumnRender"><column>name</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Name</block><template>sales/items/column/name.phtml</template></action>
                         <action method="addColumnRender"><column>name</column><block>Mage_Adminhtml_Block_Sales_Items_Column_Name_Grouped</block><template>sales/items/column/name.phtml</template><type>grouped</type></action>
-                        <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"></block>
+                        <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"/>
                     </block>
                     <block type="Mage_Adminhtml_Block_Sales_Order_Comments_View" name="order_comments" template="sales/order/comments/view.phtml">
                         <action method="setParentType"><type>creditmemo</type></action>
@@ -485,7 +485,7 @@
         </reference>
     </adminhtml_sales_transactions_index>
     <adminhtml_sales_transactions_grid>
-        <block type="Mage_Adminhtml_Block_Sales_Transactions_Grid" name="sales_transactions.grid" output="toHtml"></block>
+        <block type="Mage_Adminhtml_Block_Sales_Transactions_Grid" name="sales_transactions.grid" output="1"></block>
     </adminhtml_sales_transactions_grid>
     <adminhtml_sales_transactions_view>
         <reference name="content">
@@ -558,7 +558,7 @@
                         <block type="Mage_Adminhtml_Block_Template" name="gift_options" template="sales/order/giftoptions.phtml">
                             <block type="Mage_Adminhtml_Block_Sales_Order_Create_Giftmessage" template="sales/order/create/giftmessage.phtml" name="giftmessage" />
                         </block>
-                        <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"></block>
+                        <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"/>
                     </block>
                 </block>
             </block>
@@ -577,7 +577,7 @@
 
     <adminhtml_sales_order_create_load_block_plain>
         <reference name="root">
-            <block type="Mage_Core_Block_Text_List" name="content" />
+            <container name="content" label="Content"/>
         </reference>
     </adminhtml_sales_order_create_load_block_plain>
 
@@ -620,7 +620,7 @@
                 <block type="Mage_Adminhtml_Block_Template" name="gift_options" template="sales/order/giftoptions.phtml">
                     <block type="Mage_Adminhtml_Block_Sales_Order_Create_Giftmessage" template="sales/order/create/giftmessage.phtml" name="giftmessage" />
                 </block>
-                <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"></block>
+                <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"/>
             </block>
         </reference>
     </adminhtml_sales_order_create_load_block_data>
@@ -711,7 +711,7 @@
                     </block>
                 </block>
             </block>
-            <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"></block>
+            <block type="Mage_Core_Block_Text_List" name="order_item_extra_info"/>
         </reference>
     </adminhtml_sales_order_create_load_block_items>
 
@@ -969,11 +969,11 @@
 
     <adminhtml_sales_recurring_profile_grid>
         <remove name="root"/>
-        <block type="Mage_Sales_Block_Adminhtml_Recurring_Profile_Grid" name="sales.recurring.profile.grid" output="toHtml"/>
+        <block type="Mage_Sales_Block_Adminhtml_Recurring_Profile_Grid" name="sales.recurring.profile.grid" output="1"/>
     </adminhtml_sales_recurring_profile_grid>
 
     <adminhtml_sales_recurring_profile_customergrid>
-        <block type="Mage_Sales_Block_Adminhtml_Customer_Edit_Tab_Recurring_Profile" name="customer.recurring.profile.grid" output="toHtml"></block>
+        <block type="Mage_Sales_Block_Adminhtml_Customer_Edit_Tab_Recurring_Profile" name="customer.recurring.profile.grid" output="1"></block>
     </adminhtml_sales_recurring_profile_customergrid>
 
     <adminhtml_sales_recurring_profile_view>
@@ -1035,7 +1035,7 @@
 
     <adminhtml_sales_recurring_profile_orders>
         <remove name="root"/>
-        <block type="Mage_Sales_Block_Adminhtml_Recurring_Profile_View_Tab_Orders" name="sales.recurring.profile.tab.orders" output="toHtml"/>
+        <block type="Mage_Sales_Block_Adminhtml_Recurring_Profile_View_Tab_Orders" name="sales.recurring.profile.tab.orders" output="1"/>
     </adminhtml_sales_recurring_profile_orders>
 
     <adminhtml_customer_edit>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/abstract.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/abstract.phtml
index a88008cb6efbc858d45d6d3282f270e16cb94e27..af10355500e40d3d5956ae86b6a05012cba24b1d 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/abstract.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/abstract.phtml
@@ -30,6 +30,6 @@
         <h4 class="fieldset-legend <?php echo ($this->getHeaderCssClass()) ? $this->getHeaderCssClass().' icon-head' : '' ?>"><?php echo $this->getHeaderText() ?></h4>
     </div>
     <div class="fieldset">
-        <?php echo $this->getChildHtml('', true, true) ?>
+        <?php echo $this->getChildHtml('', true) ?>
     </div>
 </div>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/coupons/form.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/coupons/form.phtml
index fe95484e613e39780e06bf86ad3f7c407cb8b4e2..8d7243b02d578e97b2abb89978b5f2643b3b8fb7 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/coupons/form.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/coupons/form.phtml
@@ -38,7 +38,7 @@
          <div class="content">
             <p><input type="text" class="input-text" id="coupons:code" value="" name="coupon_code" style="width:200px" />&nbsp;<?php echo $this->getButtonHtml(Mage::helper('Mage_Sales_Helper_Data')->__('Apply'), 'order.applyCoupon($F(\'coupons:code\'))') ?></p>
             <?php if($this->getCouponCode()): ?>
-                <p><strong><?php echo $this->getCouponCode() ?></strong> [<a href="#" onclick="order.applyCoupon(''); return false;" title="<?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Remove Coupon Code') ?>"><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Remove') ?></a>]</p>
+                <p><strong><?php echo $this->escapeHtml($this->getCouponCode()) ?></strong> [<a href="#" onclick="order.applyCoupon(''); return false;" title="<?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Remove Coupon Code') ?>"><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Remove') ?></a>]</p>
             <?php endif; ?>
             <script type="text/javascript">
                 order.overlay('shipping-method-overlay', <?php if ($this->getQuote()->isVirtual()): ?>false<?php else: ?>true<?php endif; ?>);
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/data.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/data.phtml
index 576f20da91b9f3649d7c0a3bcf541c22dfbdee79..ca57263659ec0fdbe5b56341ba2ad5b7d31603b2 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/data.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/data.phtml
@@ -57,7 +57,7 @@
             <div id="order-shipping_method" class="box-right"><?php echo $this->getChildHtml('shipping_method') ?></div>
         </div>
 
-        <?php if($this->getChild('card_validation')): ?>
+        <?php if($this->getChildBlock('card_validation')): ?>
         <div class="clear"></div>
         <div id="order-methods">
             <div id="order-card_validation" class="box-left payments"><?php echo $this->getChildHtml('card_validation') ?></div>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/items/grid.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/items/grid.phtml
index 5e79118db11d8d10c5ec46502995a3ec40511e2f..8f3bf2b6c120b76b4f7ef77bb7db0e6bc24d395d 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/items/grid.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/items/grid.phtml
@@ -115,7 +115,7 @@
                             <?php if($_item->getMessage(false)): ?>
                                 <?php foreach ($_item->getMessage(false) as $message): ?>
                                 <div class="<?php if($_item->getHasError()): ?>error<?php else: ?>notice<?php endif; ?>">
-                                    <div style="font-size:95%"><?php echo $message; ?></div>
+                                    <div style="font-size:95%"><?php echo Mage::helper('Mage_Core_Helper_Data')->escapeHtml($message); ?></div>
                                 </div>
                                 <?php endforeach; ?>
                             <?php endif; ?>
@@ -397,7 +397,16 @@
                                 <?php if($this->getCustomerId() && $this->getMoveToCustomerStorage()): ?>
                                     <option value="cart"><?php echo $this->helper('Mage_Sales_Helper_Data')->__('Move to Shopping Cart') ?></option>
                                     <?php if ($this->isMoveToWishlistAllowed($_item)): ?>
-                                        <option value="wishlist"><?php echo $this->helper('Mage_Sales_Helper_Data')->__('Move to Wishlist') ?></option>
+                                        <?php $wishlists = $this->getCustomerWishlists();?>
+                                        <?php if (count($wishlists) <= 1):?>
+                                            <option value="wishlist"><?php echo $this->helper('Mage_Sales_Helper_Data')->__('Move to Wishlist') ?></option>
+                                        <?php else: ?>
+                                            <optgroup label="<?php echo $this->helper('Mage_Sales_Helper_Data')->__('Move to Wishlist') ?>">
+                                                <?php foreach ($wishlists as $wishlist):?>
+                                                    <option value="wishlist_<?php echo $wishlist->getId();?>"><?php echo $this->escapeHtml($wishlist->getName());?></option>
+                                                <?php endforeach;?>
+                                            </optgroup>
+                                        <?php endif; ?>
                                     <?php endif; ?>
                                 <?php endif; ?>
                             </select>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/scripts.js b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/scripts.js
index d046613a534d9fa9235eb3ddbb246a3b359fc90a..08ec691d03786a9139316184af765c98cac328f7 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/scripts.js
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/scripts.js
@@ -64,8 +64,18 @@ AdminOrder.prototype = {
                 searchAreaId = this.getAreaId('search');
             searchButton.onClick = function() {
                 $(searchAreaId).show();
-                this.remove();
+                var el = this;
+                window.setTimeout(function () {
+                    el.remove();
+                }, 10);
             }
+
+            this.dataArea.onLoad = this.dataArea.onLoad.wrap(function(proceed) {
+                proceed();
+                this._parent.itemsArea.setNode($(this._parent.getAreaId('items')));
+                this._parent.itemsArea.onLoad();
+            });
+
             this.itemsArea.onLoad = this.itemsArea.onLoad.wrap(function(proceed) {
                 proceed();
                 if (!$(searchAreaId).visible()) {
@@ -73,6 +83,7 @@ AdminOrder.prototype = {
                 }
             });
             this.areasLoaded();
+            this.itemsArea.onLoad();
         }).bind(this));
     },
 
@@ -1155,12 +1166,14 @@ AdminOrder.prototype = {
                         }
                     } else if (response.success) {
                         message = parameters.vatInvalidMessage.replace(/%s/, params.vat);
+                        groupChangeRequired = true;
                     } else {
                         message = parameters.vatValidationFailedMessage;
+                        groupChangeRequired = true;
                     }
 
                 } catch (e) {
-                    message = parameters.vatValidationFailedMessage;
+                    message = parameters.vatErrorMessage;
                 }
                 if (!groupChangeRequired) {
                     alert(message);
@@ -1230,7 +1243,8 @@ ControlButton.prototype = {
     initialize: function(label){
         this._label = label;
         this._node = new Element('button', {
-            'class': 'scalable add'
+            'class': 'scalable add',
+            'type':  'button'
         });
     },
 
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/shipping/method/form.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/shipping/method/form.phtml
index cc67d26832048ab140defc5df5bf681c0516dcd5..82a3ed18f406562a4939347323b6237d2c9c291c 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/shipping/method/form.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/shipping/method/form.phtml
@@ -24,11 +24,13 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 ?>
-<?php if($_shippingRateGroups = $this->getShippingRates()): ?>
+<?php /** @var $this Mage_Adminhtml_Block_Sales_Order_Create_Shipping_Method_Form */ ?>
+<?php $_shippingRateGroups = $this->getShippingRates(); ?>
+<?php if ($_shippingRateGroups): ?>
     <div id="order-shipping-method-choose" style="display:none">
     <dl class="shipment-methods">
     <?php foreach ($_shippingRateGroups as $code => $_rates): ?>
-        <dt><strong><?php echo $this->getCarrierName($code) ?></strong></dt>
+        <dt><strong><?php echo $this->escapeHtml($this->getCarrierName($code)) ?></strong></dt>
         <dd>
             <ul>
             <?php foreach ($_rates as $_rate): ?>
@@ -37,13 +39,13 @@
                 <li>
                    <?php if ($_rate->getErrorMessage()): ?>
                         <ul class="messages">
-                            <li class="error-msg"><?php echo $_rate->getErrorMessage() ?></li>
+                            <li class="error-msg"><?php echo $this->escapeHtml($_rate->getErrorMessage()) ?></li>
                         </ul>
                    <?php else: ?>
                         <?php $_checked = $this->isMethodActive($_code) ? 'checked="checked"' : '' ?>
                         <input <?php echo $_radioProperty ?> value="<?php echo $_code ?>" id="s_method_<?php echo $_code ?>" <?php echo $_checked ?>/>
                         <label class="normal" for="s_method_<?php echo $_code ?>">
-                            <?php echo $_rate->getMethodTitle() ? $_rate->getMethodTitle() : $_rate->getMethodDescription()?> -
+                            <?php echo $this->escapeHtml($_rate->getMethodTitle() ? $_rate->getMethodTitle() : $_rate->getMethodDescription()) ?> -
                             <strong>
                                 <?php $_excl = $this->getShippingPrice($_rate->getPrice(), $this->helper('Mage_Tax_Helper_Data')->displayShippingPriceIncludingTax()); ?>
                                 <?php $_incl = $this->getShippingPrice($_rate->getPrice(), true); ?>
@@ -64,8 +66,8 @@
     </div>
     <?php if ($_rate = $this->getActiveMethodRate()): ?>
         <div id="order-shipping-method-info">
-            <strong><?php echo $this->getCarrierName($_rate->getCarrier()) ?></strong><br/>
-            <?php echo $_rate->getMethodTitle() ? $_rate->getMethodTitle() : $_rate->getMethodDescription() ?> -
+            <strong><?php echo $this->escapeHtml($this->getCarrierName($_rate->getCarrier())) ?></strong><br/>
+            <?php echo $this->escapeHtml($_rate->getMethodTitle() ? $_rate->getMethodTitle() : $_rate->getMethodDescription()) ?> -
             <strong>
                 <?php $_excl = $this->getShippingPrice($_rate->getPrice(), $this->helper('Mage_Tax_Helper_Data')->displayShippingPriceIncludingTax()); ?>
                 <?php $_incl = $this->getShippingPrice($_rate->getPrice(), true); ?>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/sidebar.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/sidebar.phtml
index e81cab68e1f6ce8ce0b5e1501208cd53680f514a..c27e4924aa8d4b9b7492061755a2cb5c0b7ef4e1 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/sidebar.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/sidebar.phtml
@@ -23,11 +23,13 @@
  * @copyright   Copyright (c) 2012 Magento 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_Sales_Order_Create_Sidebar */
 ?>
 <div class="entry-edit"><div class="entry-edit-head"><h4><?php echo $this->helper('Mage_Sales_Helper_Data')->__('Customer\'s Current Activities') ?></h4></div></div>
 <div class="create-order-sidebar-container">
 <?php echo $this->getChildHtml('top_button'); ?>
-<?php foreach ($this->getChild() as $_child): ?>
+<?php foreach ($this->getLayout()->getChildBlocks($this->getNameInLayout()) as $_child): ?>
     <?php $_alias = $_child->getBlockAlias(); ?>
     <?php if ($_alias != 'top_button' && $_alias != 'bottom_button'): ?>
         <div id="order-sidebar_<?php echo $_alias ?>">
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/store/select.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/store/select.phtml
index cb19c36c07984f099d008b022a730d222472cce1..21f396ccaea4bc97b9a6e450bd9483c6b7d2af0d 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/store/select.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/store/select.phtml
@@ -25,26 +25,30 @@
  */
 ?>
 <?php /* @var $this Mage_Adminhtml_Block_Sales_Order_Create_Store_Select */ ?>
-<?php echo $this->getHintHtml() ?>
-<?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; ?>
-                <h3><?php echo $this->escapeHtml($_website->getName()) ?></h3>
+<div class="storeScope">
+    <?php echo $this->getHintHtml() ?>
+    <div class="tree-storeScope">
+    <?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; ?>
+                    <h3><?php echo $this->escapeHtml($_website->getName()) ?></h3>
+                <?php endif; ?>
+                <?php if ($showGroup == false): ?>
+                    <?php $showGroup = true; ?>
+                    <h4 style="margin-left:12px;"><?php echo $this->escapeHtml($_group->getName()) ?></h4>
+                <?php endif; ?>
+                <span class="field-row" style="margin-left:28px;">
+                    <input type="radio" id="store_<?php echo $_store->getId() ?>" class="radio" onclick="order.setStoreId('<?php echo $_store->getId() ?>')"/>
+                    <label for="store_<?php echo $_store->getId() ?>" class="inline"><?php echo $this->escapeHtml($_store->getName()) ?></label>
+                </span>
+            <?php endforeach; ?>
+            <?php if ($showGroup): ?>
             <?php endif; ?>
-            <?php if ($showGroup == false): ?>
-                <?php $showGroup = true; ?>
-                <h4 style="margin-left:12px;"><?php echo $this->escapeHtml($_group->getName()) ?></h4>
-            <?php endif; ?>
-            <span class="field-row" style="margin-left:28px;">
-                <input type="radio" id="store_<?php echo $_store->getId() ?>" class="radio" onclick="order.setStoreId('<?php echo $_store->getId() ?>')"/>
-                <label for="store_<?php echo $_store->getId() ?>" class="inline"><?php echo $this->escapeHtml($_store->getName()) ?></label>
-            </span>
         <?php endforeach; ?>
-        <?php if ($showGroup): ?>
-        <?php endif; ?>
     <?php endforeach; ?>
-<?php endforeach; ?>
+    </div>
+</div>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/totals/shipping.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/totals/shipping.phtml
index 69c4371a0075a1c699f9e90dbc99e0e3d9305d04..3c3bf6cab4f2b653e2c4dc3152492937fcccb47a 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/totals/shipping.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/totals/shipping.phtml
@@ -57,7 +57,7 @@
 <?php else:?>
 <tr>
     <td style="<?php echo $this->getStyle() ?>" class="a-right" colspan="<?php echo $this->getColspan(); ?>">
-        <?php echo $this->getTotal()->getTitle() ?>
+        <?php echo $this->escapeHtml($this->getTotal()->getTitle()) ?>
     </td>
     <td style="<?php echo $this->getStyle() ?>" class="a-right">
         <?php echo $this->formatPrice($this->getShippingExcludeTax()) ?>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/totals/tax.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/totals/tax.phtml
index 13b1b0497eba1655f35a0ba79597648e849166c7..82613bc3df9406994e7cd4f40303effc4997be81 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/totals/tax.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/create/totals/tax.phtml
@@ -37,7 +37,7 @@
                 <?php foreach ($rates as $rate): ?>
                 <tr class="summary-details-<?php echo $taxIter; ?> summary-details<?php if ($isTop): echo ' summary-details-first'; endif; ?>" style="display:none;">
                     <td class="a-right" style="<?php echo $this->getTotal()->getStyle() ?>" colspan="<?php echo $this->getColspan(); ?>">
-                        <?php echo $rate['title']; ?>
+                        <?php echo $this->escapeHtml($rate['title']); ?>
                         <?php if (!is_null($rate['percent'])): ?>
                             (<?php echo (float)$rate['percent']; ?>%)
                         <?php endif; ?>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/invoice/create/tracking.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/invoice/create/tracking.phtml
index 9b1d50936ea994d0d31dd2327422dc23b50aa529..b84759bc741a8cb71d556cdb1dffca3af15d91db 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/invoice/create/tracking.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/invoice/create/tracking.phtml
@@ -24,9 +24,10 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 ?>
+<?php /** @var $this Mage_Adminhtml_Block_Sales_Order_Invoice_Create_Tracking */ ?>
 <script type="text/javascript">
 //<![CDATA[
-var trackingControl = {};
+var trackingControl;
 trackingControl = {
     index : 0,
     add : function () {
@@ -91,7 +92,7 @@ trackingControl = {
             <td>
                 <select name="tracking[__index__][carrier_code]" id="trackingC__index__" class="select carrier" style="width:110px;" disabled="disabled">
                     <?php foreach ($this->getCarriers() as $_code=>$_name): ?>
-                    <option value="<?php echo $_code ?>"><?php echo $_name ?></option>
+                    <option value="<?php echo $_code ?>"><?php echo $this->escapeHtml($_name) ?></option>
                     <?php endforeach; ?>
                 </select>
             </td>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/shipment/create/tracking.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/shipment/create/tracking.phtml
index 7a095d19d42688d69b4ed28578bd66edd723d959..1463f7ec4e2e4eacb7dfe7b5d30d3d7e8b1b021d 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/shipment/create/tracking.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/shipment/create/tracking.phtml
@@ -24,13 +24,10 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 ?>
-<?php
-/**
- * @see Mage_Adminhtml_Block_Sales_Order_Shipment_Create_Tracking
- */
-?>
+<?php /** @var $this Mage_Adminhtml_Block_Sales_Order_Shipment_Create_Tracking */ ?>
 <script type="text/javascript">
-var trackingControl = {};
+//<![CDATA[
+var trackingControl;
 trackingControl = {
     index : 0,
     add : function () {
@@ -69,6 +66,7 @@ trackingControl = {
         }
     }
 }
+//]]>
 </script>
 <div class="grid">
 <table cellspacing="0" class="data" id="tracking_numbers_table">
@@ -94,7 +92,7 @@ trackingControl = {
             <td>
                 <select name="tracking[__index__][carrier_code]" id="trackingC__index__" class="select carrier" style="width:110px;" disabled="disabled">
                     <?php foreach ($this->getCarriers() as $_code=>$_name): ?>
-                    <option value="<?php echo $_code ?>"><?php echo $_name ?></option>
+                    <option value="<?php echo $_code ?>"><?php echo $this->escapeHtml($_name) ?></option>
                     <?php endforeach; ?>
                 </select>
             </td>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/shipment/packaging/packed.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/shipment/packaging/packed.phtml
index c2ddd754047d424f602269338dabe2d26ab0e0c8..74e17de23308119f629da8a899e8564b791c7734 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/shipment/packaging/packed.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/shipment/packaging/packed.phtml
@@ -69,7 +69,7 @@
                                 <tr>
                                     <?php if ($this->displayCustomsValue()): ?>
                                         <th><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Customs Value') ?></th>
-                                        <td><?php echo $this->displayPrice($params->getCustomsValue()) ?></td>
+                                        <td><?php echo $this->displayCustomsPrice($params->getCustomsValue()) ?></td>
                                     <?php else: ?>
                                         <th><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Total Weight') ?></th>
                                         <td><?php echo $params->getWeight() .' '. Mage::helper('Mage_Usa_Helper_Data')->getMeasureWeightName($params->getWeightUnits()) ?></td>
@@ -85,7 +85,7 @@
                                     <?php if ($params->getContentType() != null): ?>
                                         <th><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Contents') ?></th>
                                         <?php if ($params->getContentType() == 'OTHER'): ?>
-                                            <td><?php echo $params->getContentTypeOther() ?></td>
+                                            <td><?php echo $this->escapeHtml($params->getContentTypeOther()) ?></td>
                                         <?php else: ?>
                                             <td><?php echo $this->getContentTypeByCode($params->getContentType()) ?></td>
                                         <?php endif; ?>
@@ -170,7 +170,7 @@
                                             <?php echo $item->getWeight(); ?>
                                         </td>
                                         <?php if ($this->displayCustomsValue()): ?>
-                                            <td class="a-right"><?php echo $this->displayPrice($item->getCustomsValue()) ?></td>
+                                            <td class="a-right"><?php echo $this->displayCustomsPrice($item->getCustomsValue()) ?></td>
                                         <?php endif; ?>
                                         <td class="a-right">
                                             <?php echo $this->getQtyOrderedItem($item->getOrderItemId()); ?>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/shipment/view/tracking.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/shipment/view/tracking.phtml
index 7457113720068ed7fcd2df74908f39fb330c1f44..a96b3a2fd384a1749ea620032c6bb880e14c15bb 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/shipment/view/tracking.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/shipment/view/tracking.phtml
@@ -24,6 +24,7 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 ?>
+<?php /** @var $this Mage_Adminhtml_Block_Sales_Order_Shipment_View_Tracking */ ?>
 <div class="field-row grid" id="shipment_tracking_info">
 <table cellspacing="0" class="data">
     <col width="100" />
@@ -43,7 +44,7 @@
             <td>
                 <select name="carrier" class="select" style="width:110px" onchange="selectCarrier(this)">
                     <?php foreach ($this->getCarriers() as $_code=>$_name): ?>
-                    <option value="<?php echo $_code ?>"><?php echo $_name ?></option>
+                    <option value="<?php echo $_code ?>"><?php echo $this->escapeHtml($_name) ?></option>
                     <?php endforeach; ?>
                 </select>
             </td>
@@ -56,7 +57,7 @@
     <tbody>
     <?php $i=0;foreach ($_tracks as $_track):$i++ ?>
         <tr class="<?php echo ($i%2==0)?'even':'odd' ?>">
-            <td><?php echo $this->getCarrierTitle($_track->getCarrierCode()) ?></td>
+            <td><?php echo $this->escapeHtml($this->getCarrierTitle($_track->getCarrierCode())) ?></td>
             <td><?php echo $this->escapeHtml($_track->getTitle()) ?></td>
             <td>
                 <?php if ($_track->isCustom()): ?>
@@ -76,13 +77,8 @@
 <script type="text/javascript">
 //<![CDATA[
 function selectCarrier(elem) {
-    option = elem.options[elem.selectedIndex];
-    if (option.value && option.value != 'custom') {
-        $('tracking_title').value = option.text;
-    }
-    else {
-        $('tracking_title').value = '';
-    }
+    var option = elem.options[elem.selectedIndex];
+    $('tracking_title').value = option.value && option.value != 'custom' ? option.text : '';
 }
 
 function deleteTrackingNumber(url) {
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/totals/tax.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/totals/tax.phtml
index e08b9049e6567f331a9f2fa8269e7afbad48f443..62c68421f9d664c030403847b169ebcfb143b5a6 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/totals/tax.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/totals/tax.phtml
@@ -73,9 +73,9 @@ $_fullInfo  = $this->getFullTaxInfo();
 
             <tr class="summary-details<?php if ($isTop): echo ' summary-details-first'; endif; ?>" style="display:none;">
                 <?php if (!is_null($info['percent'])): ?>
-                    <td class="label"><?php echo $info['title']; ?> (<?php echo (float)$info['percent']; ?>%)<br /></td>
+                    <td class="label"><?php echo $this->escapeHtml($info['title']); ?> (<?php echo (float)$info['percent']; ?>%)<br /></td>
                 <?php else: ?>
-                    <td class="label"><?php echo $info['title']; ?><br /></td>
+                    <td class="label"><?php echo $this->escapeHtml($info['title']); ?><br /></td>
                 <?php endif; ?>
                     <td><?php echo $this->displayAmount($amount, $baseAmount); ?></td>
             </tr>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/view/info.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/view/info.phtml
index 7c1666437c4a7e84df510a9954558ca2e11ad7b5..fb3b48635c799b5ff44f44463c3cfb348c2ae509 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/view/info.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/view/info.phtml
@@ -81,7 +81,7 @@ $orderStoreDate = $this->formatDate($_order->getCreatedAtStoreDate(), 'medium',
                 </a></td>
             </tr>
             <?php endif; ?>
-            <?php if($_order->getRemoteIp()): ?>
+            <?php if($_order->getRemoteIp() && $this->shouldDisplayCustomerIp()): ?>
             <tr>
                 <td class="label"><label><?php echo Mage::helper('Mage_Sales_Helper_Data')->__('Placed from IP') ?></label></td>
                 <td class="value"><strong><?php echo $_order->getRemoteIp(); echo ($_order->getXForwardedFor())?' (' . $_order->getXForwardedFor() . ')':''; ?></strong></td>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/view/tab/info.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/view/tab/info.phtml
index 57b1ffec9a1f14ed308cb6ebad72187fb149e332..19edcfa78d74bc8d9db59f4c9ca4e47a49373593 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/view/tab/info.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/sales/order/view/tab/info.phtml
@@ -24,6 +24,7 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 ?>
+<?php /** @var $this Mage_Adminhtml_Block_Sales_Order_View_Tab_Info */ ?>
 <?php $_order = $this->getOrder() ?>
 <div>
     <div id="order-messages">
@@ -60,7 +61,7 @@
                 <br/>
                 <?php endif; ?>
                 <?php if ($_order->getShippingDescription()): ?>
-                    <strong><?php echo $_order->getShippingDescription() ?></strong>
+                    <strong><?php echo $this->escapeHtml($_order->getShippingDescription()) ?></strong>
 
                     <?php if ($this->helper('Mage_Tax_Helper_Data')->displayShippingPriceIncludingTax()): ?>
                         <?php $_excl = $this->displayShippingPriceInclTax($_order); ?>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/store/switcher/form/renderer/fieldset.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/store/switcher/form/renderer/fieldset.phtml
index 296aea419a4d3b89f52db4690e06956c1891cf2c..767548745be6040fddef3b8db3a78f892c36841c 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/store/switcher/form/renderer/fieldset.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/store/switcher/form/renderer/fieldset.phtml
@@ -37,8 +37,9 @@
 <?php if (!$_element->getNoContainer()): ?>
     <div class="fieldset <?php echo $_element->getClass() ?>" id="<?php echo $_element->getHtmlId() ?>">
 <?php endif; ?>
+<div class="storeScope">
     <?php echo $this->getHintHtml() ?>
-    <div class="hor-scroll">
+    <div class="tree-storeScope">
         <?php if ($_element->getComment()): ?>
             <p class="comment"><?php echo $this->escapeHtml($_element->getComment()) ?></p>
         <?php endif; ?>
@@ -52,6 +53,7 @@
         </table>
         <?php endif; ?>
     </div>
+</div>
     <?php echo $_element->getSubFieldsetHtml() ?>
 <?php if (!$_element->getNoContainer()): ?>
     </div>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/tag.xml b/app/code/core/Mage/Adminhtml/view/adminhtml/tag.xml
index 7f036133d956157253c3b56cf1227b32903d4c20..67c0e7f7aa5e8e2df369770a1b17748f326dd8a8 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/tag.xml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/tag.xml
@@ -33,8 +33,8 @@
     </adminhtml_tag_edit>
     <adminhtml_tag_assigned>
             <remove name="root" />
-            <block type="Mage_Adminhtml_Block_Tag_Assigned_Grid" name="tag_assigned_grid" output="toHtml" />
-            <block type="Mage_Adminhtml_Block_Widget_Grid_Serializer" name="tag_grid_serializer" output="toHtml">
+            <block type="Mage_Adminhtml_Block_Tag_Assigned_Grid" name="tag_assigned_grid" output="1" />
+            <block type="Mage_Adminhtml_Block_Widget_Grid_Serializer" name="tag_grid_serializer" output="1">
                 <reference name="tag_grid_serializer">
                     <action method="initSerializerBlock">
                         <grid_block_name>tag_assigned_grid</grid_block_name>
@@ -47,7 +47,7 @@
     </adminhtml_tag_assigned>
     <adminhtml_tag_assignedgridonly>
         <remove name="root" />
-        <block type="Mage_Adminhtml_Block_Tag_Assigned_Grid" name="assigned_grid" output="toHtml" />
+        <block type="Mage_Adminhtml_Block_Tag_Assigned_Grid" name="assigned_grid" output="1" />
     </adminhtml_tag_assignedgridonly>
 
     <adminhtml_tag_index>
@@ -63,26 +63,26 @@
     </adminhtml_tag_pending>
 
     <adminhtml_tag_ajaxgrid>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Tag_Tag_Grid" name="adminhtml.tag.tag.grid"/>
-        </block>
+        </container>
     </adminhtml_tag_ajaxgrid>
 
     <adminhtml_tag_ajaxpendinggrid>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Tag_Grid_Pending" name="adminhtml.tag.grid.pending"/>
-        </block>
+        </container>
     </adminhtml_tag_ajaxpendinggrid>
 
     <adminhtml_tag_product>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Tag_Product_Grid" name="adminhtml.tag.product.grid"/>
-        </block>
+        </container>
     </adminhtml_tag_product>
 
     <adminhtml_tag_customer>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_Adminhtml_Block_Tag_Customer_Grid" name="adminhtml.tag.customer.grid"/>
-        </block>
+        </container>
     </adminhtml_tag_customer>
 </layout>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/urlrewrite/edit.phtml b/app/code/core/Mage/Adminhtml/view/adminhtml/urlrewrite/edit.phtml
index 7ae6052b52f01109d5916e3c1fc229f51f496290..bc3761462227a5bf6348b1f7082abddd348fa7e6 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/urlrewrite/edit.phtml
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/urlrewrite/edit.phtml
@@ -37,7 +37,7 @@
 
 <?php echo $this->getChildHtml() ?>
 
-<?php if ($this->getChild('form')): ?>
+<?php if ($this->getChildBlock('form')): ?>
 <script type="text/javascript">
     var editForm = new varienForm('edit_form', '<?php echo $this->getValidationUrl() ?>');
 </script>
diff --git a/app/code/core/Mage/Adminhtml/view/adminhtml/variables.js b/app/code/core/Mage/Adminhtml/view/adminhtml/variables.js
index cf9ffd27bdbe3996a804bd661809af63b3daa0be..15f8e49ea854573e2899fec4ba694272e11be4ad 100644
--- a/app/code/core/Mage/Adminhtml/view/adminhtml/variables.js
+++ b/app/code/core/Mage/Adminhtml/view/adminhtml/variables.js
@@ -106,7 +106,7 @@ var Variables = {
     },
     prepareVariableRow: function(varValue, varLabel) {
         var value = (varValue).replace(/"/g, '&quot;').replace(/'/g, '\\&#39;');
-        var content = '<a href="#" onclick="'+this.insertFunction+'(\''+ value +'\');">' + varLabel + '</a>';
+        var content = '<a href="#" onclick="'+this.insertFunction+'(\''+ value +'\');return false;">' + varLabel + '</a>';
         return content;
     },
     insertVariable: function(value) {
diff --git a/app/code/core/Mage/Adminhtml/view/email/password_reset_confirmation.html b/app/code/core/Mage/Adminhtml/view/email/password_reset_confirmation.html
index 6278841c635c341b91464d38dbc8bfbd8a85fade..5b797286f866ba1a7db990c87e476fc43699e0b1 100644
--- a/app/code/core/Mage/Adminhtml/view/email/password_reset_confirmation.html
+++ b/app/code/core/Mage/Adminhtml/view/email/password_reset_confirmation.html
@@ -1,8 +1,9 @@
 <!--@subject Password Reset Confirmation for {{var user.name}} @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
-"escapehtml var=$user.name":"Admin Name",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
+"htmlescape var=$user.name":"Admin Name",
 "store url=\"adminhtml/index/resetpassword/\" _query_id=$user.id _query_token=$user.rp_token":"Reset Password URL",
 "store url=\"adminhtml/system_account/\"":"Admin Account Url"}
 @-->
@@ -19,7 +20,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
                     <table bgcolor="FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
                         <tr>
                             <td valign="top">
-                                <a href="{{store url=""}}" style="color:#1E7EC8;"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}" border="0"/></a>
+                                <a href="{{store url=""}}" style="color:#1E7EC8;"><img src="{{var logo_url}}" alt="{{var logo_alt}}" border="0"/></a>
                             </td>
                         </tr>
                         <tr>
diff --git a/app/code/core/Mage/Api/Controller/Action.php b/app/code/core/Mage/Api/Controller/Action.php
index 8781fda354c808261b1e46f9f3a0d6a17d17bf27..086a43e20674c0a14bfa470cc9a66c0d367a07b7 100644
--- a/app/code/core/Mage/Api/Controller/Action.php
+++ b/app/code/core/Mage/Api/Controller/Action.php
@@ -25,24 +25,32 @@
  */
 
 /**
- * Base api controller
- *
- * @category   Mage
- * @package    Mage_Api
-*/
+ * Generic API controller
+ */
 class Mage_Api_Controller_Action extends Mage_Core_Controller_Front_Action
 {
+    /**
+     * Currently used area
+     *
+     * @var string
+     */
+    protected $_currentArea = 'adminhtml';
+
+    /**
+     * Use 'admin' store and prevent the session from starting
+     *
+     * @return Mage_Api_Controller_Action
+     */
     public function preDispatch()
     {
-        $this->getLayout()->setArea('adminhtml');
         Mage::app()->setCurrentStore('admin');
-        $this->setFlag('', self::FLAG_NO_START_SESSION, 1); // Do not start standart session
+        $this->setFlag('', self::FLAG_NO_START_SESSION, 1);
         parent::preDispatch();
         return $this;
     }
 
     /**
-     * Retrive webservice server
+     * Retrieve webservice server
      *
      * @return Mage_Api_Model_Server
      */
diff --git a/app/code/core/Mage/Authorizenet/Block/Directpost/Iframe.php b/app/code/core/Mage/Authorizenet/Block/Directpost/Iframe.php
index 9cadfc3ccdd53c5f002ac743ca2c07e6d99c0561..434233684f9f6619d08e30067f4fc9939e8cb76e 100644
--- a/app/code/core/Mage/Authorizenet/Block/Directpost/Iframe.php
+++ b/app/code/core/Mage/Authorizenet/Block/Directpost/Iframe.php
@@ -34,41 +34,19 @@
 class Mage_Authorizenet_Block_Directpost_Iframe extends Mage_Core_Block_Template
 {
     /**
-     * Request params
-     * @var array
-     */
-    protected $_params = array();
-
-    /**
-     * Internal constructor
-     * Set template for iframe
-     *
-     */
-    protected function _construct()
-    {
-        parent::_construct();
-        $this->setTemplate('directpost/iframe.phtml');
-    }
-
-    /**
-     * Set output params
+     * Preparing global layout
      *
-     * @param array $params
-     * @return Mage_Authorizenet_Block_Directpost_Iframe
-     */
-    public function setParams($params)
-    {
-        $this->_params = $params;
-        return $this;
-    }
-
-    /**
-     * Get params
+     * You can redefine this method in child classes for changing layout
      *
-     * @return array
+     * @return Mage_Core_Block_Abstract
      */
-    public function getParams()
+    protected function _prepareLayout()
     {
-        return $this->_params;
+        $params = Mage::registry(Mage_Authorizenet_Directpost_PaymentController::REGISTRY_FORM_PARAMS_KEY);
+        if (is_null($params)) {
+            $params = array();
+        }
+        $this->setParams($params);
+        return parent::_prepareLayout();
     }
 }
diff --git a/app/code/core/Mage/Authorizenet/controllers/Directpost/PaymentController.php b/app/code/core/Mage/Authorizenet/controllers/Directpost/PaymentController.php
index 87a489758a0629e4640b0518a2d5e78f12298655..69778a4c21676ff3ed92af11c9e928d35b3a31ec 100644
--- a/app/code/core/Mage/Authorizenet/controllers/Directpost/PaymentController.php
+++ b/app/code/core/Mage/Authorizenet/controllers/Directpost/PaymentController.php
@@ -33,6 +33,13 @@
  */
 class Mage_Authorizenet_Directpost_PaymentController extends Mage_Core_Controller_Front_Action
 {
+    /**
+     * Register key name for form params
+     *
+     * @const string
+     */
+    const REGISTRY_FORM_PARAMS_KEY = 'authorizenet_directpost_form_params';
+
     /**
      * @return Mage_Checkout_Model_Session
      */
@@ -51,22 +58,13 @@ class Mage_Authorizenet_Directpost_PaymentController extends Mage_Core_Controlle
         return Mage::getSingleton('Mage_Authorizenet_Model_Directpost_Session');
     }
 
-    /**
-     * Get iframe block instance
-     *
-     * @return Mage_Authorizenet_Block_Directpost_Iframe
-     */
-    protected function _getIframeBlock()
-    {
-        return $this->getLayout()->createBlock('Mage_Authorizenet_Block_Directpost_Iframe');
-    }
-
     /**
      * Response action.
      * Action for Authorize.net SIM Relay Request.
      */
     public function responseAction()
     {
+        $params = array();
         $data = $this->getRequest()->getPost();
         /* @var $paymentMethod Mage_Authorizenet_Model_DirectPost */
         $paymentMethod = Mage::getModel('Mage_Authorizenet_Model_Directpost');
@@ -102,8 +100,10 @@ class Mage_Authorizenet_Directpost_PaymentController extends Mage_Core_Controlle
             $result['is_secure'] = isset($data['is_secure']) ? $data['is_secure'] : false;
             $params['redirect'] = Mage::helper('Mage_Authorizenet_Helper_Data')->getRedirectIframeUrl($result);
         }
-        $block = $this->_getIframeBlock()->setParams($params);
-        $this->getResponse()->setBody($block->toHtml());
+
+        Mage::register(self::REGISTRY_FORM_PARAMS_KEY, $params);
+        $this->addPageLayoutHandles();
+        $this->loadLayout(false)->renderLayout();
     }
 
     /**
@@ -125,8 +125,9 @@ class Mage_Authorizenet_Directpost_PaymentController extends Mage_Core_Controlle
             $cancelOrder = empty($redirectParams['x_invoice_num']);
             $this->_returnCustomerQuote($cancelOrder, $redirectParams['error_msg']);
         }
-        $block = $this->_getIframeBlock()->setParams(array_merge($params, $redirectParams));
-        $this->getResponse()->setBody($block->toHtml());
+        Mage::register(self::REGISTRY_FORM_PARAMS_KEY, array_merge($params, $redirectParams));
+        $this->addPageLayoutHandles();
+        $this->loadLayout(false)->renderLayout();
     }
 
     /**
diff --git a/app/code/core/Mage/Authorizenet/view/frontend/layout.xml b/app/code/core/Mage/Authorizenet/view/frontend/layout.xml
index 558852a8590375fba13dc7ea9a5ffe06cf88cd4c..a6da3e97d87952c27d76237826bfac6821e01383 100644
--- a/app/code/core/Mage/Authorizenet/view/frontend/layout.xml
+++ b/app/code/core/Mage/Authorizenet/view/frontend/layout.xml
@@ -32,6 +32,7 @@
             <action method="addJs"><file>mage/directpost.js</file></action>
         </reference>
     </checkout_onepage_index>
+
     <checkout_onepage_review>
         <reference name="checkout.onepage.review.info.items.after">
             <block type="Mage_Authorizenet_Block_Directpost_Form" name="payment.form.directpost" template="directpost/form.phtml">
@@ -39,4 +40,18 @@
             </block>
         </reference>
     </checkout_onepage_review>
+
+    <authorizenet_directpost_payment_redirect translate="label" type="page" parent="ajax_index">
+        <label>AuthorizeNet Directpost Redirect</label>
+        <reference name="root">
+            <block type="Mage_Authorizenet_Block_Directpost_Iframe" name="iframe" template="directpost/iframe.phtml"/>
+        </reference>
+    </authorizenet_directpost_payment_redirect>
+
+    <authorizenet_directpost_payment_response translate="label" type="page" parent="ajax_index">
+        <label>AuthorizeNet Directpost Response</label>
+        <reference name="root">
+            <block type="Mage_Authorizenet_Block_Directpost_Iframe" name="iframe" template="directpost/iframe.phtml"/>
+        </reference>
+    </authorizenet_directpost_payment_response>
 </layout>
diff --git a/app/code/core/Mage/Backup/Helper/Data.php b/app/code/core/Mage/Backup/Helper/Data.php
index 3f53a87aa62bbfe2802e3ed601e79d141b308a68..2eacad0169231ce147c5d7175df6e4daa755fe4c 100644
--- a/app/code/core/Mage/Backup/Helper/Data.php
+++ b/app/code/core/Mage/Backup/Helper/Data.php
@@ -31,38 +31,28 @@ class Mage_Backup_Helper_Data extends Mage_Core_Helper_Abstract
 {
     /**
      * Backup type constant for database backup
-     *
-     * @const string
      */
-    const TYPE_DB              = 'db';
+    const TYPE_DB = 'db';
 
     /**
      * Backup type constant for filesystem backup
-     *
-     * @const string
      */
-    const TYPE_FILESYSTEM      = 'filesystem';
+    const TYPE_FILESYSTEM = 'filesystem';
 
     /**
      * Backup type constant for full system backup(database + filesystem)
-     *
-     * @const string
      */
     const TYPE_SYSTEM_SNAPSHOT = 'snapshot';
 
     /**
      * Backup type constant for media and database backup
-     *
-     * @const string
      */
-    const TYPE_MEDIA      = 'media';
+    const TYPE_MEDIA = 'media';
 
     /**
      * Backup type constant for full system backup excluding media folder
-     *
-     * @const string
      */
-    const TYPE_SNAPSHOT_WITHOUT_MEDIA   = 'nomedia';
+    const TYPE_SNAPSHOT_WITHOUT_MEDIA = 'nomedia';
 
     /**
      * Get all possible backup type values with descriptive title
@@ -234,7 +224,7 @@ class Mage_Backup_Helper_Data extends Mage_Core_Helper_Abstract
     {
         $messagesMap = array(
             self::TYPE_SYSTEM_SNAPSHOT => $this->__('The system backup has been created.'),
-            self::TYPE_SNAPSHOT_WITHOUT_MEDIA => $this->__('The system backup has been created.'),
+            self::TYPE_SNAPSHOT_WITHOUT_MEDIA => $this->__('The system (excluding Media) backup has been created.'),
             self::TYPE_MEDIA => $this->__('The database and media backup has been created.'),
             self::TYPE_DB => $this->__('The database backup has been created.')
         );
diff --git a/app/code/core/Mage/Backup/Model/Db.php b/app/code/core/Mage/Backup/Model/Db.php
index 2126f41b9ce63df7b91a2addd5df6230b9a16318..8f5da7e1a4af430e7b83c44604abfa83aff915f8 100644
--- a/app/code/core/Mage/Backup/Model/Db.php
+++ b/app/code/core/Mage/Backup/Model/Db.php
@@ -42,6 +42,15 @@ class Mage_Backup_Model_Db
      */
     const BUFFER_LENGTH = 102400;
 
+    /**
+     * List of tables which data should not be backed up
+     *
+     * @var array
+     */
+    protected $_ignoreDataTablesList = array(
+        'importexport/importdata'
+    );
+
     /**
      * Retrieve resource model
      *
@@ -108,13 +117,16 @@ class Mage_Backup_Model_Db
 
         $backup->write($this->getResource()->getHeader());
 
+        $ignoreDataTablesList = $this->getIgnoreDataTablesList();
+
         foreach ($tables as $table) {
-            $backup->write($this->getResource()->getTableHeader($table) . $this->getResource()->getTableDropSql($table) . "\n");
+            $backup->write($this->getResource()->getTableHeader($table)
+                . $this->getResource()->getTableDropSql($table) . "\n");
             $backup->write($this->getResource()->getTableCreateSql($table, false) . "\n");
 
             $tableStatus = $this->getResource()->getTableStatus($table);
 
-            if ($tableStatus->getRows()) {
+            if ($tableStatus->getRows() && !in_array($table, $ignoreDataTablesList)) {
                 $backup->write($this->getResource()->getTableDataBeforeSql($table));
 
                 if ($tableStatus->getDataLength() > self::BUFFER_LENGTH) {
@@ -149,4 +161,20 @@ class Mage_Backup_Model_Db
         return $this;
     }
 
+    /**.
+     * Returns the list of tables which data should not be backed up
+     *
+     * @return array
+     */
+    public function getIgnoreDataTablesList()
+    {
+        $result = array();
+        $resource = Mage::getSingleton('Mage_Core_Model_Resource');
+
+        foreach ($this->_ignoreDataTablesList as $table) {
+            $result[] = $resource->getTableName($table);
+        }
+
+        return $result;
+    }
 }
diff --git a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option.php b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option.php
index 79672d7390e721f470f4fd4286022830268216b0..0747c086d691c019914868da6091ad1de31a56b4 100644
--- a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option.php
+++ b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option.php
@@ -187,7 +187,7 @@ class Mage_Bundle_Block_Adminhtml_Catalog_Product_Edit_Tab_Bundle_Option extends
     {
         $buttonId = $this->getLayout()
                 ->getBlock('admin.product.bundle.items')
-                ->getChild('add_button')->getId();
+                ->getChildBlock('add_button')->getId();
         return $buttonId;
     }
 
diff --git a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search.php b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search.php
index a1b9e6bec9be8984b09b030005c1e0a83a764f6e..935b803048f0ad5eb919ab31ba6e727e492faf68 100644
--- a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search.php
+++ b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search.php
@@ -58,7 +58,7 @@ class Mage_Bundle_Block_Adminhtml_Catalog_Product_Edit_Tab_Bundle_Option_Search
 
     protected function _beforeToHtml()
     {
-        $this->getChild('grid')->setIndex($this->getIndex())
+        $this->getChildBlock('grid')->setIndex($this->getIndex())
             ->setFirstShow($this->getFirstShow());
 
         return parent::_beforeToHtml();
diff --git a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search/Grid.php b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search/Grid.php
index 65ccd040e74a68976fe37c4a12768314c0ce1611..f6a13fd727230e2672da6fb54665db2ab7685f55 100644
--- a/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search/Grid.php
+++ b/app/code/core/Mage/Bundle/Block/Adminhtml/Catalog/Product/Edit/Tab/Bundle/Option/Search/Grid.php
@@ -48,8 +48,8 @@ class Mage_Bundle_Block_Adminhtml_Catalog_Product_Edit_Tab_Bundle_Option_Search_
     protected function _beforeToHtml()
     {
         $this->setId($this->getId().'_'.$this->getIndex());
-        $this->getChild('reset_filter_button')->setData('onclick', $this->getJsObjectName().'.resetFilter()');
-        $this->getChild('search_button')->setData('onclick', $this->getJsObjectName().'.doFilter()');
+        $this->getChildBlock('reset_filter_button')->setData('onclick', $this->getJsObjectName().'.resetFilter()');
+        $this->getChildBlock('search_button')->setData('onclick', $this->getJsObjectName().'.doFilter()');
 
         return parent::_beforeToHtml();
     }
diff --git a/app/code/core/Mage/Bundle/Block/Catalog/Product/View/Type/Bundle.php b/app/code/core/Mage/Bundle/Block/Catalog/Product/View/Type/Bundle.php
index 473d10108420520fd44ed5fb79060cd3c327463a..fd66f73c13e362f14c1ede060160b0d9b593d449 100644
--- a/app/code/core/Mage/Bundle/Block/Catalog/Product/View/Type/Bundle.php
+++ b/app/code/core/Mage/Bundle/Block/Catalog/Product/View/Type/Bundle.php
@@ -58,7 +58,9 @@ class Mage_Bundle_Block_Catalog_Product_View_Type_Bundle extends Mage_Catalog_Bl
                 $product
             );
 
-            $this->_options = $optionCollection->appendSelections($selectionCollection, false, false);
+            $this->_options = $optionCollection->appendSelections($selectionCollection, false,
+                Mage::helper('Mage_Catalog_Helper_Product')->getSkipSaleableCheck()
+            );
         }
 
         return $this->_options;
@@ -87,6 +89,10 @@ class Mage_Bundle_Block_Catalog_Product_View_Type_Bundle extends Mage_Catalog_Bl
         $currentProduct = $this->getProduct();
         /* @var $coreHelper Mage_Core_Helper_Data */
         $coreHelper   = Mage::helper('Mage_Core_Helper_Data');
+        /* @var $catalogHelper Mage_Catalog_Helper_Data */
+        $catalogHelper = Mage::helper('Mage_Catalog_Helper_Data');
+        /* @var $taxHelper Mage_Tax_Helper_Data */
+        $taxHelper = Mage::helper('Mage_Tax_Helper_Data');
         /* @var $bundlePriceModel Mage_Bundle_Model_Product_Price */
         $bundlePriceModel = Mage::getModel('Mage_Bundle_Model_Product_Price');
 
@@ -122,7 +128,7 @@ class Mage_Bundle_Block_Catalog_Product_View_Type_Bundle extends Mage_Catalog_Bl
                 unset($tierPriceInfo); // break the reference with the last element
 
                 $itemPrice = $bundlePriceModel->getSelectionFinalTotalPrice($currentProduct, $_selection,
-                        $currentProduct->getQty(), $_selection->getQty(), false, false
+                    $currentProduct->getQty(), $_selection->getQty(), false, false
                 );
 
                 $canApplyMAP = false;
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 832fd99648a6369795c11acee2182e93a6d7223a..181c7eef903908bd32402eecb60bb514e14e048f 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
@@ -180,7 +180,7 @@ class Mage_Bundle_Block_Catalog_Product_View_Type_Bundle_Option extends Mage_Bun
     {
         $price = $this->getProduct()->getPriceModel()->getSelectionPreFinalPrice($this->getProduct(), $_selection);
         $this->setFormatProduct($_selection);
-        $priceTitle = $_selection->getSelectionQty()*1 . ' x ' . $_selection->getName();
+        $priceTitle = $_selection->getSelectionQty()*1 . ' x ' . $this->escapeHtml($_selection->getName());
 
         $priceTitle .= ' &nbsp; ' . ($includeContainer ? '<span class="price-notice">' : '')
             . '+' . $this->formatPriceString($price, $includeContainer)
@@ -219,7 +219,7 @@ class Mage_Bundle_Block_Catalog_Product_View_Type_Bundle_Option extends Mage_Bun
     {
         $price = $this->getProduct()->getPriceModel()->getSelectionPreFinalPrice($this->getProduct(), $_selection, 1);
         $this->setFormatProduct($_selection);
-        $priceTitle = $_selection->getName();
+        $priceTitle = $this->escapeHtml($_selection->getName());
         $priceTitle .= ' &nbsp; ' . ($includeContainer ? '<span class="price-notice">' : '')
             . '+' . $this->formatPriceString($price, $includeContainer)
             . ($includeContainer ? '</span>' : '');
diff --git a/app/code/core/Mage/Bundle/Model/Observer.php b/app/code/core/Mage/Bundle/Model/Observer.php
index 06b83504c65db83c59c4766ea86e976b9c6bf24f..7171272fb9b5767e1fa15a951e86f3f550674904 100644
--- a/app/code/core/Mage/Bundle/Model/Observer.php
+++ b/app/code/core/Mage/Bundle/Model/Observer.php
@@ -253,4 +253,17 @@ class Mage_Bundle_Model_Observer
         }
         return $this;
     }
+
+    /**
+     * Initialize product options renderer with bundle specific params
+     *
+     * @param Varien_Event_Observer $observer
+     * @return Mage_Bundle_Model_Observer
+     */
+    public function initOptionRenderer(Varien_Event_Observer $observer)
+    {
+        $block = $observer->getBlock();
+        $block->addOptionsRenderCfg('bundle', 'Mage_Bundle_Helper_Catalog_Product_Configuration');
+        return $this;
+    }
 }
diff --git a/app/code/core/Mage/Bundle/Model/Product/Price.php b/app/code/core/Mage/Bundle/Model/Product/Price.php
index 7854949d24bfd6a8e0cce0694156116d7af7037e..200619e5294ebecb55946dffc89796a50750e577 100644
--- a/app/code/core/Mage/Bundle/Model/Product/Price.php
+++ b/app/code/core/Mage/Bundle/Model/Product/Price.php
@@ -116,13 +116,13 @@ class Mage_Bundle_Model_Product_Price extends Mage_Catalog_Model_Product_Type_Pr
         }
 
         $finalPrice = $this->getBasePrice($product, $qty);
-
         $product->setFinalPrice($finalPrice);
         Mage::dispatchEvent('catalog_product_get_final_price', array('product' => $product, 'qty' => $qty));
         $finalPrice = $product->getData('final_price');
 
-        $finalPrice += $this->getTotalBundleItemsPrice($product, $qty);
         $finalPrice = $this->_applyOptionsPrice($product, $qty, $finalPrice);
+        $finalPrice += $this->getTotalBundleItemsPrice($product, $qty);
+
         $product->setFinalPrice($finalPrice);
         return max(0, $product->getData('final_price'));
     }
@@ -381,7 +381,14 @@ class Mage_Bundle_Model_Product_Price extends Mage_Catalog_Model_Product_Type_Pr
             $price = $selectionProduct->getFinalPrice($takeTierPrice ? $selectionQty : 1);
         } else {
             if ($selectionProduct->getSelectionPriceType()) { // percent
-                $price = $this->getPrice($bundleProduct) * ($selectionProduct->getSelectionPriceValue() / 100);
+                $product = clone $bundleProduct;
+                $product->setFinalPrice($this->getPrice($product));
+                Mage::dispatchEvent(
+                    'catalog_product_get_final_price',
+                    array('product' => $product, 'qty' => $bundleQty)
+                );
+                $price = $product->getData('final_price') * ($selectionProduct->getSelectionPriceValue() / 100);
+
             } else { // fixed
                 $price = $selectionProduct->getSelectionPriceValue();
             }
diff --git a/app/code/core/Mage/Bundle/Model/Product/Type.php b/app/code/core/Mage/Bundle/Model/Product/Type.php
index 0983cb1330beb776fe59b1bb7ef9a296ed439c02..468216617cb46ad70dfff83f9c84ceaeb215cad4 100644
--- a/app/code/core/Mage/Bundle/Model/Product/Type.php
+++ b/app/code/core/Mage/Bundle/Model/Product/Type.php
@@ -531,7 +531,9 @@ class Mage_Bundle_Model_Product_Type extends Mage_Catalog_Model_Product_Type_Abs
 
         $selections = array();
         $isStrictProcessMode = $this->_isStrictProcessMode($processMode);
-        $_appendAllSelections = (bool)$product->getSkipCheckRequiredOption();
+
+        $skipSaleableCheck = Mage::helper('Mage_Catalog_Helper_Product')->getSkipSaleableCheck();
+        $_appendAllSelections = (bool)$product->getSkipCheckRequiredOption() || $skipSaleableCheck;
 
         $options = $buyRequest->getBundleOption();
         if (is_array($options)) {
@@ -578,7 +580,7 @@ class Mage_Bundle_Model_Product_Type extends Mage_Catalog_Model_Product_Type_Abs
 
                 // Check if added selections are still on sale
                 foreach ($selections->getItems() as $key => $selection) {
-                    if (!$selection->isSalable()) {
+                    if (!$selection->isSalable() && !$skipSaleableCheck) {
                         $_option = $optionsCollection->getItemById($selection->getOptionId());
                         if (is_array($options[$_option->getId()]) && count($options[$_option->getId()]) > 1) {
                             $moreSelections = true;
@@ -891,6 +893,16 @@ class Mage_Bundle_Model_Product_Type extends Mage_Catalog_Model_Product_Type_Abs
         return true;
     }
 
+    /**
+     * Force apply discount for parent item
+     *
+     * @return bool
+     */
+    public function getForceApplyDiscountToParentItem()
+    {
+        return true;
+    }
+
     /**
      * Retrieve additional searchable data from type instance
      * Using based on product id and store_id data
@@ -933,10 +945,11 @@ class Mage_Bundle_Model_Product_Type extends Mage_Catalog_Model_Product_Type_Abs
             Mage::throwException($this->getSpecifyOptionMessage());
         }
 
+        $skipSaleableCheck = Mage::helper('Mage_Catalog_Helper_Product')->getSkipSaleableCheck();
         foreach ($selectionIds as $selectionId) {
             /* @var $selection Mage_Bundle_Model_Selection */
             $selection = $productSelections->getItemById($selectionId);
-            if (!$selection || !$selection->isSalable()) {
+            if (!$selection || (!$selection->isSalable() && !$skipSaleableCheck)) {
                 Mage::throwException(
                     Mage::helper('Mage_Bundle_Helper_Data')->__('Selected required options are not available.')
                 );
diff --git a/app/code/core/Mage/Bundle/Model/Sales/Order/Pdf/Items/Abstract.php b/app/code/core/Mage/Bundle/Model/Sales/Order/Pdf/Items/Abstract.php
index a2810309cdae9f433effdf5490ad2801ae2a57d5..0b790fbfd3be1d74c67fafff01a373ad7b57e246 100644
--- a/app/code/core/Mage/Bundle/Model/Sales/Order/Pdf/Items/Abstract.php
+++ b/app/code/core/Mage/Bundle/Model/Sales/Order/Pdf/Items/Abstract.php
@@ -24,7 +24,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
 /**
  * Sales Order Pdf Items renderer
  *
@@ -134,7 +133,9 @@ abstract class Mage_Bundle_Model_Sales_Order_Pdf_Items_Abstract extends Mage_Sal
             if ($parentItem) {
                 $options = $parentItem->getProductOptions();
                 if ($options) {
-                    if (isset($options['product_calculations']) && $options['product_calculations'] == Mage_Catalog_Model_Product_Type_Abstract::CALCULATE_CHILD) {
+                    if (isset($options['product_calculations']) &&
+                        $options['product_calculations'] == Mage_Catalog_Model_Product_Type_Abstract::CALCULATE_CHILD
+                    ) {
                         return true;
                     } else {
                         return false;
@@ -143,7 +144,9 @@ abstract class Mage_Bundle_Model_Sales_Order_Pdf_Items_Abstract extends Mage_Sal
             } else {
                 $options = $item->getProductOptions();
                 if ($options) {
-                    if (isset($options['product_calculations']) && $options['product_calculations'] == Mage_Catalog_Model_Product_Type_Abstract::CALCULATE_CHILD) {
+                    if (isset($options['product_calculations']) &&
+                        $options['product_calculations'] == Mage_Catalog_Model_Product_Type_Abstract::CALCULATE_CHILD
+                    ) {
                         return false;
                     } else {
                         return true;
diff --git a/app/code/core/Mage/Bundle/Model/Sales/Order/Pdf/Items/Creditmemo.php b/app/code/core/Mage/Bundle/Model/Sales/Order/Pdf/Items/Creditmemo.php
index d94f213333bc6ddfb65366bd1f36c7cb6e07c8ae..ad0c8dfe4a6598e18f37f98914424af9a3c4fa2e 100644
--- a/app/code/core/Mage/Bundle/Model/Sales/Order/Pdf/Items/Creditmemo.php
+++ b/app/code/core/Mage/Bundle/Model/Sales/Order/Pdf/Items/Creditmemo.php
@@ -24,7 +24,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
 /**
  * Sales Order Creditmemo Pdf default items renderer
  *
@@ -47,8 +46,8 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Creditmemo extends Mage_Bundle_Mod
 
         $items = $this->getChilds($item);
         $_prevOptionId = '';
-        $drawItems = array();
-        $leftBound  =  35;
+        $drawItems  = array();
+        $leftBound  = 35;
         $rightBound = 565;
 
         $stringHelper = Mage::helper('Mage_Core_Helper_String');
@@ -67,7 +66,7 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Creditmemo extends Mage_Bundle_Mod
             if (!isset($drawItems[$optionId])) {
                 $drawItems[$optionId] = array(
                     'lines'  => array(),
-                    'height' => 10
+                    'height' => 15
                 );
             }
 
@@ -76,13 +75,13 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Creditmemo extends Mage_Bundle_Mod
                 if ($_prevOptionId != $attributes['option_id']) {
                     $line[0] = array(
                         'font'  => 'italic',
-                        'text'  => $stringHelper->str_split($attributes['option_label'],60, true, true),
+                        'text'  => Mage::helper('Mage_Core_Helper_String')->str_split($attributes['option_label'], 38, true, true),
                         'feed'  => $x
                     );
 
                     $drawItems[$optionId] = array(
                         'lines'  => array($line),
-                        'height' => 10
+                        'height' => 15
                     );
 
                     $line = array();
@@ -100,7 +99,7 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Creditmemo extends Mage_Bundle_Mod
             }
 
             $line[] = array(
-                'text'  => $stringHelper->str_split($name, 60, true, true),
+                'text'  => Mage::helper('Mage_Core_Helper_String')->str_split($name, 35, true, true),
                 'feed'  => $feed
             );
 
@@ -109,7 +108,7 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Creditmemo extends Mage_Bundle_Mod
             // draw SKUs
             if (!$_item->getOrderItem()->getParentItem()) {
                 $text = array();
-                foreach ($stringHelper->str_split($item->getSku(), 30) as $part) {
+                foreach (Mage::helper('Mage_Core_Helper_String')->str_split($item->getSku(), 17) as $part) {
                     $text[] = $part;
                 }
                 $line[] = array(
@@ -167,7 +166,9 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Creditmemo extends Mage_Bundle_Mod
                 $x += 45;
 
                 // draw Total(inc)
-                $text = $order->formatPriceTxt($_item->getRowTotal()+$_item->getTaxAmount()-$_item->getDiscountAmount());
+                $text = $order->formatPriceTxt(
+                    $_item->getRowTotal() + $_item->getTaxAmount() - $_item->getDiscountAmount()
+                );
                 $line[] = array(
                     'text'  => $text,
                     'feed'  => $rightBound,
@@ -187,17 +188,19 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Creditmemo extends Mage_Bundle_Mod
                 foreach ($options['options'] as $option) {
                     $lines = array();
                     $lines[][] = array(
-                        'text'  => $stringHelper->str_split(strip_tags($option['label']), 70, true, true),
+                        'text'  => Mage::helper('Mage_Core_Helper_String')->str_split(strip_tags($option['label']), 40, true, true),
                         'font'  => 'italic',
                         'feed'  => $leftBound
                     );
 
                     if ($option['value']) {
                         $text = array();
-                        $_printValue = isset($option['print_value']) ? $option['print_value'] : strip_tags($option['value']);
+                        $_printValue = isset($option['print_value'])
+                            ? $option['print_value']
+                            : strip_tags($option['value']);
                         $values = explode(', ', $_printValue);
                         foreach ($values as $value) {
-                            foreach ($stringHelper->str_split($value, 50, true, true) as $_value) {
+                            foreach (Mage::helper('Mage_Core_Helper_String')->str_split($value, 30, true, true) as $_value) {
                                 $text[] = $_value;
                             }
                         }
@@ -210,7 +213,7 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Creditmemo extends Mage_Bundle_Mod
 
                     $drawItems[] = array(
                         'lines'  => $lines,
-                        'height' => 10
+                        'height' => 15
                     );
                 }
             }
diff --git a/app/code/core/Mage/Bundle/Model/Sales/Order/Pdf/Items/Invoice.php b/app/code/core/Mage/Bundle/Model/Sales/Order/Pdf/Items/Invoice.php
index eda3fffc320d287456cc4b0d3bf3bebb91906d54..95bedd36d833c4059c689722f75ad5587fe6f477 100644
--- a/app/code/core/Mage/Bundle/Model/Sales/Order/Pdf/Items/Invoice.php
+++ b/app/code/core/Mage/Bundle/Model/Sales/Order/Pdf/Items/Invoice.php
@@ -24,7 +24,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
 /**
  * Sales Order Invoice Pdf default items renderer
  *
@@ -66,7 +65,7 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Invoice extends Mage_Bundle_Model_
             if (!isset($drawItems[$optionId])) {
                 $drawItems[$optionId] = array(
                     'lines'  => array(),
-                    'height' => 10
+                    'height' => 15
                 );
             }
 
@@ -74,13 +73,13 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Invoice extends Mage_Bundle_Model_
                 if ($_prevOptionId != $attributes['option_id']) {
                     $line[0] = array(
                         'font'  => 'italic',
-                        'text'  => $stringHelper->str_split($attributes['option_label'], 70, true, true),
+                        'text'  => Mage::helper('Mage_Core_Helper_String')->str_split($attributes['option_label'], 45, true, true),
                         'feed'  => 35
                     );
 
                     $drawItems[$optionId] = array(
                         'lines'  => array($line),
-                        'height' => 10
+                        'height' => 15
                     );
 
                     $line = array();
@@ -98,14 +97,14 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Invoice extends Mage_Bundle_Model_
                 $name = $_item->getName();
             }
             $line[] = array(
-                'text'  => $stringHelper->str_split($name, 55, true, true),
+                'text'  => Mage::helper('Mage_Core_Helper_String')->str_split($name, 35, true, true),
                 'feed'  => $feed
             );
 
             // draw SKUs
             if (!$_item->getOrderItem()->getParentItem()) {
                 $text = array();
-                foreach ($stringHelper->str_split($item->getSku(), 30) as $part) {
+                foreach (Mage::helper('Mage_Core_Helper_String')->str_split($item->getSku(), 17) as $part) {
                     $text[] = $part;
                 }
                 $line[] = array(
@@ -156,17 +155,19 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Invoice extends Mage_Bundle_Model_
                 foreach ($options['options'] as $option) {
                     $lines = array();
                     $lines[][] = array(
-                        'text'  => $stringHelper->str_split(strip_tags($option['label']), 70, true, true),
+                        'text'  => Mage::helper('Mage_Core_Helper_String')->str_split(strip_tags($option['label']), 40, true, true),
                         'font'  => 'italic',
                         'feed'  => 35
                     );
 
                     if ($option['value']) {
                         $text = array();
-                        $_printValue = isset($option['print_value']) ? $option['print_value'] : strip_tags($option['value']);
+                        $_printValue = isset($option['print_value'])
+                            ? $option['print_value']
+                            : strip_tags($option['value']);
                         $values = explode(', ', $_printValue);
                         foreach ($values as $value) {
-                            foreach ($stringHelper->str_split($value, 50, true, true) as $_value) {
+                            foreach (Mage::helper('Mage_Core_Helper_String')->str_split($value, 30, true, true) as $_value) {
                                 $text[] = $_value;
                             }
                         }
@@ -179,7 +180,7 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Invoice extends Mage_Bundle_Model_
 
                     $drawItems[] = array(
                         'lines'  => $lines,
-                        'height' => 10
+                        'height' => 15
                     );
                 }
             }
diff --git a/app/code/core/Mage/Bundle/Model/Sales/Order/Pdf/Items/Shipment.php b/app/code/core/Mage/Bundle/Model/Sales/Order/Pdf/Items/Shipment.php
index 561937eda553456429b3b743b3071564be366018..c032811e767b5a45dcfc561b0e41771c787cc23e 100644
--- a/app/code/core/Mage/Bundle/Model/Sales/Order/Pdf/Items/Shipment.php
+++ b/app/code/core/Mage/Bundle/Model/Sales/Order/Pdf/Items/Shipment.php
@@ -24,7 +24,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
 /**
  * Sales Order Shipment Pdf items renderer
  *
@@ -67,7 +66,7 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Shipment extends Mage_Bundle_Model
             if (!isset($drawItems[$optionId])) {
                 $drawItems[$optionId] = array(
                     'lines'  => array(),
-                    'height' => 10
+                    'height' => 15
                 );
             }
 
@@ -75,13 +74,13 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Shipment extends Mage_Bundle_Model
                 if ($_prevOptionId != $attributes['option_id']) {
                     $line[0] = array(
                         'font'  => 'italic',
-                        'text'  => $stringHelper->str_split($attributes['option_label'],60, true, true),
+                        'text'  => Mage::helper('Mage_Core_Helper_String')->str_split($attributes['option_label'], 60, true, true),
                         'feed'  => 60
                     );
 
                     $drawItems[$optionId] = array(
                         'lines'  => array($line),
-                        'height' => 10
+                        'height' => 15
                     );
 
                     $line = array();
@@ -90,7 +89,9 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Shipment extends Mage_Bundle_Model
                 }
             }
 
-            if (($this->isShipmentSeparately() && $_item->getParentItem()) || (!$this->isShipmentSeparately() && !$_item->getParentItem())) {
+            if (($this->isShipmentSeparately() && $_item->getParentItem())
+                || (!$this->isShipmentSeparately() && !$_item->getParentItem())
+            ) {
                 if (isset($shipItems[$_item->getId()])) {
                     $qty = $shipItems[$_item->getId()]->getQty()*1;
                 } else if ($_item->getIsVirtual()) {
@@ -126,7 +127,7 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Shipment extends Mage_Bundle_Model
 
             // draw SKUs
             $text = array();
-            foreach ($stringHelper->str_split($_item->getSku(), 30) as $part) {
+            foreach (Mage::helper('Mage_Core_Helper_String')->str_split($_item->getSku(), 25) as $part) {
                 $text[] = $part;
             }
             $line[] = array(
@@ -151,7 +152,9 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Shipment extends Mage_Bundle_Model
 
                     if ($option['value']) {
                         $text = array();
-                        $_printValue = isset($option['print_value']) ? $option['print_value'] : strip_tags($option['value']);
+                        $_printValue = isset($option['print_value'])
+                            ? $option['print_value']
+                            : strip_tags($option['value']);
                         $values = explode(', ', $_printValue);
                         foreach ($values as $value) {
                             foreach ($stringHelper->str_split($value, 50, true, true) as $_value) {
@@ -167,7 +170,7 @@ class Mage_Bundle_Model_Sales_Order_Pdf_Items_Shipment extends Mage_Bundle_Model
 
                     $drawItems[] = array(
                         'lines'  => $lines,
-                        'height' => 10
+                        'height' => 15
                     );
                 }
             }
diff --git a/app/code/core/Mage/Bundle/etc/config.xml b/app/code/core/Mage/Bundle/etc/config.xml
index af9c2188587d432fd5853d05194688b5f6a48eb5..b709d5898b048184839da98817ccdb5c25bdf5e4 100644
--- a/app/code/core/Mage/Bundle/etc/config.xml
+++ b/app/code/core/Mage/Bundle/etc/config.xml
@@ -152,6 +152,14 @@
                     </bundle_observer>
                 </observers>
             </catalog_product_collection_load_after>
+            <product_option_renderer_init>
+                <observers>
+                    <bundle_observer>
+                        <class>Mage_Bundle_Model_Observer</class>
+                        <method>initOptionRenderer</method>
+                    </bundle_observer>
+                </observers>
+            </product_option_renderer_init>
         </events>
     </frontend>
     <admin>
diff --git a/app/code/core/Mage/Bundle/view/adminhtml/layout.xml b/app/code/core/Mage/Bundle/view/adminhtml/layout.xml
index 04088e94f24f70a95e1ac9b0fa38e5c4138e1a47..17a9b0d6ab104055bc9a84451f828a9bad5d2be2 100644
--- a/app/code/core/Mage/Bundle/view/adminhtml/layout.xml
+++ b/app/code/core/Mage/Bundle/view/adminhtml/layout.xml
@@ -105,7 +105,7 @@ Layout handle for budle products
         </reference>
     </adminhtml_customer_wishlist>
 
-    <PRODUCT_TYPE_bundle>
+    <catalog_product_view_type_bundle>
         <reference name="product.composite.fieldset">
             <block type="Mage_Bundle_Block_Adminhtml_Catalog_Product_Composite_Fieldset_Bundle" before="product.composite.fieldset.options" name="product.composite.fieldset.bundle" template="product/composite/fieldset/options/bundle.phtml">
                 <action method="addRenderer"><type>select</type><block>Mage_Bundle_Block_Adminhtml_Catalog_Product_Composite_Fieldset_Options_Type_Select</block></action>
@@ -114,5 +114,5 @@ Layout handle for budle products
                 <action method="addRenderer"><type>checkbox</type><block>Mage_Bundle_Block_Adminhtml_Catalog_Product_Composite_Fieldset_Options_Type_Checkbox</block></action>
             </block>
         </reference>
-    </PRODUCT_TYPE_bundle>
+    </catalog_product_view_type_bundle>
 </layout>
diff --git a/app/code/core/Mage/Bundle/view/adminhtml/product/composite/fieldset/options/type/checkbox.phtml b/app/code/core/Mage/Bundle/view/adminhtml/product/composite/fieldset/options/type/checkbox.phtml
index 5e99121107a7bf2e74f01f9c81726a3ae0b22832..b5cdc6506c0cee477da0335e9b3c920b9c0ded4d 100644
--- a/app/code/core/Mage/Bundle/view/adminhtml/product/composite/fieldset/options/type/checkbox.phtml
+++ b/app/code/core/Mage/Bundle/view/adminhtml/product/composite/fieldset/options/type/checkbox.phtml
@@ -28,6 +28,7 @@
 <?php /* @var $this Mage_Bundle_Block_Adminhtml_Catalog_Product_Composite_Fieldset_Options_Type_Checkbox */ ?>
 <?php $_option = $this->getOption(); ?>
 <?php $_selections = $_option->getSelections(); ?>
+<?php $_skipSaleableCheck = Mage::helper('Mage_Catalog_Helper_Product')->getSkipSaleableCheck(); ?>
 <dt><label<?php if ($_option->getRequired()) echo ' class="required"' ?>><?php if ($_option->getRequired()) echo '<em>*</em>' ?><?php echo $this->escapeHtml($_option->getTitle()) ?></label></dt>
 <dd<?php if ($_option->getDecoratedIsLast()):?> class="last"<?php endif; ?>>
     <div class="input-box">
@@ -37,7 +38,7 @@
     <?php else:?>
         <ul class="options-list">
         <?php foreach($_selections as $_selection): ?>
-            <li><input class="change-container-classname checkbox bundle-option-<?php echo $_option->getId() ?> <?php if ($_option->getRequired()) echo 'validate-one-required-by-name' ?>" id="bundle-option-<?php echo $_option->getId() ?>-<?php echo $_selection->getSelectionId() ?>" type="checkbox" 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() ?>" onclick="ProductConfigure.bundleControl.changeSelection(this)" price="<?php echo $this->getSelectionPrice($_selection) ?>"/>
+            <li><input class="change-container-classname checkbox bundle-option-<?php echo $_option->getId() ?> <?php if ($_option->getRequired()) echo 'validate-one-required-by-name' ?>" id="bundle-option-<?php echo $_option->getId() ?>-<?php echo $_selection->getSelectionId() ?>" type="checkbox" name="bundle_option[<?php echo $_option->getId() ?>][]"<?php if ($this->_isSelected($_selection)) echo ' checked="checked"' ?><?php if (!$_selection->isSaleable() && !$_skipSaleableCheck) echo ' disabled="disabled"' ?> value="<?php echo $_selection->getSelectionId() ?>" onclick="ProductConfigure.bundleControl.changeSelection(this)" price="<?php echo $this->getSelectionPrice($_selection) ?>"/>
                 <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') ?>
diff --git a/app/code/core/Mage/Bundle/view/adminhtml/product/composite/fieldset/options/type/multi.phtml b/app/code/core/Mage/Bundle/view/adminhtml/product/composite/fieldset/options/type/multi.phtml
index fb6fc84c93251aa31e14d8674370b2cc58c40352..69e3d1614bd45accc9c6c8e7c2603135e4ae046a 100644
--- a/app/code/core/Mage/Bundle/view/adminhtml/product/composite/fieldset/options/type/multi.phtml
+++ b/app/code/core/Mage/Bundle/view/adminhtml/product/composite/fieldset/options/type/multi.phtml
@@ -28,6 +28,7 @@
 <?php /* @var $this Mage_Bundle_Block_Adminhtml_Catalog_Product_Composite_Fieldset_Options_Type_Multi */ ?>
 <?php $_option = $this->getOption(); ?>
 <?php $_selections = $_option->getSelections(); ?>
+<?php $_skipSaleableCheck = Mage::helper('Mage_Catalog_Helper_Product')->getSkipSaleableCheck(); ?>
 <dt><label<?php if ($_option->getRequired()) echo ' class="required"' ?>><?php if ($_option->getRequired()) echo '<em>*</em>' ?><?php echo $this->escapeHtml($_option->getTitle()) ?></label></dt>
 <dd<?php if ($_option->getDecoratedIsLast()):?> class="last"<?php endif; ?>>
     <div class="input-box">
@@ -40,7 +41,7 @@
             <option value=""><?php echo $this->__('None') ?></option>
         <?php endif; ?>
         <?php foreach ($_selections as $_selection): ?>
-            <option value="<?php echo $_selection->getSelectionId() ?>"<?php if ($this->_isSelected($_selection)) echo ' selected="selected"' ?><?php if (!$_selection->isSaleable()) echo ' disabled="disabled"' ?> price="<?php echo $this->getSelectionPrice($_selection) ?>"><?php echo $this->getSelectionQtyTitlePrice($_selection, false) ?></option>
+            <option value="<?php echo $_selection->getSelectionId() ?>"<?php if ($this->_isSelected($_selection)) echo ' selected="selected"' ?><?php if (!$_selection->isSaleable() && !$_skipSaleableCheck) echo ' disabled="disabled"' ?> price="<?php echo $this->getSelectionPrice($_selection) ?>"><?php echo $this->getSelectionQtyTitlePrice($_selection, false) ?></option>
         <?php endforeach; ?>
         </select>
     <?php endif; ?>
diff --git a/app/code/core/Mage/Bundle/view/adminhtml/product/composite/fieldset/options/type/radio.phtml b/app/code/core/Mage/Bundle/view/adminhtml/product/composite/fieldset/options/type/radio.phtml
index 2675e600acd9fb8e6f8099cbbcf1a69cada88586..729234136ead2c3b069c34313c69aa41408d3e1c 100644
--- a/app/code/core/Mage/Bundle/view/adminhtml/product/composite/fieldset/options/type/radio.phtml
+++ b/app/code/core/Mage/Bundle/view/adminhtml/product/composite/fieldset/options/type/radio.phtml
@@ -29,6 +29,7 @@
 <?php $_option = $this->getOption(); ?>
 <?php $_selections  = $_option->getSelections(); ?>
 <?php $_default = $_option->getDefaultSelection(); ?>
+<?php $_skipSaleableCheck = Mage::helper('Mage_Catalog_Helper_Product')->getSkipSaleableCheck(); ?>
 <?php list($_defaultQty, $_canChangeQty) = $this->_getDefaultValues(); ?>
 
 <dt>
@@ -50,7 +51,7 @@
             </li>
         <?php endif; ?>
         <?php foreach ($_selections as $_selection): ?>
-            <li><input type="radio" class="radio<?php echo $_option->getRequired()?' validate-one-required-by-name':'' ?> change-container-classname" id="bundle-option-<?php echo $_option->getId() ?>-<?php echo $_selection->getSelectionId() ?>" 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() ?>" onclick="ProductConfigure.bundleControl.changeSelection(this)" price="<?php echo $this->getSelectionPrice($_selection) ?>" qtyId="bundle-option-<?php echo $_option->getId() ?>-qty-input"/>
+            <li><input type="radio" class="radio<?php echo $_option->getRequired()?' validate-one-required-by-name':'' ?> change-container-classname" id="bundle-option-<?php echo $_option->getId() ?>-<?php echo $_selection->getSelectionId() ?>" name="bundle_option[<?php echo $_option->getId() ?>]"<?php if ($this->_isSelected($_selection)) echo ' checked="checked"' ?><?php if (!$_selection->isSaleable() && !$_skipSaleableCheck) echo ' disabled="disabled"' ?>value="<?php echo $_selection->getSelectionId() ?>" onclick="ProductConfigure.bundleControl.changeSelection(this)" price="<?php echo $this->getSelectionPrice($_selection) ?>" qtyId="bundle-option-<?php echo $_option->getId() ?>-qty-input"/>
             <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') ?>
diff --git a/app/code/core/Mage/Bundle/view/adminhtml/product/composite/fieldset/options/type/select.phtml b/app/code/core/Mage/Bundle/view/adminhtml/product/composite/fieldset/options/type/select.phtml
index 31526f0428680882f3da9960225c4c864cc72679..c687ce0079dbe40c0c67b9ce9bfcc61343c5fe69 100644
--- a/app/code/core/Mage/Bundle/view/adminhtml/product/composite/fieldset/options/type/select.phtml
+++ b/app/code/core/Mage/Bundle/view/adminhtml/product/composite/fieldset/options/type/select.phtml
@@ -29,6 +29,7 @@
 <?php $_option      = $this->getOption(); ?>
 <?php $_selections  = $_option->getSelections(); ?>
 <?php $_default     = $_option->getDefaultSelection(); ?>
+<?php $_skipSaleableCheck = Mage::helper('Mage_Catalog_Helper_Product')->getSkipSaleableCheck(); ?>
 <?php list($_defaultQty, $_canChangeQty) = $this->_getDefaultValues(); ?>
 
 <dt>
@@ -46,7 +47,7 @@
         <select id="bundle-option-<?php echo $_option->getId() ?>" name="bundle_option[<?php echo $_option->getId() ?>]" class="bundle-option-<?php echo $_option->getId() ?><?php if ($_option->getRequired()) echo ' required-entry' ?> bundle-option-select change-container-classname" onchange="ProductConfigure.bundleControl.changeSelection(this)">
             <option value=""><?php echo $this->__('Choose a selection...') ?></option>
         <?php foreach ($_selections as $_selection): ?>
-            <option value="<?php echo $_selection->getSelectionId() ?>"<?php if ($this->_isSelected($_selection)) echo ' selected="selected"' ?><?php if (!$_selection->isSaleable()) echo ' disabled="disabled"' ?> price="<?php echo $this->getSelectionPrice($_selection) ?>" qtyId="bundle-option-<?php echo $_option->getId() ?>-qty-input"><?php echo $this->getSelectionTitlePrice($_selection, false) ?></option>
+            <option value="<?php echo $_selection->getSelectionId() ?>"<?php if ($this->_isSelected($_selection)) echo ' selected="selected"' ?><?php if (!$_selection->isSaleable() && !$_skipSaleableCheck) echo ' disabled="disabled"' ?> price="<?php echo $this->getSelectionPrice($_selection) ?>" qtyId="bundle-option-<?php echo $_option->getId() ?>-qty-input"><?php echo $this->getSelectionTitlePrice($_selection, false) ?></option>
         <?php endforeach; ?>
         </select>
     <?php endif; ?>
diff --git a/app/code/core/Mage/Bundle/view/adminhtml/product/edit/bundle/option.phtml b/app/code/core/Mage/Bundle/view/adminhtml/product/edit/bundle/option.phtml
index 0eddff17e2f2b48143f90f1dcbe61b681e4f2061..c71257693f730dc05b64aff2b706a9da5ee8b931 100644
--- a/app/code/core/Mage/Bundle/view/adminhtml/product/edit/bundle/option.phtml
+++ b/app/code/core/Mage/Bundle/view/adminhtml/product/edit/bundle/option.phtml
@@ -212,6 +212,7 @@ bOption = new Bundle.Option(optionTemplate);
 optionIndex = bOption.add(<?php echo $_option->toJson() ?>);
 <?php if ($_option->getSelections()):?>
     <?php foreach ($_option->getSelections() as $_selection): ?>
+    <?php $_selection->setName($this->escapeHtml($_selection->getName())); ?>
 bSelection.addRow(optionIndex, <?php echo $_selection->toJson() ?>);
     <?php endforeach; ?>
 <?php endif; ?>
diff --git a/app/code/core/Mage/Bundle/view/frontend/layout.xml b/app/code/core/Mage/Bundle/view/frontend/layout.xml
index b03fe0fcd2ec3a88a988661d4ab3303c27281637..2f8336d81a405bfa74854ee620425f119e0372d8 100644
--- a/app/code/core/Mage/Bundle/view/frontend/layout.xml
+++ b/app/code/core/Mage/Bundle/view/frontend/layout.xml
@@ -32,24 +32,12 @@
 Adding custom product price block
 -->
 
-    <catalog_category_default>
-        <reference name="product_list">
-            <action method="addPriceBlockType"><type>bundle</type><block>Mage_Bundle_Block_Catalog_Product_Price</block><template>catalog/product/price.phtml</template></action>
-        </reference>
-    </catalog_category_default>
-
     <catalog_category_view>
         <reference name="product_list">
             <action method="addPriceBlockType"><type>bundle</type><block>Mage_Bundle_Block_Catalog_Product_Price</block><template>catalog/product/price.phtml</template></action>
         </reference>
     </catalog_category_view>
 
-    <catalog_category_layered>
-        <reference name="product_list">
-            <action method="addPriceBlockType"><type>bundle</type><block>Mage_Bundle_Block_Catalog_Product_Price</block><template>catalog/product/price.phtml</template></action>
-        </reference>
-    </catalog_category_layered>
-
     <catalog_product_compare_index>
         <reference name="catalog.compare.list">
             <action method="addPriceBlockType"><type>bundle</type><block>Mage_Bundle_Block_Catalog_Product_Price</block><template>catalog/product/price.phtml</template></action>
@@ -92,12 +80,6 @@ Adding custom product price block
         </reference>
     </default>
 
-    <wishlist_index_index>
-        <reference name="customer.wishlist">
-            <action method="addOptionsRenderCfg"><type>bundle</type><helper>Mage_Bundle_Helper_Catalog_Product_Configuration</helper></action>
-        </reference>
-    </wishlist_index_index>
-
     <catalog_product_view>
         <reference name="catalog.product.related">
             <action method="addPriceBlockType"><type>bundle</type><block>Mage_Bundle_Block_Catalog_Product_Price</block><template>catalog/product/price.phtml</template></action>
@@ -108,12 +90,12 @@ Adding custom product price block
 Partof block for simple products
 -->
 
-   <PRODUCT_TYPE_simple>
+   <catalog_product_view_type_simple>
         <reference name="product.info.upsell">
             <action method="addPriceBlockType"><type>bundle</type><block>Mage_Bundle_Block_Catalog_Product_Price</block><template>catalog/product/price.phtml</template></action>
             <action method="setItemLimit"><type>bundle</type><limit>4</limit></action>
         </reference>
-    </PRODUCT_TYPE_simple>
+    </catalog_product_view_type_simple>
 
 <!--
 Shopping cart item renderer (sidebar)
@@ -143,7 +125,7 @@ Onepage Checkout Review Page
 -->
 
     <checkout_onepage_review>
-        <reference name="root">
+        <reference name="order_review">
             <action method="addItemRender"><type>bundle</type><block>Mage_Bundle_Block_Checkout_Cart_Item_Renderer</block><template>Mage_Checkout::onepage/review/item.phtml</template></action>
         </reference>
     </checkout_onepage_review>
@@ -186,7 +168,7 @@ Onepage Checkout Review Page
         </reference>
     </paypaluk_express_review>
     <paypaluk_express_review_details>
-        <reference name="root">
+        <reference name="order_review">
             <action method="addItemRender"><type>bundle</type><block>Mage_Bundle_Block_Checkout_Cart_Item_Renderer</block><template>Mage_Checkout::onepage/review/item.phtml</template></action>
         </reference>
     </paypaluk_express_review_details>
@@ -204,7 +186,7 @@ Onepage Checkout Review Page
 Additional block for bundle product type
 -->
 
-    <PRODUCT_TYPE_bundle translate="label" module="Mage_Bundle">
+    <catalog_product_view_type_bundle translate="label" module="Mage_Bundle" type="page" parent="catalog_product_view">
         <label>Catalog Product View (Bundle)</label>
         <reference name="head">
             <action method="addJs"><file>Mage_Bundle::bundle.js</file></action>
@@ -229,12 +211,12 @@ Additional block for bundle product type
         <reference name="product.info.options.wrapper.bottom">
             <remove name="product.tierprices" />
             <block type="Mage_Bundle_Block_Catalog_Product_View" name="bundle.tierprices" as="tierprices" before="-" template="catalog/product/view/tierprices.phtml"/>
-            <block type="Mage_CatalogInventory_Block_Qtyincrements" name="product.info.extrahint" as="extrahint" template="qtyincrements.phtml"/>
+            <block type="Mage_CatalogInventory_Block_Qtyincrements" name="product.info.qtyincrements" before="-" template="qtyincrements.phtml"/>
         </reference>
         <reference name="product.clone_prices">
             <action method="addPriceBlockType"><type>bundle</type><block>Mage_Bundle_Block_Catalog_Product_Price</block><template>catalog/product/view/price.phtml</template></action>
         </reference>
-    </PRODUCT_TYPE_bundle>
+    </catalog_product_view_type_bundle>
 
     <sales_order_view>
         <reference name="order_items">
diff --git a/app/code/core/Mage/Captcha/Model/Resource/Log.php b/app/code/core/Mage/Captcha/Model/Resource/Log.php
index 9a9490611cdd64d738696dff067675c455ba60f9..a834f12897fd9150ded3f9a9dc379e9e5a20c65a 100755
--- a/app/code/core/Mage/Captcha/Model/Resource/Log.php
+++ b/app/code/core/Mage/Captcha/Model/Resource/Log.php
@@ -37,6 +37,7 @@ class Mage_Captcha_Model_Resource_Log extends Mage_Core_Model_Resource_Db_Abstra
      * Type Remote Address
      */
     const TYPE_REMOTE_ADDRESS = 1;
+
     /**
      * Type User Login Name
      */
@@ -48,7 +49,7 @@ class Mage_Captcha_Model_Resource_Log extends Mage_Core_Model_Resource_Db_Abstra
      */
     protected function _construct()
     {
-        $this->_init('captcha_log', array('type','value'));
+        $this->_setMainTable('captcha_log');
     }
 
     /**
diff --git a/app/code/core/Mage/Captcha/view/frontend/layout.xml b/app/code/core/Mage/Captcha/view/frontend/layout.xml
index 8de21d6a6a17aeeeba71fd9ae9c86e9260079539..a3a1d146576dd4c9677b2c103bd0b3ae34746d38 100644
--- a/app/code/core/Mage/Captcha/view/frontend/layout.xml
+++ b/app/code/core/Mage/Captcha/view/frontend/layout.xml
@@ -28,7 +28,7 @@
 <layout version="0.1.0">
     <customer_account_login>
         <reference name="customer_form_login">
-            <block type="Mage_Core_Block_Text_List" name="form.additional.info">
+            <container name="form.additional.info" label="Form Additional Info">
                 <block type="Mage_Captcha_Block_Captcha" name="captcha">
                     <reference name="head">
                         <action method="addJs"><file>mage/captcha.js</file></action>
@@ -37,12 +37,12 @@
                     <action method="setImgWidth"><width>230</width></action>
                     <action method="setImgHeight"><width>50</width></action>
                 </block>
-            </block>
+            </container>
         </reference>
     </customer_account_login>
     <customer_account_forgotpassword>
         <reference name="forgotPassword">
-            <block type="Mage_Core_Block_Text_List" name="form.additional.info">
+            <container name="form.additional.info" label="Form Additional Info">
                 <block type="Mage_Captcha_Block_Captcha" name="captcha">
                     <reference name="head">
                         <action method="addJs"><file>mage/captcha.js</file></action>
@@ -51,12 +51,12 @@
                     <action method="setImgWidth"><width>230</width></action>
                     <action method="setImgHeight"><width>50</width></action>
                 </block>
-            </block>
+            </container>
         </reference>
     </customer_account_forgotpassword>
     <customer_account_create>
         <reference name="customer_form_register">
-            <block type="Mage_Core_Block_Text_List" name="form.additional.info">
+            <container name="form.additional.info" label="Form Additional Info">
                 <block type="Mage_Captcha_Block_Captcha" name="captcha">
                     <reference name="head">
                         <action method="addJs"><file>mage/captcha.js</file></action>
@@ -65,12 +65,12 @@
                     <action method="setImgWidth"><width>230</width></action>
                     <action method="setImgHeight"><width>50</width></action>
                 </block>
-            </block>
+            </container>
         </reference>
     </customer_account_create>
     <checkout_onepage_index>
         <reference name="checkout.onepage.login">
-            <block type="Mage_Core_Block_Text_List" name="form.additional.info">
+            <container name="form.additional.info" label="Form Additional Info">
                 <block type="Mage_Captcha_Block_Captcha" name="captcha">
                     <reference name="head">
                         <action method="addJs"><file>mage/captcha.js</file></action>
@@ -79,10 +79,10 @@
                     <action method="setImgWidth"><width>230</width></action>
                     <action method="setImgHeight"><width>50</width></action>
                 </block>
-            </block>
+            </container>
         </reference>
         <reference name="checkout.onepage.billing">
-            <block type="Mage_Core_Block_Text_List" name="form.additional.info">
+            <container name="form.additional.info" label="Form Additional Info">
                 <block type="Mage_Captcha_Block_Captcha" name="captcha.guest.checkout">
                     <reference name="head">
                         <action method="addJs"><file>mage/captcha.js</file></action>
@@ -99,7 +99,7 @@
                     <action method="setImgWidth"><width>230</width></action>
                     <action method="setImgHeight"><width>50</width></action>
                 </block>
-            </block>
+            </container>
         </reference>
     </checkout_onepage_index>
 </layout>
diff --git a/app/code/core/Mage/Captcha/view/frontend/zend.phtml b/app/code/core/Mage/Captcha/view/frontend/zend.phtml
index f6732e8972db12621e4ec6bbdc33fe614410a3d3..8940366f4733fa1e45dcc4ecaeae90fbadfbd0bf 100644
--- a/app/code/core/Mage/Captcha/view/frontend/zend.phtml
+++ b/app/code/core/Mage/Captcha/view/frontend/zend.phtml
@@ -38,10 +38,10 @@
     <div class="captcha-image" id="captcha-image-box-<?php echo $this->getFormId()?>">
         <script type="text/javascript">
         //<![CDATA[
-            var captcha_<?php echo $this->getFormId()?> = new Captcha('<?php echo $this->getRefreshUrl() ?>', '<?php echo $this->getFormId() ?>');
+            var captcha_image_<?php echo $this->getFormId()?> = new Captcha('<?php echo $this->getRefreshUrl() ?>', '<?php echo $this->getFormId() ?>');
         //]]>
         </script>
-        <img id="catpcha-reload" class="captcha-reload" src="<?php echo $this->getSkinUrl('Mage_Captcha::reload.png') ?>" alt="<?php echo $this->__('Reload captcha') ?>" onclick="captcha_<?php echo $this->getFormId()?>.refresh(this)">
+        <img id="catpcha-reload" class="captcha-reload" src="<?php echo $this->getSkinUrl('Mage_Captcha::reload.png') ?>" alt="<?php echo $this->__('Reload captcha') ?>" onclick="captcha_image_<?php echo $this->getFormId()?>.refresh(this)">
         <img id="<?php echo $this->getFormId() ?>" class="captcha-img" height="<?php echo $this->getImgHeight() ?>" src="<?php echo $captcha->getImgSrc() ?>"/>
         <?php if ($captcha->isCaseSensitive()) :?>
         <div class="captcha-note">
diff --git a/app/code/core/Mage/Catalog/Block/Layer/Filter/Abstract.php b/app/code/core/Mage/Catalog/Block/Layer/Filter/Abstract.php
index 2708dfe3c127b8b913c4977841a36d24ebb0778b..a8de488a8a4e426c3a2d6e5c95c06ddb3a20b18a 100644
--- a/app/code/core/Mage/Catalog/Block/Layer/Filter/Abstract.php
+++ b/app/code/core/Mage/Catalog/Block/Layer/Filter/Abstract.php
@@ -47,6 +47,12 @@ abstract class Mage_Catalog_Block_Layer_Filter_Abstract extends Mage_Core_Block_
      */
     protected $_filterModelName;
 
+    /**
+     * Whether to display product count for layer navigation items
+     * @var bool
+     */
+    protected $_displayProductCount = null;
+
     /**
      * Initialize filter template
      *
@@ -126,6 +132,18 @@ abstract class Mage_Catalog_Block_Layer_Filter_Abstract extends Mage_Core_Block_
         return $this->_filter->getItemsCount();
     }
 
+    /**
+     * Getter for $_displayProductCount
+     * @return bool
+     */
+    public function shouldDisplayProductCount()
+    {
+        if ($this->_displayProductCount === null) {
+            $this->_displayProductCount = Mage::helper('Mage_Catalog_Helper_Data')->shouldDisplayProductCountOnLayer();
+        }
+        return $this->_displayProductCount;
+    }
+
     /**
      * Retrieve block html
      *
diff --git a/app/code/core/Mage/Catalog/Block/Layer/View.php b/app/code/core/Mage/Catalog/Block/Layer/View.php
index dd991f8cb6e7fc1554cd572b9ff942e73f6085f3..6254cb8e4019780ad10c281ff029c32bb7d13347 100644
--- a/app/code/core/Mage/Catalog/Block/Layer/View.php
+++ b/app/code/core/Mage/Catalog/Block/Layer/View.php
@@ -179,7 +179,7 @@ class Mage_Catalog_Block_Layer_View extends Mage_Core_Block_Template
 
         $filterableAttributes = $this->_getFilterableAttributes();
         foreach ($filterableAttributes as $attribute) {
-            $filters[] = $this->getChild($attribute->getAttributeCode() . '_filter');
+            $filters[] = $this->getChildBlock($attribute->getAttributeCode() . '_filter');
         }
 
         return $filters;
@@ -192,7 +192,7 @@ class Mage_Catalog_Block_Layer_View extends Mage_Core_Block_Template
      */
     protected function _getCategoryFilter()
     {
-        return $this->getChild('category_filter');
+        return $this->getChildBlock('category_filter');
     }
 
     /**
@@ -228,7 +228,7 @@ class Mage_Catalog_Block_Layer_View extends Mage_Core_Block_Template
      */
     protected function _getPriceFilter()
     {
-        return $this->getChild('_price_filter');
+        return $this->getChildBlock('_price_filter');
     }
 
     /**
@@ -238,6 +238,6 @@ class Mage_Catalog_Block_Layer_View extends Mage_Core_Block_Template
      */
     public function getClearUrl()
     {
-        return $this->getChild('layer_state')->getClearUrl();
+        return $this->getChildBlock('layer_state')->getClearUrl();
     }
 }
diff --git a/app/code/core/Mage/Catalog/Block/Product/List.php b/app/code/core/Mage/Catalog/Block/Product/List.php
index d2b02ce4d5456598afac9959f693336e30fd6a83..812db9f4fb6a7180278004a01a58020f03a96077 100644
--- a/app/code/core/Mage/Catalog/Block/Product/List.php
+++ b/app/code/core/Mage/Catalog/Block/Product/List.php
@@ -126,7 +126,7 @@ class Mage_Catalog_Block_Product_List extends Mage_Catalog_Block_Product_Abstrac
      */
     public function getMode()
     {
-        return $this->getChild('toolbar')->getCurrentMode();
+        return $this->getChildBlock('toolbar')->getCurrentMode();
     }
 
     /**
diff --git a/app/code/core/Mage/Catalog/Block/Product/List/Crosssell.php b/app/code/core/Mage/Catalog/Block/Product/List/Crosssell.php
index 4eea20cd68e1098e21edb013e192726c5ad22d35..051fcbc6474bd71678b0699130dfeb3786afa1fa 100644
--- a/app/code/core/Mage/Catalog/Block/Product/List/Crosssell.php
+++ b/app/code/core/Mage/Catalog/Block/Product/List/Crosssell.php
@@ -61,9 +61,8 @@ class Mage_Catalog_Block_Product_List_Crosssell extends Mage_Catalog_Block_Produ
 
         $this->_itemCollection = $product->getCrossSellProductCollection()
             ->addAttributeToSelect(Mage::getSingleton('Mage_Catalog_Model_Config')->getProductAttributes())
-            ->addAttributeToSort('position', 'asc')
-            ->addStoreFilter()
-            ->setVisibility(Mage::getSingleton('Mage_Catalog_Model_Product_Visibility')->getVisibleInCatalogIds());
+            ->setPositionOrder()
+            ->addStoreFilter();
 
         $this->_itemCollection->load();
 
diff --git a/app/code/core/Mage/Catalog/Block/Product/List/Related.php b/app/code/core/Mage/Catalog/Block/Product/List/Related.php
index cd8b13f1ad0c8c99323c41b2d447083f849d713c..b0fa5a01ce5b7d8e9a96d9f4957c96667702d59f 100644
--- a/app/code/core/Mage/Catalog/Block/Product/List/Related.php
+++ b/app/code/core/Mage/Catalog/Block/Product/List/Related.php
@@ -50,7 +50,7 @@ class Mage_Catalog_Block_Product_List_Related extends Mage_Catalog_Block_Product
 
         $this->_itemCollection = $product->getRelatedProductCollection()
             ->addAttributeToSelect('required_options')
-            ->addAttributeToSort('position', Varien_Db_Select::SQL_ASC)
+            ->setPositionOrder()
             ->addStoreFilter()
         ;
 
diff --git a/app/code/core/Mage/Catalog/Block/Product/List/Toolbar.php b/app/code/core/Mage/Catalog/Block/Product/List/Toolbar.php
index 0cd04af31b4359fa7ddd7b9662339bd32451b46c..fd1ce252b11f28bdcc7036de0692454227699730 100644
--- a/app/code/core/Mage/Catalog/Block/Product/List/Toolbar.php
+++ b/app/code/core/Mage/Catalog/Block/Product/List/Toolbar.php
@@ -805,7 +805,7 @@ class Mage_Catalog_Block_Product_List_Toolbar extends Mage_Core_Block_Template
      */
     public function getPagerHtml()
     {
-        $pagerBlock = $this->getChild('product_list_toolbar_pager');
+        $pagerBlock = $this->getChildBlock('product_list_toolbar_pager');
 
         if ($pagerBlock instanceof Varien_Object) {
 
diff --git a/app/code/core/Mage/Catalog/Block/Product/List/Upsell.php b/app/code/core/Mage/Catalog/Block/Product/List/Upsell.php
index 4f3b7311b51bf8ba00c83996a979057f2b5cb402..6201fc32eac9205b7bf1caf865cfa5c71bee0873 100644
--- a/app/code/core/Mage/Catalog/Block/Product/List/Upsell.php
+++ b/app/code/core/Mage/Catalog/Block/Product/List/Upsell.php
@@ -54,7 +54,7 @@ class Mage_Catalog_Block_Product_List_Upsell extends Mage_Catalog_Block_Product_
         $product = Mage::registry('product');
         /* @var $product Mage_Catalog_Model_Product */
         $this->_itemCollection = $product->getUpSellProductCollection()
-            ->addAttributeToSort('position', Varien_Db_Select::SQL_ASC)
+            ->setPositionOrder()
             ->addStoreFilter()
         ;
         if (Mage::helper('Mage_Catalog_Helper_Data')->isModuleEnabled('Mage_Checkout')) {
diff --git a/app/code/core/Mage/Catalog/Block/Product/Price.php b/app/code/core/Mage/Catalog/Block/Product/Price.php
index 672bb8bfd7087fa552db0ec058d3f82bc4ad2a66..11f823c90b29878e4c623e9142530345b513b028 100644
--- a/app/code/core/Mage/Catalog/Block/Product/Price.php
+++ b/app/code/core/Mage/Catalog/Block/Product/Price.php
@@ -36,6 +36,11 @@ class Mage_Catalog_Block_Product_Price extends Mage_Core_Block_Template
     protected $_priceDisplayType = null;
     protected $_idSuffix = '';
 
+    /**
+     * Retrieve product
+     *
+     * @return Mage_Catalog_Model_Product
+     */
     public function getProduct()
     {
         $product = $this->_getData('product');
diff --git a/app/code/core/Mage/Catalog/Block/Product/View/Additional.php b/app/code/core/Mage/Catalog/Block/Product/View/Additional.php
index 14beb1bf0e2b39128adcb5e90cd6c426cc190b8f..ce4edffaaf2007240010ce0e8f4092451bac30da 100644
--- a/app/code/core/Mage/Catalog/Block/Product/View/Additional.php
+++ b/app/code/core/Mage/Catalog/Block/Product/View/Additional.php
@@ -47,12 +47,9 @@ class Mage_Catalog_Block_Product_View_Additional extends Mage_Core_Block_Templat
     {
         if (is_null($this->_list)) {
             $this->_list = array();
-            foreach ($this->getSortedChildren() as $name) {
-                $block = $this->getLayout()->getBlock($name);
-                if (!$block) {
-                    Mage::exception('Mage_Catalog', Mage::helper('Mage_Catalog_Helper_Data')->__('Invalid block: %s.', $name));
-                }
-                $this->_list[] = $block->toHtml();
+            $layout = $this->getLayout();
+            foreach ($this->getChildNames() as $name) {
+                $this->_list[] = $layout->renderElement($name);
             }
         }
         return $this->_list;
diff --git a/app/code/core/Mage/Catalog/Block/Product/View/Type/Configurable.php b/app/code/core/Mage/Catalog/Block/Product/View/Type/Configurable.php
index 01c98a965732223756198e83ea49674794552aac..e7d96b992501d5c60fc6f1d0e83f40d4892de44d 100644
--- a/app/code/core/Mage/Catalog/Block/Product/View/Type/Configurable.php
+++ b/app/code/core/Mage/Catalog/Block/Product/View/Type/Configurable.php
@@ -87,10 +87,11 @@ class Mage_Catalog_Block_Product_View_Type_Configurable extends Mage_Catalog_Blo
     {
         if (!$this->hasAllowProducts()) {
             $products = array();
+            $skipSaleableCheck = Mage::helper('Mage_Catalog_Helper_Product')->getSkipSaleableCheck();
             $allProducts = $this->getProduct()->getTypeInstance()
-                ->getUsedProducts($this->getProduct());
+                ->getUsedProducts($this->getProduct(), null);
             foreach ($allProducts as $product) {
-                if ($product->isSaleable()) {
+                if ($product->isSaleable() || $skipSaleableCheck) {
                     $products[] = $product;
                 }
             }
diff --git a/app/code/core/Mage/Catalog/Helper/Data.php b/app/code/core/Mage/Catalog/Helper/Data.php
index 1ec0743468e9d9cbb0e1c57962217a91821bb99a..13b32d1c905f607af4ef30210ac4e8bff628e1cc 100644
--- a/app/code/core/Mage/Catalog/Helper/Data.php
+++ b/app/code/core/Mage/Catalog/Helper/Data.php
@@ -41,6 +41,7 @@ class Mage_Catalog_Helper_Data extends Mage_Core_Helper_Abstract
     const CONFIG_USE_STATIC_URLS           = 'cms/wysiwyg/use_static_urls_in_catalog';
     const CONFIG_PARSE_URL_DIRECTIVES      = 'catalog/frontend/parse_url_directives';
     const XML_PATH_CONTENT_TEMPLATE_FILTER = 'global/catalog/content/tempate_filter';
+    const XML_PATH_DISPLAY_PRODUCT_COUNT   = 'catalog/layered_navigation/display_product_count';
 
     /**
      * Minimum advertise price constants
@@ -451,4 +452,14 @@ class Mage_Catalog_Helper_Data extends Mage_Core_Helper_Abstract
             Mage_Catalog_Model_Product_Attribute_Source_Msrp_Type::TYPE_ON_GESTURE
         );
     }
+
+    /**
+     * Whether to display items count for each filter option
+     * @param int $storeId Store view ID
+     * @return bool
+     */
+    public function shouldDisplayProductCountOnLayer($storeId = null)
+    {
+        return Mage::getStoreConfigFlag(self::XML_PATH_DISPLAY_PRODUCT_COUNT, $storeId);
+    }
 }
diff --git a/app/code/core/Mage/Catalog/Helper/Product.php b/app/code/core/Mage/Catalog/Helper/Product.php
index 378b76917063384c3b7473c9d31a97e7a1568340..31fe39a725c9122c696f4b24ace406082793bbf8 100644
--- a/app/code/core/Mage/Catalog/Helper/Product.php
+++ b/app/code/core/Mage/Catalog/Helper/Product.php
@@ -1,5 +1,5 @@
-<?php
-/**
+<?php
+/**
  * Magento
  *
  * NOTICE OF LICENSE
@@ -17,423 +17,455 @@
  * 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
+ *
+ * @category    Mage
+ * @package     Mage_Catalog
  * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
- */
-
-/**
- * Catalog category helper
- *
- * @author      Magento Core Team <core@magentocommerce.com>
- */
-class Mage_Catalog_Helper_Product extends Mage_Core_Helper_Url
-{
-    const XML_PATH_PRODUCT_URL_SUFFIX           = 'catalog/seo/product_url_suffix';
-    const XML_PATH_PRODUCT_URL_USE_CATEGORY     = 'catalog/seo/product_use_categories';
-    const XML_PATH_USE_PRODUCT_CANONICAL_TAG    = 'catalog/seo/product_canonical_tag';
-
-    /**
-     * Cache for product rewrite suffix
-     *
-     * @var array
-     */
-    protected $_productUrlSuffix = array();
-
-    protected $_statuses;
-
-    protected $_priceBlock;
-
-    /**
-     * Retrieve product view page url
-     *
-     * @param   mixed $product
-     * @return  string
-     */
-    public function getProductUrl($product)
-    {
-        if ($product instanceof Mage_Catalog_Model_Product) {
-            return $product->getProductUrl();
-        }
-        elseif (is_numeric($product)) {
-            return Mage::getModel('Mage_Catalog_Model_Product')->load($product)->getProductUrl();
-        }
-        return false;
-    }
-
-    /**
-     * Retrieve product price
-     *
-     * @param   Mage_Catalog_Model_Product $product
-     * @return  float
-     */
-    public function getPrice($product)
-    {
-        return $product->getPrice();
-    }
-
-    /**
-     * Retrieve product final price
-     *
-     * @param   Mage_Catalog_Model_Product $product
-     * @return  float
-     */
-    public function getFinalPrice($product)
-    {
-        return $product->getFinalPrice();
-    }
-
-    /**
-     * Retrieve base image url
-     *
-     * @return string
-     */
-    public function getImageUrl($product)
-    {
-        $url = false;
-        if (!$product->getImage()) {
-            $url = Mage::getDesign()->getSkinUrl('Mage_Catalog::images/product/placeholder/image.jpg');
-        }
-        elseif ($attribute = $product->getResource()->getAttribute('image')) {
-            $url = $attribute->getFrontend()->getUrl($product);
-        }
-        return $url;
-    }
-
-    /**
-     * Retrieve small image url
-     *
-     * @return unknown
-     */
-    public function getSmallImageUrl($product)
-    {
-        $url = false;
-        if (!$product->getSmallImage()) {
-            $url = Mage::getDesign()->getSkinUrl('Mage_Catalog::images/product/placeholder/small_image.jpg');
-        }
-        elseif ($attribute = $product->getResource()->getAttribute('small_image')) {
-            $url = $attribute->getFrontend()->getUrl($product);
-        }
-        return $url;
-    }
-
-    /**
-     * Retrieve thumbnail image url
-     *
-     * @return unknown
-     */
-    public function getThumbnailUrl($product)
-    {
-        return '';
-    }
-
-    public function getEmailToFriendUrl($product)
-    {
-        $categoryId = null;
-        if ($category = Mage::registry('current_category')) {
-            $categoryId = $category->getId();
-        }
-        return $this->_getUrl('sendfriend/product/send', array(
-            'id' => $product->getId(),
-            'cat_id' => $categoryId
-        ));
-    }
-
-    public function getStatuses()
-    {
-        if(is_null($this->_statuses)) {
-            $this->_statuses = array();//Mage::getModel('Mage_Catalog_Model_Product_Status')->getResourceCollection()->load();
-        }
-
-        return $this->_statuses;
-    }
-
-    /**
-     * Check if a product can be shown
-     *
-     * @param  Mage_Catalog_Model_Product|int $product
-     * @return boolean
-     */
-    public function canShow($product, $where = 'catalog')
-    {
-        if (is_int($product)) {
-            $product = Mage::getModel('Mage_Catalog_Model_Product')->load($product);
-        }
-
-        /* @var $product Mage_Catalog_Model_Product */
-
-        if (!$product->getId()) {
-            return false;
-        }
-
-        return $product->isVisibleInCatalog() && $product->isVisibleInSiteVisibility();
-    }
-
-    /**
-     * Retrieve product rewrite sufix for store
-     *
-     * @param int $storeId
-     * @return string
-     */
-    public function getProductUrlSuffix($storeId = null)
-    {
-        if (is_null($storeId)) {
-            $storeId = Mage::app()->getStore()->getId();
-        }
-
-        if (!isset($this->_productUrlSuffix[$storeId])) {
-            $this->_productUrlSuffix[$storeId] = Mage::getStoreConfig(self::XML_PATH_PRODUCT_URL_SUFFIX, $storeId);
-        }
-        return $this->_productUrlSuffix[$storeId];
-    }
-
-    /**
-     * Check if <link rel="canonical"> can be used for product
-     *
-     * @param $store
-     * @return bool
-     */
-    public function canUseCanonicalTag($store = null)
-    {
-        return Mage::getStoreConfig(self::XML_PATH_USE_PRODUCT_CANONICAL_TAG, $store);
-    }
-
-    /**
-     * Return information array of product attribute input types
-     * Only a small number of settings returned, so we won't break anything in current dataflow
-     * As soon as development process goes on we need to add there all possible settings
-     *
-     * @param string $inputType
-     * @return array
-     */
-    public function getAttributeInputTypes($inputType = null)
-    {
-        /**
-        * @todo specify there all relations for properties depending on input type
-        */
-        $inputTypes = array(
-            'multiselect'   => array(
-                'backend_model'     => 'Mage_Eav_Model_Entity_Attribute_Backend_Array'
-            ),
-            'boolean'       => array(
-                'source_model'      => 'Mage_Eav_Model_Entity_Attribute_Source_Boolean'
-            )
-        );
-
-        if (is_null($inputType)) {
-            return $inputTypes;
-        } else if (isset($inputTypes[$inputType])) {
-            return $inputTypes[$inputType];
-        }
-        return array();
-    }
-
-    /**
-     * Return default attribute backend model by input type
-     *
-     * @param string $inputType
-     * @return string|null
-     */
-    public function getAttributeBackendModelByInputType($inputType)
-    {
-        $inputTypes = $this->getAttributeInputTypes();
-        if (!empty($inputTypes[$inputType]['backend_model'])) {
-            return $inputTypes[$inputType]['backend_model'];
-        }
-        return null;
-    }
-
-    /**
-     * Return default attribute source model by input type
-     *
-     * @param string $inputType
-     * @return string|null
-     */
-    public function getAttributeSourceModelByInputType($inputType)
-    {
-        $inputTypes = $this->getAttributeInputTypes();
-        if (!empty($inputTypes[$inputType]['source_model'])) {
-            return $inputTypes[$inputType]['source_model'];
-        }
-        return null;
-    }
-
-    /**
-     * Inits product to be used for product controller actions and layouts
-     * $params can have following data:
-     *   'category_id' - id of category to check and append to product as current.
-     *     If empty (except FALSE) - will be guessed (e.g. from last visited) to load as current.
-     *
-     * @param int $productId
-     * @param Mage_Core_Controller_Front_Action $controller
-     * @param Varien_Object $params
-     *
-     * @return false|Mage_Catalog_Model_Product
-     */
-    public function initProduct($productId, $controller, $params = null)
-    {
-        // Prepare data for routine
-        if (!$params) {
-            $params = new Varien_Object();
-        }
-
-        // Init and load product
-        Mage::dispatchEvent('catalog_controller_product_init_before', array(
-            'controller_action' => $controller,
-            'params' => $params,
-        ));
-
-        if (!$productId) {
-            return false;
-        }
-
-        $product = Mage::getModel('Mage_Catalog_Model_Product')
-            ->setStoreId(Mage::app()->getStore()->getId())
-            ->load($productId);
-
-        if (!$this->canShow($product)) {
-            return false;
-        }
-        if (!in_array(Mage::app()->getStore()->getWebsiteId(), $product->getWebsiteIds())) {
-            return false;
-        }
-
-        // Load product current category
-        $categoryId = $params->getCategoryId();
-        if (!$categoryId && ($categoryId !== false)) {
-            $lastId = Mage::getSingleton('Mage_Catalog_Model_Session')->getLastVisitedCategoryId();
-            if ($product->canBeShowInCategory($lastId)) {
-                $categoryId = $lastId;
-            }
-        }
-
-        if ($categoryId) {
-            $category = Mage::getModel('Mage_Catalog_Model_Category')->load($categoryId);
-            $product->setCategory($category);
-            Mage::register('current_category', $category);
-        }
-
-        // Register current data and dispatch final events
-        Mage::register('current_product', $product);
-        Mage::register('product', $product);
-
-        try {
-            Mage::dispatchEvent('catalog_controller_product_init', array('product' => $product));
-            Mage::dispatchEvent('catalog_controller_product_init_after',
-                            array('product' => $product,
-                                'controller_action' => $controller
-                            )
-            );
-        } catch (Mage_Core_Exception $e) {
-            Mage::logException($e);
-            return false;
-        }
-
-        return $product;
-    }
-
-    /**
-     * Prepares product options by buyRequest: retrieves values and assigns them as default.
-     * Also parses and adds product management related values - e.g. qty
-     *
-     * @param  Mage_Catalog_Model_Product $product
-     * @param  Varien_Object $buyRequest
-     * @return Mage_Catalog_Helper_Product
-     */
-    public function prepareProductOptions($product, $buyRequest)
-    {
-        $optionValues = $product->processBuyRequest($buyRequest);
-        $optionValues->setQty($buyRequest->getQty());
-        $product->setPreconfiguredValues($optionValues);
-
-        return $this;
-    }
-
-    /**
-     * Process $buyRequest and sets its options before saving configuration to some product item.
-     * This method is used to attach additional parameters to processed buyRequest.
-     *
-     * $params holds parameters of what operation must be performed:
-     * - 'current_config', Varien_Object or array - current buyRequest that configures product in this item,
-     *   used to restore currently attached files
-     * - 'files_prefix': string[a-z0-9_] - prefix that was added at frontend to names of file inputs,
-     *   so they won't intersect with other submitted options
-     *
-     * @param Varien_Object|array $buyRequest
-     * @param Varien_Object|array $params
-     * @return Varien_Object
-     */
-    public function addParamsToBuyRequest($buyRequest, $params)
-    {
-        if (is_array($buyRequest)) {
-            $buyRequest = new Varien_Object($buyRequest);
-        }
-        if (is_array($params)) {
-            $params = new Varien_Object($params);
-        }
-
-
-        // Ensure that currentConfig goes as Varien_Object - for easier work with it later
-        $currentConfig = $params->getCurrentConfig();
-        if ($currentConfig) {
-            if (is_array($currentConfig)) {
-                $params->setCurrentConfig(new Varien_Object($currentConfig));
-            } else if (!($currentConfig instanceof Varien_Object)) {
-                $params->unsCurrentConfig();
-            }
-        }
-
-        /*
-         * Notice that '_processing_params' must always be object to protect processing forged requests
-         * where '_processing_params' comes in $buyRequest as array from user input
-         */
-        $processingParams = $buyRequest->getData('_processing_params');
-        if (!$processingParams || !($processingParams instanceof Varien_Object)) {
-            $processingParams = new Varien_Object();
-            $buyRequest->setData('_processing_params', $processingParams);
-        }
-        $processingParams->addData($params->getData());
-
-        return $buyRequest;
-    }
-
-    /**
-     * Return loaded product instance
-     *
-     * @param  int|string $productId (SKU or ID)
-     * @param  int $store
-     * @param  string $identifierType
-     * @return Mage_Catalog_Model_Product
-     */
-    public function getProduct($productId, $store, $identifierType = null)
-    {
-        /** @var $product Mage_Catalog_Model_Product */
-        $product = Mage::getModel('Mage_Catalog_Model_Product')->setStoreId(Mage::app()->getStore($store)->getId());
-
-        $expectedIdType = false;
-        if ($identifierType === null) {
-            if (is_string($productId) && !preg_match("/^[+-]?[1-9][0-9]*$|^0$/", $productId)) {
-                $expectedIdType = 'sku';
-            }
-        }
-
-        if ($identifierType == 'sku' || $expectedIdType == 'sku') {
-            $idBySku = $product->getIdBySku($productId);
-            if ($idBySku) {
-                $productId = $idBySku;
-            } else if ($identifierType == 'sku') {
-                // Return empty product because it was not found by originally specified SKU identifier
-                return $product;
-            }
-        }
-
-        if ($productId && is_numeric($productId)) {
-            $product->load((int) $productId);
-        }
-
-        return $product;
-    }
-
-}
\ No newline at end of file
+ */
+
+/**
+ * Catalog category helper
+ *
+ * @author      Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_Catalog_Helper_Product extends Mage_Core_Helper_Url
+{
+    const XML_PATH_PRODUCT_URL_SUFFIX           = 'catalog/seo/product_url_suffix';
+    const XML_PATH_PRODUCT_URL_USE_CATEGORY     = 'catalog/seo/product_use_categories';
+    const XML_PATH_USE_PRODUCT_CANONICAL_TAG    = 'catalog/seo/product_canonical_tag';
+
+    /**
+     * Flag that shows if Magento has to check product to be saleable (enabled and/or inStock)
+     *
+     * @var boolean
+     */
+    protected $_skipSaleableCheck = false;
+
+    /**
+     * Cache for product rewrite suffix
+     *
+     * @var array
+     */
+    protected $_productUrlSuffix = array();
+
+    protected $_statuses;
+
+    protected $_priceBlock;
+
+    /**
+     * Retrieve product view page url
+     *
+     * @param   mixed $product
+     * @return  string
+     */
+    public function getProductUrl($product)
+    {
+        if ($product instanceof Mage_Catalog_Model_Product) {
+            return $product->getProductUrl();
+        }
+        elseif (is_numeric($product)) {
+            return Mage::getModel('Mage_Catalog_Model_Product')->load($product)->getProductUrl();
+        }
+        return false;
+    }
+
+    /**
+     * Retrieve product price
+     *
+     * @param   Mage_Catalog_Model_Product $product
+     * @return  float
+     */
+    public function getPrice($product)
+    {
+        return $product->getPrice();
+    }
+
+    /**
+     * Retrieve product final price
+     *
+     * @param   Mage_Catalog_Model_Product $product
+     * @return  float
+     */
+    public function getFinalPrice($product)
+    {
+        return $product->getFinalPrice();
+    }
+
+    /**
+     * Retrieve base image url
+     *
+     * @return string
+     */
+    public function getImageUrl($product)
+    {
+        $url = false;
+        if (!$product->getImage()) {
+            $url = Mage::getDesign()->getSkinUrl('Mage_Catalog::images/product/placeholder/image.jpg');
+        }
+        elseif ($attribute = $product->getResource()->getAttribute('image')) {
+            $url = $attribute->getFrontend()->getUrl($product);
+        }
+        return $url;
+    }
+
+    /**
+     * Retrieve small image url
+     *
+     * @return unknown
+     */
+    public function getSmallImageUrl($product)
+    {
+        $url = false;
+        if (!$product->getSmallImage()) {
+            $url = Mage::getDesign()->getSkinUrl('Mage_Catalog::images/product/placeholder/small_image.jpg');
+        }
+        elseif ($attribute = $product->getResource()->getAttribute('small_image')) {
+            $url = $attribute->getFrontend()->getUrl($product);
+        }
+        return $url;
+    }
+
+    /**
+     * Retrieve thumbnail image url
+     *
+     * @return unknown
+     */
+    public function getThumbnailUrl($product)
+    {
+        return '';
+    }
+
+    public function getEmailToFriendUrl($product)
+    {
+        $categoryId = null;
+        if ($category = Mage::registry('current_category')) {
+            $categoryId = $category->getId();
+        }
+        return $this->_getUrl('sendfriend/product/send', array(
+            'id' => $product->getId(),
+            'cat_id' => $categoryId
+        ));
+    }
+
+    public function getStatuses()
+    {
+        if(is_null($this->_statuses)) {
+            $this->_statuses = array();//Mage::getModel('Mage_Catalog_Model_Product_Status')->getResourceCollection()->load();
+        }
+
+        return $this->_statuses;
+    }
+
+    /**
+     * Check if a product can be shown
+     *
+     * @param  Mage_Catalog_Model_Product|int $product
+     * @return boolean
+     */
+    public function canShow($product, $where = 'catalog')
+    {
+        if (is_int($product)) {
+            $product = Mage::getModel('Mage_Catalog_Model_Product')->load($product);
+        }
+
+        /* @var $product Mage_Catalog_Model_Product */
+
+        if (!$product->getId()) {
+            return false;
+        }
+
+        return $product->isVisibleInCatalog() && $product->isVisibleInSiteVisibility();
+    }
+
+    /**
+     * Retrieve product rewrite sufix for store
+     *
+     * @param int $storeId
+     * @return string
+     */
+    public function getProductUrlSuffix($storeId = null)
+    {
+        if (is_null($storeId)) {
+            $storeId = Mage::app()->getStore()->getId();
+        }
+
+        if (!isset($this->_productUrlSuffix[$storeId])) {
+            $this->_productUrlSuffix[$storeId] = Mage::getStoreConfig(self::XML_PATH_PRODUCT_URL_SUFFIX, $storeId);
+        }
+        return $this->_productUrlSuffix[$storeId];
+    }
+
+    /**
+     * Check if <link rel="canonical"> can be used for product
+     *
+     * @param $store
+     * @return bool
+     */
+    public function canUseCanonicalTag($store = null)
+    {
+        return Mage::getStoreConfig(self::XML_PATH_USE_PRODUCT_CANONICAL_TAG, $store);
+    }
+
+    /**
+     * Return information array of product attribute input types
+     * Only a small number of settings returned, so we won't break anything in current dataflow
+     * As soon as development process goes on we need to add there all possible settings
+     *
+     * @param string $inputType
+     * @return array
+     */
+    public function getAttributeInputTypes($inputType = null)
+    {
+        /**
+        * @todo specify there all relations for properties depending on input type
+        */
+        $inputTypes = array(
+            'multiselect'   => array(
+                'backend_model'     => 'Mage_Eav_Model_Entity_Attribute_Backend_Array'
+            ),
+            'boolean'       => array(
+                'source_model'      => 'Mage_Eav_Model_Entity_Attribute_Source_Boolean'
+            )
+        );
+
+        if (is_null($inputType)) {
+            return $inputTypes;
+        } else if (isset($inputTypes[$inputType])) {
+            return $inputTypes[$inputType];
+        }
+        return array();
+    }
+
+    /**
+     * Return default attribute backend model by input type
+     *
+     * @param string $inputType
+     * @return string|null
+     */
+    public function getAttributeBackendModelByInputType($inputType)
+    {
+        $inputTypes = $this->getAttributeInputTypes();
+        if (!empty($inputTypes[$inputType]['backend_model'])) {
+            return $inputTypes[$inputType]['backend_model'];
+        }
+        return null;
+    }
+
+    /**
+     * Return default attribute source model by input type
+     *
+     * @param string $inputType
+     * @return string|null
+     */
+    public function getAttributeSourceModelByInputType($inputType)
+    {
+        $inputTypes = $this->getAttributeInputTypes();
+        if (!empty($inputTypes[$inputType]['source_model'])) {
+            return $inputTypes[$inputType]['source_model'];
+        }
+        return null;
+    }
+
+    /**
+     * Inits product to be used for product controller actions and layouts
+     * $params can have following data:
+     *   'category_id' - id of category to check and append to product as current.
+     *     If empty (except FALSE) - will be guessed (e.g. from last visited) to load as current.
+     *
+     * @param int $productId
+     * @param Mage_Core_Controller_Front_Action $controller
+     * @param Varien_Object $params
+     *
+     * @return false|Mage_Catalog_Model_Product
+     */
+    public function initProduct($productId, $controller, $params = null)
+    {
+        // Prepare data for routine
+        if (!$params) {
+            $params = new Varien_Object();
+        }
+
+        // Init and load product
+        Mage::dispatchEvent('catalog_controller_product_init_before', array(
+            'controller_action' => $controller,
+            'params' => $params,
+        ));
+
+        if (!$productId) {
+            return false;
+        }
+
+        $product = Mage::getModel('Mage_Catalog_Model_Product')
+            ->setStoreId(Mage::app()->getStore()->getId())
+            ->load($productId);
+
+        if (!$this->canShow($product)) {
+            return false;
+        }
+        if (!in_array(Mage::app()->getStore()->getWebsiteId(), $product->getWebsiteIds())) {
+            return false;
+        }
+
+        // Load product current category
+        $categoryId = $params->getCategoryId();
+        if (!$categoryId && ($categoryId !== false)) {
+            $lastId = Mage::getSingleton('Mage_Catalog_Model_Session')->getLastVisitedCategoryId();
+            if ($product->canBeShowInCategory($lastId)) {
+                $categoryId = $lastId;
+            }
+        } elseif (!$product->canBeShowInCategory($categoryId)) {
+            $categoryId = null;
+        }
+
+        if ($categoryId) {
+            $category = Mage::getModel('Mage_Catalog_Model_Category')->load($categoryId);
+            $product->setCategory($category);
+            Mage::register('current_category', $category);
+        }
+
+        // Register current data and dispatch final events
+        Mage::register('current_product', $product);
+        Mage::register('product', $product);
+
+        try {
+            Mage::dispatchEvent('catalog_controller_product_init', array('product' => $product));
+            Mage::dispatchEvent('catalog_controller_product_init_after',
+                            array('product' => $product,
+                                'controller_action' => $controller
+                            )
+            );
+        } catch (Mage_Core_Exception $e) {
+            Mage::logException($e);
+            return false;
+        }
+
+        return $product;
+    }
+
+    /**
+     * Prepares product options by buyRequest: retrieves values and assigns them as default.
+     * Also parses and adds product management related values - e.g. qty
+     *
+     * @param  Mage_Catalog_Model_Product $product
+     * @param  Varien_Object $buyRequest
+     * @return Mage_Catalog_Helper_Product
+     */
+    public function prepareProductOptions($product, $buyRequest)
+    {
+        $optionValues = $product->processBuyRequest($buyRequest);
+        $optionValues->setQty($buyRequest->getQty());
+        $product->setPreconfiguredValues($optionValues);
+
+        return $this;
+    }
+
+    /**
+     * Process $buyRequest and sets its options before saving configuration to some product item.
+     * This method is used to attach additional parameters to processed buyRequest.
+     *
+     * $params holds parameters of what operation must be performed:
+     * - 'current_config', Varien_Object or array - current buyRequest that configures product in this item,
+     *   used to restore currently attached files
+     * - 'files_prefix': string[a-z0-9_] - prefix that was added at frontend to names of file inputs,
+     *   so they won't intersect with other submitted options
+     *
+     * @param Varien_Object|array $buyRequest
+     * @param Varien_Object|array $params
+     * @return Varien_Object
+     */
+    public function addParamsToBuyRequest($buyRequest, $params)
+    {
+        if (is_array($buyRequest)) {
+            $buyRequest = new Varien_Object($buyRequest);
+        }
+        if (is_array($params)) {
+            $params = new Varien_Object($params);
+        }
+
+
+        // Ensure that currentConfig goes as Varien_Object - for easier work with it later
+        $currentConfig = $params->getCurrentConfig();
+        if ($currentConfig) {
+            if (is_array($currentConfig)) {
+                $params->setCurrentConfig(new Varien_Object($currentConfig));
+            } else if (!($currentConfig instanceof Varien_Object)) {
+                $params->unsCurrentConfig();
+            }
+        }
+
+        /*
+         * Notice that '_processing_params' must always be object to protect processing forged requests
+         * where '_processing_params' comes in $buyRequest as array from user input
+         */
+        $processingParams = $buyRequest->getData('_processing_params');
+        if (!$processingParams || !($processingParams instanceof Varien_Object)) {
+            $processingParams = new Varien_Object();
+            $buyRequest->setData('_processing_params', $processingParams);
+        }
+        $processingParams->addData($params->getData());
+
+        return $buyRequest;
+    }
+
+    /**
+     * Return loaded product instance
+     *
+     * @param  int|string $productId (SKU or ID)
+     * @param  int $store
+     * @param  string $identifierType
+     * @return Mage_Catalog_Model_Product
+     */
+    public function getProduct($productId, $store, $identifierType = null)
+    {
+        /** @var $product Mage_Catalog_Model_Product */
+        $product = Mage::getModel('Mage_Catalog_Model_Product')->setStoreId(Mage::app()->getStore($store)->getId());
+
+        $expectedIdType = false;
+        if ($identifierType === null) {
+            if (is_string($productId) && !preg_match("/^[+-]?[1-9][0-9]*$|^0$/", $productId)) {
+                $expectedIdType = 'sku';
+            }
+        }
+
+        if ($identifierType == 'sku' || $expectedIdType == 'sku') {
+            $idBySku = $product->getIdBySku($productId);
+            if ($idBySku) {
+                $productId = $idBySku;
+            } else if ($identifierType == 'sku') {
+                // Return empty product because it was not found by originally specified SKU identifier
+                return $product;
+            }
+        }
+
+        if ($productId && is_numeric($productId)) {
+            $product->load((int) $productId);
+        }
+
+        return $product;
+    }
+
+    /**
+     * Set flag that shows if Magento has to check product to be saleable (enabled and/or inStock)
+     *
+     * For instance, during order creation in the backend admin has ability to add any products to order
+     *
+     * @param bool $skipSaleableCheck
+     * @return Mage_Catalog_Helper_Product
+     */
+    public function setSkipSaleableCheck($skipSaleableCheck = false)
+    {
+        $this->_skipSaleableCheck = $skipSaleableCheck;
+        return $this;
+    }
+
+    /**
+     * Get flag that shows if Magento has to check product to be saleable (enabled and/or inStock)
+     *
+     * @return boolean
+     */
+    public function getSkipSaleableCheck()
+    {
+        return $this->_skipSaleableCheck;
+    }
+}
diff --git a/app/code/core/Mage/Catalog/Helper/Product/View.php b/app/code/core/Mage/Catalog/Helper/Product/View.php
index 0d1f4350866e2189e534cfce0cceeac79d43a865..f2944d70ac7bb336b72bd6752f75736fdf6e57a3 100644
--- a/app/code/core/Mage/Catalog/Helper/Product/View.php
+++ b/app/code/core/Mage/Catalog/Helper/Product/View.php
@@ -53,13 +53,10 @@ class Mage_Catalog_Helper_Product_View extends Mage_Core_Helper_Abstract
         }
 
         $update = $controller->getLayout()->getUpdate();
-        $update->addHandle('default');
-        $controller->addActionLayoutHandles();
-
-        $update->addHandle('PRODUCT_TYPE_' . $product->getTypeId());
-        $update->addHandle('PRODUCT_' . $product->getId());
+        $controller->addPageLayoutHandles(
+            array('id' => $product->getId(), 'sku' => $product->getSku(), 'type' => $product->getTypeId())
+        );
         $controller->loadLayoutUpdates();
-
         // Apply custom layout update once layout is loaded
         $layoutUpdates = $settings->getLayoutUpdates();
         if ($layoutUpdates) {
diff --git a/app/code/core/Mage/Catalog/Model/Category.php b/app/code/core/Mage/Catalog/Model/Category.php
index 6635187282634ee948bf79ea5dacc4265453ec8f..e0e078a8c496f27537e0a32d0c48227b4c5603b8 100644
--- a/app/code/core/Mage/Catalog/Model/Category.php
+++ b/app/code/core/Mage/Catalog/Model/Category.php
@@ -1,5 +1,5 @@
-<?php
-/**
+<?php
+/**
  * Magento
  *
  * NOTICE OF LICENSE
@@ -17,931 +17,914 @@
  * 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
+ *
+ * @category    Mage
+ * @package     Mage_Catalog
  * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
- */
-
-
-/**
- * Catalog category
- *
- * @category   Mage
- * @package    Mage_Catalog
- * @author     Magento Core Team <core@magentocommerce.com>
- */
-class Mage_Catalog_Model_Category extends Mage_Catalog_Model_Abstract
-{
-    /**
-     * Entity code.
-     * Can be used as part of method name for entity processing
-     */
-    const ENTITY                = 'catalog_category';
-    /**
-     * Category display modes
-     */
-    const DM_PRODUCT            = 'PRODUCTS';
-    const DM_PAGE               = 'PAGE';
-    const DM_MIXED              = 'PRODUCTS_AND_PAGE';
-    const TREE_ROOT_ID          = 1;
-
-    const CACHE_TAG             = 'catalog_category';
-
-    /**
-     * Prefix of model events names
-     *
-     * @var string
-     */
-    protected $_eventPrefix     = 'catalog_category';
-
-    /**
-     * Parameter name in event
-     *
-     * @var string
-     */
-    protected $_eventObject     = 'category';
-
-    /**
-     * Model cache tag for clear cache in after save and after delete
-     */
-    protected $_cacheTag        = self::CACHE_TAG;
-
-    /**
-     * URL Model instance
-     *
-     * @var Mage_Core_Model_Url
-     */
-    protected static $_url;
-
-    /**
-     * URL rewrite model
-     *
-     * @var Mage_Core_Model_Url_Rewrite
-     */
-    protected static $_urlRewrite;
-
-    /**
-     * Use flat resource model flag
-     *
-     * @var bool
-     */
-    protected $_useFlatResource = false;
-
-    /**
-     * Category design attributes
-     *
-     * @var array
-     */
-    private $_designAttributes  = array(
-        'custom_design',
-        'custom_design_from',
-        'custom_design_to',
-        'page_layout',
-        'custom_layout_update',
-        'custom_apply_to_products'
-    );
-
-    /**
-     * Category tree model
-     *
-     * @var Mage_Catalog_Model_Resource_Category_Tree
-     */
-    protected $_treeModel = null;
-
-    /**
-     * Initialize resource mode
-     *
-     */
-    protected function _construct()
-    {
-        if (Mage::helper('Mage_Catalog_Helper_Category_Flat')->isEnabled()) {
-            $this->_init('Mage_Catalog_Model_Resource_Category_Flat');
-            $this->_useFlatResource = true;
-        } else {
-            $this->_init('Mage_Catalog_Model_Resource_Category');
-        }
-    }
-
-    /**
-     * Retrieve URL instance
-     *
-     * @return Mage_Core_Model_Url
-     */
-    public function getUrlInstance()
-    {
-        if (!self::$_url) {
-            self::$_url = Mage::getModel('Mage_Core_Model_Url');
-        }
-        return self::$_url;
-    }
-
-    /**
-     * Get url rewrite model
-     *
-     * @return Mage_Core_Model_Url_Rewrite
-     */
-    public function getUrlRewrite()
-    {
-        if (!self::$_urlRewrite) {
-            self::$_urlRewrite = Mage::getModel('Mage_Core_Model_Url_Rewrite');
-        }
-        return self::$_urlRewrite;
-    }
-
-    /**
-     * Retrieve category tree model
-     *
-     * @return Mage_Catalog_Model_Resource_Category_Tree
-     */
-    public function getTreeModel()
-    {
-        return Mage::getResourceModel('Mage_Catalog_Model_Resource_Category_Tree');
-    }
-
-    /**
-     * Enter description here...
-     *
-     * @return Mage_Catalog_Model_Resource_Category_Tree
-     */
-    public function getTreeModelInstance()
-    {
-        if (is_null($this->_treeModel)) {
-            $this->_treeModel = Mage::getResourceSingleton('Mage_Catalog_Model_Resource_Category_Tree');
-        }
-        return $this->_treeModel;
-    }
-
-    /**
-     * Move category
-     *
-     * @param   int $parentId new parent category id
-     * @param   int $afterCategoryId category id after which we have put current category
-     * @return  Mage_Catalog_Model_Category
-     */
-    public function move($parentId, $afterCategoryId)
-    {
-        /**
-         * Validate new parent category id. (category model is used for backward
-         * compatibility in event params)
-         */
-        $parent = Mage::getModel('Mage_Catalog_Model_Category')
-            ->setStoreId($this->getStoreId())
-            ->load($parentId);
-
-        if (!$parent->getId()) {
-            Mage::throwException(
-                Mage::helper('Mage_Catalog_Helper_Data')->__('Category move operation is not possible: the new parent category was not found.')
-            );
-        }
-
-        if (!$this->getId()) {
-            Mage::throwException(
-                Mage::helper('Mage_Catalog_Helper_Data')->__('Category move operation is not possible: the current category was not found.')
-            );
-        } elseif ($parent->getId() == $this->getId()) {
-            Mage::throwException(
-                Mage::helper('Mage_Catalog_Helper_Data')->__('Category move operation is not possible: parent category is equal to child category.')
-            );
-        }
-
-        /**
-         * Setting affected category ids for third party engine index refresh
-        */
-        $this->setMovedCategoryId($this->getId());
-
-        $eventParams = array(
-            $this->_eventObject => $this,
-            'parent'        => $parent,
-            'category_id'   => $this->getId(),
-            'prev_parent_id'=> $this->getParentId(),
-            'parent_id'     => $parentId
-        );
-        $moveComplete = false;
-
-        $this->_getResource()->beginTransaction();
-        try {
-            /**
-             * catalog_category_tree_move_before and catalog_category_tree_move_after
-             * events declared for backward compatibility
-             */
-            Mage::dispatchEvent('catalog_category_tree_move_before', $eventParams);
-            Mage::dispatchEvent($this->_eventPrefix.'_move_before', $eventParams);
-
-            $this->getResource()->changeParent($this, $parent, $afterCategoryId);
-
-            Mage::dispatchEvent($this->_eventPrefix.'_move_after', $eventParams);
-            Mage::dispatchEvent('catalog_category_tree_move_after', $eventParams);
-            $this->_getResource()->commit();
-
-            // Set data for indexer
-            $this->setAffectedCategoryIds(array($this->getId(), $this->getParentId(), $parentId));
-
-            $moveComplete = true;
-        } catch (Exception $e) {
-            $this->_getResource()->rollBack();
-            throw $e;
-        }
-        if ($moveComplete) {
-            Mage::dispatchEvent('category_move', $eventParams);
-            Mage::getSingleton('Mage_Index_Model_Indexer')->processEntityAction(
-                $this, self::ENTITY, Mage_Index_Model_Event::TYPE_SAVE
-            );
-            Mage::app()->cleanCache(array(self::CACHE_TAG));
-        }
-
-        return $this;
-    }
-
-    /**
-     * Retrieve default attribute set id
-     *
-     * @return int
-     */
-    public function getDefaultAttributeSetId()
-    {
-        return $this->getResource()->getEntityType()->getDefaultAttributeSetId();
-    }
-
-    /**
-     * Get category products collection
-     *
-     * @return Varien_Data_Collection_Db
-     */
-    public function getProductCollection()
-    {
-        $collection = Mage::getResourceModel('Mage_Catalog_Model_Resource_Product_Collection')
-            ->setStoreId($this->getStoreId())
-            ->addCategoryFilter($this);
-        return $collection;
-    }
-
-    /**
-     * Retrieve all customer attributes
-     *
-     * @todo Use with Flat Resource
-     * @return array
-     */
-    public function getAttributes($noDesignAttributes = false)
-    {
-        $result = $this->getResource()
-            ->loadAllAttributes($this)
-            ->getSortedAttributes();
-
-        if ($noDesignAttributes){
-            foreach ($result as $k=>$a){
-                if (in_array($k, $this->_designAttributes)) {
-                    unset($result[$k]);
-                }
-            }
-        }
-
-        return $result;
-    }
-
-    /**
-     * Retrieve array of product id's for category
-     *
-     * array($productId => $position)
-     *
-     * @return array
-     */
-    public function getProductsPosition()
-    {
-        if (!$this->getId()) {
-            return array();
-        }
-
-        $array = $this->getData('products_position');
-        if (is_null($array)) {
-            $array = $this->getResource()->getProductsPosition($this);
-            $this->setData('products_position', $array);
-        }
-        return $array;
-    }
-
-    /**
-     * Retrieve array of store ids for category
-     *
-     * @return array
-     */
-    public function getStoreIds()
-    {
-        if ($this->getInitialSetupFlag()) {
-            return array();
-        }
-
-        if ($storeIds = $this->getData('store_ids')) {
-            return $storeIds;
-        }
-
-        if (!$this->getId()) {
-            return array();
-        }
-
-        $nodes = array();
-        foreach ($this->getPathIds() as $id) {
-            $nodes[] = $id;
-        }
-
-        $storeIds = array();
-        $storeCollection = Mage::getModel('Mage_Core_Model_Store')->getCollection()->loadByCategoryIds($nodes);
-        foreach ($storeCollection as $store) {
-            $storeIds[$store->getId()] = $store->getId();
-        }
-
-        $entityStoreId = $this->getStoreId();
-        if (!in_array($entityStoreId, $storeIds)) {
-            array_unshift($storeIds, $entityStoreId);
-        }
-        if (!in_array(0, $storeIds)) {
-            array_unshift($storeIds, 0);
-        }
-
-        $this->setData('store_ids', $storeIds);
-        return $storeIds;
-    }
-
-    /**
-     * Retrieve Layout Update Handle name
-     *
-     * @return string
-     */
-    public function getLayoutUpdateHandle()
-    {
-        $layout = 'catalog_category_';
-        if ($this->getIsAnchor()) {
-            $layout .= 'layered';
-        }
-        else {
-            $layout .= 'default';
-        }
-        return $layout;
-    }
-
-    /**
-     * Return store id.
-     *
-     * If store id is underfined for category return current active store id
-     *
-     * @return integer
-     */
-    public function getStoreId()
-    {
-        if ($this->hasData('store_id')) {
-            return $this->_getData('store_id');
-        }
-        return Mage::app()->getStore()->getId();
-    }
-
-    /**
-     * Set store id
-     *
-     * @param integer $storeId
-     * @return Mage_Catalog_Model_Category
-     */
-    public function setStoreId($storeId)
-    {
-        if (!is_numeric($storeId)) {
-            $storeId = Mage::app($storeId)->getStore()->getId();
-        }
-        $this->setData('store_id', $storeId);
-        $this->getResource()->setStoreId($storeId);
-        return $this;
-    }
-
-    /**
-     * Get category url
-     *
-     * @return string
-     */
-    public function getUrl()
-    {
-        $url = $this->_getData('url');
-        if (is_null($url)) {
-            Magento_Profiler::start('REWRITE: '.__METHOD__);
-
-            if ($this->hasData('request_path') && $this->getRequestPath() != '') {
-                $this->setData('url', $this->getUrlInstance()->getDirectUrl($this->getRequestPath()));
-                Magento_Profiler::stop('REWRITE: '.__METHOD__);
-                return $this->getData('url');
-            }
-
-            $rewrite = $this->getUrlRewrite();
-            if ($this->getStoreId()) {
-                $rewrite->setStoreId($this->getStoreId());
-            }
-            $idPath = 'category/' . $this->getId();
-            $rewrite->loadByIdPath($idPath);
-
-            if ($rewrite->getId()) {
-                $this->setData('url', $this->getUrlInstance()->getDirectUrl($rewrite->getRequestPath()));
-                Magento_Profiler::stop('REWRITE: '.__METHOD__);
-                return $this->getData('url');
-            }
-
-            Magento_Profiler::stop('REWRITE: '.__METHOD__);
-
-            $this->setData('url', $this->getCategoryIdUrl());
-            return $this->getData('url');
-        }
-        return $url;
-    }
-
-    /**
-     * Retrieve category id URL
-     *
-     * @return string
-     */
-    public function getCategoryIdUrl()
-    {
-        Magento_Profiler::start('REGULAR: '.__METHOD__);
-        $urlKey = $this->getUrlKey() ? $this->getUrlKey() : $this->formatUrlKey($this->getName());
-        $url = $this->getUrlInstance()->getUrl('catalog/category/view', array(
-            's'=>$urlKey,
-            'id'=>$this->getId(),
-        ));
-        Magento_Profiler::stop('REGULAR: '.__METHOD__);
-        return $url;
-    }
-
-    /**
-     * Format URL key from name or defined key
-     *
-     * @param string $str
-     * @return string
-     */
-    public function formatUrlKey($str)
-    {
-        $str = Mage::helper('Mage_Core_Helper_Data')->removeAccents($str);
-        $urlKey = preg_replace('#[^0-9a-z]+#i', '-', $str);
-        $urlKey = strtolower($urlKey);
-        $urlKey = trim($urlKey, '-');
-        return $urlKey;
-    }
-
-    /**
-     * Retrieve image URL
-     *
-     * @return string
-     */
-    public function getImageUrl()
-    {
-        $url = false;
-        if ($image = $this->getImage()) {
-            $url = Mage::getBaseUrl('media').'catalog/category/'.$image;
-        }
-        return $url;
-    }
-
-    /**
-     * Retrieve URL path
-     *
-     * @return string
-     */
-    public function getUrlPath()
-    {
-        $path = $this->getData('url_path');
-        if ($path) {
-            return $path;
-        }
-
-        $path = $this->getUrlKey();
-
-        if ($this->getParentId()) {
-            $parentPath = Mage::getModel('Mage_Catalog_Model_Category')->load($this->getParentId())->getCategoryPath();
-            $path = $parentPath.'/'.$path;
-        }
-
-        $this->setUrlPath($path);
-
-        return $path;
-    }
-
-    /**
-     * Get parent category object
-     *
-     * @return Mage_Catalog_Model_Category
-     */
-    public function getParentCategory()
-    {
-        if (!$this->hasData('parent_category')) {
-            $this->setData('parent_category', Mage::getModel('Mage_Catalog_Model_Category')->load($this->getParentId()));
-        }
-        return $this->_getData('parent_category');
-    }
-
-    /**
-     * Get parent category identifier
-     *
-     * @return int
-     */
-    public function getParentId()
-    {
-        $parentIds = $this->getParentIds();
-        return intval(array_pop($parentIds));
-    }
-
-    /**
-     * Get all parent categories ids
-     *
-     * @return array
-     */
-    public function getParentIds()
-    {
-        return array_diff($this->getPathIds(), array($this->getId()));
-    }
-
-    /**
-     * Retrieve dates for custom design (from & to)
-     *
-     * @return array
-     */
-    public function getCustomDesignDate()
-    {
-        $result = array();
-        $result['from'] = $this->getData('custom_design_from');
-        $result['to'] = $this->getData('custom_design_to');
-
-        return $result;
-    }
-
-    /**
-     * Retrieve design attributes array
-     *
-     * @return array
-     */
-    public function getDesignAttributes()
-    {
-        $result = array();
-        foreach ($this->_designAttributes as $attrName) {
-            $result[] = $this->_getAttribute($attrName);
-        }
-        return $result;
-    }
-
-    /**
-     * Retrieve attribute by code
-     *
-     * @param string $attributeCode
-     * @return Mage_Eav_Model_Entity_Attribute_Abstract
-     */
-    private function _getAttribute($attributeCode)
-    {
-        if (!$this->_useFlatResource) {
-            $attribute = $this->getResource()->getAttribute($attributeCode);
-        }
-        else {
-            $attribute = Mage::getSingleton('Mage_Catalog_Model_Config')
-                ->getAttribute(self::ENTITY, $attributeCode);
-        }
-        return $attribute;
-    }
-
-    /**
-     * Get all children categories IDs
-     *
-     * @param boolean $asArray return result as array instead of comma-separated list of IDs
-     * @return array|string
-     */
-    public function getAllChildren($asArray = false)
-    {
-        $children = $this->getResource()->getAllChildren($this);
-        if ($asArray) {
-            return $children;
-        }
-        else {
-            return implode(',', $children);
-        }
-
-//        $this->getTreeModelInstance()->load();
-//        $children = $this->getTreeModelInstance()->getChildren($this->getId());
-//
-//        $myId = array($this->getId());
-//        if (is_array($children)) {
-//            $children = array_merge($myId, $children);
-//        }
-//        else {
-//            $children = $myId;
-//        }
-//        if ($asArray) {
-//            return $children;
-//        }
-//        else {
-//            return implode(',', $children);
-//        }
-    }
-
-    /**
-     * Retrieve children ids comma separated
-     *
-     * @return string
-     */
-    public function getChildren()
-    {
-        return implode(',', $this->getResource()->getChildren($this, false));
-    }
-
-    /**
-     * Retrieve Stores where isset category Path
-     * Return comma separated string
-     *
-     * @return string
-     */
-    public function getPathInStore()
-    {
-        $result = array();
-        //$path = $this->getTreeModelInstance()->getPath($this->getId());
-        $path = array_reverse($this->getPathIds());
-        foreach ($path as $itemId) {
-            if ($itemId == Mage::app()->getStore()->getRootCategoryId()) {
-                break;
-            }
-            $result[] = $itemId;
-        }
-        return implode(',', $result);
-    }
-
-    /**
-     * Check category id exising
-     *
-     * @param   int $id
-     * @return  bool
-     */
-    public function checkId($id)
-    {
-        return $this->_getResource()->checkId($id);
-    }
-
-    /**
-     * Get array categories ids which are part of category path
-     * Result array contain id of current category because it is part of the path
-     *
-     * @return array
-     */
-    public function getPathIds()
-    {
-        $ids = $this->getData('path_ids');
-        if (is_null($ids)) {
-            $ids = explode('/', $this->getPath());
-            $this->setData('path_ids', $ids);
-        }
-        return $ids;
-    }
-
-    /**
-     * Retrieve level
-     *
-     * @return int
-     */
-    public function getLevel()
-    {
-        if (!$this->hasLevel()) {
-            return count(explode('/', $this->getPath())) - 1;
-        }
-        return $this->getData('level');
-    }
-
-    /**
-     * Verify category ids
-     *
-     * @param array $ids
-     * @return bool
-     */
-    public function verifyIds(array $ids)
-    {
-        return $this->getResource()->verifyIds($ids);
-    }
-
-    /**
-     * Retrieve Is Category has children flag
-     *
-     * @return bool
-     */
-    public function hasChildren()
-    {
-        return $this->_getResource()->getChildrenAmount($this) > 0;
-    }
-
-    /**
-     * Retrieve Request Path
-     *
-     * @return string
-     */
-    public function getRequestPath()
-    {
-        return $this->_getData('request_path');
-    }
-
-    /**
-     * Retrieve Name data wraper
-     *
-     * @return string
-     */
-    public function getName()
-    {
-        return $this->_getData('name');
-    }
-
-    /**
-     * Before delete process
-     *
-     * @return Mage_Catalog_Model_Category
-     */
-    protected function _beforeDelete()
-    {
-        $this->_protectFromNonAdmin();
-        if ($this->getResource()->isForbiddenToDelete($this->getId())) {
-            Mage::throwException("Can't delete root category.");
-        }
-        return parent::_beforeDelete();
-    }
-
-    /**
-     * Retrieve anchors above
-     *
-     * @return array
-     */
-    public function getAnchorsAbove()
-    {
-        $anchors = array();
-        $path = $this->getPathIds();
-
-        if (in_array($this->getId(), $path)) {
-            unset($path[array_search($this->getId(), $path)]);
-        }
-
-        if ($this->_useFlatResource) {
-            $anchors = $this->_getResource()->getAnchorsAbove($path, $this->getStoreId());
-        }
-        else {
-            if (!Mage::registry('_category_is_anchor_attribute')) {
-                $model = $this->_getAttribute('is_anchor');
-                Mage::register('_category_is_anchor_attribute', $model);
-            }
-
-            if ($isAnchorAttribute = Mage::registry('_category_is_anchor_attribute')) {
-                $anchors = $this->getResource()->findWhereAttributeIs($path, $isAnchorAttribute, 1);
-            }
-        }
-        return $anchors;
-    }
-
-    /**
-     * Retrieve count products of category
-     *
-     * @return int
-     */
-    public function getProductCount()
-    {
-        if (!$this->hasProductCount()) {
-            $count = $this->_getResource()->getProductCount($this); // load product count
-            $this->setData('product_count', $count);
-        }
-        return $this->getData('product_count');
-    }
-
-    /**
-     * Retrieve categories by parent
-     *
-     * @param int $parent
-     * @param int $recursionLevel
-     * @param bool $sorted
-     * @param bool $asCollection
-     * @param bool $toLoad
-     * @return mixed
-     */
-    public function getCategories($parent, $recursionLevel = 0, $sorted=false, $asCollection=false, $toLoad=true)
-    {
-        $categories = $this->getResource()
-            ->getCategories($parent, $recursionLevel, $sorted, $asCollection, $toLoad);
-        return $categories;
-    }
-
-    /**
-     * Return parent categories of current category
-     *
-     * @return array
-     */
-    public function getParentCategories()
-    {
-        return $this->getResource()->getParentCategories($this);
-    }
-
-    /**
-     * Retuen children categories of current category
-     *
-     * @return array
-     */
-    public function getChildrenCategories()
-    {
-        return $this->getResource()->getChildrenCategories($this);
-    }
-
-    /**
-     * Return parent category of current category with own custom design settings
-     *
-     * @return Mage_Catalog_Model_Category
-     */
-    public function getParentDesignCategory()
-    {
-        return $this->getResource()->getParentDesignCategory($this);
-    }
-
-    /**
-     * Check category is in Root Category list
-     *
-     * @return bool
-     */
-    public function isInRootCategoryList()
-    {
-        return $this->getResource()->isInRootCategoryList($this);
-    }
-
-    /**
-     * Retrieve Available int Product Listing sort by
-     *
-     * @return null|array
-     */
-    public function getAvailableSortBy()
-    {
-        $available = $this->getData('available_sort_by');
-        if (empty($available)) {
-            return array();
-        }
-        if ($available && !is_array($available)) {
-            $available = explode(',', $available);
-        }
-        return $available;
-    }
-
-    /**
-     * Retrieve Available Product Listing  Sort By
-     * code as key, value - name
-     *
-     * @return array
-     */
-    public function getAvailableSortByOptions() {
-        $availableSortBy = array();
-        $defaultSortBy   = Mage::getSingleton('Mage_Catalog_Model_Config')
-            ->getAttributeUsedForSortByArray();
-        if ($this->getAvailableSortBy()) {
-            foreach ($this->getAvailableSortBy() as $sortBy) {
-                if (isset($defaultSortBy[$sortBy])) {
-                    $availableSortBy[$sortBy] = $defaultSortBy[$sortBy];
-                }
-            }
-        }
-
-        if (!$availableSortBy) {
-            $availableSortBy = $defaultSortBy;
-        }
-
-        return $availableSortBy;
-    }
-
-    /**
-     * Retrieve Product Listing Default Sort By
-     *
-     * @return string
-     */
-    public function getDefaultSortBy() {
-        if (!$sortBy = $this->getData('default_sort_by')) {
-            $sortBy = Mage::getSingleton('Mage_Catalog_Model_Config')
-                ->getProductListDefaultSortBy($this->getStoreId());
-        }
-        $available = $this->getAvailableSortByOptions();
-        if (!isset($available[$sortBy])) {
-            $sortBy = array_keys($available);
-            $sortBy = $sortBy[0];
-        }
-
-        return $sortBy;
-    }
-
-    /**
-     * Validate attribute values
-     *
-     * @throws Mage_Eav_Model_Entity_Attribute_Exception
-     * @return bool|array
-     */
-    public function validate()
-    {
-        return $this->_getResource()->validate($this);
-    }
-
-    /**
+ */
+
+
+/**
+ * Catalog category
+ *
+ * @category   Mage
+ * @package    Mage_Catalog
+ * @author     Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_Catalog_Model_Category extends Mage_Catalog_Model_Abstract
+{
+    /**
+     * Entity code.
+     * Can be used as part of method name for entity processing
+     */
+    const ENTITY                = 'catalog_category';
+    /**
+     * Category display modes
+     */
+    const DM_PRODUCT            = 'PRODUCTS';
+    const DM_PAGE               = 'PAGE';
+    const DM_MIXED              = 'PRODUCTS_AND_PAGE';
+    const TREE_ROOT_ID          = 1;
+
+    const CACHE_TAG             = 'catalog_category';
+
+    /**
+     * Prefix of model events names
+     *
+     * @var string
+     */
+    protected $_eventPrefix     = 'catalog_category';
+
+    /**
+     * Parameter name in event
+     *
+     * @var string
+     */
+    protected $_eventObject     = 'category';
+
+    /**
+     * Model cache tag for clear cache in after save and after delete
+     */
+    protected $_cacheTag        = self::CACHE_TAG;
+
+    /**
+     * URL Model instance
+     *
+     * @var Mage_Core_Model_Url
+     */
+    protected static $_url;
+
+    /**
+     * URL rewrite model
+     *
+     * @var Mage_Core_Model_Url_Rewrite
+     */
+    protected static $_urlRewrite;
+
+    /**
+     * Use flat resource model flag
+     *
+     * @var bool
+     */
+    protected $_useFlatResource = false;
+
+    /**
+     * Category design attributes
+     *
+     * @var array
+     */
+    private $_designAttributes  = array(
+        'custom_design',
+        'custom_design_from',
+        'custom_design_to',
+        'page_layout',
+        'custom_layout_update',
+        'custom_apply_to_products'
+    );
+
+    /**
+     * Category tree model
+     *
+     * @var Mage_Catalog_Model_Resource_Category_Tree
+     */
+    protected $_treeModel = null;
+
+    /**
+     * Initialize resource mode
+     *
+     */
+    protected function _construct()
+    {
+        if (Mage::helper('Mage_Catalog_Helper_Category_Flat')->isEnabled()) {
+            $this->_init('Mage_Catalog_Model_Resource_Category_Flat');
+            $this->_useFlatResource = true;
+        } else {
+            $this->_init('Mage_Catalog_Model_Resource_Category');
+        }
+    }
+
+    /**
+     * Retrieve URL instance
+     *
+     * @return Mage_Core_Model_Url
+     */
+    public function getUrlInstance()
+    {
+        if (!self::$_url) {
+            self::$_url = Mage::getModel('Mage_Core_Model_Url');
+        }
+        return self::$_url;
+    }
+
+    /**
+     * Get url rewrite model
+     *
+     * @return Mage_Core_Model_Url_Rewrite
+     */
+    public function getUrlRewrite()
+    {
+        if (!self::$_urlRewrite) {
+            self::$_urlRewrite = Mage::getModel('Mage_Core_Model_Url_Rewrite');
+        }
+        return self::$_urlRewrite;
+    }
+
+    /**
+     * Retrieve category tree model
+     *
+     * @return Mage_Catalog_Model_Resource_Category_Tree
+     */
+    public function getTreeModel()
+    {
+        return Mage::getResourceModel('Mage_Catalog_Model_Resource_Category_Tree');
+    }
+
+    /**
+     * Enter description here...
+     *
+     * @return Mage_Catalog_Model_Resource_Category_Tree
+     */
+    public function getTreeModelInstance()
+    {
+        if (is_null($this->_treeModel)) {
+            $this->_treeModel = Mage::getResourceSingleton('Mage_Catalog_Model_Resource_Category_Tree');
+        }
+        return $this->_treeModel;
+    }
+
+    /**
+     * Move category
+     *
+     * @param   int $parentId new parent category id
+     * @param   int $afterCategoryId category id after which we have put current category
+     * @return  Mage_Catalog_Model_Category
+     */
+    public function move($parentId, $afterCategoryId)
+    {
+        /**
+         * Validate new parent category id. (category model is used for backward
+         * compatibility in event params)
+         */
+        $parent = Mage::getModel('Mage_Catalog_Model_Category')
+            ->setStoreId($this->getStoreId())
+            ->load($parentId);
+
+        if (!$parent->getId()) {
+            Mage::throwException(
+                Mage::helper('Mage_Catalog_Helper_Data')->__('Category move operation is not possible: the new parent category was not found.')
+            );
+        }
+
+        if (!$this->getId()) {
+            Mage::throwException(
+                Mage::helper('Mage_Catalog_Helper_Data')->__('Category move operation is not possible: the current category was not found.')
+            );
+        } elseif ($parent->getId() == $this->getId()) {
+            Mage::throwException(
+                Mage::helper('Mage_Catalog_Helper_Data')->__('Category move operation is not possible: parent category is equal to child category.')
+            );
+        }
+
+        /**
+         * Setting affected category ids for third party engine index refresh
+        */
+        $this->setMovedCategoryId($this->getId());
+
+        $eventParams = array(
+            $this->_eventObject => $this,
+            'parent'        => $parent,
+            'category_id'   => $this->getId(),
+            'prev_parent_id'=> $this->getParentId(),
+            'parent_id'     => $parentId
+        );
+        $moveComplete = false;
+
+        $this->_getResource()->beginTransaction();
+        try {
+            /**
+             * catalog_category_tree_move_before and catalog_category_tree_move_after
+             * events declared for backward compatibility
+             */
+            Mage::dispatchEvent('catalog_category_tree_move_before', $eventParams);
+            Mage::dispatchEvent($this->_eventPrefix.'_move_before', $eventParams);
+
+            $this->getResource()->changeParent($this, $parent, $afterCategoryId);
+
+            Mage::dispatchEvent($this->_eventPrefix.'_move_after', $eventParams);
+            Mage::dispatchEvent('catalog_category_tree_move_after', $eventParams);
+            $this->_getResource()->commit();
+
+            // Set data for indexer
+            $this->setAffectedCategoryIds(array($this->getId(), $this->getParentId(), $parentId));
+
+            $moveComplete = true;
+        } catch (Exception $e) {
+            $this->_getResource()->rollBack();
+            throw $e;
+        }
+        if ($moveComplete) {
+            Mage::dispatchEvent('category_move', $eventParams);
+            Mage::getSingleton('Mage_Index_Model_Indexer')->processEntityAction(
+                $this, self::ENTITY, Mage_Index_Model_Event::TYPE_SAVE
+            );
+            Mage::app()->cleanCache(array(self::CACHE_TAG));
+        }
+
+        return $this;
+    }
+
+    /**
+     * Retrieve default attribute set id
+     *
+     * @return int
+     */
+    public function getDefaultAttributeSetId()
+    {
+        return $this->getResource()->getEntityType()->getDefaultAttributeSetId();
+    }
+
+    /**
+     * Get category products collection
+     *
+     * @return Varien_Data_Collection_Db
+     */
+    public function getProductCollection()
+    {
+        $collection = Mage::getResourceModel('Mage_Catalog_Model_Resource_Product_Collection')
+            ->setStoreId($this->getStoreId())
+            ->addCategoryFilter($this);
+        return $collection;
+    }
+
+    /**
+     * Retrieve all customer attributes
+     *
+     * @todo Use with Flat Resource
+     * @return array
+     */
+    public function getAttributes($noDesignAttributes = false)
+    {
+        $result = $this->getResource()
+            ->loadAllAttributes($this)
+            ->getSortedAttributes();
+
+        if ($noDesignAttributes){
+            foreach ($result as $k=>$a){
+                if (in_array($k, $this->_designAttributes)) {
+                    unset($result[$k]);
+                }
+            }
+        }
+
+        return $result;
+    }
+
+    /**
+     * Retrieve array of product id's for category
+     *
+     * array($productId => $position)
+     *
+     * @return array
+     */
+    public function getProductsPosition()
+    {
+        if (!$this->getId()) {
+            return array();
+        }
+
+        $array = $this->getData('products_position');
+        if (is_null($array)) {
+            $array = $this->getResource()->getProductsPosition($this);
+            $this->setData('products_position', $array);
+        }
+        return $array;
+    }
+
+    /**
+     * Retrieve array of store ids for category
+     *
+     * @return array
+     */
+    public function getStoreIds()
+    {
+        if ($this->getInitialSetupFlag()) {
+            return array();
+        }
+
+        if ($storeIds = $this->getData('store_ids')) {
+            return $storeIds;
+        }
+
+        if (!$this->getId()) {
+            return array();
+        }
+
+        $nodes = array();
+        foreach ($this->getPathIds() as $id) {
+            $nodes[] = $id;
+        }
+
+        $storeIds = array();
+        $storeCollection = Mage::getModel('Mage_Core_Model_Store')->getCollection()->loadByCategoryIds($nodes);
+        foreach ($storeCollection as $store) {
+            $storeIds[$store->getId()] = $store->getId();
+        }
+
+        $entityStoreId = $this->getStoreId();
+        if (!in_array($entityStoreId, $storeIds)) {
+            array_unshift($storeIds, $entityStoreId);
+        }
+        if (!in_array(0, $storeIds)) {
+            array_unshift($storeIds, 0);
+        }
+
+        $this->setData('store_ids', $storeIds);
+        return $storeIds;
+    }
+
+    /**
+     * Return store id.
+     *
+     * If store id is underfined for category return current active store id
+     *
+     * @return integer
+     */
+    public function getStoreId()
+    {
+        if ($this->hasData('store_id')) {
+            return $this->_getData('store_id');
+        }
+        return Mage::app()->getStore()->getId();
+    }
+
+    /**
+     * Set store id
+     *
+     * @param integer $storeId
+     * @return Mage_Catalog_Model_Category
+     */
+    public function setStoreId($storeId)
+    {
+        if (!is_numeric($storeId)) {
+            $storeId = Mage::app($storeId)->getStore()->getId();
+        }
+        $this->setData('store_id', $storeId);
+        $this->getResource()->setStoreId($storeId);
+        return $this;
+    }
+
+    /**
+     * Get category url
+     *
+     * @return string
+     */
+    public function getUrl()
+    {
+        $url = $this->_getData('url');
+        if (is_null($url)) {
+            Magento_Profiler::start('REWRITE: '.__METHOD__);
+
+            if ($this->hasData('request_path') && $this->getRequestPath() != '') {
+                $this->setData('url', $this->getUrlInstance()->getDirectUrl($this->getRequestPath()));
+                Magento_Profiler::stop('REWRITE: '.__METHOD__);
+                return $this->getData('url');
+            }
+
+            $rewrite = $this->getUrlRewrite();
+            if ($this->getStoreId()) {
+                $rewrite->setStoreId($this->getStoreId());
+            }
+            $idPath = 'category/' . $this->getId();
+            $rewrite->loadByIdPath($idPath);
+
+            if ($rewrite->getId()) {
+                $this->setData('url', $this->getUrlInstance()->getDirectUrl($rewrite->getRequestPath()));
+                Magento_Profiler::stop('REWRITE: '.__METHOD__);
+                return $this->getData('url');
+            }
+
+            Magento_Profiler::stop('REWRITE: '.__METHOD__);
+
+            $this->setData('url', $this->getCategoryIdUrl());
+            return $this->getData('url');
+        }
+        return $url;
+    }
+
+    /**
+     * Retrieve category id URL
+     *
+     * @return string
+     */
+    public function getCategoryIdUrl()
+    {
+        Magento_Profiler::start('REGULAR: '.__METHOD__);
+        $urlKey = $this->getUrlKey() ? $this->getUrlKey() : $this->formatUrlKey($this->getName());
+        $url = $this->getUrlInstance()->getUrl('catalog/category/view', array(
+            's'=>$urlKey,
+            'id'=>$this->getId(),
+        ));
+        Magento_Profiler::stop('REGULAR: '.__METHOD__);
+        return $url;
+    }
+
+    /**
+     * Format URL key from name or defined key
+     *
+     * @param string $str
+     * @return string
+     */
+    public function formatUrlKey($str)
+    {
+        $str = Mage::helper('Mage_Core_Helper_Data')->removeAccents($str);
+        $urlKey = preg_replace('#[^0-9a-z]+#i', '-', $str);
+        $urlKey = strtolower($urlKey);
+        $urlKey = trim($urlKey, '-');
+        return $urlKey;
+    }
+
+    /**
+     * Retrieve image URL
+     *
+     * @return string
+     */
+    public function getImageUrl()
+    {
+        $url = false;
+        if ($image = $this->getImage()) {
+            $url = Mage::getBaseUrl('media').'catalog/category/'.$image;
+        }
+        return $url;
+    }
+
+    /**
+     * Retrieve URL path
+     *
+     * @return string
+     */
+    public function getUrlPath()
+    {
+        $path = $this->getData('url_path');
+        if ($path) {
+            return $path;
+        }
+
+        $path = $this->getUrlKey();
+
+        if ($this->getParentId()) {
+            $parentPath = Mage::getModel('Mage_Catalog_Model_Category')->load($this->getParentId())->getCategoryPath();
+            $path = $parentPath.'/'.$path;
+        }
+
+        $this->setUrlPath($path);
+
+        return $path;
+    }
+
+    /**
+     * Get parent category object
+     *
+     * @return Mage_Catalog_Model_Category
+     */
+    public function getParentCategory()
+    {
+        if (!$this->hasData('parent_category')) {
+            $this->setData('parent_category', Mage::getModel('Mage_Catalog_Model_Category')->load($this->getParentId()));
+        }
+        return $this->_getData('parent_category');
+    }
+
+    /**
+     * Get parent category identifier
+     *
+     * @return int
+     */
+    public function getParentId()
+    {
+        $parentIds = $this->getParentIds();
+        return intval(array_pop($parentIds));
+    }
+
+    /**
+     * Get all parent categories ids
+     *
+     * @return array
+     */
+    public function getParentIds()
+    {
+        return array_diff($this->getPathIds(), array($this->getId()));
+    }
+
+    /**
+     * Retrieve dates for custom design (from & to)
+     *
+     * @return array
+     */
+    public function getCustomDesignDate()
+    {
+        $result = array();
+        $result['from'] = $this->getData('custom_design_from');
+        $result['to'] = $this->getData('custom_design_to');
+
+        return $result;
+    }
+
+    /**
+     * Retrieve design attributes array
+     *
+     * @return array
+     */
+    public function getDesignAttributes()
+    {
+        $result = array();
+        foreach ($this->_designAttributes as $attrName) {
+            $result[] = $this->_getAttribute($attrName);
+        }
+        return $result;
+    }
+
+    /**
+     * Retrieve attribute by code
+     *
+     * @param string $attributeCode
+     * @return Mage_Eav_Model_Entity_Attribute_Abstract
+     */
+    private function _getAttribute($attributeCode)
+    {
+        if (!$this->_useFlatResource) {
+            $attribute = $this->getResource()->getAttribute($attributeCode);
+        }
+        else {
+            $attribute = Mage::getSingleton('Mage_Catalog_Model_Config')
+                ->getAttribute(self::ENTITY, $attributeCode);
+        }
+        return $attribute;
+    }
+
+    /**
+     * Get all children categories IDs
+     *
+     * @param boolean $asArray return result as array instead of comma-separated list of IDs
+     * @return array|string
+     */
+    public function getAllChildren($asArray = false)
+    {
+        $children = $this->getResource()->getAllChildren($this);
+        if ($asArray) {
+            return $children;
+        }
+        else {
+            return implode(',', $children);
+        }
+
+//        $this->getTreeModelInstance()->load();
+//        $children = $this->getTreeModelInstance()->getChildren($this->getId());
+//
+//        $myId = array($this->getId());
+//        if (is_array($children)) {
+//            $children = array_merge($myId, $children);
+//        }
+//        else {
+//            $children = $myId;
+//        }
+//        if ($asArray) {
+//            return $children;
+//        }
+//        else {
+//            return implode(',', $children);
+//        }
+    }
+
+    /**
+     * Retrieve children ids comma separated
+     *
+     * @return string
+     */
+    public function getChildren()
+    {
+        return implode(',', $this->getResource()->getChildren($this, false));
+    }
+
+    /**
+     * Retrieve Stores where isset category Path
+     * Return comma separated string
+     *
+     * @return string
+     */
+    public function getPathInStore()
+    {
+        $result = array();
+        //$path = $this->getTreeModelInstance()->getPath($this->getId());
+        $path = array_reverse($this->getPathIds());
+        foreach ($path as $itemId) {
+            if ($itemId == Mage::app()->getStore()->getRootCategoryId()) {
+                break;
+            }
+            $result[] = $itemId;
+        }
+        return implode(',', $result);
+    }
+
+    /**
+     * Check category id exising
+     *
+     * @param   int $id
+     * @return  bool
+     */
+    public function checkId($id)
+    {
+        return $this->_getResource()->checkId($id);
+    }
+
+    /**
+     * Get array categories ids which are part of category path
+     * Result array contain id of current category because it is part of the path
+     *
+     * @return array
+     */
+    public function getPathIds()
+    {
+        $ids = $this->getData('path_ids');
+        if (is_null($ids)) {
+            $ids = explode('/', $this->getPath());
+            $this->setData('path_ids', $ids);
+        }
+        return $ids;
+    }
+
+    /**
+     * Retrieve level
+     *
+     * @return int
+     */
+    public function getLevel()
+    {
+        if (!$this->hasLevel()) {
+            return count(explode('/', $this->getPath())) - 1;
+        }
+        return $this->getData('level');
+    }
+
+    /**
+     * Verify category ids
+     *
+     * @param array $ids
+     * @return bool
+     */
+    public function verifyIds(array $ids)
+    {
+        return $this->getResource()->verifyIds($ids);
+    }
+
+    /**
+     * Retrieve Is Category has children flag
+     *
+     * @return bool
+     */
+    public function hasChildren()
+    {
+        return $this->_getResource()->getChildrenAmount($this) > 0;
+    }
+
+    /**
+     * Retrieve Request Path
+     *
+     * @return string
+     */
+    public function getRequestPath()
+    {
+        return $this->_getData('request_path');
+    }
+
+    /**
+     * Retrieve Name data wraper
+     *
+     * @return string
+     */
+    public function getName()
+    {
+        return $this->_getData('name');
+    }
+
+    /**
+     * Before delete process
+     *
+     * @return Mage_Catalog_Model_Category
+     */
+    protected function _beforeDelete()
+    {
+        $this->_protectFromNonAdmin();
+        if ($this->getResource()->isForbiddenToDelete($this->getId())) {
+            Mage::throwException("Can't delete root category.");
+        }
+        return parent::_beforeDelete();
+    }
+
+    /**
+     * Retrieve anchors above
+     *
+     * @return array
+     */
+    public function getAnchorsAbove()
+    {
+        $anchors = array();
+        $path = $this->getPathIds();
+
+        if (in_array($this->getId(), $path)) {
+            unset($path[array_search($this->getId(), $path)]);
+        }
+
+        if ($this->_useFlatResource) {
+            $anchors = $this->_getResource()->getAnchorsAbove($path, $this->getStoreId());
+        }
+        else {
+            if (!Mage::registry('_category_is_anchor_attribute')) {
+                $model = $this->_getAttribute('is_anchor');
+                Mage::register('_category_is_anchor_attribute', $model);
+            }
+
+            if ($isAnchorAttribute = Mage::registry('_category_is_anchor_attribute')) {
+                $anchors = $this->getResource()->findWhereAttributeIs($path, $isAnchorAttribute, 1);
+            }
+        }
+        return $anchors;
+    }
+
+    /**
+     * Retrieve count products of category
+     *
+     * @return int
+     */
+    public function getProductCount()
+    {
+        if (!$this->hasProductCount()) {
+            $count = $this->_getResource()->getProductCount($this); // load product count
+            $this->setData('product_count', $count);
+        }
+        return $this->getData('product_count');
+    }
+
+    /**
+     * Retrieve categories by parent
+     *
+     * @param int $parent
+     * @param int $recursionLevel
+     * @param bool $sorted
+     * @param bool $asCollection
+     * @param bool $toLoad
+     * @return mixed
+     */
+    public function getCategories($parent, $recursionLevel = 0, $sorted=false, $asCollection=false, $toLoad=true)
+    {
+        $categories = $this->getResource()
+            ->getCategories($parent, $recursionLevel, $sorted, $asCollection, $toLoad);
+        return $categories;
+    }
+
+    /**
+     * Return parent categories of current category
+     *
+     * @return array
+     */
+    public function getParentCategories()
+    {
+        return $this->getResource()->getParentCategories($this);
+    }
+
+    /**
+     * Retuen children categories of current category
+     *
+     * @return array
+     */
+    public function getChildrenCategories()
+    {
+        return $this->getResource()->getChildrenCategories($this);
+    }
+
+    /**
+     * Return parent category of current category with own custom design settings
+     *
+     * @return Mage_Catalog_Model_Category
+     */
+    public function getParentDesignCategory()
+    {
+        return $this->getResource()->getParentDesignCategory($this);
+    }
+
+    /**
+     * Check category is in Root Category list
+     *
+     * @return bool
+     */
+    public function isInRootCategoryList()
+    {
+        return $this->getResource()->isInRootCategoryList($this);
+    }
+
+    /**
+     * Retrieve Available int Product Listing sort by
+     *
+     * @return null|array
+     */
+    public function getAvailableSortBy()
+    {
+        $available = $this->getData('available_sort_by');
+        if (empty($available)) {
+            return array();
+        }
+        if ($available && !is_array($available)) {
+            $available = explode(',', $available);
+        }
+        return $available;
+    }
+
+    /**
+     * Retrieve Available Product Listing  Sort By
+     * code as key, value - name
+     *
+     * @return array
+     */
+    public function getAvailableSortByOptions() {
+        $availableSortBy = array();
+        $defaultSortBy   = Mage::getSingleton('Mage_Catalog_Model_Config')
+            ->getAttributeUsedForSortByArray();
+        if ($this->getAvailableSortBy()) {
+            foreach ($this->getAvailableSortBy() as $sortBy) {
+                if (isset($defaultSortBy[$sortBy])) {
+                    $availableSortBy[$sortBy] = $defaultSortBy[$sortBy];
+                }
+            }
+        }
+
+        if (!$availableSortBy) {
+            $availableSortBy = $defaultSortBy;
+        }
+
+        return $availableSortBy;
+    }
+
+    /**
+     * Retrieve Product Listing Default Sort By
+     *
+     * @return string
+     */
+    public function getDefaultSortBy() {
+        if (!$sortBy = $this->getData('default_sort_by')) {
+            $sortBy = Mage::getSingleton('Mage_Catalog_Model_Config')
+                ->getProductListDefaultSortBy($this->getStoreId());
+        }
+        $available = $this->getAvailableSortByOptions();
+        if (!isset($available[$sortBy])) {
+            $sortBy = array_keys($available);
+            $sortBy = $sortBy[0];
+        }
+
+        return $sortBy;
+    }
+
+    /**
+     * Validate attribute values
+     *
+     * @throws Mage_Eav_Model_Entity_Attribute_Exception
+     * @return bool|array
+     */
+    public function validate()
+    {
+        return $this->_getResource()->validate($this);
+    }
+
+    /**
      * Init indexing process after category save
-     *
-     * @return Mage_Catalog_Model_Category
-     */
-    protected function _afterSave()
-    {
+     *
+     * @return Mage_Catalog_Model_Category
+     */
+    protected function _afterSave()
+    {
         $result = parent::_afterSave();
-        Mage::getSingleton('Mage_Index_Model_Indexer')->processEntityAction(
-            $this, self::ENTITY, Mage_Index_Model_Event::TYPE_SAVE
-        );
+        Mage::getSingleton('Mage_Index_Model_Indexer')->processEntityAction(
+            $this, self::ENTITY, Mage_Index_Model_Event::TYPE_SAVE
+        );
         return $result;
-    }
-}
+    }
+}
diff --git a/app/code/core/Mage/Catalog/Model/Indexer/Url.php b/app/code/core/Mage/Catalog/Model/Indexer/Url.php
index fc0a8632cbadbb684a7c318e5201ec471d353ca7..16907e0b54c6d0434346609db5a6049763875014 100644
--- a/app/code/core/Mage/Catalog/Model/Indexer/Url.php
+++ b/app/code/core/Mage/Catalog/Model/Indexer/Url.php
@@ -222,6 +222,7 @@ class Mage_Catalog_Model_Indexer_Url extends Mage_Index_Model_Indexer_Abstract
             $this->reindexAll();
         }
 
+        /* @var $urlModel Mage_Catalog_Model_Url */
         $urlModel = Mage::getSingleton('Mage_Catalog_Model_Url');
 
         // Force rewrites history saving
diff --git a/app/code/core/Mage/Catalog/Model/Layer.php b/app/code/core/Mage/Catalog/Model/Layer.php
index fae1238644799d0078fff644d6852566066aa254..f534a58a6ce127112e6db7e11bda61a0063bd743 100644
--- a/app/code/core/Mage/Catalog/Model/Layer.php
+++ b/app/code/core/Mage/Catalog/Model/Layer.php
@@ -110,7 +110,6 @@ class Mage_Catalog_Model_Layer extends Varien_Object
             ->addMinimalPrice()
             ->addFinalPrice()
             ->addTaxPercents()
-            //->addStoreFilter()
             ->addUrlRewrite($this->getCurrentCategory()->getId())
             ->setVisibility(Mage::getSingleton('Mage_Catalog_Model_Product_Visibility')->getVisibleInCatalogIds());
 
diff --git a/app/code/core/Mage/Catalog/Model/Layer/Filter/Attribute.php b/app/code/core/Mage/Catalog/Model/Layer/Filter/Attribute.php
index 4c92b0a8a85b04a66af281a20e4220844d954385..a3515cb4e06e08aebad5efe0681864b793569aa3 100644
--- a/app/code/core/Mage/Catalog/Model/Layer/Filter/Attribute.php
+++ b/app/code/core/Mage/Catalog/Model/Layer/Filter/Attribute.php
@@ -122,7 +122,6 @@ class Mage_Catalog_Model_Layer_Filter_Attribute extends Mage_Catalog_Model_Layer
         $options = $attribute->getFrontend()->getSelectOptions();
         $optionsCount = $this->_getResource()->getCount($this);
         $data = array();
-
         foreach ($options as $option) {
             if (is_array($option['value'])) {
                 continue;
diff --git a/app/code/core/Mage/Catalog/Model/Layer/Filter/Price.php b/app/code/core/Mage/Catalog/Model/Layer/Filter/Price.php
index 14f119f7ccd6d39f7236f8dd01ab3eb815a5953a..8f9b5f7cca141690835b1abf698ed6c470ae2ca5 100644
--- a/app/code/core/Mage/Catalog/Model/Layer/Filter/Price.php
+++ b/app/code/core/Mage/Catalog/Model/Layer/Filter/Price.php
@@ -38,14 +38,25 @@
  */
 class Mage_Catalog_Model_Layer_Filter_Price extends Mage_Catalog_Model_Layer_Filter_Abstract
 {
-    const XML_PATH_RANGE_CALCULATION    = 'catalog/layered_navigation/price_range_calculation';
-    const XML_PATH_RANGE_STEP           = 'catalog/layered_navigation/price_range_step';
-    const XML_PATH_RANGE_MAX_INTERVALS  = 'catalog/layered_navigation/price_range_max_intervals';
-    const XML_PATH_ONE_PRICE_INTERVAL  = 'catalog/layered_navigation/one_price_interval';
-    const XML_PATH_INTERVAL_DIVISION_LIMIT  = 'catalog/layered_navigation/interval_division_limit';
-
-    const RANGE_CALCULATION_AUTO    = 'auto';
-    const RANGE_CALCULATION_MANUAL  = 'manual';
+    /**
+     * XML configuration paths for Price Layered Navigation
+     */
+    const XML_PATH_RANGE_CALCULATION       = 'catalog/layered_navigation/price_range_calculation';
+    const XML_PATH_RANGE_STEP              = 'catalog/layered_navigation/price_range_step';
+    const XML_PATH_RANGE_MAX_INTERVALS     = 'catalog/layered_navigation/price_range_max_intervals';
+    const XML_PATH_ONE_PRICE_INTERVAL      = 'catalog/layered_navigation/one_price_interval';
+    const XML_PATH_INTERVAL_DIVISION_LIMIT = 'catalog/layered_navigation/interval_division_limit';
+
+    /**
+     * Price layered navigation modes: Automatic (equalize price ranges), Automatic (equalize product counts), Manual
+     */
+    const RANGE_CALCULATION_AUTO     = 'auto'; // equalize price ranges
+    const RANGE_CALCULATION_IMPROVED = 'improved'; // equalize product counts
+    const RANGE_CALCULATION_MANUAL   = 'manual';
+
+    /**
+     * Minimal size of the range
+     */
     const MIN_RANGE_POWER = 10;
 
     /**
@@ -106,7 +117,7 @@ class Mage_Catalog_Model_Layer_Filter_Price extends Mage_Catalog_Model_Layer_Fil
                     }
                     while($range > self::MIN_RANGE_POWER && count($items) < 2);
                 } else {
-                    $range = Mage::app()->getStore()->getConfig(self::XML_PATH_RANGE_STEP);
+                    $range = (float)Mage::app()->getStore()->getConfig(self::XML_PATH_RANGE_STEP);
                 }
             }
 
@@ -125,7 +136,7 @@ class Mage_Catalog_Model_Layer_Filter_Price extends Mage_Catalog_Model_Layer_Fil
     {
         $maxPrice = $this->getData('max_price_int');
         if (is_null($maxPrice)) {
-            $maxPrice = $this->_getResource()->getMaxPrice($this);
+            $maxPrice = $this->getLayer()->getProductCollection()->getMaxPrice();
             $maxPrice = floor($maxPrice);
             $this->setData('max_price_int', $maxPrice);
         }
@@ -149,9 +160,10 @@ class Mage_Catalog_Model_Layer_Filter_Price extends Mage_Catalog_Model_Layer_Fil
             $i = 0;
             $lastIndex = null;
             $maxIntervalsNumber = $this->getMaxIntervalsNumber();
+            $calculation = Mage::app()->getStore()->getConfig(self::XML_PATH_RANGE_CALCULATION);
             foreach ($items as $k => $v) {
                 ++$i;
-                if ($i > 1 && $i > $maxIntervalsNumber) {
+                if ($calculation == self::RANGE_CALCULATION_MANUAL && $i > 1 && $i > $maxIntervalsNumber) {
                     $items[$lastIndex] += $v;
                     unset($items[$k]);
                 } else {
@@ -192,7 +204,7 @@ class Mage_Catalog_Model_Layer_Filter_Price extends Mage_Catalog_Model_Layer_Fil
     {
         $store      = Mage::app()->getStore();
         $formattedFromPrice  = $store->formatPrice($fromPrice);
-        if (empty($toPrice)) {
+        if ($toPrice === '') {
             return Mage::helper('Mage_Catalog_Helper_Data')->__('%s and above', $formattedFromPrice);
         } elseif ($fromPrice == $toPrice && Mage::app()->getStore()->getConfig(self::XML_PATH_ONE_PRICE_INTERVAL)) {
             return $formattedFromPrice;
@@ -233,11 +245,23 @@ class Mage_Catalog_Model_Layer_Filter_Price extends Mage_Catalog_Model_Layer_Fil
     {
         /** @var $algorithmModel Mage_Catalog_Model_Layer_Filter_Price_Algorithm */
         $algorithmModel = Mage::getSingleton('Mage_Catalog_Model_Layer_Filter_Price_Algorithm');
+        $collection = $this->getLayer()->getProductCollection();
+        if ($collection->getPricesCount() <= $this->getIntervalDivisionLimit()) {
+            return array();
+        }
+        $algorithmModel->setPricesModel($this)->setStatistics(
+            $collection->getMinPrice(),
+            $collection->getMaxPrice(),
+            $collection->getPriceStandardDeviation(),
+            $collection->getPricesCount()
+        );
         $appliedInterval = $this->getInterval();
         if ($appliedInterval) {
+            if ($appliedInterval[0] == $appliedInterval[1]) {
+                return array();
+            }
             $algorithmModel->setLimits($appliedInterval[0], $appliedInterval[1]);
         }
-        $this->_getResource()->loadAllPrices($algorithmModel, $this);
 
         $items = array();
         foreach ($algorithmModel->calculateSeparators() as $separator) {
@@ -259,7 +283,7 @@ class Mage_Catalog_Model_Layer_Filter_Price extends Mage_Catalog_Model_Layer_Fil
      */
     protected function _getItemsData()
     {
-        if (Mage::app()->getStore()->getConfig(self::XML_PATH_RANGE_CALCULATION) == self::RANGE_CALCULATION_AUTO) {
+        if (Mage::app()->getStore()->getConfig(self::XML_PATH_RANGE_CALCULATION) == self::RANGE_CALCULATION_IMPROVED) {
             return $this->_getCalculatedItemsData();
         } elseif ($this->getInterval()) {
             return array();
@@ -312,7 +336,7 @@ class Mage_Catalog_Model_Layer_Filter_Price extends Mage_Catalog_Model_Layer_Fil
             return false;
         }
         foreach ($filter as $v) {
-            if ($v !== '' && (float)$v <= 0) {
+            if (($v !== '' && $v !== '0' && (float)$v <= 0) || is_infinite((float)$v)) {
                 return false;
             }
         }
@@ -485,10 +509,67 @@ class Mage_Catalog_Model_Layer_Filter_Price extends Mage_Catalog_Model_Layer_Fil
      */
     public function getClearLinkText()
     {
-        if (Mage::app()->getStore()->getConfig(self::XML_PATH_RANGE_CALCULATION) == self::RANGE_CALCULATION_AUTO) {
+        if (Mage::app()->getStore()->getConfig(self::XML_PATH_RANGE_CALCULATION) == self::RANGE_CALCULATION_IMPROVED
+            && $this->getPriorIntervals()
+        ) {
             return Mage::helper('Mage_Catalog_Helper_Data')->__('Clear Price');
         }
 
         return parent::getClearLinkText();
     }
+
+    /**
+     * Load range of product prices
+     *
+     * @param int $limit
+     * @param null|int $offset
+     * @param null|int $lowerPrice
+     * @param null|int $upperPrice
+     * @return array|false
+     */
+    public function loadPrices($limit, $offset = null, $lowerPrice = null, $upperPrice = null)
+    {
+        $prices = $this->_getResource()->loadPrices($this, $limit, $offset, $lowerPrice, $upperPrice);
+        if ($prices) {
+            $prices = array_map('floatval', $prices);
+        }
+
+        return $prices;
+    }
+
+    /**
+     * Load range of product prices, preceding the price
+     *
+     * @param float $price
+     * @param int $index
+     * @param null|int $lowerPrice
+     * @return array|false
+     */
+    public function loadPreviousPrices($price, $index, $lowerPrice = null)
+    {
+        $prices = $this->_getResource()->loadPreviousPrices($this, $price, $index, $lowerPrice);
+        if ($prices) {
+            $prices = array_map('floatval', $prices);
+        }
+
+        return $prices;
+    }
+
+    /**
+     * Load range of product prices, next to the price
+     *
+     * @param float $price
+     * @param int $rightIndex
+     * @param null|int $upperPrice
+     * @return array|false
+     */
+    public function loadNextPrices($price, $rightIndex, $upperPrice = null)
+    {
+        $prices = $this->_getResource()->loadNextPrices($this, $price, $rightIndex, $upperPrice);
+        if ($prices) {
+            $prices = array_map('floatval', $prices);
+        }
+
+        return $prices;
+    }
 }
diff --git a/app/code/core/Mage/Catalog/Model/Layer/Filter/Price/Algorithm.php b/app/code/core/Mage/Catalog/Model/Layer/Filter/Price/Algorithm.php
index 8d2a8afe8cc2f6dce29086c9c0f7012d94bfab85..82b61a5551b4f3dc1492e393513dbcfbac015304 100644
--- a/app/code/core/Mage/Catalog/Model/Layer/Filter/Price/Algorithm.php
+++ b/app/code/core/Mage/Catalog/Model/Layer/Filter/Price/Algorithm.php
@@ -33,16 +33,41 @@
  */
 class Mage_Catalog_Model_Layer_Filter_Price_Algorithm
 {
-    const MIN_POSSIBLE_PRICE = .01;
+    /**
+     * Rounding factor coefficient
+     */
     const TEN_POWER_ROUNDING_FACTOR = 4;
+
+    /**
+     * Interval deflection coefficient
+     */
     const INTERVAL_DEFLECTION_LIMIT = .3;
 
     /**
-     * Sorted array of all products prices
+     * Standard normal distribution's  a/2 quantile
+     * Depends on predefined a. In case of a=0.05
+     */
+    const STANDARD_NORMAL_DISTRIBUTION = 1.96;
+
+    /**
+     * Min and Max number of intervals
+     */
+    const MIN_INTERVALS_NUMBER = 2;
+    const MAX_INTERVALS_NUMBER = 10;
+
+    /**
+     * Upper prices limit
      *
-     * @var array
+     * @var null|float
      */
-    protected $_prices = null;
+    protected $_upperLimit = null;
+
+    /**
+     * Lower prices limit
+     *
+     * @var null|float
+     */
+    protected $_lowerLimit = null;
 
     /**
      * Number of segmentation intervals
@@ -59,29 +84,77 @@ class Mage_Catalog_Model_Layer_Filter_Price_Algorithm
     protected $_skippedQuantilesUpperLimits = array();
 
     /**
-     * Upper prices limit
+     * Total count of prices
      *
-     * @var null|float
+     * @var int
      */
-    protected $_upperLimit = null;
+    protected $_count = 0;
 
     /**
-     * Lower prices limit
+     * Prices model
      *
-     * @var null|float
+     * @var null|Mage_Catalog_Model_Layer_Filter_Price
      */
-    protected $_lowerLimit = null;
+    protected $_pricesModel = null;
 
     /**
-     * Search index of price, that satisfy conditions to be less or greater-or-equal than $value
+     * Current quantile interval
+     *
+     * @var array [from, to]
+     */
+    protected $_quantileInterval = array(0, 0);
+
+    /**
+     * Prices of current quantile
+     *
+     * @var array
+     */
+    protected $_prices = array();
+
+    /**
+     * Max price
+     *
+     * @var float
+     */
+    protected $_maxPrice = 0;
+
+    /**
+     * Min price
+     *
+     * @var float
+     */
+    protected $_minPrice = 0;
+
+    /**
+     * Last price query limiter
+     *
+     * @var array [index, value]
+     */
+    protected $_lastPriceLimiter = array(null, 0);
+
+    /**
+     * Set lower and upper limit for algorithm
+     *
+     * @param null|float $lowerLimit
+     * @param null|float $upperLimit
+     * @return Mage_Catalog_Model_Layer_Filter_Price_Algorithm
+     */
+    public function setLimits($lowerLimit = null, $upperLimit = null)
+    {
+        $this->_lowerLimit = empty($lowerLimit) ? null : (float)$lowerLimit;
+        $this->_upperLimit = empty($upperLimit) ? null : (float)$upperLimit;
+        return $this;
+    }
+
+    /**
+     * Search first index of price, that satisfy conditions to be 'greater or equal' than $value
      * Returns -1 if index was not found
      *
      * @param float $value
      * @param null|array $limits search [from, to]
-     * @param bool $isLess (to be less or greater-or-equal)
      * @return int
      */
-    protected function _binarySearch($value, $limits = null, $isLess = true)
+    protected function _binarySearch($value, $limits = null)
     {
         if (empty($this->_prices)) {
             return -1;
@@ -97,95 +170,65 @@ class Mage_Catalog_Model_Layer_Filter_Price_Algorithm
             $limits[1] = count($this->_prices) - 1;
         }
 
-        if ($limits[0] > $limits[1]
-            || ($isLess && $this->_prices[$limits[1]] < $value)
-            || (!$isLess && $this->_prices[$limits[0]] >= $value)
-        ) {
+        if ($limits[0] > $limits[1] || $this->_prices[$limits[1]] < $value) {
             return -1;
         }
 
         if ($limits[1] - $limits[0] <= 1) {
-            if ($isLess) {
-                return ($this->_prices[$limits[0]] < $value) ? $limits[1] : $limits[0];
-            } else {
-                return ($this->_prices[$limits[1]] >= $value) ? $limits[0] : $limits[1];
-            }
+            return ($this->_prices[$limits[0]] < $value) ? $limits[1] : $limits[0];
         }
 
         $separator = floor(($limits[0] + $limits[1]) / 2);
-        if ($isLess) {
-            if ($this->_prices[$separator] < $value) {
-                $limits[0] = $separator + 1;
-            } else {
-                $limits[1] = $separator;
-            }
+        if ($this->_prices[$separator] < $value) {
+            $limits[0] = $separator + 1;
         } else {
-            if ($this->_prices[$separator] >= $value) {
-                $limits[1] = $separator - 1;
-            } else {
-                $limits[0] = $separator;
-            }
+            $limits[1] = $separator;
         }
 
-        return $this->_binarySearch($value, array($limits[0], $limits[1]), $isLess);
+        return $this->_binarySearch($value, array($limits[0], $limits[1]));
     }
 
     /**
-     * Check prices to be in limits interval
+     * Set prices statistics
      *
+     * @param float $min
+     * @param float $max
+     * @param float $standardDeviation
+     * @param int $count
      * @return Mage_Catalog_Model_Layer_Filter_Price_Algorithm
      */
-    protected function _checkPrices()
+    public function setStatistics($min, $max, $standardDeviation, $count)
     {
-        if (is_null($this->_prices)) {
+        $this->_count = $count;
+        $this->_minPrice = $min;
+        $this->_maxPrice = $max;
+        $priceRange = $max - $min;
+        if ($count < 2 || ($priceRange <= 0)) {
+            //Same price couldn't be separated with several intervals
+            $this->_intervalsNumber = 1;
             return $this;
         }
 
-        if (!is_null($this->_upperLimit) || !is_null($this->_lowerLimit)) {
-            $right = is_null($this->_upperLimit)
-                ? (count($this->_prices) - 1)
-                : $this->_binarySearch($this->_upperLimit, null, false);
-            $left = is_null($this->_lowerLimit)
-                ? 0
-                : $this->_binarySearch($this->_lowerLimit, array(0, $right));
-            if ($left > $right) {
-                $this->_prices = array();
-            } else {
-                $this->_prices = array_slice($this->_prices, $left, $right - $left + 1);
-            }
+        if ($standardDeviation <= 0) {
+            $intervalsNumber = pow(10, self::TEN_POWER_ROUNDING_FACTOR);
+        } else {
+            $intervalsNumber = $priceRange * pow($count, 1 / 3) / (3.5 * $standardDeviation);
         }
-        return $this;
-    }
+        $this->_intervalsNumber = max(ceil($intervalsNumber), self::MIN_INTERVALS_NUMBER);
+        $this->_intervalsNumber = (int)min($this->_intervalsNumber, self::MAX_INTERVALS_NUMBER);
 
-    /**
-     * Set lower and upper limit for algorithm
-     *
-     * @param null|float $lowerLimit
-     * @param null|float $upperLimit
-     * @return Mage_Catalog_Model_Layer_Filter_Price_Algorithm
-     */
-    public function setLimits($lowerLimit = null, $upperLimit = null)
-    {
-        $this->_lowerLimit = empty($lowerLimit) ? null : (float)$lowerLimit;
-        $this->_upperLimit = empty($upperLimit) ? null : (float)$upperLimit;
-        $this->_checkPrices();
         return $this;
     }
 
     /**
-     * Set products prices
+     * Set prices model
      *
-     * @param array $prices due to performance issue prices should be sorted (by DBMS engine)
+     * @param Mage_Catalog_Model_Layer_Filter_Price $pricesModel
      * @return Mage_Catalog_Model_Layer_Filter_Price_Algorithm
      */
-    public function setPrices(array $prices)
+    public function setPricesModel($pricesModel)
     {
-        $this->_prices = $prices;
-
-        $this->_checkPrices();
-        $this->_intervalsNumber = null;
-        $this->_skippedQuantilesUpperLimits = array();
-
+        $this->_pricesModel = $pricesModel;
         return $this;
     }
 
@@ -200,30 +243,7 @@ class Mage_Catalog_Model_Layer_Filter_Price_Algorithm
             return $this->_intervalsNumber;
         }
 
-        $pricesCount = count($this->_prices);
-        $priceRange = empty($this->_prices) ? 0 : ($this->_prices[count($this->_prices) - 1] - $this->_prices[0]);
-        if ($pricesCount < 2 || ($priceRange == 0)) {
-            //Same price couldn't be separated with several intervals
-            $this->_intervalsNumber = 1;
-            return $this->_intervalsNumber;
-        }
-
-        $sum = 0;
-        $sumSquares = 0;
-        foreach ($this->_prices as $price) {
-            $sum += $price;
-            $sumSquares += $price * $price;
-        }
-
-        if ($pricesCount * $sumSquares - $sum * $sum <= 0) {
-            $intervalsNumber = 1000;
-        } else {
-            $intervalsNumber = $priceRange * pow($pricesCount, 5 / 6)
-                * sqrt(($pricesCount - 1) / ($pricesCount * $sumSquares - $sum * $sum)) / 3.5;
-        }
-        $this->_intervalsNumber = min(max(ceil($intervalsNumber), 2), 10);
-
-        return $this->_intervalsNumber;
+        return 1;
     }
 
     /**
@@ -248,7 +268,7 @@ class Mage_Catalog_Model_Layer_Filter_Price_Algorithm
             return 0;
         }
 
-        return $quantileNumber * count($this->_prices) / $this->getIntervalsNumber() - .5;
+        return $quantileNumber * $this->_count / $this->getIntervalsNumber() - .5;
     }
 
     /**
@@ -262,16 +282,15 @@ class Mage_Catalog_Model_Layer_Filter_Price_Algorithm
         if ($quantileNumber < 1 || $quantileNumber >= $this->getIntervalsNumber()) {
             return null;
         }
-        $pricesCount = count($this->_prices);
         $quantile = $this->_getQuantile($quantileNumber);
-        $deflectionLimit = floor($pricesCount / 2 / $this->getIntervalsNumber());
+        $deflectionLimit = floor($this->_count / 2 / $this->getIntervalsNumber());
         $limits = array(
             min(floor($quantile - $deflectionLimit), floor($quantile)),
             max(ceil($quantile + $deflectionLimit - 1), ceil($quantile)),
         );
 
-        $deflection = $this->_getStandardNormalDistribution()
-            * sqrt($pricesCount * $quantileNumber * ($this->getIntervalsNumber() - $quantileNumber))
+        $deflection = self::STANDARD_NORMAL_DISTRIBUTION
+            * sqrt($this->_count * $quantileNumber * ($this->getIntervalsNumber() - $quantileNumber))
             / $this->getIntervalsNumber();
         $left = max(floor($quantile - $deflection - 1), $limits[0], 0);
         if (array_key_exists($quantileNumber - 1, $this->_skippedQuantilesUpperLimits)
@@ -279,73 +298,8 @@ class Mage_Catalog_Model_Layer_Filter_Price_Algorithm
         ) {
             $left = $this->_skippedQuantilesUpperLimits[$quantileNumber - 1];
         }
-        $right = min(ceil($quantile + $deflection), $limits[1], $pricesCount - 1);
+        $right = min(ceil($quantile + $deflection), $limits[1], $this->_count - 1);
         return array($left, $right);
-     }
-
-    /**
-     * Get standard normal distribution
-     *
-     * @return float
-     */
-    protected function _getStandardNormalDistribution()
-    {
-        return 1.96;
-    }
-
-    /**
-     * Find max rounding factor with given price range
-     *
-     * @param float $lowerPrice
-     * @param float $upperPrice
-     * @param bool $returnEmpty whether empty result is acceptable
-     * @param null|float $roundingFactor if given, checks for range to contain the factor
-     * @return false|array
-     */
-    protected function _findRoundPrice($lowerPrice, $upperPrice, $returnEmpty = true, $roundingFactor = null)
-    {
-        $lowerPrice = round($lowerPrice, 3);
-        $upperPrice = round($upperPrice, 3);
-
-        if (!is_null($roundingFactor)) {
-            // Can't separate if prices are equal
-            if ($lowerPrice >= $upperPrice) {
-                if ($lowerPrice > $upperPrice || $returnEmpty) {
-                    return false;
-                }
-            }
-            // round is used for such examples: (1194.32 / 0.02) or (5 / 100000)
-            $lowerDivision = ceil(round($lowerPrice / $roundingFactor, self::TEN_POWER_ROUNDING_FACTOR + 3));
-            $upperDivision = floor(round($upperPrice / $roundingFactor, self::TEN_POWER_ROUNDING_FACTOR + 3));
-
-            $result = array();
-            for ($i = $lowerDivision; $i <= $upperDivision; ++$i) {
-                $result[] = round($i * $roundingFactor, 2);
-            }
-
-            return $result;
-        }
-
-        $result = array();
-        $tenPower = pow(10, self::TEN_POWER_ROUNDING_FACTOR);
-        $roundingFactorCoefficients = array(10, 5, 2);
-        while ($tenPower >= self::MIN_POSSIBLE_PRICE) {
-            if ($tenPower == self::MIN_POSSIBLE_PRICE) {
-                $roundingFactorCoefficients[] = 1;
-            }
-            foreach ($roundingFactorCoefficients as $roundingFactorCoefficient) {
-                $roundingFactorCoefficient *= $tenPower;
-                $roundPrices = $this->_findRoundPrice(
-                    $lowerPrice, $upperPrice, $returnEmpty, $roundingFactorCoefficient
-                );
-                if ($roundPrices) {
-                    $result[round($roundingFactorCoefficient / self::MIN_POSSIBLE_PRICE)] = $roundPrices;
-                }
-            }
-            $tenPower /= 10;
-        }
-
-        return empty($result) ? array(1 => array()) : $result;
     }
 
     /**
@@ -381,33 +335,70 @@ class Mage_Catalog_Model_Layer_Filter_Price_Algorithm
             return null;
         }
 
+        $prices = array();
         $quantileInterval = $this->_getQuantileInterval($quantileNumber);
+        $intervalPricesCount = $quantileInterval[1] - $quantileInterval[0] + 1;
+        $offset = $quantileInterval[0];
+        if (!is_null($this->_lastPriceLimiter[0])) {
+            $offset -= $this->_lastPriceLimiter[0];
+        }
+        if ($offset < 0) {
+            $intervalPricesCount += $offset;
+            $prices = array_slice(
+                $this->_prices,
+                $this->_lastPriceLimiter[0] + $offset - $this->_quantileInterval[0],
+                -$offset
+            );
+            $offset = 0;
+        }
+        $lowerPrice = $this->_lastPriceLimiter[1];
+        if (!is_null($this->_lowerLimit)) {
+            $lowerPrice = max($lowerPrice, $this->_lowerLimit);
+        }
+        if ($intervalPricesCount >= 0) {
+            $prices = array_merge($prices, $this->_pricesModel->loadPrices(
+                $intervalPricesCount + 1,
+                $offset,
+                $lowerPrice,
+                $this->_upperLimit
+            ));
+        }
+        $lastPrice = $prices[$intervalPricesCount - 1];
         $bestRoundPrice = array();
-
-        if ($this->_prices[$quantileInterval[0]] == $this->_prices[$quantileInterval[1]]) {
-            if ($quantileNumber == 1) {
-                $index = $this->_binarySearch(
-                    $this->_prices[$quantileInterval[1]],
-                    array(0, $quantileInterval[0]),
-                    false
-                );
-                if ($index != -1) {
+        if ($lastPrice == $prices[0]) {
+            if ($quantileNumber == 1 && $offset) {
+                $additionalPrices = $this->_pricesModel
+                    ->loadPreviousPrices($lastPrice, $quantileInterval[0], $this->_lowerLimit);
+                if ($additionalPrices) {
+                    $quantileInterval[0] -= count($additionalPrices);
+                    $prices = array_merge($additionalPrices, $prices);
                     $bestRoundPrice = $this->_findRoundPrice(
-                        $this->_prices[$index] + self::MIN_POSSIBLE_PRICE / 10,
-                        $this->_prices[$quantileInterval[1]],
+                        $prices[0] + Mage_Catalog_Model_Resource_Layer_Filter_Price::MIN_POSSIBLE_PRICE / 10,
+                        $lastPrice,
                         false
                     );
                 }
             }
             if ($quantileNumber == $this->getIntervalsNumber() - 1) {
-                $index = $this->_binarySearch(
-                    $this->_prices[$quantileInterval[0]] + self::MIN_POSSIBLE_PRICE / 10,
-                    array($quantileInterval[1])
-                );
-                if ($index != -1) {
+                $pricesCount = count($prices);
+                if ($prices[$pricesCount - 1] > $lastPrice) {
+                    $additionalPrices = array($prices[$pricesCount - 1]);
+                } else {
+                    $additionalPrices = $this->_pricesModel->loadNextPrices(
+                        $lastPrice,
+                        $this->_count - $quantileInterval[0] - count($prices),
+                        $this->_upperLimit
+                    );
+                }
+                if ($additionalPrices) {
+                    $quantileInterval[1] = $quantileInterval[0] + count($prices) - 1;
+                    if ($prices[$pricesCount - 1] <= $lastPrice) {
+                        $quantileInterval[1] += count($additionalPrices);
+                        $prices = array_merge($prices, $additionalPrices);
+                    }
                     $upperBestRoundPrice = $this->_findRoundPrice(
-                        $this->_prices[$quantileInterval[0]] + self::MIN_POSSIBLE_PRICE / 10,
-                        $this->_prices[$index],
+                        $lastPrice + Mage_Catalog_Model_Resource_Layer_Filter_Price::MIN_POSSIBLE_PRICE / 10,
+                        $prices[count($prices) - 1],
                         false
                     );
                     $this->_mergeRoundPrices($bestRoundPrice, $upperBestRoundPrice);
@@ -415,16 +406,24 @@ class Mage_Catalog_Model_Layer_Filter_Price_Algorithm
             }
         } else {
             $bestRoundPrice = $this->_findRoundPrice(
-                $this->_prices[$quantileInterval[0]] + self::MIN_POSSIBLE_PRICE / 10,
-                $this->_prices[$quantileInterval[1]]
+                $prices[0] + Mage_Catalog_Model_Resource_Layer_Filter_Price::MIN_POSSIBLE_PRICE / 10,
+                $lastPrice
             );
         }
 
+        $this->_quantileInterval = $quantileInterval;
+        $this->_prices = $prices;
+
         if (empty($bestRoundPrice)) {
             $this->_skippedQuantilesUpperLimits[$quantileNumber] = $quantileInterval[1];
             return $bestRoundPrice;
         }
 
+        $pricesCount = count($prices);
+        if ($prices[$pricesCount - 1] > $lastPrice) {
+            $this->_lastPriceLimiter = array($quantileInterval[0] + $pricesCount - 1, $prices[$pricesCount - 1]);
+        }
+
         ksort($bestRoundPrice, SORT_NUMERIC);
         foreach ($bestRoundPrice as $index => &$bestRoundPriceValues) {
             if (empty($bestRoundPriceValues)) {
@@ -436,19 +435,79 @@ class Mage_Catalog_Model_Layer_Filter_Price_Algorithm
         return array_reverse($bestRoundPrice);
     }
 
+    /**
+     * Find max rounding factor with given price range
+     *
+     * @param float $lowerPrice
+     * @param float $upperPrice
+     * @param bool $returnEmpty whether empty result is acceptable
+     * @param null|float $roundingFactor if given, checks for range to contain the factor
+     * @return false|array
+     */
+    protected function _findRoundPrice($lowerPrice, $upperPrice, $returnEmpty = true, $roundingFactor = null)
+    {
+        $lowerPrice = round($lowerPrice, 3);
+        $upperPrice = round($upperPrice, 3);
+
+        if (!is_null($roundingFactor)) {
+            // Can't separate if prices are equal
+            if ($lowerPrice >= $upperPrice) {
+                if ($lowerPrice > $upperPrice || $returnEmpty) {
+                    return false;
+                }
+            }
+            // round is used for such examples: (1194.32 / 0.02) or (5 / 100000)
+            $lowerDivision = ceil(round($lowerPrice / $roundingFactor, self::TEN_POWER_ROUNDING_FACTOR + 3));
+            $upperDivision = floor(round($upperPrice / $roundingFactor, self::TEN_POWER_ROUNDING_FACTOR + 3));
+
+            $result = array();
+            if ($upperDivision <= 0 || $upperDivision - $lowerDivision > 10) {
+                return $result;
+            }
+
+            for ($i = $lowerDivision; $i <= $upperDivision; ++$i) {
+                $result[] = round($i * $roundingFactor, 2);
+            }
+
+            return $result;
+        }
+
+        $result = array();
+        $tenPower = pow(10, self::TEN_POWER_ROUNDING_FACTOR);
+        $roundingFactorCoefficients = array(10, 5, 2);
+        while ($tenPower >= Mage_Catalog_Model_Resource_Layer_Filter_Price::MIN_POSSIBLE_PRICE) {
+            if ($tenPower == Mage_Catalog_Model_Resource_Layer_Filter_Price::MIN_POSSIBLE_PRICE) {
+                $roundingFactorCoefficients[] = 1;
+            }
+            foreach ($roundingFactorCoefficients as $roundingFactorCoefficient) {
+                $roundingFactorCoefficient *= $tenPower;
+                $roundPrices = $this->_findRoundPrice(
+                    $lowerPrice, $upperPrice, $returnEmpty, $roundingFactorCoefficient
+                );
+                if ($roundPrices) {
+                    $index = round($roundingFactorCoefficient
+                        / Mage_Catalog_Model_Resource_Layer_Filter_Price::MIN_POSSIBLE_PRICE);
+                    $result[$index] = $roundPrices;
+                }
+            }
+            $tenPower /= 10;
+        }
+
+        return empty($result) ? array(1 => array()) : $result;
+    }
+
     /**
      * Get separator nearest to quantile among the separators
      *
      * @param int $quantileNumber
      * @param array $separators
-     * @param int $priceIndex
-     * @return bool|array [separatorPrice, pricesCount]
+     * @return bool|array [deflection, separatorPrice, $priceIndex]
      */
-    protected function _findBestSeparator($quantileNumber, $separators, $priceIndex)
+    protected function _findBestSeparator($quantileNumber, $separators)
     {
         $result = false;
 
-        $i = $priceIndex;
+        $i = 0;
         $pricesCount = count($this->_prices);
         while ($i < $pricesCount && !empty($separators)) {
             $i = $this->_binarySearch($separators[0], array($i));
@@ -458,9 +517,10 @@ class Mage_Catalog_Model_Layer_Filter_Price_Algorithm
 
             $separator = array_shift($separators);
 
-            $deflection = abs(($quantileNumber + 1) * $pricesCount - $i * $this->_getCalculatedIntervalsNumber());
+            $deflection = abs($quantileNumber * $this->_count
+                - ($this->_quantileInterval[0] + $i) * $this->_getCalculatedIntervalsNumber());
             if (!$result || $deflection < $result[0]) {
-                $result = array($deflection, $separator, $i - $priceIndex);
+                $result = array($deflection, $separator, $i);
             }
         }
 
@@ -474,67 +534,74 @@ class Mage_Catalog_Model_Layer_Filter_Price_Algorithm
      */
     public function calculateSeparators()
     {
-        $this->_checkPrices();
-        $separators = array();
-        for ($i = 1; $i < $this->getIntervalsNumber(); ++$i) {
-            $separators[] = $this->_findPriceSeparator($i);
-        }
-        $pricesCount = count($this->_prices);
-
-        $i = 0;
         $result = array();
+        $lastCount = 0;
+        $intervalFirstPrice = $this->_minPrice;
         $lastSeparator = is_null($this->_lowerLimit) ? 0 : $this->_lowerLimit;
-        $quantile = 0;
-        $pricesPerInterval = $pricesCount / $this->_getCalculatedIntervalsNumber();
-        while (!empty($separators) && ($i < $pricesCount)) {
-            while (!empty($separators) && empty($separators[0])) {
-                array_shift($separators);
+
+        for ($i = 1; $i < $this->getIntervalsNumber(); ++$i) {
+            $separator = $this->_findPriceSeparator($i);
+            if (empty($separator)) {
+                continue;
             }
-            if (empty($separators)) {
-                break;
+            if ($this->_quantileInterval[0] == 0) {
+                $intervalFirstPrice = $this->_prices[0];
             }
-
             $separatorCandidate = false;
+            $newIntervalFirstPrice = $intervalFirstPrice;
             $newLastSeparator = $lastSeparator;
-            while (!empty($separators[0]) && !array_key_exists($quantile, $result)) {
-                $separatorsPortion = array_shift($separators[0]);
-                $bestSeparator = $this->_findBestSeparator($quantile, $separatorsPortion, $i);
+
+            $pricesPerInterval = $this->_count / $this->_getCalculatedIntervalsNumber();
+            while (!empty($separator) && !array_key_exists($i, $result)) {
+                $separatorsPortion = array_shift($separator);
+                $bestSeparator = $this->_findBestSeparator($i, $separatorsPortion);
                 if ($bestSeparator && $bestSeparator[2] > 0) {
-                    $isEqualPrice = ($this->_prices[$i] == $this->_prices[$i + $bestSeparator[2] - 1])
-                        ? $this->_prices[$i]
+                    $isEqualPrice = ($intervalFirstPrice == $this->_prices[$bestSeparator[2] - 1])
+                        ? $this->_prices[0]
                         : false;
+                    $count = $bestSeparator[2] + $this->_quantileInterval[0] - $lastCount;
                     $separatorData = array(
                         'from'  => ($isEqualPrice !== false) ? $isEqualPrice : $lastSeparator,
                         'to'    => ($isEqualPrice !== false) ? $isEqualPrice : $bestSeparator[1],
-                        'count' => $bestSeparator[2],
+                        'count' => $count,
                     );
-                    if (abs(1 - $bestSeparator[2] / $pricesPerInterval) <= self::INTERVAL_DEFLECTION_LIMIT) {
+                    if (abs(1 - $count / $pricesPerInterval) <= self::INTERVAL_DEFLECTION_LIMIT) {
                         $newLastSeparator = $bestSeparator[1];
-                        $result[$quantile] = $separatorData;
+                        $newIntervalFirstPrice = $this->_prices[$bestSeparator[2]];
+                        $result[$i] = $separatorData;
                     } elseif (!$separatorCandidate || $bestSeparator[0] < $separatorCandidate[0]) {
-                        $separatorCandidate = array($bestSeparator[0], $separatorData, $bestSeparator[1]);
+                        $separatorCandidate = array(
+                            $bestSeparator[0],
+                            $separatorData,
+                            $bestSeparator[1],
+                            $this->_prices[$bestSeparator[2]]
+                        );
                     }
                 }
             }
 
-            if (!array_key_exists($quantile, $result) && $separatorCandidate) {
+            if (!array_key_exists($i, $result) && $separatorCandidate) {
                 $newLastSeparator = $separatorCandidate[2];
-                $result[$quantile] = $separatorCandidate[1];
+                $newIntervalFirstPrice = $separatorCandidate[3];
+                $result[$i] = $separatorCandidate[1];
             }
 
-            if (array_key_exists($quantile, $result)) {
+            if (array_key_exists($i, $result)) {
                 $lastSeparator = $newLastSeparator;
-                $i = $this->_binarySearch($lastSeparator, array($i));
-                array_shift($separators);
+                $intervalFirstPrice = $newIntervalFirstPrice;
+                $priceIndex = $this->_binarySearch($lastSeparator);
+                $lastCount += $result[$i]['count'];
+                if ($priceIndex != -1 && $lastSeparator > $this->_lastPriceLimiter[1]) {
+                    $this->_lastPriceLimiter = array($priceIndex + $this->_quantileInterval[0], $lastSeparator);
+                }
             }
-            ++$quantile;
         }
-        if ($i < $pricesCount) {
-            $isEqualPrice = ($this->_prices[$i] == $this->_prices[$pricesCount - 1]) ? $this->_prices[$i] : false;
-            $result[$quantile] = array(
+        if ($this->_lastPriceLimiter[0] < $this->_count) {
+            $isEqualPrice = ($intervalFirstPrice == $this->_maxPrice) ? $intervalFirstPrice : false;
+            $result[$this->getIntervalsNumber()] = array(
                 'from'  => $isEqualPrice ? $isEqualPrice : $lastSeparator,
                 'to'    => $isEqualPrice ? $isEqualPrice : (is_null($this->_upperLimit) ? '' : $this->_upperLimit),
-                'count' => $pricesCount - $i,
+                'count' => $this->_count - $lastCount,
             );
         }
 
diff --git a/app/code/core/Mage/Catalog/Model/Observer.php b/app/code/core/Mage/Catalog/Model/Observer.php
index f05222203689a56a8f9f734adc172dffdd2eb9c5..19617ab39f41f9dda4114b608e602f56b1918051 100644
--- a/app/code/core/Mage/Catalog/Model/Observer.php
+++ b/app/code/core/Mage/Catalog/Model/Observer.php
@@ -245,4 +245,71 @@ class Mage_Catalog_Model_Observer
             $indexProcess->reindexAll();
         }
     }
+
+    /**
+     * Adds catalog categories to top menu
+     *
+     * @param Varien_Event_Observer $observer
+     */
+    public function addCatalogToTopmenuItems(Varien_Event_Observer $observer)
+    {
+        $this->_addCategoriesToMenu(Mage::helper('Mage_Catalog_Helper_Category')->getStoreCategories(), $observer->getMenu());
+    }
+
+    /**
+     * Recursively adds categories to top menu
+     *
+     * @param Varien_Data_Tree_Node_Collection|array $categories
+     * @param Varien_Data_Tree_Node $parentCategoryNode
+     */
+    protected function _addCategoriesToMenu($categories, $parentCategoryNode)
+    {
+        foreach ($categories as $category) {
+            if (!$category->getIsActive()) {
+                continue;
+            }
+
+            $nodeId = 'category-node-' . $category->getId();
+
+            $tree = $parentCategoryNode->getTree();
+            $categoryData = array(
+                'name' => $category->getName(),
+                'id' => $nodeId,
+                'url' => Mage::helper('Mage_Catalog_Helper_Category')->getCategoryUrl($category),
+                'is_active' => $this->_isActiveMenuCategory($category)
+            );
+            $categoryNode = new Varien_Data_Tree_Node($categoryData, 'id', $tree, $parentCategoryNode);
+            $parentCategoryNode->addChild($categoryNode);
+
+            if (Mage::helper('Mage_Catalog_Helper_Category_Flat')->isEnabled()) {
+                $subcategories = (array)$category->getChildrenNodes();
+            } else {
+                $subcategories = $category->getChildren();
+            }
+
+            $this->_addCategoriesToMenu($subcategories, $categoryNode);
+        }
+    }
+
+    /**
+     * Checks whether category belongs to active category's path
+     *
+     * @param Varien_Data_Tree_Node $category
+     * @return bool
+     */
+    protected function _isActiveMenuCategory($category)
+    {
+        $catalogLayer = Mage::getSingleton('Mage_Catalog_Model_Layer');
+        if (!$catalogLayer) {
+            return false;
+        }
+
+        $currentCategory = $catalogLayer->getCurrentCategory();
+        if (!$currentCategory) {
+            return false;
+        }
+
+        $categoryPathIds = explode(',', $currentCategory->getPathInStore());
+        return in_array($category->getId(), $categoryPathIds);
+    }
 }
\ No newline at end of file
diff --git a/app/code/core/Mage/Catalog/Model/Product.php b/app/code/core/Mage/Catalog/Model/Product.php
index 0e533dfd2281125e3d58eff00ea945d855873eaf..541d4d059ef15cf59a7fca384d55f3b6affe4b03 100644
--- a/app/code/core/Mage/Catalog/Model/Product.php
+++ b/app/code/core/Mage/Catalog/Model/Product.php
@@ -1281,7 +1281,8 @@ class Mage_Catalog_Model_Product extends Mage_Catalog_Model_Abstract
      */
     public function isAvailable()
     {
-        return $this->getTypeInstance()->isSalable($this);
+        return $this->getTypeInstance()->isSalable($this)
+            || Mage::helper('Mage_Catalog_Helper_Product')->getSkipSaleableCheck();
     }
 
     /**
@@ -1968,4 +1969,14 @@ class Mage_Catalog_Model_Product extends Mage_Catalog_Model_Abstract
     {
         return $this->_getResource()->getProductEntitiesInfo($columns);
     }
+
+    /**
+     * Checks whether product has disabled status
+     *
+     * @return bool
+     */
+    public function isDisabled()
+    {
+        return $this->getStatus() == Mage_Catalog_Model_Product_Status::STATUS_DISABLED;
+    }
 }
diff --git a/app/code/core/Mage/Catalog/Model/Product/Option.php b/app/code/core/Mage/Catalog/Model/Product/Option.php
index 73d012569118d89da7a3c22c0e0f3cb9121e39a9..f72f2edf18aa11540eee182eb7fb22ecfae2ad97 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Option.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Option.php
@@ -266,7 +266,11 @@ class Mage_Catalog_Model_Product_Option extends Mage_Core_Model_Abstract
             } else {
                 if ($this->getData('previous_type') != '') {
                     $previousType = $this->getData('previous_type');
-                    //if previous option has dfferent group from one is came now need to remove all data of previous group
+
+                    /**
+                     * if previous option has different group from one is came now
+                     * need to remove all data of previous group
+                     */
                     if ($this->getGroupByType($previousType) != $this->getGroupByType($this->getData('type'))) {
 
                         switch ($this->getGroupByType($previousType)) {
@@ -373,9 +377,13 @@ class Mage_Catalog_Model_Product_Option extends Mage_Core_Model_Abstract
             ->addTitleToResult($product->getStoreId())
             ->addPriceToResult($product->getStoreId())
             ->setOrder('sort_order', 'asc')
-            ->setOrder('title', 'asc')
-            ->addValuesToResult($product->getStoreId());
+            ->setOrder('title', 'asc');
+
+        if ($this->getAddRequiredFilter()) {
+            $collection->addRequiredFilter($this->getAddRequiredFilterValue());
+        }
 
+        $collection->addValuesToResult($product->getStoreId());
         return $collection;
     }
 
diff --git a/app/code/core/Mage/Catalog/Model/Product/Option/Type/Date.php b/app/code/core/Mage/Catalog/Model/Product/Option/Type/Date.php
index 9669ed349a0136d55bc18e06562370a4885a6352..8a9cbdea7a43c5dfce71911d8d190a5394ccd0b9 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Option/Type/Date.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Option/Type/Date.php
@@ -33,6 +33,11 @@
  */
 class Mage_Catalog_Model_Product_Option_Type_Date extends Mage_Catalog_Model_Product_Option_Type_Default
 {
+    /**
+     * @var mixed
+     */
+    protected $_formattedOptionValue = null;
+
     /**
      * Validate user input for option
      *
diff --git a/app/code/core/Mage/Catalog/Model/Product/Option/Type/File.php b/app/code/core/Mage/Catalog/Model/Product/Option/Type/File.php
index bb07dc8ac17e9cd62494a90e15fd824fa806d3f6..7061ebbb7063683cd1acc9c3fb9224568bf7cfb9 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Option/Type/File.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Option/Type/File.php
@@ -39,6 +39,11 @@ class Mage_Catalog_Model_Product_Option_Type_File extends Mage_Catalog_Model_Pro
      */
     protected $_customOptionDownloadUrl = 'sales/download/downloadCustomOption';
 
+    /**
+     * @var mixed
+     */
+    protected $_formattedOptionValue = null;
+
     public function isCustomizedView()
     {
         return true;
diff --git a/app/code/core/Mage/Catalog/Model/Product/Option/Type/Select.php b/app/code/core/Mage/Catalog/Model/Product/Option/Type/Select.php
index 68e09f0cee4caa14ef1a4dbd99821fa1edaf5ddf..7b08a7841741d2388274c257289958f4ebb9301a 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Option/Type/Select.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Option/Type/Select.php
@@ -33,6 +33,11 @@
  */
 class Mage_Catalog_Model_Product_Option_Type_Select extends Mage_Catalog_Model_Product_Option_Type_Default
 {
+    /**
+     * @var mixed
+     */
+    protected $_formattedOptionValue = null;
+
     /**
      * Validate user input for option
      *
diff --git a/app/code/core/Mage/Catalog/Model/Product/Type/Abstract.php b/app/code/core/Mage/Catalog/Model/Product/Type/Abstract.php
index c91dfe0ed6bbf31dc59b09dca88d4e96b6e4a12c..5aa15e838c09d362f7cbda8634ae360d1c7e2a00 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Type/Abstract.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Type/Abstract.php
@@ -792,6 +792,16 @@ abstract class Mage_Catalog_Model_Product_Type_Abstract
         return false;
     }
 
+    /**
+     * Force apply discount for parent item
+     *
+     * @return bool
+     */
+    public function getForceApplyDiscountToParentItem()
+    {
+        return false;
+    }
+
     /**
      * Prepare Quote Item Quantity
      *
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 f2012a3745f8502d1ccabc07ee4ec4af69db32cd..79b198b63923e7972e6a97b54fb50318c47e5936 100644
--- a/app/code/core/Mage/Catalog/Model/Product/Type/Configurable.php
+++ b/app/code/core/Mage/Catalog/Model/Product/Type/Configurable.php
@@ -31,7 +31,7 @@
  *
  * @category   Mage
  * @package    Mage_Catalog
- * @author      Magento Core Team <core@magentocommerce.com>
+ * @author     Magento Core Team <core@magentocommerce.com>
  */
 class Mage_Catalog_Model_Product_Type_Configurable extends Mage_Catalog_Model_Product_Type_Abstract
 {
@@ -124,7 +124,7 @@ class Mage_Catalog_Model_Product_Type_Configurable extends Mage_Catalog_Model_Pr
     }
 
     /**
-     * Retrieve parent ids array by requered child
+     * Retrieve parent ids array by required child
      *
      * @param  int|array $childId
      * @return array
@@ -173,7 +173,7 @@ class Mage_Catalog_Model_Product_Type_Configurable extends Mage_Catalog_Model_Pr
     }
 
     /**
-     * Declare attribute identifiers used for asign subproducts
+     * Declare attribute identifiers used for assign subproducts
      *
      * @param   array $ids
      * @param   Mage_Catalog_Model_Product $product
@@ -239,7 +239,7 @@ class Mage_Catalog_Model_Product_Type_Configurable extends Mage_Catalog_Model_Pr
     }
 
     /**
-     * Retrieve configurable attrbutes data
+     * Retrieve configurable attributes data
      *
      * @param  Mage_Catalog_Model_Product $product
      * @return array
@@ -283,7 +283,7 @@ class Mage_Catalog_Model_Product_Type_Configurable extends Mage_Catalog_Model_Pr
     }
 
     /**
-     * Retrieve configurable atrribute collection
+     * Retrieve configurable attribute collection
      *
      * @param Mage_Catalog_Model_Product $product
      * @return Mage_Catalog_Model_Resource_Product_Type_Configurable_Attribute_Collection
@@ -446,6 +446,7 @@ class Mage_Catalog_Model_Product_Type_Configurable extends Mage_Catalog_Model_Pr
     /**
      * Check is product available for sale
      *
+     * @param Mage_Catalog_Model_Product $product
      * @return bool
      */
     public function isSalable($product)
@@ -472,6 +473,7 @@ class Mage_Catalog_Model_Product_Type_Configurable extends Mage_Catalog_Model_Pr
      * Check whether the product is available for sale
      * is alias to isSalable for compatibility
      *
+     * @param Mage_Catalog_Model_Product $product
      * @return bool
      */
     public function getIsSalable($product)
@@ -485,14 +487,14 @@ class Mage_Catalog_Model_Product_Type_Configurable extends Mage_Catalog_Model_Pr
      *      $attributeId => $attributeValue
      *  )
      *
-     * @param  array $attrbutesInfo
+     * @param  array $attributesInfo
      * @param  Mage_Catalog_Model_Product $product
      * @return Mage_Catalog_Model_Product|null
      */
     public function getProductByAttributes($attributesInfo, $product)
     {
         if (is_array($attributesInfo) && !empty($attributesInfo)) {
-            $productCollection = $this->getUsedProductCollection($product);
+            $productCollection = $this->getUsedProductCollection($product)->addAttributeToSelect('name');
             foreach ($attributesInfo as $attributeId => $attributeValue) {
                 $productCollection->addAttributeToFilter($attributeId, $attributeValue);
             }
@@ -586,6 +588,7 @@ class Mage_Catalog_Model_Product_Type_Configurable extends Mage_Catalog_Model_Pr
                 $subProduct = true;
                 if ($this->_isStrictProcessMode($processMode)) {
                     foreach($this->getConfigurableAttributes($product) as $attributeItem){
+                        /* @var $attributeItem Varien_Object */
                         $attrId = $attributeItem->getData('attribute_id');
                         if(!isset($attributes[$attrId]) || empty($attributes[$attrId])) {
                             $subProduct = null;
@@ -709,6 +712,7 @@ class Mage_Catalog_Model_Product_Type_Configurable extends Mage_Catalog_Model_Pr
     /**
      * Check is virtual product
      *
+     * @param Mage_Catalog_Model_Product $product
      * @return bool
      */
     public function isVirtual($product)
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 1de0b3f75e3c500a56fec462f333bb1e03fa4226..823e56943337a9b2531fca4cb493eec9a449e640 100755
--- a/app/code/core/Mage/Catalog/Model/Resource/Category/Flat.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Category/Flat.php
@@ -216,7 +216,7 @@ class Mage_Catalog_Model_Resource_Category_Flat extends Mage_Index_Model_Resourc
     /**
      * Load nodes by parent id
      *
-     * @param unknown_type $parentNode
+     * @param Mage_Catalog_Model_Category|int $parentNode
      * @param integer $recursionLevel
      * @param integer $storeId
      * @return Mage_Catalog_Model_Resource_Category_Flat
@@ -234,7 +234,8 @@ class Mage_Catalog_Model_Resource_Category_Flat extends Mage_Index_Model_Resourc
                 ->from($this->getMainStoreTable($storeId))
                 ->where('entity_id = ?', $parentNode)
                 ->where('store_id = ?', $storeId);
-            if ($parentNode = $_conn->fetchRow($selectParent)) {
+            $parentNode = $_conn->fetchRow($selectParent);
+            if ($parentNode) {
                 $parentPath = $parentNode['path'];
                 $startLevel = $parentNode['level'];
             }
@@ -273,6 +274,9 @@ class Mage_Catalog_Model_Resource_Category_Flat extends Mage_Index_Model_Resourc
             $select->where('main_table.entity_id NOT IN (?)', $inactiveCategories);
         }
 
+        // Allow extensions to modify select (e.g. add custom category attributes to select)
+        Mage::dispatchEvent('catalog_category_flat_loadnodes_before', array('select' => $select));
+
         $arrNodes = $_conn->fetchAll($select);
         $nodes = array();
         foreach ($arrNodes as $node) {
@@ -563,7 +567,9 @@ class Mage_Catalog_Model_Resource_Category_Flat extends Mage_Index_Model_Resourc
 
         // Adding indexes
         $table->addIndex(
-            $_writeAdapter->getIndexName($tableName, array('entity_id')), array('entity_id'), array('type' => 'primary')
+            $_writeAdapter->getIndexName($tableName, array('entity_id')),
+            array('entity_id'),
+            array('type' => 'primary')
         );
         $table->addIndex(
             $_writeAdapter->getIndexName($tableName, array('store_id')), array('store_id'), array('type' => 'index')
@@ -1087,7 +1093,7 @@ class Mage_Catalog_Model_Resource_Category_Flat extends Mage_Index_Model_Resourc
      *  'field_name' => 'value'
      * )
      *
-     * @param Mage_Catalog_Model_Category $category
+     * @param Varien_Object $category
      * @param array $replaceFields
      * @return array
      */
@@ -1097,8 +1103,9 @@ class Mage_Catalog_Model_Resource_Category_Flat extends Mage_Index_Model_Resourc
         $this->_getWriteAdapter()->resetDdlCache($table);
         $table = $this->_getWriteAdapter()->describeTable($table);
         $data = array();
-        foreach ($table as $column=>$columnData) {
-            if (null !== $category->getData($column)) {
+        $idFieldName = Mage::getSingleton('Mage_Catalog_Model_Category')->getIdFieldName();
+        foreach ($table as $column => $columnData) {
+            if ($column != $idFieldName || null !== $category->getData($column)) {
                 if (key_exists($column, $replaceFields)) {
                     $value = $category->getData($replaceFields[$column]);
                 } else {
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Layer/Filter/Price.php b/app/code/core/Mage/Catalog/Model/Resource/Layer/Filter/Price.php
index a8d04b9fde65ae66194692ffbbeab2673219780f..a6b81f089b1d8381e5daceae24af43c848a6e600 100755
--- a/app/code/core/Mage/Catalog/Model/Resource/Layer/Filter/Price.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Layer/Filter/Price.php
@@ -34,6 +34,11 @@
  */
 class Mage_Catalog_Model_Resource_Layer_Filter_Price extends Mage_Core_Model_Resource_Db_Abstract
 {
+    /**
+     * Minimal possible price
+     */
+    const MIN_POSSIBLE_PRICE = .0001;
+
     /**
      * Initialize connection and define main table name
      *
@@ -53,6 +58,29 @@ class Mage_Catalog_Model_Resource_Layer_Filter_Price extends Mage_Core_Model_Res
         return 'price_index';
     }
 
+    /**
+     * Replace table alias in condition string
+     *
+     * @param string|null $conditionString
+     * @return string|null
+     */
+    protected function _replaceTableAlias($conditionString)
+    {
+        if (is_null($conditionString)) {
+            return null;
+        }
+        $adapter = $this->_getReadAdapter();
+        $oldAlias = array(
+            Mage_Catalog_Model_Resource_Product_Collection::INDEX_TABLE_ALIAS . '.',
+            $adapter->quoteIdentifier(Mage_Catalog_Model_Resource_Product_Collection::INDEX_TABLE_ALIAS) . '.',
+        );
+        $newAlias = array(
+            Mage_Catalog_Model_Resource_Product_Collection::MAIN_TABLE_ALIAS . '.',
+            $adapter->quoteIdentifier(Mage_Catalog_Model_Resource_Product_Collection::MAIN_TABLE_ALIAS) . '.',
+        );
+        return str_replace($oldAlias, $newAlias, $conditionString);
+    }
+
     /**
      * Retrieve clean select with joined price index table
      *
@@ -64,14 +92,54 @@ class Mage_Catalog_Model_Resource_Layer_Filter_Price extends Mage_Core_Model_Res
         $collection = $filter->getLayer()->getProductCollection();
         $collection->addPriceData($filter->getCustomerGroupId(), $filter->getWebsiteId());
 
-        // clone select from collection with filters
-        $select = clone $collection->getSelect();
+        if (!is_null($collection->getCatalogPreparedSelect())) {
+            $select = clone $collection->getCatalogPreparedSelect();
+        } else {
+            $select = clone $collection->getSelect();
+        }
+
         // reset columns, order and limitation conditions
         $select->reset(Zend_Db_Select::COLUMNS);
         $select->reset(Zend_Db_Select::ORDER);
         $select->reset(Zend_Db_Select::LIMIT_COUNT);
         $select->reset(Zend_Db_Select::LIMIT_OFFSET);
 
+        // remove join with main table
+        $fromPart = $select->getPart(Zend_Db_Select::FROM);
+        if (!isset($fromPart[Mage_Catalog_Model_Resource_Product_Collection::INDEX_TABLE_ALIAS])
+            || !isset($fromPart[Mage_Catalog_Model_Resource_Product_Collection::MAIN_TABLE_ALIAS])
+        ) {
+            return $select;
+        }
+
+        // processing FROM part
+        $priceIndexJoinPart = $fromPart[Mage_Catalog_Model_Resource_Product_Collection::INDEX_TABLE_ALIAS];
+        $priceIndexJoinConditions = explode('AND', $priceIndexJoinPart['joinCondition']);
+        $priceIndexJoinPart['joinType'] = Zend_Db_Select::FROM;
+        $priceIndexJoinPart['joinCondition'] = null;
+        $fromPart[Mage_Catalog_Model_Resource_Product_Collection::MAIN_TABLE_ALIAS] = $priceIndexJoinPart;
+        unset($fromPart[Mage_Catalog_Model_Resource_Product_Collection::INDEX_TABLE_ALIAS]);
+        $select->setPart(Zend_Db_Select::FROM, $fromPart);
+        foreach ($fromPart as $key => $fromJoinItem) {
+            $fromPart[$key]['joinCondition'] = $this->_replaceTableAlias($fromJoinItem['joinCondition']);
+        }
+        $select->setPart(Zend_Db_Select::FROM, $fromPart);
+
+        // processing WHERE part
+        $wherePart = $select->getPart(Zend_Db_Select::WHERE);
+        foreach ($wherePart as $key => $wherePartItem) {
+            $wherePart[$key] = $this->_replaceTableAlias($wherePartItem);
+        }
+        $select->setPart(Zend_Db_Select::WHERE, $wherePart);
+        $excludeJoinPart = Mage_Catalog_Model_Resource_Product_Collection::MAIN_TABLE_ALIAS . '.entity_id';
+        foreach ($priceIndexJoinConditions as $condition) {
+            if (strpos($condition, $excludeJoinPart) !== false) {
+                continue;
+            }
+            $select->where($this->_replaceTableAlias($condition));
+        }
+        $select->where($this->_getPriceExpression($filter, $select) . ' IS NOT NULL');
+
         return $select;
     }
 
@@ -79,6 +147,7 @@ class Mage_Catalog_Model_Resource_Layer_Filter_Price extends Mage_Core_Model_Res
      * Prepare response object and dispatch prepare price event
      * Return response object
      *
+     * @deprecated since 1.7.0.0
      * @param Mage_Catalog_Model_Layer_Filter_Price $filter
      * @param Varien_Db_Select $select
      * @return Varien_Object
@@ -108,23 +177,65 @@ class Mage_Catalog_Model_Resource_Layer_Filter_Price extends Mage_Core_Model_Res
     /**
      * Retrieve maximal price for attribute
      *
+     * @deprecated since 1.7.0.0
      * @param Mage_Catalog_Model_Layer_Filter_Price $filter
      * @return float
      */
     public function getMaxPrice($filter)
     {
-        $select     = $this->_getSelect($filter);
-        $connection = $this->_getReadAdapter();
-        $response   = $this->_dispatchPreparePriceEvent($filter, $select);
+        return $filter->getLayer()->getProductCollection()->getMaxPrice();
+    }
 
-        $table = $this->_getIndexTableAlias();
+    /**
+     * Price expression generated by products collection
+     *
+     * @param Mage_Catalog_Model_Layer_Filter_Price $filter
+     * @param Varien_Db_Select $select
+     * @param bool $replaceAlias
+     * @return string
+     */
+    protected function _getPriceExpression($filter, $select, $replaceAlias = true)
+    {
+        $priceExpression = $filter->getLayer()->getProductCollection()->getPriceExpression($select);
+        $additionalPriceExpression = $filter->getLayer()->getProductCollection()->getAdditionalPriceExpression($select);
+        $result = empty($additionalPriceExpression)
+            ? $priceExpression
+            : "({$priceExpression} {$additionalPriceExpression})";
+        if ($replaceAlias) {
+            $result = $this->_replaceTableAlias($result);
+        }
 
-        $additional   = join('', $response->getAdditionalCalculations());
-        $maxPriceExpr = new Zend_Db_Expr("MAX({$table}.min_price {$additional})");
+        return $result;
+    }
 
-        $select->columns(array($maxPriceExpr));
+    /**
+     * Get comparing value sql part
+     *
+     * @param float $price
+     * @param Mage_Catalog_Model_Layer_Filter_Price $filter
+     * @param bool $decrease
+     * @return float
+     */
+    protected function _getComparingValue($price, $filter, $decrease = true)
+    {
+        $currencyRate = $filter->getLayer()->getProductCollection()->getCurrencyRate();
+        if ($decrease) {
+            return round(($price - (self::MIN_POSSIBLE_PRICE / 2)) / $currencyRate, 3);
+        }
+        return round(($price + (self::MIN_POSSIBLE_PRICE / 2)) / $currencyRate, 3);
+    }
 
-        return $connection->fetchOne($select) * $filter->getCurrencyRate();
+    /**
+     * Get full price expression generated by products collection
+     *
+     * @param Mage_Catalog_Model_Layer_Filter_Price $filter
+     * @param Varien_Db_Select $select
+     * @return Zend_Db_Expr
+     */
+    protected function _getFullPriceExpression($filter, $select)
+    {
+        return new Zend_Db_Expr('ROUND((' . $this->_getPriceExpression($filter, $select) . ') * '
+            . $filter->getLayer()->getProductCollection()->getCurrencyRate() . ', 2)');
     }
 
     /**
@@ -136,24 +247,20 @@ class Mage_Catalog_Model_Resource_Layer_Filter_Price extends Mage_Core_Model_Res
      */
     public function getCount($filter, $range)
     {
-        $select     = $this->_getSelect($filter);
-        $connection = $this->_getReadAdapter();
-        $response   = $this->_dispatchPreparePriceEvent($filter, $select);
-        $table      = $this->_getIndexTableAlias();
-
-        $additional = join('', $response->getAdditionalCalculations());
-        $rate       = $filter->getCurrencyRate();
+        $select = $this->_getSelect($filter);
+        $priceExpression = $this->_getPriceExpression($filter, $select);
+        $rate = $filter->getCurrencyRate();
 
         /**
          * Check and set correct variable values to prevent SQL-injections
          */
-        $rate       = floatval($rate);
-        $range      = floatval($range);
+        $rate = floatval($rate);
+        $range = floatval($range) / $rate;
         if ($range == 0) {
             $range = 1;
         }
-        $countExpr  = new Zend_Db_Expr('COUNT(*)');
-        $rangeExpr  = new Zend_Db_Expr("FLOOR((({$table}.min_price {$additional}) * {$rate}) / {$range}) + 1");
+        $countExpr = new Zend_Db_Expr('COUNT(*)');
+        $rangeExpr = new Zend_Db_Expr("FLOOR(({$priceExpression}) / {$range}) + 1");
 
         $select->columns(array(
             'range' => $rangeExpr,
@@ -161,79 +268,113 @@ class Mage_Catalog_Model_Resource_Layer_Filter_Price extends Mage_Core_Model_Res
         ));
         $select->group($rangeExpr)->order("$rangeExpr ASC");
 
-        return $connection->fetchPairs($select);
+        return $this->_getReadAdapter()->fetchPairs($select);
     }
 
     /**
-     * Prepare filter apply
+     * Apply attribute filter to product collection
      *
+     * @deprecated since 1.7.0.0
      * @param Mage_Catalog_Model_Layer_Filter_Price $filter
-     * @return array
+     * @param int $range
+     * @param int $index    the range factor
+     * @return Mage_Catalog_Model_Resource_Layer_Filter_Price
      */
-    protected function _prepareApply($filter)
+    public function applyFilterToCollection($filter, $range, $index)
     {
-        $collection = $filter->getLayer()->getProductCollection();
-        $collection->addPriceData($filter->getCustomerGroupId(), $filter->getWebsiteId());
+        $priceExpr = $this->_getPriceExpression($filter);
+        $filter->getLayer()->getProductCollection()
+            ->getSelect()
+            ->where($priceExpr . ' >= ' . $this->_getComparingValue(($range * ($index - 1)), $filter))
+            ->where($priceExpr . ' < ' . $this->_getComparingValue(($range * $index), $filter));
 
-        $select     = $collection->getSelect();
-        $response   = $this->_dispatchPreparePriceEvent($filter, $select);
+        return $this;
+    }
 
-        $table      = $this->_getIndexTableAlias();
-        $additional = join('', $response->getAdditionalCalculations());
-        $rate       = $filter->getCurrencyRate();
-        $priceExpr  = new Zend_Db_Expr("ROUND(({$table}.min_price {$additional}) * {$rate}, 2)");
+    /**
+     * Load range of product prices
+     *
+     * @param Mage_Catalog_Model_Layer_Filter_Price $filter
+     * @param int $limit
+     * @param null|int $offset
+     * @param null|int $lowerPrice
+     * @param null|int $upperPrice
+     * @return array
+     */
+    public function loadPrices($filter, $limit, $offset = null, $lowerPrice = null, $upperPrice = null)
+    {
+        $select = $this->_getSelect($filter);
+        $priceExpression = $this->_getPriceExpression($filter, $select);
+        $select->columns(array($this->_getFullPriceExpression($filter, $select)));
+        if (!is_null($lowerPrice)) {
+            $select->where("$priceExpression >= " . $this->_getComparingValue($lowerPrice, $filter));
+        }
+        if (!is_null($upperPrice)) {
+            $select->where("$priceExpression < " . $this->_getComparingValue($upperPrice, $filter));
+        }
+        $select->order("$priceExpression ASC")->limit($limit, $offset);
 
-        return array($select, $priceExpr);
+        return $this->_getReadAdapter()->fetchCol($select);
     }
 
     /**
-     * Apply attribute filter to product collection
+     * Load range of product prices, preceding the price
      *
      * @param Mage_Catalog_Model_Layer_Filter_Price $filter
-     * @param int $range
-     * @param int $index    the range factor
-     * @return Mage_Catalog_Model_Resource_Layer_Filter_Price
+     * @param float $price
+     * @param int $index
+     * @return array|false
      */
-    public function applyFilterToCollection($filter, $range, $index)
+    public function loadPreviousPrices($filter, $price, $index, $lowerPrice = null)
     {
-        list($select, $priceExpr) = $this->_prepareApply($filter);
-        $select
-            ->where($priceExpr . ' >= ?', ($range * ($index - 1)))
-            ->where($priceExpr . ' < ?', ($range * $index));
+        $select = $this->_getSelect($filter);
+        $priceExpression = $this->_getPriceExpression($filter, $select);
+        $select->columns('COUNT(*)')->where("$priceExpression < " . $this->_getComparingValue($price, $filter));
+        if (!is_null($lowerPrice)) {
+            $select->where("$priceExpression >= " . $this->_getComparingValue($lowerPrice, $filter));
+        }
+        $offset = $this->_getReadAdapter()->fetchOne($select);
+        if (!$offset) {
+            return false;
+        }
 
-        return $this;
+        return $this->loadPrices($filter, $index - $offset + 1, $offset - 1, $lowerPrice);
     }
 
     /**
-     * Load all product prices to algorithm model
+     * Load range of product prices, next to the price
      *
-     * @param Mage_Catalog_Model_Layer_Filter_Price_Algorithm $algorithm
      * @param Mage_Catalog_Model_Layer_Filter_Price $filter
+     * @param float $price
+     * @param int $rightIndex
+     * @param null|int $upperPrice
      * @return array
      */
-    public function loadAllPrices($algorithm, $filter)
+    public function loadNextPrices($filter, $price, $rightIndex, $upperPrice = null)
     {
-        $select     = $this->_getSelect($filter);
-        $connection = $this->_getReadAdapter();
-        $response   = $this->_dispatchPreparePriceEvent($filter, $select);
+        $select = $this->_getSelect($filter);
 
-        $table = $this->_getIndexTableAlias();
+        $pricesSelect = clone $select;
+        $priceExpression = $this->_getPriceExpression($filter, $pricesSelect);
 
-        $additional   = join('', $response->getAdditionalCalculations());
-        $maxPriceExpr = new Zend_Db_Expr(
-            "ROUND(({$table}.min_price {$additional}) * " . $connection->quote($filter->getCurrencyRate()) . ", 2)"
-        );
-
-        $select->columns(array($maxPriceExpr))->order("$maxPriceExpr ASC");
+        $select->columns('COUNT(*)')->where("$priceExpression > " . $this->_getComparingValue($price, $filter, false));
+        if (!is_null($upperPrice)) {
+            $select->where("$priceExpression < " . $this->_getComparingValue($upperPrice, $filter));
+        }
+        $offset = $this->_getReadAdapter()->fetchOne($select);
+        if (!$offset) {
+            return false;
+        }
 
-        $prices = $connection->fetchCol($select);
-        if ($filter->getInterval() && count($prices) <= $filter->getIntervalDivisionLimit()) {
-            $algorithm->setPrices(array());
-        } else {
-            $algorithm->setPrices($prices);
+        $pricesSelect
+            ->columns(array($this->_getFullPriceExpression($filter, $pricesSelect)))
+            ->where("$priceExpression >= " . $this->_getComparingValue($price, $filter));
+        if (!is_null($upperPrice)) {
+            $pricesSelect->where("$priceExpression < " . $this->_getComparingValue($upperPrice, $filter));
         }
+        $pricesSelect->order("$priceExpression DESC")->limit($rightIndex - $offset + 1, $offset - 1);
 
-        return $prices;
+        return array_reverse($this->_getReadAdapter()->fetchCol($pricesSelect));
     }
 
     /**
@@ -254,19 +395,23 @@ class Mage_Catalog_Model_Resource_Layer_Filter_Price extends Mage_Core_Model_Res
             return $this;
         }
 
-        list($select, $priceExpr) = $this->_prepareApply($filter);
+        $select = $filter->getLayer()->getProductCollection()->getSelect();
+        $priceExpr = $this->_getPriceExpression($filter, $select, false);
 
-        if ($from == $to && !empty($to)) {
-            $select->where($priceExpr . ' = ?', $from);
-        } else {
-            if ($from !== '') {
-                $select->where($priceExpr . ' >= ?', $from);
-            }
-            if ($to !== '') {
-                $select->where($priceExpr . ' < ?', $to);
+        if ($to !== '') {
+            $to = (float)$to;
+            if ($from == $to) {
+                $to += self::MIN_POSSIBLE_PRICE;
             }
         }
 
+        if ($from !== '') {
+            $select->where($priceExpr . ' >= ' . $this->_getComparingValue($from, $filter));
+        }
+        if ($to !== '') {
+            $select->where($priceExpr . ' < ' . $this->_getComparingValue($to, $filter));
+        }
+
         return $this;
 
     }
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product.php b/app/code/core/Mage/Catalog/Model/Resource/Product.php
index 6d9dc25cb6900778bb0e8c466a05502bdc351f80..0831b9d7e117da8196ec28ebb3dc7dc3267280f6 100755
--- a/app/code/core/Mage/Catalog/Model/Resource/Product.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product.php
@@ -102,11 +102,19 @@ class Mage_Catalog_Model_Resource_Product extends Mage_Catalog_Model_Resource_Ab
     public function getWebsiteIdsByProductIds($productIds)
     {
         $select = $this->_getWriteAdapter()->select()
-            ->from($this->_productWebsiteTable, array('product_id', 'website_ids' =>'GROUP_CONCAT(website_id)'))
-            ->where('product_id IN (?)', $productIds)
-            ->group('product_id');
+            ->from($this->_productWebsiteTable, array('product_id', 'website_id'))
+            ->where('product_id IN (?)', $productIds);
+        $productsWebsites = array();
+        foreach ($this->_getWriteAdapter()->fetchAll($select) as $productInfo) {
+            $productId = $productInfo['product_id'];
+            if (!isset($productsWebsites[$productId])) {
+                $productsWebsites[$productId] = array();
+            }
+            $productsWebsites[$productId][] = $productInfo['website_id'];
+
+        }
 
-        return $this->_getWriteAdapter()->fetchAll($select);
+        return $productsWebsites;
     }
 
     /**
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Collection.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Collection.php
index b0492af8dd7eabaf0d070ab4115f9c35b817d0b6..add86897c73704aef63e9a3b48d7cfa452f97ca2 100755
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Collection.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Collection.php
@@ -34,6 +34,16 @@
  */
 class Mage_Catalog_Model_Resource_Product_Collection extends Mage_Catalog_Model_Resource_Collection_Abstract
 {
+    /**
+     * Alias for index table
+     */
+    const INDEX_TABLE_ALIAS = 'price_index';
+
+    /**
+     * Alias for main table
+     */
+    const MAIN_TABLE_ALIAS = 'e';
+
     /**
      * Catalog Product Flat is enabled cache per store
      *
@@ -142,6 +152,134 @@ class Mage_Catalog_Model_Resource_Product_Collection extends Mage_Catalog_Model_
         'special_price' => 'price_index.special_price',
     ));
 
+    /**
+     * Price expression sql
+     *
+     * @var string|null
+     */
+    protected $_priceExpression;
+
+    /**
+     * Additional price expression sql part
+     *
+     * @var string|null
+     */
+    protected $_additionalPriceExpression;
+
+    /**
+     * Max prise (statistics data)
+     *
+     * @var float
+     */
+    protected $_maxPrice;
+
+    /**
+     * Min prise (statistics data)
+     *
+     * @var float
+     */
+    protected $_minPrice;
+
+    /**
+     * Prise standard deviation (statistics data)
+     *
+     * @var float
+     */
+    protected $_priceStandardDeviation;
+
+    /**
+     * Prises count (statistics data)
+     *
+     * @var int
+     */
+    protected $_pricesCount = null;
+
+    /**
+     * Cloned Select after dispatching 'catalog_prepare_price_select' event
+     *
+     * @var Varien_Db_Select
+     */
+    protected $_catalogPreparePriceSelect = null;
+
+    /**
+     * Get cloned Select after dispatching 'catalog_prepare_price_select' event
+     *
+     * @return Varien_Db_Select
+     */
+    public function getCatalogPreparedSelect()
+    {
+        return $this->_catalogPreparePriceSelect;
+    }
+
+    /**
+     * Prepare additional price expression sql part
+     *
+     * @param Varien_Db_Select $select
+     * @return Mage_Catalog_Model_Resource_Product_Collection
+     */
+    protected function _preparePriceExpressionParameters($select)
+    {
+        // prepare response object for event
+        $response = new Varien_Object();
+        $response->setAdditionalCalculations(array());
+        $table = self::INDEX_TABLE_ALIAS;
+
+        // prepare event arguments
+        $eventArgs = array(
+            'select'          => $select,
+            'table'           => $table,
+            'store_id'        => $this->getStoreId(),
+            'response_object' => $response
+        );
+
+        Mage::dispatchEvent('catalog_prepare_price_select', $eventArgs);
+
+        $additional   = join('', $response->getAdditionalCalculations());
+        $this->_priceExpression = $table . '.min_price';
+        $this->_additionalPriceExpression = $additional;
+        $this->_catalogPreparePriceSelect = clone $select;
+
+        return $this;
+    }
+
+    /**
+     * Get price expression sql part
+     *
+     * @param Varien_Db_Select $select
+     * @return string
+     */
+    public function getPriceExpression($select)
+    {
+        if (is_null($this->_priceExpression)) {
+            $this->_preparePriceExpressionParameters($select);
+        }
+        return $this->_priceExpression;
+    }
+
+    /**
+     * Get additional price expression sql part
+     *
+     * @param Varien_Db_Select $select
+     * @return string
+     */
+    public function getAdditionalPriceExpression($select)
+    {
+        if (is_null($this->_additionalPriceExpression)) {
+            $this->_preparePriceExpressionParameters($select);
+        }
+        return $this->_additionalPriceExpression;
+    }
+
+    /**
+     * Get currency rate
+     *
+     * @return float
+     */
+    public function getCurrencyRate()
+    {
+        return Mage::app()->getStore($this->getStoreId())->getCurrentCurrencyRate();
+    }
+
     /**
      * Retrieve Catalog Product Flat Helper object
      *
@@ -280,7 +418,7 @@ class Mage_Catalog_Model_Resource_Product_Collection extends Mage_Catalog_Model_
     {
         if ($this->isEnabledFlat()) {
             $this->getSelect()
-                ->from(array('e' => $this->getEntity()->getFlatTableName()), null)
+                ->from(array(self::MAIN_TABLE_ALIAS => $this->getEntity()->getFlatTableName()), null)
                 ->columns(array('status' => new Zend_Db_Expr(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)));
             $this->addAttributeToSelect(array('entity_id', 'type_id', 'attribute_set_id'));
             if ($this->getFlatHelper()->isAddChildData()) {
@@ -289,7 +427,7 @@ class Mage_Catalog_Model_Resource_Product_Collection extends Mage_Catalog_Model_
                 $this->addAttributeToSelect(array('child_id', 'is_child'));
             }
         } else {
-            $this->getSelect()->from(array('e'=>$this->getEntity()->getEntityTable()));
+            $this->getSelect()->from(array(self::MAIN_TABLE_ALIAS => $this->getEntity()->getEntityTable()));
         }
         return $this;
     }
@@ -716,20 +854,58 @@ class Mage_Catalog_Model_Resource_Product_Collection extends Mage_Catalog_Model_
     }
 
     /**
-     * Get SQL for get record count
+     * Get SQL for get record count without left JOINs
      *
      * @return Varien_Db_Select
      */
     public function getSelectCountSql()
     {
-        $this->_renderFilters();
+        return $this->_getSelectCountSql();
+    }
 
-        $countSelect = $this->_getClearSelect()
-            ->columns('COUNT(DISTINCT e.entity_id)')
-            ->resetJoinLeft();
+    /**
+     * Get SQL for get record count
+     *
+     * @param bool $resetLeftJoins
+     * @return Varien_Db_Select
+     */
+    protected function _getSelectCountSql($select = null, $resetLeftJoins = true)
+    {
+        $this->_renderFilters();
+        $countSelect = (is_null($select)) ?
+            $this->_getClearSelect() :
+            $this->_buildClearSelect($select);
+        $countSelect->columns('COUNT(DISTINCT e.entity_id)');
+        if ($resetLeftJoins) {
+            $countSelect->resetJoinLeft();
+        }
         return $countSelect;
     }
 
+    /**
+     * Prepare statistics data
+     *
+     * @return Mage_Catalog_Model_Resource_Product_Collection
+     */
+    protected function _prepareStatisticsData()
+    {
+        $select = clone $this->getSelect();
+        $priceExpression = $this->getPriceExpression($select) . ' ' . $this->getAdditionalPriceExpression($select);
+        $sqlEndPart = ') * ' . $this->getCurrencyRate() . ', 2)';
+        $select = $this->_getSelectCountSql($select, false);
+        $select->columns('ROUND(MAX(' . $priceExpression . $sqlEndPart);
+        $select->columns('ROUND(MIN(' . $priceExpression . $sqlEndPart);
+        $select->columns($this->getConnection()->getStandardDeviationSql('ROUND((' . $priceExpression . $sqlEndPart));
+        $select->where($this->getPriceExpression($select) . ' IS NOT NULL');
+        $row = $this->getConnection()->fetchRow($select, $this->_bindParams, Zend_Db::FETCH_NUM);
+        $this->_pricesCount = (int)$row[0];
+        $this->_maxPrice = (float)$row[1];
+        $this->_minPrice = (float)$row[2];
+        $this->_priceStandardDeviation = (float)$row[3];
+
+        return $this;
+    }
+
     /**
      * Retreive clear select
      *
@@ -737,7 +913,20 @@ class Mage_Catalog_Model_Resource_Product_Collection extends Mage_Catalog_Model_
      */
     protected function _getClearSelect()
     {
-        $select = clone $this->getSelect();
+        return $this->_buildClearSelect();
+    }
+
+    /**
+     * Build clear select
+     *
+     * @param Varien_Db_Select $select
+     * @return Varien_Db_Select
+     */
+    protected function _buildClearSelect($select = null)
+    {
+        if (is_null($select)) {
+            $select = clone $this->getSelect();
+        }
         $select->reset(Zend_Db_Select::ORDER);
         $select->reset(Zend_Db_Select::LIMIT_COUNT);
         $select->reset(Zend_Db_Select::LIMIT_OFFSET);
@@ -745,6 +934,7 @@ class Mage_Catalog_Model_Resource_Product_Collection extends Mage_Catalog_Model_
 
         return $select;
     }
+
     /**
      * Retrive all ids for collection
      *
@@ -1796,4 +1986,77 @@ class Mage_Catalog_Model_Resource_Product_Collection extends Mage_Catalog_Model_
         return parent::clear();
     }
 
+    /**
+     * Set Order field
+     *
+     * @param string $attribute
+     * @param string $dir
+     * @return Mage_Catalog_Model_Resource_Product_Collection
+     */
+    public function setOrder($attribute, $dir = 'desc')
+    {
+        if ($attribute == 'price') {
+            $this->addAttributeToSort($attribute, $dir);
+        } else {
+            parent::setOrder($attribute, $dir);
+        }
+        return $this;
+    }
+
+    /**
+     * Get products max price
+     *
+     * @return float
+     */
+    public function getMaxPrice()
+    {
+        if (is_null($this->_maxPrice)) {
+            $this->_prepareStatisticsData();
+        }
+
+        return $this->_maxPrice;
+    }
+
+    /**
+     * Get products min price
+     *
+     * @return float
+     */
+    public function getMinPrice()
+    {
+        if (is_null($this->_minPrice)) {
+            $this->_prepareStatisticsData();
+        }
+
+        return $this->_minPrice;
+    }
+
+    /**
+     * Get standard deviation of products price
+     *
+     * @return float
+     */
+    public function getPriceStandardDeviation()
+    {
+        if (is_null($this->_priceStandardDeviation)) {
+            $this->_prepareStatisticsData();
+        }
+
+        return $this->_priceStandardDeviation;
+    }
+
+
+    /**
+     * Get count of product prices
+     *
+     * @return int
+     */
+    public function getPricesCount()
+    {
+        if (is_null($this->_pricesCount)) {
+            $this->_prepareStatisticsData();
+        }
+
+        return $this->_pricesCount;
+    }
 }
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Eav/Abstract.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Eav/Abstract.php
index 8046cf03a9c6ee59cda53edc6ff59028bdc7e073..dfc14241233122788bf727d8bf7ad7c1a32ab996 100755
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Eav/Abstract.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Indexer/Eav/Abstract.php
@@ -83,7 +83,7 @@ abstract class Mage_Catalog_Model_Resource_Product_Indexer_Eav_Abstract
         if ($parentIds) {
             $processIds = array_unique(array_merge($processIds, $parentIds));
         }
-        $childIds  = $this->getRelationsByParent($parentIds);
+        $childIds  = $this->getRelationsByParent($processIds);
         if ($childIds) {
             $processIds = array_unique(array_merge($processIds, $childIds));
         }
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Product/Option/Collection.php b/app/code/core/Mage/Catalog/Model/Resource/Product/Option/Collection.php
index 986ca7aee0c763405eb8461ed5898708e72cc5dd..72055291669c4e158b21a709485260fe80a63ad9 100755
--- a/app/code/core/Mage/Catalog/Model/Resource/Product/Option/Collection.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Product/Option/Collection.php
@@ -66,14 +66,20 @@ class Mage_Catalog_Model_Resource_Product_Option_Collection extends Mage_Core_Mo
     {
         $productOptionTitleTable = $this->getTable('catalog_product_option_title');
         $adapter        = $this->getConnection();
-        $titleExpr      = $adapter->getCheckSql('store_option_title.title IS NULL', 'default_option_title.title', 'store_option_title.title');
+        $titleExpr      = $adapter->getCheckSql(
+            'store_option_title.title IS NULL',
+            'default_option_title.title',
+            'store_option_title.title'
+        );
 
         $this->getSelect()
             ->join(array('default_option_title' => $productOptionTitleTable),
                 'default_option_title.option_id = main_table.option_id',
                 array('default_title' => 'title'))
-            ->joinLeft(array('store_option_title' => $productOptionTitleTable),
-                'store_option_title.option_id = main_table.option_id AND ' . $adapter->quoteInto('store_option_title.store_id = ?', $storeId),
+            ->joinLeft(
+                array('store_option_title' => $productOptionTitleTable),
+                'store_option_title.option_id = main_table.option_id AND '
+                    . $adapter->quoteInto('store_option_title.store_id = ?', $storeId),
                 array(
                     'store_title'   => 'title',
                     'title'         => $titleExpr
@@ -93,18 +99,33 @@ class Mage_Catalog_Model_Resource_Product_Option_Collection extends Mage_Core_Mo
     {
         $productOptionPriceTable = $this->getTable('catalog_product_option_price');
         $adapter        = $this->getConnection();
-        $priceExpr      = $adapter->getCheckSql('store_option_price.price IS NULL', 'default_option_price.price', 'store_option_price.price');
-        $priceTypeExpr  = $adapter->getCheckSql('store_option_price.price_type IS NULL', 'default_option_price.price_type', 'store_option_price.price_type');
+        $priceExpr      = $adapter->getCheckSql(
+            'store_option_price.price IS NULL',
+            'default_option_price.price',
+            'store_option_price.price'
+        );
+        $priceTypeExpr  = $adapter->getCheckSql(
+            'store_option_price.price_type IS NULL',
+            'default_option_price.price_type',
+            'store_option_price.price_type'
+        );
 
         $this->getSelect()
-            ->joinLeft(array('default_option_price' => $productOptionPriceTable),
-                'default_option_price.option_id = main_table.option_id AND ' . $adapter->quoteInto('default_option_price.store_id = ?', Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID),
+            ->joinLeft(
+                array('default_option_price' => $productOptionPriceTable),
+                'default_option_price.option_id = main_table.option_id AND '
+                    . $adapter->quoteInto(
+                        'default_option_price.store_id = ?',
+                        Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID
+                    ),
                 array(
                     'default_price' => 'price',
                     'default_price_type' => 'price_type'
                 ))
-            ->joinLeft(array('store_option_price' => $productOptionPriceTable),
-                'store_option_price.option_id = main_table.option_id AND ' . $adapter->quoteInto('store_option_price.store_id = ?', $storeId),
+            ->joinLeft(
+                array('store_option_price' => $productOptionPriceTable),
+                'store_option_price.option_id = main_table.option_id AND '
+                    . $adapter->quoteInto('store_option_price.store_id = ?', $storeId),
                 array(
                     'store_price'       => 'price',
                     'store_price_type'  => 'price_type',
@@ -173,6 +194,18 @@ class Mage_Catalog_Model_Resource_Product_Option_Collection extends Mage_Core_Mo
         return $this;
     }
 
+    /**
+     * Add is_required filter to select
+     *
+     * @param bool $required
+     * @return Mage_Catalog_Model_Resource_Product_Option_Collection
+     */
+    public function addRequiredFilter($required = true)
+    {
+        $this->addFieldToFilter('main_table.is_require', (string)$required);
+        return $this;
+    }
+
     /**
      * Add filtering by option ids
      *
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 094831d6a873daf2519a0b7eab47cdb437d4ba77..0c48f164c07db824dc541e6a6377de9bcb9d6729 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
@@ -59,10 +59,7 @@ class Mage_Catalog_Model_Resource_Product_Type_Configurable extends Mage_Core_Mo
         } else {
             $mainProductId = $mainProduct;
         }
-        $select = $this->_getReadAdapter()->select()
-            ->from($this->getMainTable(), 'product_id')
-            ->where('parent_id = ?', $mainProductId);
-        $old    = $this->_getReadAdapter()->fetchCol($select);
+        $old = $mainProduct->getTypeInstance()->getUsedProductIds($mainProduct);
 
         $insert = array_diff($productIds, $old);
         $delete = array_diff($old, $productIds);
diff --git a/app/code/core/Mage/Catalog/Model/Resource/Url.php b/app/code/core/Mage/Catalog/Model/Resource/Url.php
index bdaad52a56bcc5a41819cd0d42303786106f6d62..66e472d46aca2f3df3b3e986bf5596e381800990 100755
--- a/app/code/core/Mage/Catalog/Model/Resource/Url.php
+++ b/app/code/core/Mage/Catalog/Model/Resource/Url.php
@@ -242,7 +242,7 @@ class Mage_Catalog_Model_Resource_Url extends Mage_Core_Model_Resource_Db_Abstra
     public function prepareRewrites($storeId, $categoryIds = null, $productIds = null)
     {
         $rewrites   = array();
-        $adapter    = $this->_getReadAdapter();
+        $adapter    = $this->_getWriteAdapter();
         $select     = $adapter->select()
             ->from($this->getMainTable())
             ->where('store_id = :store_id')
@@ -296,11 +296,15 @@ class Mage_Catalog_Model_Resource_Url extends Mage_Core_Model_Resource_Db_Abstra
     public function saveRewrite($rewriteData, $rewrite)
     {
         $adapter = $this->_getWriteAdapter();
+        try {
+            $adapter->insertOnDuplicate($this->getMainTable(), $rewriteData);
+        } catch (Exception $e) {
+            Mage::logException($e);
+            Mage::throwException(Mage::helper('Mage_Catalog_Helper_Data')->__('An error occurred while saving the URL rewrite'));
+        }
+
         if ($rewrite && $rewrite->getId()) {
             if ($rewriteData['request_path'] != $rewrite->getRequestPath()) {
-                $where = array($this->getIdFieldName() . '=?' => $rewrite->getId());
-                $adapter->update($this->getMainTable(), $rewriteData, $where);
-
                 // Update existing rewrites history and avoid chain redirects
                 $where = array('target_path = ?' => $rewrite->getRequestPath());
                 if ($rewrite->getStoreId()) {
@@ -312,13 +316,6 @@ class Mage_Catalog_Model_Resource_Url extends Mage_Core_Model_Resource_Db_Abstra
                     $where
                 );
             }
-        } else {
-            try {
-                $adapter->insert($this->getMainTable(), $rewriteData);
-            } catch (Exception $e) {
-                Mage::logException($e);
-                Mage::throwException(Mage::helper('Mage_Catalog_Helper_Data')->__('An error occurred while saving the URL rewrite'));
-            }
         }
         unset($rewriteData);
 
diff --git a/app/code/core/Mage/Catalog/controllers/CategoryController.php b/app/code/core/Mage/Catalog/controllers/CategoryController.php
index 94f9cd49af6a54c16219176f4a6b6b1e6f040f8e..07f3539758ea93d1e293534247528011c534e5de 100644
--- a/app/code/core/Mage/Catalog/controllers/CategoryController.php
+++ b/app/code/core/Mage/Catalog/controllers/CategoryController.php
@@ -88,15 +88,14 @@ class Mage_Catalog_CategoryController extends Mage_Core_Controller_Front_Action
             Mage::getSingleton('Mage_Catalog_Model_Session')->setLastViewedCategoryId($category->getId());
 
             $update = $this->getLayout()->getUpdate();
-            $update->addHandle('default');
-
-            if (!$category->hasChildren()) {
-                $update->addHandle('catalog_category_layered_nochildren');
+            if ($category->getIsAnchor()) {
+                $type = $category->hasChildren() ? 'layered' : 'layered_without_children';
+            } else {
+                $type = $category->hasChildren() ? 'default' : 'default_without_children';
             }
-
-            $this->addActionLayoutHandles();
-            $update->addHandle($category->getLayoutUpdateHandle());
-            $update->addHandle('CATEGORY_' . $category->getId());
+            $this->addPageLayoutHandles(
+                array('type' => $type, 'id' => $category->getId())
+            );
             $this->loadLayoutUpdates();
 
             // apply custom layout update once layout is loaded
diff --git a/app/code/core/Mage/Catalog/controllers/ProductController.php b/app/code/core/Mage/Catalog/controllers/ProductController.php
index 3ba82f2988db08912ab8000cf58707352697fbd3..690268ed4de597fe309331d296ed0eab0843bb1f 100644
--- a/app/code/core/Mage/Catalog/controllers/ProductController.php
+++ b/app/code/core/Mage/Catalog/controllers/ProductController.php
@@ -1,5 +1,5 @@
-<?php
-/**
+<?php
+/**
  * Magento
  *
  * NOTICE OF LICENSE
@@ -17,98 +17,98 @@
  * 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
+ *
+ * @category    Mage
+ * @package     Mage_Catalog
  * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
- */
-
-/**
- * Product controller
- *
- * @category   Mage
- * @package    Mage_Catalog
- */
-class Mage_Catalog_ProductController extends Mage_Core_Controller_Front_Action
-    implements Mage_Catalog_Controller_Product_View_Interface
-{
-    /**
-     * Initialize requested product object
-     *
-     * @return Mage_Catalog_Model_Product
-     */
-    protected function _initProduct()
-    {
-        $categoryId = (int) $this->getRequest()->getParam('category', false);
-        $productId  = (int) $this->getRequest()->getParam('id');
-
-        $params = new Varien_Object();
-        $params->setCategoryId($categoryId);
-
-        return Mage::helper('Mage_Catalog_Helper_Product')->initProduct($productId, $this, $params);
-    }
-
-    /**
-     * Initialize product view layout
-     *
-     * @param   Mage_Catalog_Model_Product $product
-     * @return  Mage_Catalog_ProductController
-     */
-    protected function _initProductLayout($product)
-    {
-        Mage::helper('Mage_Catalog_Helper_Product_View')->initProductLayout($product, $this);
-        return $this;
-    }
-
-    /**
-     * Product view action
-     */
-    public function viewAction()
-    {
-        // Get initial data from request
-        $categoryId = (int) $this->getRequest()->getParam('category', false);
-        $productId  = (int) $this->getRequest()->getParam('id');
-        $specifyOptions = $this->getRequest()->getParam('options');
-
-        // Prepare helper and params
-        $viewHelper = Mage::helper('Mage_Catalog_Helper_Product_View');
-
-        $params = new Varien_Object();
-        $params->setCategoryId($categoryId);
-        $params->setSpecifyOptions($specifyOptions);
-
-        // Render page
-        try {
-            $viewHelper->prepareAndRender($productId, $this, $params);
-        } catch (Exception $e) {
-            if ($e->getCode() == $viewHelper->ERR_NO_PRODUCT_LOADED) {
-                if (isset($_GET['store'])  && !$this->getResponse()->isRedirect()) {
-                    $this->_redirect('');
-                } elseif (!$this->getResponse()->isRedirect()) {
-                    $this->_forward('noRoute');
-                }
-            } else {
-                Mage::logException($e);
-                $this->_forward('noRoute');
-            }
-        }
-    }
-
-    /**
-     * View product gallery action
-     */
-    public function galleryAction()
-    {
-        if (!$this->_initProduct()) {
-            if (isset($_GET['store']) && !$this->getResponse()->isRedirect()) {
-                $this->_redirect('');
-            } elseif (!$this->getResponse()->isRedirect()) {
-                $this->_forward('noRoute');
-            }
-            return;
-        }
-        $this->loadLayout();
-        $this->renderLayout();
-    }
-}
+ */
+
+/**
+ * Product controller
+ *
+ * @category   Mage
+ * @package    Mage_Catalog
+ */
+class Mage_Catalog_ProductController extends Mage_Core_Controller_Front_Action
+    implements Mage_Catalog_Controller_Product_View_Interface
+{
+    /**
+     * Initialize requested product object
+     *
+     * @return Mage_Catalog_Model_Product
+     */
+    protected function _initProduct()
+    {
+        $categoryId = (int) $this->getRequest()->getParam('category', false);
+        $productId  = (int) $this->getRequest()->getParam('id');
+
+        $params = new Varien_Object();
+        $params->setCategoryId($categoryId);
+
+        return Mage::helper('Mage_Catalog_Helper_Product')->initProduct($productId, $this, $params);
+    }
+
+    /**
+     * Initialize product view layout
+     *
+     * @param   Mage_Catalog_Model_Product $product
+     * @return  Mage_Catalog_ProductController
+     */
+    protected function _initProductLayout($product)
+    {
+        Mage::helper('Mage_Catalog_Helper_Product_View')->initProductLayout($product, $this);
+        return $this;
+    }
+
+    /**
+     * Product view action
+     */
+    public function viewAction()
+    {
+        // Get initial data from request
+        $categoryId = (int) $this->getRequest()->getParam('category', false);
+        $productId  = (int) $this->getRequest()->getParam('id');
+        $specifyOptions = $this->getRequest()->getParam('options');
+
+        // Prepare helper and params
+        $viewHelper = Mage::helper('Mage_Catalog_Helper_Product_View');
+
+        $params = new Varien_Object();
+        $params->setCategoryId($categoryId);
+        $params->setSpecifyOptions($specifyOptions);
+
+        // Render page
+        try {
+            $viewHelper->prepareAndRender($productId, $this, $params);
+        } catch (Exception $e) {
+            if ($e->getCode() == $viewHelper->ERR_NO_PRODUCT_LOADED) {
+                if (isset($_GET['store'])  && !$this->getResponse()->isRedirect()) {
+                    $this->_redirect('');
+                } elseif (!$this->getResponse()->isRedirect()) {
+                    $this->_forward('noRoute');
+                }
+            } else {
+                Mage::logException($e);
+                $this->_forward('noRoute');
+            }
+        }
+    }
+
+    /**
+     * View product gallery action
+     */
+    public function galleryAction()
+    {
+        if (!$this->_initProduct()) {
+            if (isset($_GET['store']) && !$this->getResponse()->isRedirect()) {
+                $this->_redirect('');
+            } elseif (!$this->getResponse()->isRedirect()) {
+                $this->_forward('noRoute');
+            }
+            return;
+        }
+        $this->loadLayout();
+        $this->renderLayout();
+    }
+}
diff --git a/app/code/core/Mage/Catalog/controllers/Seo/SitemapController.php b/app/code/core/Mage/Catalog/controllers/Seo/SitemapController.php
index 914ff48adefbf8a345ea631a1e72a5d194cf22a0..4b02782dca0590f3a71dc6765c0e3a791729f7ce 100644
--- a/app/code/core/Mage/Catalog/controllers/Seo/SitemapController.php
+++ b/app/code/core/Mage/Catalog/controllers/Seo/SitemapController.php
@@ -54,12 +54,8 @@ class Mage_Catalog_Seo_SitemapController extends Mage_Core_Controller_Front_Acti
      */
     public function categoryAction()
     {
-        $update = $this->getLayout()->getUpdate();
-        $update->addHandle('default');
-        $this->addActionLayoutHandles();
-        if (Mage::helper('Mage_Catalog_Helper_Map')->getIsUseCategoryTreeMode()) {
-            $update->addHandle(strtolower($this->getFullActionName()).'_tree');
-        }
+        $type = Mage::helper('Mage_Catalog_Helper_Map')->getIsUseCategoryTreeMode() ? 'tree' : 'plain';
+        $this->addPageLayoutHandles(array('type' => $type));
         $this->loadLayoutUpdates();
         $this->generateLayoutXml()->generateLayoutBlocks();
         $this->renderLayout();
diff --git a/app/code/core/Mage/Catalog/data/catalog_setup/data-upgrade-1.6.0.0.12-1.6.0.0.13.php b/app/code/core/Mage/Catalog/data/catalog_setup/data-upgrade-1.6.0.0.12-1.6.0.0.13.php
new file mode 100644
index 0000000000000000000000000000000000000000..68ed77f3901a141dceb3f8b7bfbe8f1f5cf094f2
--- /dev/null
+++ b/app/code/core/Mage/Catalog/data/catalog_setup/data-upgrade-1.6.0.0.12-1.6.0.0.13.php
@@ -0,0 +1,54 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/** @var $installer Mage_Catalog_Model_Resource_Setup */
+$installer = $this;
+$groupPriceAttrId = $installer->getAttribute('catalog_product', 'group_price', 'attribute_id');
+$priceAttrId = $installer->getAttribute('catalog_product', 'price', 'attribute_id');
+$connection = $installer->getConnection();
+
+// update sort_order of Group Price attribute to be after Price
+$select = $connection->select()
+    ->join(
+        array('t2' => $installer->getTable('eav_entity_attribute')),
+        't1.attribute_group_id = t2.attribute_group_id',
+        array('sort_order' => new Zend_Db_Expr('t2.sort_order + 1'))
+    )->where('t1.attribute_id = ?', $groupPriceAttrId)
+    ->where('t2.attribute_id = ?', $priceAttrId);
+$query = $select->crossUpdateFromSelect(array('t1' => $installer->getTable('eav_entity_attribute')));
+$connection->query($query);
+
+// update sort_order of all other attributes to be after Group Price
+$select = $connection->select()
+    ->join(
+        array('t2' => $installer->getTable('eav_entity_attribute')),
+        't1.attribute_group_id = t2.attribute_group_id',
+        array('sort_order' => new Zend_Db_Expr('t1.sort_order + 1'))
+    )->where('t1.attribute_id != ?', $groupPriceAttrId)
+    ->where('t1.sort_order >= t2.sort_order')
+    ->where('t2.attribute_id = ?', $groupPriceAttrId);
+$query = $select->crossUpdateFromSelect(array('t1' => $installer->getTable('eav_entity_attribute')));
+$connection->query($query);
diff --git a/app/code/core/Mage/Catalog/etc/adminhtml.xml b/app/code/core/Mage/Catalog/etc/adminhtml.xml
index 870118d399a154a34a63270ee3d9f4905da5c21f..5986aa3a0348f0ee144c2dbcb8dee649e778efae 100644
--- a/app/code/core/Mage/Catalog/etc/adminhtml.xml
+++ b/app/code/core/Mage/Catalog/etc/adminhtml.xml
@@ -107,7 +107,7 @@
                                 <title>Update Attributes</title>
                             </update_attributes>
                             <urlrewrite translate="title">
-                                <title>Url Rewrite Management</title>
+                                <title>URL Rewrite Management</title>
                             </urlrewrite>
                         </children>
                     </catalog>
diff --git a/app/code/core/Mage/Catalog/etc/config.xml b/app/code/core/Mage/Catalog/etc/config.xml
index 3bd81a75c911f1341a9c94bb9886e4e17fe870ee..1a4e92fc2ff75bef18e2fc0335acdcd01f38fe8c 100644
--- a/app/code/core/Mage/Catalog/etc/config.xml
+++ b/app/code/core/Mage/Catalog/etc/config.xml
@@ -28,7 +28,7 @@
 <config>
     <modules>
         <Mage_Catalog>
-            <version>1.6.0.0.11</version>
+            <version>1.6.0.0.13</version>
         </Mage_Catalog>
     </modules>
     <global>
@@ -71,6 +71,14 @@
                     </catalog_product_compare_item>
                 </observers>
             </log_log_clean_after>
+            <page_block_html_topmenu_gethtml_before>
+                <observers>
+                    <catalog_add_topmenu_items>
+                        <class>Mage_Catalog_Model_Observer</class>
+                        <method>addCatalogToTopmenuItems</method>
+                    </catalog_add_topmenu_items>
+                </observers>
+            </page_block_html_topmenu_gethtml_before>
         </events>
         <catalog>
             <product>
@@ -395,6 +403,7 @@
                 <price_range_max_intervals>10</price_range_max_intervals>
                 <one_price_interval>0</one_price_interval>
                 <interval_division_limit>9</interval_division_limit>
+                <display_product_count>1</display_product_count>
             </layered_navigation>
         </catalog>
         <system>
diff --git a/app/code/core/Mage/Catalog/etc/fieldset.xml b/app/code/core/Mage/Catalog/etc/fieldset.xml
index 9310bb06098d4bcc2ea42cdda6521bd3338e3cd2..39cacfb8d4cae5853087fea5dce9c04adfdede4d 100644
--- a/app/code/core/Mage/Catalog/etc/fieldset.xml
+++ b/app/code/core/Mage/Catalog/etc/fieldset.xml
@@ -53,6 +53,13 @@
                         <virtual/>
                     </product_type>
                 </is_qty_decimal>
+                <is_decimal_divided>
+                    <inventory>1</inventory>
+                    <product_type>
+                        <simple/>
+                        <virtual/>
+                    </product_type>
+                </is_decimal_divided>
                 <backorders>
                     <inventory>1</inventory>
                     <use_config>1</use_config>
diff --git a/app/code/core/Mage/Catalog/etc/system.xml b/app/code/core/Mage/Catalog/etc/system.xml
index 80eb337ed88a94fc008701404c6a99c784ba52dd..84116a88f58fed6615a5ef05ac0825f2ad0b2ae1 100644
--- a/app/code/core/Mage/Catalog/etc/system.xml
+++ b/app/code/core/Mage/Catalog/etc/system.xml
@@ -312,11 +312,20 @@
                     <show_in_website>1</show_in_website>
                     <show_in_store>1</show_in_store>
                     <fields>
+                        <display_product_count translate="label">
+                            <label>Display Product Count</label>
+                            <frontend_type>select</frontend_type>
+                            <sort_order>5</sort_order>
+                            <source_model>Mage_Adminhtml_Model_System_Config_Source_Yesno</source_model>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>1</show_in_store>
+                        </display_product_count>
                         <price_range_calculation translate="label">
                             <label>Price Navigation Step Calculation</label>
                             <frontend_type>select</frontend_type>
                             <source_model>Mage_Adminhtml_Model_System_Config_Source_Price_Step</source_model>
-                            <sort_order>1</sort_order>
+                            <sort_order>10</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
                             <show_in_store>1</show_in_store>
@@ -325,7 +334,7 @@
                             <label>Default Price Navigation Step</label>
                             <frontend_type>text</frontend_type>
                             <validate>validate-number validate-number-range number-range-0.01-1000000000</validate>
-                            <sort_order>2</sort_order>
+                            <sort_order>15</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
                             <show_in_store>1</show_in_store>
@@ -336,7 +345,7 @@
                             <comment>Maximum number of price intervals is 100</comment>
                             <frontend_type>text</frontend_type>
                             <validate>validate-digits validate-digits-range digits-range-2-100</validate>
-                            <sort_order>3</sort_order>
+                            <sort_order>20</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
                             <show_in_store>1</show_in_store>
@@ -347,22 +356,22 @@
                             <comment>This setting will be applied when all prices in the specific price interval are equal.</comment>
                             <frontend_type>select</frontend_type>
                             <source_model>Mage_Adminhtml_Model_System_Config_Source_Yesno</source_model>
-                            <sort_order>4</sort_order>
+                            <sort_order>15</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
                             <show_in_store>1</show_in_store>
-                            <depends><price_range_calculation>auto</price_range_calculation></depends>
+                            <depends><price_range_calculation>improved</price_range_calculation></depends>
                         </one_price_interval>
                         <interval_division_limit translate="label comment">
                             <label>Interval Division Limit</label>
                             <comment>Please specify the number of products, that will not be divided into subintervals.</comment>
                             <frontend_type>text</frontend_type>
-                            <sort_order>5</sort_order>
+                            <sort_order>20</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
                             <show_in_store>1</show_in_store>
                             <validate>validate-digits validate-digits-range digits-range-1-10000</validate>
-                            <depends><price_range_calculation>auto</price_range_calculation></depends>
+                            <depends><price_range_calculation>improved</price_range_calculation></depends>
                         </interval_division_limit>
                     </fields>
                 </layered_navigation>
diff --git a/app/code/core/Mage/Catalog/etc/widget.xml b/app/code/core/Mage/Catalog/etc/widget.xml
index 62044a87fc79a7aa20ce59df6da6eb065e8dabca..5deb9780709535f523213a9c920844f4186601b8 100644
--- a/app/code/core/Mage/Catalog/etc/widget.xml
+++ b/app/code/core/Mage/Catalog/etc/widget.xml
@@ -75,9 +75,9 @@
                 <type>text</type>
             </cache_lifetime>
         </parameters>
-        <supported_blocks>
+        <supported_containers>
             <left_column>
-                <block_name>left</block_name>
+                <container_name>left</container_name>
                 <template>
                     <default>list_default</default>
                     <names_only>list_names</names_only>
@@ -85,21 +85,21 @@
                 </template>
             </left_column>
             <main_content>
-                <block_name>content</block_name>
+                <container_name>content</container_name>
                 <template>
                     <grid>default</grid>
                     <list>list</list>
                 </template>
             </main_content>
             <right_column>
-                <block_name>right</block_name>
+                <container_name>right</container_name>
                 <template>
                     <default>list_default</default>
                     <names_only>list_names</names_only>
                     <images_only>list_images</images_only>
                 </template>
             </right_column>
-        </supported_blocks>
+        </supported_containers>
     </new_products>
 
     <catalog_product_link type="Mage_Catalog_Block_Product_Widget_Link" translate="name description" module="Mage_Catalog">
diff --git a/app/code/core/Mage/Catalog/sql/catalog_setup/upgrade-1.6.0.0.11-1.6.0.0.12.php b/app/code/core/Mage/Catalog/sql/catalog_setup/upgrade-1.6.0.0.11-1.6.0.0.12.php
new file mode 100644
index 0000000000000000000000000000000000000000..dc2241060b9d669175ccba536c8a83dfd0787340
--- /dev/null
+++ b/app/code/core/Mage/Catalog/sql/catalog_setup/upgrade-1.6.0.0.11-1.6.0.0.12.php
@@ -0,0 +1,34 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/** @var $installer Mage_Catalog_Model_Resource_Setup */
+$installer  = $this;
+$indexFields = array('website_id', 'customer_group_id', 'min_price');
+$installer->getConnection()->addIndex(
+    $installer->getTable('catalog_product_index_price'),
+    $installer->getIdxName('catalog_product_index_price', $indexFields),
+    $indexFields
+);
diff --git a/app/code/core/Mage/Catalog/view/frontend/layer/filter.phtml b/app/code/core/Mage/Catalog/view/frontend/layer/filter.phtml
index 50977c6b21eb2209ca6c26d5e06b0e2396d8184d..ec4a2c9a79fd8d4921fca6ff2d5fda0211f3c861 100644
--- a/app/code/core/Mage/Catalog/view/frontend/layer/filter.phtml
+++ b/app/code/core/Mage/Catalog/view/frontend/layer/filter.phtml
@@ -39,7 +39,9 @@
         <a href="<?php echo $this->escapeUrl($_item->getUrl()) ?>"><?php echo $_item->getLabel() ?></a>
         <?php else: echo $_item->getLabel() ?>
         <?php endif; ?>
+        <?php if ($this->shouldDisplayProductCount()): ?>
         (<?php echo $_item->getCount() ?>)
+        <?php endif; ?>
     </li>
 <?php endforeach ?>
 </ol>
diff --git a/app/code/core/Mage/Catalog/view/frontend/layer/state.phtml b/app/code/core/Mage/Catalog/view/frontend/layer/state.phtml
index 02395ab901fb06beca93cd640c910f92ffb4d510..59af49888c33b06b58b262bc77393ddb69cf97af 100644
--- a/app/code/core/Mage/Catalog/view/frontend/layer/state.phtml
+++ b/app/code/core/Mage/Catalog/view/frontend/layer/state.phtml
@@ -38,13 +38,15 @@
     <ol>
     <?php foreach ($_filters as $_filter): ?>
         <li>
-            <a href="<?php echo $_filter->getRemoveUrl() ?>" title="<?php echo $this->__('Remove This Item') ?>" class="btn-remove"><?php echo $this->__('Remove This Item') ?></a>
-            <span class="label"><?php echo $this->__($_filter->getName()) ?>:</span> <?php echo $this->stripTags($_filter->getLabel()) ?>
+            <span class="label"><?php echo $this->__($_filter->getName()) ?>:</span> <span class="value"><?php echo $this->stripTags($_filter->getLabel()) ?></span>
             <?php
                 $clearLinkUrl = $_filter->getClearLinkUrl();
                 if ($clearLinkUrl):
             ?>
-                <div class="actions"><a href="<?php echo $clearLinkUrl ?>"><?php echo $this->escapeHtml($_filter->getFilter()->getClearLinkText()) ?></a></div>
+                <a  class="btn-previous" href="<?php echo $_filter->getRemoveUrl() ?>" title="<?php echo $this->__('Previous') ?>"><?php echo $this->__('Previous') ?></a>
+                <a  class="btn-remove" title="<?php echo $this->escapeHtml($_filter->getFilter()->getClearLinkText()) ?>" href="<?php echo $clearLinkUrl ?>"><?php echo $this->escapeHtml($_filter->getFilter()->getClearLinkText()) ?></a>
+            <?php else: ?>
+                <a  class="btn-remove" href="<?php echo $_filter->getRemoveUrl() ?>" title="<?php echo $this->__('Remove This Item') ?>"><?php echo $this->__('Remove This Item') ?></a>
             <?php endif; ?>
         </li>
     <?php endforeach; ?>
diff --git a/app/code/core/Mage/Catalog/view/frontend/layer/view.phtml b/app/code/core/Mage/Catalog/view/frontend/layer/view.phtml
index a7eda469aac84e29e2358349dbbd33dce6a684c1..06a5a6536455e79231d1df1bb1110cee64358c3b 100644
--- a/app/code/core/Mage/Catalog/view/frontend/layer/view.phtml
+++ b/app/code/core/Mage/Catalog/view/frontend/layer/view.phtml
@@ -38,6 +38,9 @@
     </div>
     <div class="block-content">
         <?php echo $this->getStateHtml() ?>
+        <?php if ($this->getLayer()->getState()->getFilters()): ?>
+            <div class="actions"><a href="<?php echo $this->getClearUrl() ?>"><?php echo $this->__('Clear All') ?></a></div>
+        <?php endif; ?>
         <?php if($this->canShowOptions()): ?>
             <p class="block-subtitle"><?php echo $this->__('Shopping Options') ?></p>
             <dl id="narrow-by-list">
@@ -51,9 +54,6 @@
             </dl>
             <script type="text/javascript">decorateDataList('narrow-by-list')</script>
         <?php endif; ?>
-        <?php if ($this->getLayer()->getState()->getFilters()): ?>
-            <div class="actions"><a href="<?php echo $this->getClearUrl() ?>"><?php echo $this->__('Clear All') ?></a></div>
-        <?php endif; ?>
     </div>
 </div>
 <?php endif; ?>
diff --git a/app/code/core/Mage/Catalog/view/frontend/layout.xml b/app/code/core/Mage/Catalog/view/frontend/layout.xml
index 4109dfe718d64d58a3c3e8251c3eef1050441e76..46fa9fec3c46d6160cbd1fdffa84067f8a799357 100644
--- a/app/code/core/Mage/Catalog/view/frontend/layout.xml
+++ b/app/code/core/Mage/Catalog/view/frontend/layout.xml
@@ -47,12 +47,6 @@ Default layout, loads most of the pages
             <action method="addCss"><file>Mage_Catalog::widgets.css</file></action>
         </reference>
         <!-- Mage_Catalog -->
-        <reference name="top.menu">
-            <block type="Mage_Catalog_Block_Navigation" name="catalog.topnav" template="navigation/top.phtml"/>
-        </reference>
-        <reference name="header">
-            <block type="Mage_Catalog_Block_Product_Compare_Sidebar" name="catalogCompareLink" template="product/compare/sidebar.phtml"/>
-        </reference>
         <reference name="left">
             <block type="Mage_Core_Block_Template" name="left.permanent.callout" template="Mage_Page::callouts/left_col.phtml">
                 <action method="setImgSrc"><src>images/media/col_left_callout.jpg</src></action>
@@ -61,6 +55,7 @@ Default layout, loads most of the pages
             </block>
         </reference>
         <reference name="right">
+            <block type="Mage_Catalog_Block_Product_Compare_Sidebar" before="cart_sidebar" name="catalog.compare.sidebar" template="product/compare/sidebar.phtml"/>
             <block type="Mage_Core_Block_Template" name="right.permanent.callout" template="Mage_Page::callouts/right_col.phtml">
                 <action method="setImgSrc"><src>images/media/col_right_callout.jpg</src></action>
                 <action method="setImgAlt" translate="alt" module="Mage_Catalog"><alt>Keep your eyes open for our special Back to School items and save A LOT!</alt></action>
@@ -72,57 +67,12 @@ Default layout, loads most of the pages
         <block type="Mage_Catalog_Block_Product_Price_Template" name="catalog_product_price_template" />
     </default>
 
-    <print>
-        <reference name="head">
-            <action method="addCss"><file>Mage_Catalog::widgets.css</file></action>
-        </reference>
-    </print>
-
 <!--
 Category default layout
 -->
 
-    <catalog_category_default translate="label">
-        <label>Catalog Category (Non-Anchor)</label>
-        <reference name="left">
-            <block type="Mage_Catalog_Block_Navigation" name="catalog.leftnav" after="currency" template="navigation/left.phtml"/>
-        </reference>
-        <reference name="content">
-            <block type="Mage_Catalog_Block_Category_View" name="category.products" template="category/view.phtml">
-                <block type="Mage_Catalog_Block_Product_List" name="product_list" template="product/list.phtml">
-                    <block type="Mage_Catalog_Block_Product_List_Toolbar" name="product_list_toolbar" template="product/list/toolbar.phtml">
-                        <block type="Mage_Page_Block_Html_Pager" name="product_list_toolbar_pager"/>
-                        <!-- The following code shows how to set your own pager increments -->
-                        <!--
-                            <action method="setDefaultListPerPage"><limit>4</limit></action>
-                            <action method="setDefaultGridPerPage"><limit>9</limit></action>
-                            <action method="addPagerLimit"><mode>list</mode><limit>2</limit></action>
-                            <action method="addPagerLimit"><mode>list</mode><limit>4</limit></action>
-                            <action method="addPagerLimit"><mode>list</mode><limit>6</limit></action>
-                            <action method="addPagerLimit"><mode>list</mode><limit>8</limit></action>
-                            <action method="addPagerLimit" translate="label"><mode>list</mode><limit>all</limit><label>All</label></action>
-                        -->
-                    </block>
-                    <action method="addColumnCountLayoutDepend"><layout>empty</layout><count>6</count></action>
-                    <action method="addColumnCountLayoutDepend"><layout>one_column</layout><count>5</count></action>
-                    <action method="addColumnCountLayoutDepend"><layout>two_columns_left</layout><count>4</count></action>
-                    <action method="addColumnCountLayoutDepend"><layout>two_columns_right</layout><count>4</count></action>
-                    <action method="addColumnCountLayoutDepend"><layout>three_columns</layout><count>3</count></action>
-                    <action method="setToolbarBlockName"><name>product_list_toolbar</name></action>
-                </block>
-            </block>
-        </reference>
-    </catalog_category_default>
-
-<!--
-Category layered navigation layout
--->
-
-    <catalog_category_layered translate="label">
-        <label>Catalog Category (Anchor)</label>
-        <reference name="left">
-            <block type="Mage_Catalog_Block_Layer_View" name="catalog.leftnav" after="currency" template="layer/view.phtml"/>
-        </reference>
+    <catalog_category_view translate="label" type="page" parent="default">
+        <label>Catalog Category</label>
         <reference name="content">
             <block type="Mage_Catalog_Block_Category_View" name="category.products" template="category/view.phtml">
                 <block type="Mage_Catalog_Block_Product_List" name="product_list" template="product/list.phtml">
@@ -151,15 +101,36 @@ Category layered navigation layout
                     <action method="setToolbarBlockName"><name>product_list_toolbar</name></action>
                 </block>
             </block>
-            <block type="Mage_Catalog_Block_Layer_View" name="catalog.leftnav" after="product_list_toolbar" template="layer/view.phtml"/>
         </reference>
-    </catalog_category_layered>
+    </catalog_category_view>
+
+    <catalog_category_view_type_default translate="label" type="page" parent="catalog_category_view">
+        <label>Non Anchor Catalog Category</label>
+        <reference name="left">
+            <block type="Mage_Catalog_Block_Navigation" name="catalog.leftnav" after="currency" template="navigation/left.phtml"/>
+        </reference>
+    </catalog_category_view_type_default>
+
+    <catalog_category_view_type_default_without_children translate="label" type="page" parent="catalog_category_view_type_default">
+        <label>Non Anchor Catalog Category Without Subcategories</label>
+    </catalog_category_view_type_default_without_children>
+
+    <catalog_category_view_type_layered translate="label" type="page" parent="catalog_category_view">
+        <label>Anchor Catalog Category</label>
+        <reference name="left">
+            <block type="Mage_Catalog_Block_Layer_View" name="catalog.leftnav" after="currency" template="layer/view.phtml"/>
+        </reference>
+    </catalog_category_view_type_layered>
+
+    <catalog_category_view_type_layered_without_children translate="label" type="page" parent="catalog_category_view_type_layered">
+        <label>Anchor Catalog Category Without Subcategories</label>
+    </catalog_category_view_type_layered_without_children>
 
 <!--
 Compare products page
 -->
 
-    <catalog_product_compare_index translate="label">
+    <catalog_product_compare_index translate="label" type="page" parent="default">
         <label>Catalog Product Compare List</label>
         <!-- Mage_Catalog -->
         <reference name="root">
@@ -184,7 +155,7 @@ Compare products page
 Product view
 -->
 
-    <catalog_product_view translate="label">
+    <catalog_product_view translate="label" type="page" parent="default">
         <label>Catalog Product View (Any)</label>
         <!-- Mage_Catalog -->
         <reference name="root">
@@ -206,9 +177,7 @@ Product view
                 <action method="addReviewSummaryTemplate"><type>...</type><template>...</template></action>
                 -->
                 <block type="Mage_Catalog_Block_Product_View_Media" name="product.info.media" as="media" template="product/view/media.phtml"/>
-                <block type="Mage_Core_Block_Text_List" name="alert.urls" as="alert_urls" translate="label">
-                    <label>Alert Urls</label>
-                </block>
+                <container name="alert.urls" as="alert_urls" label="Alert Urls"/>
 
                 <action method="setTierPriceTemplate"><template>product/view/tierprices.phtml</template></action>
 
@@ -227,9 +196,7 @@ Product view
                 <block type="Mage_Catalog_Block_Product_View" name="product.info.addto" as="addto" template="product/view/addto.phtml"/>
                 <block type="Mage_Catalog_Block_Product_View" name="product.info.addtocart" as="addtocart" template="product/view/addtocart.phtml"/>
 
-                <block type="Mage_Core_Block_Text_List" name="product.info.extrahint" as="extrahint" translate="label">
-                    <label>Product View Extra Hint</label>
-                </block>
+                <container name="product.info.extrahint" as="extrahint" label="Product View Extra Hint"/>
 
                 <block type="Mage_Catalog_Block_Product_View" name="product.info.options.wrapper" as="product_options_wrapper" template="product/view/options/wrapper.phtml" translate="label">
                     <label>Info Column Options Wrapper</label>
@@ -274,57 +241,49 @@ Product view
 <!--
 Additional block dependant on product type
 -->
-    <PRODUCT_TYPE_simple translate="label" module="Mage_Catalog">
+    <catalog_product_view_type_simple translate="label" module="Mage_Catalog" type="page" parent="catalog_product_view">
         <label>Catalog Product View (Simple)</label>
         <reference name="product.info">
             <block type="Mage_Catalog_Block_Product_View_Type_Simple" name="product.info.simple" as="product_type_data" template="product/view/type/default.phtml">
-                <block type="Mage_Core_Block_Text_List" name="product.info.simple.extra" as="product_type_data_extra" translate="label">
-                    <label>Product Extra Info</label>
-                </block>
+                <container name="product.info.simple.extra" as="product_type_data_extra" label="Product Extra Info"/>
             </block>
         </reference>
-    </PRODUCT_TYPE_simple>
-    <PRODUCT_TYPE_configurable translate="label" module="Mage_Catalog">
+    </catalog_product_view_type_simple>
+    <catalog_product_view_type_configurable translate="label" module="Mage_Catalog" type="page" parent="catalog_product_view">
         <label>Catalog Product View (Configurable)</label>
         <reference name="product.info">
             <block type="Mage_Catalog_Block_Product_View_Type_Configurable" name="product.info.configurable" as="product_type_data" template="product/view/type/default.phtml">
-                <block type="Mage_Core_Block_Text_List" name="product.info.configurable.extra" as="product_type_data_extra" translate="label">
-                    <label>Product Extra Info</label>
-                </block>
+                <container name="product.info.configurable.extra" as="product_type_data_extra" label="Product Extra Info"/>
             </block>
         </reference>
         <reference name="product.info.options.wrapper">
             <block type="Mage_Catalog_Block_Product_View_Type_Configurable" name="product.info.options.configurable" as="options_configurable" before="-" template="product/view/type/options/configurable.phtml"/>
         </reference>
-    </PRODUCT_TYPE_configurable>
-    <PRODUCT_TYPE_grouped translate="label" module="Mage_Catalog">
+    </catalog_product_view_type_configurable>
+    <catalog_product_view_type_grouped translate="label" module="Mage_Catalog" type="page" parent="catalog_product_view">
         <label>Catalog Product View (Grouped)</label>
         <reference name="product.info">
             <block type="Mage_Catalog_Block_Product_View_Type_Grouped" name="product.info.grouped" as="product_type_data" template="product/view/type/grouped.phtml">
-                <block type="Mage_Core_Block_Text_List" name="product.info.grouped.extra" as="product_type_data_extra" translate="label">
-                    <label>Product Extra Info</label>
-                </block>
+                <container name="product.info.grouped.extra" as="product_type_data_extra" label="Product Extra Info"/>
             </block>
             <block type="Mage_Catalog_Block_Product_View_Type_Grouped" name="product.info.grouped.grid" as="product_type_data_grid" template="product/view/type/grouped.phtml">
             </block>
         </reference>
-    </PRODUCT_TYPE_grouped>
-    <PRODUCT_TYPE_virtual translate="label" module="Mage_Catalog">
+    </catalog_product_view_type_grouped>
+    <catalog_product_view_type_virtual translate="label" module="Mage_Catalog" type="page" parent="catalog_product_view">
         <label>Catalog Product View (Virtual)</label>
         <reference name="product.info">
             <block type="Mage_Catalog_Block_Product_View_Type_Virtual" name="product.info.virtual" as="product_type_data" template="product/view/type/default.phtml">
-                <block type="Mage_Core_Block_Text_List" name="product.info.virtual.extra" as="product_type_data_extra" translate="label">
-                    <label>Product Extra Info</label>
-                </block>
+                <container name="product.info.virtual.extra" as="product_type_data_extra" label="Product Extra Info"/>
             </block>
         </reference>
-    </PRODUCT_TYPE_virtual>
+    </catalog_product_view_type_virtual>
 
 <!--
 Product additional images gallery popup
 -->
 
-    <catalog_product_gallery translate="label">
+    <catalog_product_gallery translate="label" type="page" parent="catalog_product_view">
         <label>Catalog Product Image Gallery Popup</label>
         <!-- Mage_Catalog -->
         <reference name="root">
@@ -339,7 +298,7 @@ Product additional images gallery popup
 SEO Site Map
 -->
 
-    <catalog_seo_sitemap translate="label">
+    <catalog_seo_sitemap translate="label" type="page" parent="default">
         <label>Catalog Seo Sitemap (Common)</label>
         <remove name="right"/>
         <remove name="left"/>
@@ -356,7 +315,7 @@ SEO Site Map
         </reference>
     </catalog_seo_sitemap>
 
-    <catalog_seo_sitemap_category translate="label">
+    <catalog_seo_sitemap_category translate="label" type="page" parent="catalog_seo_sitemap">
         <label>Catalog Seo Sitemap (Category List)</label>
         <reference name="head">
             <action method="setTitle" translate="title" module="Mage_Catalog"><title>Site Map</title></action>
@@ -380,7 +339,6 @@ SEO Site Map
                 </action>
             </block>
         </reference>
-        <update handle="catalog_seo_sitemap" />
         <reference name="seo.sitemap.container">
             <action method="setTitle" translate="title" module="Mage_Catalog"><title>Categories</title></action>
             <block type="Mage_Catalog_Block_Seo_Sitemap_Category" name="seo.sitemap.sitemap" as="sitemap" after="pager_top" template="seo/sitemap.phtml">
@@ -394,7 +352,7 @@ SEO Site Map
         </reference>
     </catalog_seo_sitemap_category>
 
-    <catalog_seo_sitemap_category_tree translate="label">
+    <catalog_seo_sitemap_category_type_tree translate="label" type="page" parent="catalog_seo_sitemap_category">
         <label>Catalog Seo Sitemap (Category Tree)</label>
         <reference name="seo.sitemap.container">
             <remove name="seo.sitemap.pager.top" />
@@ -407,9 +365,9 @@ SEO Site Map
                 <action method="bindPager"><pager>seo.sitemap.tree.pager.bottom</pager></action>
             </block>
         </reference>
-    </catalog_seo_sitemap_category_tree>
+    </catalog_seo_sitemap_category_type_tree>
 
-    <catalog_seo_sitemap_product translate="label">
+    <catalog_seo_sitemap_product translate="label" type="page" parent="catalog_seo_sitemap">
         <label>Catalog Seo Sitemap (Product List)</label>
         <reference name="head">
             <action method="setTitle" translate="title" module="Mage_Catalog"><title>Site Map</title></action>
@@ -427,5 +385,4 @@ SEO Site Map
             <action method="addLink" translate="label title" module="Mage_Catalog"><label>Categories Sitemap</label><url helper="Mage_Catalog_Helper_Map::getCategoryUrl"/><title>Categories Sitemap</title></action>
         </reference>
     </catalog_seo_sitemap_product>
-
 </layout>
diff --git a/app/code/core/Mage/Catalog/view/frontend/msrp.xml b/app/code/core/Mage/Catalog/view/frontend/msrp.xml
index 06a6442ebba62145252f4ea289e2968a1e009fb1..051f9c5eb09bcfd7ea8a44ec1ab398ab6f8fb1ad 100644
--- a/app/code/core/Mage/Catalog/view/frontend/msrp.xml
+++ b/app/code/core/Mage/Catalog/view/frontend/msrp.xml
@@ -30,12 +30,9 @@
 <!--
 Default layout, loads most of the pages
 -->
-    <catalog_category_default>
+    <catalog_category_view>
         <update handle="MAP_popup" />
-    </catalog_category_default>
-    <catalog_category_layered>
-        <update handle="MAP_popup" />
-    </catalog_category_layered>
+    </catalog_category_view>
     <catalog_product_compare_index>
         <update handle="MAP_popup" />
     </catalog_product_compare_index>
@@ -77,7 +74,8 @@ Default layout, loads most of the pages
         <update handle="MAP_popup" />
     </tag_customer_view>
 
-    <MAP_popup>
+    <MAP_popup translate="label" type="page" parent="catalog_product_view">
+        <label>Catalog MAP Popup</label>
         <reference name="head">
             <action method="addJs" ifconfig="sales/msrp/enabled"><file>Mage_Catalog::msrp.js</file></action>
         </reference>
@@ -85,7 +83,8 @@ Default layout, loads most of the pages
             <block type="Mage_Core_Block_Template" template="Mage_Catalog::msrp/popup.phtml" name="product.tooltip"></block>
         </reference>
     </MAP_popup>
-    <MAP_price_msrp_item>
+    <MAP_price_msrp_item translate="label" type="page" parent="catalog_product_view">
+        <label>Catalog MAP Price MSRP Item</label>
         <reference name="catalog_product_price_template">
             <action method="addPriceBlockType"><type>msrp</type><block>Mage_Catalog_Block_Product_Price</block><template>product/price_msrp_item.phtml</template></action>
         </reference>
@@ -93,7 +92,8 @@ Default layout, loads most of the pages
             <action method="addPriceBlockType"><type>msrp</type><block>Mage_Catalog_Block_Product_Price</block><template>product/price_msrp_item.phtml</template></action>
         </reference>
     </MAP_price_msrp_item>
-    <MAP_price_msrp_wishlist_item>
+    <MAP_price_msrp_wishlist_item translate="label" type="page" parent="wishlist_index_index">
+        <label>Catalog MAP Price MSRP Wishlist Item</label>
         <reference name="catalog_product_price_template">
             <action method="addPriceBlockType"><type>msrp</type><block>Mage_Catalog_Block_Product_Price</block><template>Mage_Wishlist::render/item/price_msrp_item.phtml</template></action>
         </reference>
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 94fd7656705db33fdb41e88a9e60ddf0cf749eda..fcfd1047e7c9ba6e0678488649f2f1fb1b6195f6 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
@@ -71,7 +71,7 @@
                     <?php endif; ?>
                     <?php if ($this->helper('Mage_Wishlist_Helper_Data')->isAllow()) : ?>
                         <ul class="add-to-links">
-                            <li><a href="#" class="link-wishlist" onclick="setPLocation('<?php echo $this->getAddToWishlistUrl($_item) ?>', true)"><?php echo $this->__('Add to Wishlist') ?></a></li>
+                            <li><a href="<?php echo $this->getAddToWishlistUrl($_item) ?>" class="link-wishlist" onclick="setPLocation(this.href, true)"><?php echo $this->__('Add to Wishlist') ?></a></li>
                         </ul>
                     <?php endif; ?>
                 </td>
@@ -124,7 +124,7 @@
                     <?php endif; ?>
                     <?php if ($this->helper('Mage_Wishlist_Helper_Data')->isAllow()) : ?>
                         <ul class="add-to-links">
-                            <li><a href="#" class="link-wishlist" onclick="setPLocation('<?php echo $this->getAddToWishlistUrl($_item) ?>', true)"><?php echo $this->__('Add to Wishlist') ?></a></li>
+                            <li><a href="<?php echo $this->getAddToWishlistUrl($_item);?>" class="link-wishlist" onclick="setPLocation(this.href, true)"><?php echo $this->__('Add to Wishlist') ?></a></li>
                         </ul>
                     <?php endif; ?>
                 </td>
diff --git a/app/code/core/Mage/Catalog/view/frontend/product/price.phtml b/app/code/core/Mage/Catalog/view/frontend/product/price.phtml
index 8ba900687ec77ac0e6707b9892c91fa15ab3c325..22429a4da8f03233a9799e61e8906a062a42412a 100644
--- a/app/code/core/Mage/Catalog/view/frontend/product/price.phtml
+++ b/app/code/core/Mage/Catalog/view/frontend/product/price.phtml
@@ -67,32 +67,32 @@
     <?php $_finalPrice = $_taxHelper->getPrice($_product, $_product->getFinalPrice()) ?>
     <?php $_finalPriceInclTax = $_taxHelper->getPrice($_product, $_product->getFinalPrice(), true) ?>
     <?php $_weeeDisplayType = $_weeeHelper->getPriceDisplayType(); ?>
-    <?php if ($_finalPrice == $_price): ?>
+    <?php if ($_finalPrice >= $_price): ?>
         <?php if ($_taxHelper->displayBothPrices()): ?>
             <?php if ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($_product, 0)): // including ?>
                 <span class="price-excluding-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Excl. Tax:') ?></span>
                     <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_price+$_weeeTaxAmount,true,false) ?>
+                        <?php echo $_coreHelper->currency($_price + $_weeeTaxAmount, true, false) ?>
                     </span>
                 </span>
                 <span class="price-including-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Incl. Tax:') ?></span>
                     <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPriceInclTax+$_weeeTaxAmountInclTaxes,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmountInclTaxes, true, false) ?>
                     </span>
                 </span>
             <?php elseif ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($_product, 1)): // incl. + weee ?>
                 <span class="price-excluding-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Excl. Tax:') ?></span>
                     <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_price+$_weeeTaxAmount,true,false) ?>
+                        <?php echo $_coreHelper->currency($_price + $_weeeTaxAmount, true, false) ?>
                     </span>
                 </span>
                 <span class="price-including-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Incl. Tax:') ?></span>
                     <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPriceInclTax+$_weeeTaxAmountInclTaxes,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmountInclTaxes, true, false) ?>
                     </span>
                     <span class="weee">(
                         <?php foreach ($_weeeTaxAttributes as $_weeeTaxAttribute): ?>
@@ -106,18 +106,18 @@
                 <span class="price-excluding-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Excl. Tax:') ?></span>
                     <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_price+$_weeeTaxAmount,true,false) ?>
+                        <?php echo $_coreHelper->currency($_price + $_weeeTaxAmount, true, false) ?>
                     </span>
                 </span>
                 <span class="price-including-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Incl. Tax:') ?></span>
                     <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPriceInclTax+$_weeeTaxAmountInclTaxes,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmountInclTaxes, true, false) ?>
                     </span>
                     <span class="weee">(
                         <?php foreach ($_weeeTaxAttributes as $_weeeTaxAttribute): ?>
                             <?php echo $_weeeSeparator; ?>
-                            <?php echo $_weeeTaxAttribute->getName(); ?>: <?php echo $_coreHelper->currency($_weeeTaxAttribute->getAmount()+$_weeeTaxAttribute->getTaxAmount(), true, true); ?>
+                            <?php echo $_weeeTaxAttribute->getName(); ?>: <?php echo $_coreHelper->currency($_weeeTaxAttribute->getAmount() + $_weeeTaxAttribute->getTaxAmount(), true, true); ?>
                             <?php $_weeeSeparator = ' + '; ?>
                         <?php endforeach; ?>
                         )</span>
@@ -126,7 +126,7 @@
                 <span class="price-excluding-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Excl. Tax:') ?></span>
                     <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_price,true,false) ?>
+                        <?php echo $_coreHelper->currency($_price, true, false) ?>
                     </span>
                 </span>
                 <?php foreach ($_weeeTaxAttributes as $_weeeTaxAttribute): ?>
@@ -137,31 +137,35 @@
                 <span class="price-including-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Incl. Tax:') ?></span>
                     <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPriceInclTax+$_weeeTaxAmountInclTaxes,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmountInclTaxes, true, false) ?>
                     </span>
                 </span>
             <?php else: ?>
                 <span class="price-excluding-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Excl. Tax:') ?></span>
                     <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_price,true,false) ?>
+                        <?php if ($_finalPrice == $_price): ?>
+                            <?php echo $_coreHelper->currency($_price, true, false) ?>
+                        <?php else: ?>
+                            <?php echo $_coreHelper->currency($_finalPrice, true, false) ?>
+                        <?php endif; ?>
                     </span>
                 </span>
                 <span class="price-including-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Incl. Tax:') ?></span>
                     <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPriceInclTax,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPriceInclTax, true, false) ?>
                     </span>
                 </span>
             <?php endif; ?>
         <?php else: ?>
             <?php if ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($_product, 0)): // including ?>
                 <span class="regular-price" id="product-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_price+$_weeeTaxAmount,true,true) ?>
+                    <?php echo $_coreHelper->currency($_price + $_weeeTaxAmount, true, true) ?>
                 </span>
             <?php elseif ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($_product, 1)): // incl. + weee ?>
                 <span class="regular-price" id="product-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_price+$_weeeTaxAmount,true,true) ?>
+                    <?php echo $_coreHelper->currency($_price + $_weeeTaxAmount, true, true) ?>
                 </span>
                 <span class="weee">(
                     <?php foreach ($_weeeTaxAttributes as $_weeeTaxAttribute): ?>
@@ -172,12 +176,12 @@
                     )</span>
             <?php elseif ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($_product, 4)): // incl. + weee ?>
                 <span class="regular-price" id="product-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_price+$_weeeTaxAmount,true,true) ?>
+                    <?php echo $_coreHelper->currency($_price + $_weeeTaxAmount, true, true) ?>
                 </span>
                 <span class="weee">(
                     <?php foreach ($_weeeTaxAttributes as $_weeeTaxAttribute): ?>
                         <?php echo $_weeeSeparator; ?>
-                        <?php echo $_weeeTaxAttribute->getName(); ?>: <?php echo $_coreHelper->currency($_weeeTaxAttribute->getAmount()+$_weeeTaxAttribute->getTaxAmount(), true, true); ?>
+                        <?php echo $_weeeTaxAttribute->getName(); ?>: <?php echo $_coreHelper->currency($_weeeTaxAttribute->getAmount() + $_weeeTaxAttribute->getTaxAmount(), true, true); ?>
                         <?php $_weeeSeparator = ' + '; ?>
                     <?php endforeach; ?>
                     )</span>
@@ -189,11 +193,15 @@
                     </span>
                 <?php endforeach; ?>
                 <span class="regular-price" id="product-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_price+$_weeeTaxAmount,true,true) ?>
+                    <?php echo $_coreHelper->currency($_price + $_weeeTaxAmount, true, true) ?>
                 </span>
             <?php else: ?>
                 <span class="regular-price" id="product-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_price,true,true) ?>
+                    <?php if ($_finalPrice == $_price): ?>
+                        <?php echo $_coreHelper->currency($_price, true, true) ?>
+                    <?php else: ?>
+                        <?php echo $_coreHelper->currency($_finalPrice, true, true) ?>
+                    <?php endif; ?>
                 </span>
             <?php endif; ?>
         <?php endif; ?>
@@ -204,7 +212,7 @@
             <p class="old-price">
                 <span class="price-label"><?php echo $this->__('Regular Price:') ?></span>
                 <span class="price" id="old-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_regularPrice+$_originalWeeeTaxAmount,true,false) ?>
+                    <?php echo $_coreHelper->currency($_regularPrice + $_originalWeeeTaxAmount, true, false) ?>
                 </span>
             </p>
 
@@ -214,13 +222,13 @@
                     <span class="price-excluding-tax">
                         <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Excl. Tax:') ?></span>
                         <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                            <?php echo $_coreHelper->currency($_finalPrice+$_weeeTaxAmount,true,false) ?>
+                            <?php echo $_coreHelper->currency($_finalPrice + $_weeeTaxAmount, true, false) ?>
                         </span>
                     </span>
                 <span class="price-including-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Incl. Tax:') ?></span>
                     <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPriceInclTax+$_weeeTaxAmountInclTaxes,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmountInclTaxes, true, false) ?>
                     </span>
                 </span>
                 </p>
@@ -228,7 +236,7 @@
             <p class="special-price">
                 <span class="price-label"><?php echo $this->__('Special Price:') ?></span>
                 <span class="price" id="product-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_finalPrice+$_weeeTaxAmountInclTaxes,true,false) ?>
+                    <?php echo $_coreHelper->currency($_finalPrice + $_weeeTaxAmountInclTaxes, true, false) ?>
                 </span>
             </p>
             <?php endif; ?>
@@ -237,7 +245,7 @@
             <p class="old-price">
                 <span class="price-label"><?php echo $this->__('Regular Price:') ?></span>
                 <span class="price" id="old-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_regularPrice+$_originalWeeeTaxAmount,true,false) ?>
+                    <?php echo $_coreHelper->currency($_regularPrice + $_originalWeeeTaxAmount, true, false) ?>
                 </span>
             </p>
 
@@ -246,7 +254,7 @@
                 <span class="price-excluding-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Excl. Tax:') ?></span>
                     <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPrice+$_weeeTaxAmount,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPrice + $_weeeTaxAmount, true, false) ?>
                     </span>
                 </span>
             <span class="weee">(
@@ -259,7 +267,7 @@
             <span class="price-including-tax">
                 <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Incl. Tax:') ?></span>
                 <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_finalPriceInclTax+$_weeeTaxAmountInclTaxes,true,false) ?>
+                    <?php echo $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmountInclTaxes, true, false) ?>
                 </span>
             </span>
             </p>
@@ -267,7 +275,7 @@
             <p class="old-price">
                 <span class="price-label"><?php echo $this->__('Regular Price:') ?></span>
                 <span class="price" id="old-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_regularPrice+$_originalWeeeTaxAmount,true,false) ?>
+                    <?php echo $_coreHelper->currency($_regularPrice + $_originalWeeeTaxAmount, true, false) ?>
                 </span>
             </p>
 
@@ -276,20 +284,20 @@
                 <span class="price-excluding-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Excl. Tax:') ?></span>
                     <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPrice+$_weeeTaxAmount,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPrice + $_weeeTaxAmount, true, false) ?>
                     </span>
                 </span>
             <span class="weee">(
                 <?php foreach ($_weeeTaxAttributes as $_weeeTaxAttribute): ?>
                     <?php echo $_weeeSeparator; ?>
-                    <?php echo $_weeeTaxAttribute->getName(); ?>: <?php echo $_coreHelper->currency($_weeeTaxAttribute->getAmount()+$_weeeTaxAttribute->getTaxAmount(), true, true); ?>
+                    <?php echo $_weeeTaxAttribute->getName(); ?>: <?php echo $_coreHelper->currency($_weeeTaxAttribute->getAmount() + $_weeeTaxAttribute->getTaxAmount(), true, true); ?>
                     <?php $_weeeSeparator = ' + '; ?>
                 <?php endforeach; ?>
                 )</span>
             <span class="price-including-tax">
                 <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Incl. Tax:') ?></span>
                 <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_finalPriceInclTax+$_weeeTaxAmountInclTaxes,true,false) ?>
+                    <?php echo $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmountInclTaxes, true, false) ?>
                 </span>
             </span>
             </p>
@@ -297,7 +305,7 @@
             <p class="old-price">
                 <span class="price-label"><?php echo $this->__('Regular Price:') ?></span>
                 <span class="price" id="old-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_regularPrice,true,false) ?>
+                    <?php echo $_coreHelper->currency($_regularPrice, true, false) ?>
                 </span>
             </p>
 
@@ -306,7 +314,7 @@
                 <span class="price-excluding-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Excl. Tax:') ?></span>
                     <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPrice,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPrice, true, false) ?>
                     </span>
                 </span>
                 <?php foreach ($_weeeTaxAttributes as $_weeeTaxAttribute): ?>
@@ -317,7 +325,7 @@
                 <span class="price-including-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Incl. Tax:') ?></span>
                     <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPriceInclTax+$_weeeTaxAmountInclTaxes,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmountInclTaxes, true, false) ?>
                     </span>
                 </span>
             </p>
@@ -325,7 +333,7 @@
             <p class="old-price">
                 <span class="price-label"><?php echo $this->__('Regular Price:') ?></span>
                 <span class="price" id="old-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_regularPrice,true,false) ?>
+                    <?php echo $_coreHelper->currency($_regularPrice, true, false) ?>
                 </span>
             </p>
 
@@ -335,13 +343,13 @@
                     <span class="price-excluding-tax">
                         <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Excl. Tax:') ?></span>
                         <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                            <?php echo $_coreHelper->currency($_finalPrice,true,false) ?>
+                            <?php echo $_coreHelper->currency($_finalPrice, true, false) ?>
                         </span>
                     </span>
                     <span class="price-including-tax">
                         <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Incl. Tax:') ?></span>
                         <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                            <?php echo $_coreHelper->currency($_finalPriceInclTax,true,false) ?>
+                            <?php echo $_coreHelper->currency($_finalPriceInclTax, true, false) ?>
                         </span>
                     </span>
                 </p>
@@ -349,7 +357,7 @@
             <p class="special-price">
                 <span class="price-label"><?php echo $this->__('Special Price:') ?></span>
                 <span class="price" id="product-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_finalPrice,true,false) ?>
+                    <?php echo $_coreHelper->currency($_finalPrice, true, false) ?>
                 </span>
             </p>
             <?php endif; ?>
@@ -361,7 +369,7 @@
 
         <?php $_minimalPriceDisplayValue = $_minimalPrice; ?>
         <?php if ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($_product, array(0, 1, 4))): ?>
-            <?php $_minimalPriceDisplayValue = $_minimalPrice+$_weeeTaxAmount; ?>
+            <?php $_minimalPriceDisplayValue = $_minimalPrice + $_weeeTaxAmount; ?>
         <?php endif; ?>
 
         <?php if ($this->getUseLinkForAsLowAs()):?>
@@ -371,7 +379,7 @@
         <?php endif?>
             <span class="label"><?php echo $this->__('As low as:') ?></span>
             <span class="price" id="product-minimal-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                <?php echo $_coreHelper->currency($_minimalPriceDisplayValue,true,false) ?>
+                <?php echo $_coreHelper->currency($_minimalPriceDisplayValue, true, false) ?>
             </span>
         <?php if ($this->getUseLinkForAsLowAs()):?>
         </a>
diff --git a/app/code/core/Mage/Catalog/view/frontend/product/view.phtml b/app/code/core/Mage/Catalog/view/frontend/product/view.phtml
index c732dd6724757bd0f1ead953cceae51da4ac953b..57e99d40279abc4e177a11cd7d4a6bd274673a41 100644
--- a/app/code/core/Mage/Catalog/view/frontend/product/view.phtml
+++ b/app/code/core/Mage/Catalog/view/frontend/product/view.phtml
@@ -148,7 +148,11 @@
     </div>
 
     <div class="product-collateral">
-<?php foreach ($this->getChildGroup('detailed_info', 'getChildHtml') as $alias => $html):?>
+    <?php $layout = $this->getLayout(); ?>
+<?php foreach ($this->getGroupChildNames('detailed_info') as $name):?>
+        <?php $html = $layout->renderElement($name); ?>
+        <?php if (!$html) continue; ?>
+        <?php $alias = $layout->getElementAlias($name); ?>
         <div class="box-collateral <?php echo "box-{$alias}"?>">
             <?php if ($title = $this->getChildData($alias, 'title')):?>
             <h2><?php echo $this->escapeHtml($title); ?></h2>
diff --git a/app/code/core/Mage/Catalog/view/frontend/product/view/addto.phtml b/app/code/core/Mage/Catalog/view/frontend/product/view/addto.phtml
index 3cc816ca913a72f59c7682da9aa6536264f446b8..ded6f1cf17c6df6e8bf0abf77d6b7e861c012527 100644
--- a/app/code/core/Mage/Catalog/view/frontend/product/view/addto.phtml
+++ b/app/code/core/Mage/Catalog/view/frontend/product/view/addto.phtml
@@ -30,7 +30,7 @@
 
 <ul class="add-to-links">
 <?php if ($this->helper('Mage_Wishlist_Helper_Data')->isAllow()) : ?>
-    <li><a href="<?php echo $_wishlistSubmitUrl ?>" onclick="productAddToCartForm.submitLight(this, '<?php echo $_wishlistSubmitUrl ?>'); return false;" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li>
+    <li><a href="<?php echo $_wishlistSubmitUrl ?>" onclick="productAddToCartForm.submitLight(this, this.href); return false;" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li>
 <?php endif; ?>
 <?php
     $_compareUrl = $this->helper('Mage_Catalog_Helper_Product_Compare')->getAddUrl($_product);
diff --git a/app/code/core/Mage/Catalog/view/frontend/product/view/addtocart.phtml b/app/code/core/Mage/Catalog/view/frontend/product/view/addtocart.phtml
index 747c7ea1957b78281beb19d47c123c1113cdbbfd..c1590f9bb4d4fdf94c13064173e145a4269ad2ee 100644
--- a/app/code/core/Mage/Catalog/view/frontend/product/view/addtocart.phtml
+++ b/app/code/core/Mage/Catalog/view/frontend/product/view/addtocart.phtml
@@ -33,6 +33,6 @@
         <input type="text" name="qty" id="qty" maxlength="12" value="<?php echo $this->getProductDefaultQty() * 1 ?>" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />
         <?php endif; ?>
         <button type="button" title="<?php echo $buttonTitle ?>" class="button btn-cart" onclick="productAddToCartForm.submit(this)"><span><span><?php echo $buttonTitle ?></span></span></button>
-        <?php echo $this->getChildHtml('', true, true) ?>
+        <?php echo $this->getChildHtml('', true) ?>
     </div>
 <?php endif; ?>
diff --git a/app/code/core/Mage/Catalog/view/frontend/product/view/options.phtml b/app/code/core/Mage/Catalog/view/frontend/product/view/options.phtml
index 67fddcdbe8de1d35495e1f9011d0bcf77a644a4a..746044a5cf198e5ef419685c6158082b7af483cf 100644
--- a/app/code/core/Mage/Catalog/view/frontend/product/view/options.phtml
+++ b/app/code/core/Mage/Catalog/view/frontend/product/view/options.phtml
@@ -104,12 +104,12 @@
 
     Product.Options = Class.create();
     Product.Options.prototype = {
-        initialize : function(config){
+        initialize : function(config) {
             this.config = config;
             this.reloadPrice();
             document.observe("dom:loaded", this.reloadPrice.bind(this));
         },
-        reloadPrice : function(){
+        reloadPrice : function() {
             var config = this.config;
             var skipIds = [];
             $$('body .product-custom-option').each(function(element){
@@ -172,7 +172,7 @@
             });
         }
     }
-    function validateOptionsCallback(elmId, result){
+    function validateOptionsCallback(elmId, result) {
         var container = $(elmId).up('ul.options-list');
         if (result == 'failed') {
             container.removeClassName('validation-passed');
diff --git a/app/code/core/Mage/Catalog/view/frontend/product/view/options/wrapper.phtml b/app/code/core/Mage/Catalog/view/frontend/product/view/options/wrapper.phtml
index 5a2af78ae8c0b2cceab815a7d4b900e2b86353a4..4a983e2f3d17ecca2b6427402310223c1656735c 100644
--- a/app/code/core/Mage/Catalog/view/frontend/product/view/options/wrapper.phtml
+++ b/app/code/core/Mage/Catalog/view/frontend/product/view/options/wrapper.phtml
@@ -25,7 +25,7 @@
  */
 ?>
 <div class="product-options" id="product-options-wrapper">
-    <?php echo $this->getChildHtml('', true, true);?>
+    <?php echo $this->getChildHtml('', true);?>
     <?php if ($this->hasRequiredOptions()):?>
         <p class="required"><?php echo $this->__('* Required Fields') ?></p>
     <?php endif;?>
diff --git a/app/code/core/Mage/Catalog/view/frontend/product/view/options/wrapper/bottom.phtml b/app/code/core/Mage/Catalog/view/frontend/product/view/options/wrapper/bottom.phtml
index 9007511245059bb1a7ed9520f1e2d244d1494950..cf9d1dbe922af9166c69340d7564a7829c985e5f 100644
--- a/app/code/core/Mage/Catalog/view/frontend/product/view/options/wrapper/bottom.phtml
+++ b/app/code/core/Mage/Catalog/view/frontend/product/view/options/wrapper/bottom.phtml
@@ -25,5 +25,5 @@
  */
 ?>
 <div class="product-options-bottom">
-    <?php echo $this->getChildHtml('', true, true);?>
+    <?php echo $this->getChildHtml('', true);?>
 </div>
diff --git a/app/code/core/Mage/CatalogInventory/Helper/Data.php b/app/code/core/Mage/CatalogInventory/Helper/Data.php
index e9a6f77a1e61d2fce5fdf229e822c1c5893aa9f5..42fef0b323f821dd75232873a0cc9a9f1342cb67 100644
--- a/app/code/core/Mage/CatalogInventory/Helper/Data.php
+++ b/app/code/core/Mage/CatalogInventory/Helper/Data.php
@@ -103,6 +103,7 @@ class Mage_CatalogInventory_Helper_Data extends Mage_Core_Helper_Abstract
             'manage_stock',
             'enable_qty_increments',
             'qty_increments',
+            'is_decimal_divided',
         );
     }
 
diff --git a/app/code/core/Mage/CatalogInventory/Model/Indexer/Stock.php b/app/code/core/Mage/CatalogInventory/Model/Indexer/Stock.php
index e23df7736a0db84d41229392c6773966a72e3073..81ff2e38b373ad1506b82c7641ebd5147ce396f3 100644
--- a/app/code/core/Mage/CatalogInventory/Model/Indexer/Stock.php
+++ b/app/code/core/Mage/CatalogInventory/Model/Indexer/Stock.php
@@ -270,7 +270,12 @@ class Mage_CatalogInventory_Model_Indexer_Stock extends Mage_Index_Model_Indexer
         // Saving stock item without product object
         // Register re-index price process if products out of stock hidden on Front-end
         if (!Mage::helper('Mage_CatalogInventory_Helper_Data')->isShowOutOfStock() && !$object->getProduct()) {
-            $event->addNewData('force_reindex_required', 1);
+            $massObject = new Varien_Object();
+            $massObject->setAttributesData(array('force_reindex_required' => 1));
+            $massObject->setProductIds(array($object->getProductId()));
+            Mage::getSingleton('Mage_Index_Model_Indexer')->logEvent(
+                $massObject, Mage_Catalog_Model_Product::ENTITY, Mage_Index_Model_Event::TYPE_MASS_ACTION
+            );
         }
 
         return $this;
diff --git a/app/code/core/Mage/CatalogInventory/Model/Observer.php b/app/code/core/Mage/CatalogInventory/Model/Observer.php
index 1d646c5134ec50581fd36109fb3e58b5f69f1496..d0b320c1f10fd116544004054de7b72667b3b2be 100644
--- a/app/code/core/Mage/CatalogInventory/Model/Observer.php
+++ b/app/code/core/Mage/CatalogInventory/Model/Observer.php
@@ -247,7 +247,28 @@ class Mage_CatalogInventory_Model_Observer
         }
 
         $quote = $item->getQuote();
-        if ($quote->getHasError()) {
+        $quoteItems = $quote->getItemsCollection();
+        $canRemoveErrorFromQuote = true;
+
+        foreach ($quoteItems as $quoteItem) {
+            if ($quoteItem->getItemId() == $item->getItemId()) {
+                continue;
+            }
+
+            $errorInfos = $quoteItem->getErrorInfos();
+            foreach ($errorInfos as $errorInfo) {
+                if ($errorInfo['code'] == $code) {
+                    $canRemoveErrorFromQuote = false;
+                    break;
+                }
+            }
+
+            if (!$canRemoveErrorFromQuote) {
+                break;
+            }
+        }
+
+        if ($quote->getHasError() && $canRemoveErrorFromQuote) {
             $params = array(
                 'origin' => 'cataloginventory',
                 'code' => $code
@@ -317,6 +338,11 @@ class Mage_CatalogInventory_Model_Observer
                 $increaseOptionQty = ($quoteItem->getQtyToAdd() ? $quoteItem->getQtyToAdd() : $qty) * $optionValue;
 
                 $stockItem = $option->getProduct()->getStockItem();
+
+                if ($quoteItem->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_CONFIGURABLE) {
+                    $stockItem->setProductName($quoteItem->getName());
+                }
+
                 /* @var $stockItem Mage_CatalogInventory_Model_Stock_Item */
                 if (!$stockItem instanceof Mage_CatalogInventory_Model_Stock_Item) {
                     Mage::throwException(
@@ -356,6 +382,7 @@ class Mage_CatalogInventory_Model_Observer
                 }
                 if (!is_null($result->getMessage())) {
                     $option->setMessage($result->getMessage());
+                    $quoteItem->setMessage($result->getMessage());
                 }
                 if (!is_null($result->getItemBackorders())) {
                     $option->setBackorders($result->getItemBackorders());
diff --git a/app/code/core/Mage/CatalogInventory/Model/Resource/Indexer/Stock.php b/app/code/core/Mage/CatalogInventory/Model/Resource/Indexer/Stock.php
index d6ee2e5f823fd096f73cb98684446abfd81a63fd..2328fa26f99c97cb0041e4dd46ff8834e1a89207 100755
--- a/app/code/core/Mage/CatalogInventory/Model/Resource/Indexer/Stock.php
+++ b/app/code/core/Mage/CatalogInventory/Model/Resource/Indexer/Stock.php
@@ -74,17 +74,6 @@ class Mage_CatalogInventory_Model_Resource_Indexer_Stock extends Mage_Catalog_Mo
         $productId = $data['product_id'];
         $this->reindexProducts($productId);
 
-        if (!empty($data['force_reindex_required'])) {
-            $massObject = new Varien_Object();
-            $massObject->setAttributesData(array(
-                'force_reindex_required'   => 1
-            ));
-            $massObject->setProductIds(array($productId));
-            Mage::getSingleton('Mage_Index_Model_Indexer')->logEvent(
-                $massObject, Mage_Catalog_Model_Product::ENTITY, Mage_Index_Model_Event::TYPE_MASS_ACTION
-            );
-        }
-
         return $this;
     }
 
diff --git a/app/code/core/Mage/CatalogInventory/Model/Stock/Item.php b/app/code/core/Mage/CatalogInventory/Model/Stock/Item.php
index 6efd72ce0ee020db3dac533415c1bacb3ce2a2e7..f03f2b34a626e3daa4990ba507d796732cb19c2b 100644
--- a/app/code/core/Mage/CatalogInventory/Model/Stock/Item.php
+++ b/app/code/core/Mage/CatalogInventory/Model/Stock/Item.php
@@ -540,6 +540,7 @@ class Mage_CatalogInventory_Model_Stock_Item extends Mage_Core_Model_Abstract
                 ->setMessage(
                     Mage::helper('Mage_CatalogInventory_Helper_Data')->__('The minimum quantity allowed for purchase is %s.', $this->getMinSaleQty() * 1)
                 )
+                ->setErrorCode('qty_min')
                 ->setQuoteMessage(Mage::helper('Mage_CatalogInventory_Helper_Data')->__('Some of the products cannot be ordered in requested quantity.'))
                 ->setQuoteMessageIndex('qty');
             return $result;
@@ -550,6 +551,7 @@ class Mage_CatalogInventory_Model_Stock_Item extends Mage_Core_Model_Abstract
                 ->setMessage(
                     Mage::helper('Mage_CatalogInventory_Helper_Data')->__('The maximum quantity allowed for purchase is %s.', $this->getMaxSaleQty() * 1)
                 )
+                ->setErrorCode('qty_max')
                 ->setQuoteMessage(Mage::helper('Mage_CatalogInventory_Helper_Data')->__('Some of the products cannot be ordered in requested quantity.'))
                 ->setQuoteMessageIndex('qty');
             return $result;
@@ -647,11 +649,12 @@ class Mage_CatalogInventory_Model_Stock_Item extends Mage_Core_Model_Abstract
             $qtyIncrements = $this->getDefaultQtyIncrements();
         }
 
-        if ($qtyIncrements && ($qty % $qtyIncrements != 0)) {
+        if ($qtyIncrements && (Mage::helper('Mage_Core_Helper_Data')->getExactDivision($qty, $qtyIncrements) != 0)) {
             $result->setHasError(true)
                 ->setQuoteMessage(
                     Mage::helper('Mage_CatalogInventory_Helper_Data')->__('Some of the products cannot be ordered in the requested quantity.')
                 )
+                ->setErrorCode('qty_increments')
                 ->setQuoteMessageIndex('qty');
             if ($this->getIsChildItem()) {
                 $result->setMessage(
diff --git a/app/code/core/Mage/CatalogInventory/etc/config.xml b/app/code/core/Mage/CatalogInventory/etc/config.xml
index 846e3d9d679a013f4ae101f0f6732e9ff9253bc8..247ca015f316fcbe2a09cf24b51aa596856f2253 100644
--- a/app/code/core/Mage/CatalogInventory/etc/config.xml
+++ b/app/code/core/Mage/CatalogInventory/etc/config.xml
@@ -28,7 +28,7 @@
 <config>
     <modules>
         <Mage_CatalogInventory>
-            <version>1.6.0.0.1</version>
+            <version>1.6.0.0.2</version>
         </Mage_CatalogInventory>
     </modules>
     <global>
diff --git a/app/code/core/Mage/CatalogInventory/etc/system.xml b/app/code/core/Mage/CatalogInventory/etc/system.xml
index 080c5eae3826bb365ec85e0f640e8d3f0c651758..b710d1782bf85a2168b16ee5e1fc4cefa842efe1 100644
--- a/app/code/core/Mage/CatalogInventory/etc/system.xml
+++ b/app/code/core/Mage/CatalogInventory/etc/system.xml
@@ -74,6 +74,7 @@
                         <stock_threshold_qty translate="label">
                             <label>Only X left Threshold</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number</validate>
                             <sort_order>4</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -112,6 +113,7 @@
                         <max_sale_qty translate="label">
                             <label>Maximum Qty Allowed in Shopping Cart</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number</validate>
                             <sort_order>4</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>0</show_in_website>
@@ -120,6 +122,7 @@
                         <min_qty translate="label">
                             <label>Qty for Item's Status to Become Out of Stock</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number</validate>
                             <backend_model>Mage_CatalogInventory_Model_System_Config_Backend_Minqty</backend_model>
                             <sort_order>5</sort_order>
                             <show_in_default>1</show_in_default>
@@ -138,6 +141,7 @@
                        <notify_stock_qty translate="label">
                             <label>Notify for Quantity Below</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number</validate>
                             <sort_order>7</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>0</show_in_website>
@@ -164,12 +168,12 @@
                        <qty_increments translate="label">
                             <label>Qty Increments</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-greater-than-zero</validate>
                             <backend_model>Mage_CatalogInventory_Model_System_Config_Backend_Qtyincrements</backend_model>
                             <sort_order>9</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>0</show_in_website>
                             <show_in_store>0</show_in_store>
-                            <frontend_class>validate-per-page-value-list</frontend_class>
                             <depends><enable_qty_increments>1</enable_qty_increments></depends>
                        </qty_increments>
                     </fields>
diff --git a/app/code/core/Mage/CatalogInventory/sql/cataloginventory_setup/upgrade-1.6.0.0.1-1.6.0.0.2.php b/app/code/core/Mage/CatalogInventory/sql/cataloginventory_setup/upgrade-1.6.0.0.1-1.6.0.0.2.php
new file mode 100644
index 0000000000000000000000000000000000000000..a67a98a63aaa182fad0cfb78938cbbfc9eed7e31
--- /dev/null
+++ b/app/code/core/Mage/CatalogInventory/sql/cataloginventory_setup/upgrade-1.6.0.0.1-1.6.0.0.2.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_CatalogInventory
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/** @var $installer Mage_Eav_Model_Entity_Setup */
+$installer = $this;
+
+/**
+ * Add new field to 'cataloginventory/stock_item'
+ */
+$installer->getConnection()
+    ->addColumn(
+        $installer->getTable('cataloginventory_stock_item'),
+        'is_decimal_divided',
+        array(
+            'TYPE' => Varien_Db_Ddl_Table::TYPE_SMALLINT,
+            'LENGTH' => 5,
+            'UNSIGNED' => true,
+            'NULLABLE' => false,
+            'DEFAULT' => 0,
+            'COMMENT' => 'Is Divided into Multiple Boxes for Shipping'
+        )
+    );
diff --git a/app/code/core/Mage/CatalogInventory/view/frontend/layout.xml b/app/code/core/Mage/CatalogInventory/view/frontend/layout.xml
index 2905be1db6261d762339077c6ebaa7300a959090..f8f10b7064194bbdd6a73a18282a1c68742e1623 100644
--- a/app/code/core/Mage/CatalogInventory/view/frontend/layout.xml
+++ b/app/code/core/Mage/CatalogInventory/view/frontend/layout.xml
@@ -40,25 +40,25 @@ Product view
 <!--
 Additional block dependent on product type
 -->
-    <PRODUCT_TYPE_simple>
+    <catalog_product_view_type_simple>
         <reference name="product.info.simple.extra">
             <block type="Mage_CatalogInventory_Block_Stockqty_Default" template="stockqty/default.phtml"/>
         </reference>
-    </PRODUCT_TYPE_simple>
-    <PRODUCT_TYPE_virtual>
+    </catalog_product_view_type_simple>
+    <catalog_product_view_type_virtual>
         <reference name="product.info.virtual.extra">
             <block type="Mage_CatalogInventory_Block_Stockqty_Default" template="stockqty/default.phtml"/>
         </reference>
-    </PRODUCT_TYPE_virtual>
-    <PRODUCT_TYPE_grouped>
+    </catalog_product_view_type_virtual>
+    <catalog_product_view_type_grouped>
         <reference name="product.info.grouped.extra">
             <block type="Mage_CatalogInventory_Block_Stockqty_Type_Grouped" template="stockqty/composite.phtml"/>
         </reference>
-    </PRODUCT_TYPE_grouped>
-    <PRODUCT_TYPE_configurable>
+    </catalog_product_view_type_grouped>
+    <catalog_product_view_type_configurable>
         <reference name="product.info.configurable.extra">
             <block type="Mage_CatalogInventory_Block_Stockqty_Type_Configurable" template="stockqty/composite.phtml"/>
         </reference>
-    </PRODUCT_TYPE_configurable>
+    </catalog_product_view_type_configurable>
 
-</layout>
\ No newline at end of file
+</layout>
diff --git a/app/code/core/Mage/CatalogRule/Helper/Data.php b/app/code/core/Mage/CatalogRule/Helper/Data.php
index 9521b57dd1aa270336e48be133177a7fece6e8f3..dad63f790b03454bd3462ea686c2266c66af1ceb 100644
--- a/app/code/core/Mage/CatalogRule/Helper/Data.php
+++ b/app/code/core/Mage/CatalogRule/Helper/Data.php
@@ -37,20 +37,18 @@ class Mage_CatalogRule_Helper_Data extends Mage_Core_Helper_Abstract
      * @param  float $price
      * @return float|int
      */
-    public function calcPriceRule ($actionOperator, $ruleAmount, $price)
+    public function calcPriceRule($actionOperator, $ruleAmount, $price)
     {
         $priceRule = 0;
         switch ($actionOperator) {
             case 'to_fixed':
-                $priceRule = $ruleAmount;
+                $priceRule = min($ruleAmount, $price);
                 break;
             case 'to_percent':
                 $priceRule = $price * $ruleAmount / 100;
                 break;
             case 'by_fixed':
-                $priceRule = $price - $ruleAmount;
-                // Price can not be negative
-                $priceRule = ($priceRule < 0) ? 0 : $priceRule;
+                $priceRule = max(0, $price - $ruleAmount);
                 break;
             case 'by_percent':
                 $priceRule = $price * (1 - $ruleAmount / 100);
diff --git a/app/code/core/Mage/CatalogRule/Model/Flag.php b/app/code/core/Mage/CatalogRule/Model/Flag.php
new file mode 100644
index 0000000000000000000000000000000000000000..891723096a1786db521c893f2fbf4b24cc5b481f
--- /dev/null
+++ b/app/code/core/Mage/CatalogRule/Model/Flag.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.
+ *
+ * @category    Mage
+ * @package     Mage_CatalogRule
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Flag stores status about availability not applied catalog price rules
+ *
+ * @category    Mage
+ * @package     Mage_CatalogRule
+ * @author      Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_CatalogRule_Model_Flag extends Mage_Core_Model_Flag
+{
+    /**
+     * Flag code
+     *
+     * @var string
+     */
+    protected $_flagCode = 'catalog_rules_dirty';
+}
diff --git a/app/code/core/Mage/CatalogRule/Model/Observer.php b/app/code/core/Mage/CatalogRule/Model/Observer.php
index 545d6d85527e0a7d43254239b3ceb53831817b76..f79bf80eec415d2cab9943c64fc8bd27342d5869 100644
--- a/app/code/core/Mage/CatalogRule/Model/Observer.php
+++ b/app/code/core/Mage/CatalogRule/Model/Observer.php
@@ -75,7 +75,9 @@ class Mage_CatalogRule_Model_Observer
     {
         $resource = Mage::getResourceSingleton('Mage_CatalogRule_Model_Resource_Rule');
         $resource->applyAllRulesForDateRange($resource->formatDate(mktime(0,0,0)));
-        Mage::app()->removeCache('catalog_rules_dirty');
+        Mage::getModel('Mage_CatalogRule_Model_Flag')->loadSelf()
+            ->setState(0)
+            ->save();
 
         return $this;
     }
diff --git a/app/code/core/Mage/CatalogRule/Model/Resource/Rule.php b/app/code/core/Mage/CatalogRule/Model/Resource/Rule.php
index 22db5c346072ed59af8142d1739ef4a8f75883e1..ff57654ea48a82096adeb5801e613e790c0ef4e5 100755
--- a/app/code/core/Mage/CatalogRule/Model/Resource/Rule.php
+++ b/app/code/core/Mage/CatalogRule/Model/Resource/Rule.php
@@ -90,13 +90,13 @@ class Mage_CatalogRule_Model_Resource_Rule extends Mage_Rule_Model_Resource_Abst
      */
     protected function _afterSave(Mage_Core_Model_Abstract $object)
     {
-         if ($object->hasWebsiteIds()) {
-             $websiteIds = $object->getWebsiteIds();
-             if (!is_array($websiteIds)) {
-                 $websiteIds = explode(',', (string)$websiteIds);
-             }
-             $this->bindRuleToEntity($object->getId(), $websiteIds, 'website');
-         }
+        if ($object->hasWebsiteIds()) {
+            $websiteIds = $object->getWebsiteIds();
+            if (!is_array($websiteIds)) {
+                $websiteIds = explode(',', (string)$websiteIds);
+            }
+            $this->bindRuleToEntity($object->getId(), $websiteIds, 'website');
+        }
 
         if ($object->hasCustomerGroupIds()) {
             $customerGroupIds = $object->getCustomerGroupIds();
@@ -106,8 +106,6 @@ class Mage_CatalogRule_Model_Resource_Rule extends Mage_Rule_Model_Resource_Abst
             $this->bindRuleToEntity($object->getId(), $customerGroupIds, 'customer_group');
         }
 
-        $this->updateRuleProductData($object);
-
         parent::_afterSave($object);
         return $this;
     }
@@ -124,12 +122,13 @@ class Mage_CatalogRule_Model_Resource_Rule extends Mage_Rule_Model_Resource_Abst
         $ruleId = $rule->getId();
         $write  = $this->_getWriteAdapter();
         $write->beginTransaction();
-
         if ($rule->getProductsFilter()) {
             $write->delete(
                 $this->getTable('catalogrule_product'),
-                $write->quoteInto('rule_id=?', $ruleId)
-                . $write->quoteInto('and product_id in (?)', implode(',' , $rule->getProductsFilter()))
+                array(
+                    'rule_id=?' => $ruleId,
+                    'product_id IN (?)' => $rule->getProductsFilter()
+                )
             );
         } else {
             $write->delete($this->getTable('catalogrule_product'), $write->quoteInto('rule_id=?', $ruleId));
@@ -153,13 +152,15 @@ class Mage_CatalogRule_Model_Resource_Rule extends Mage_Rule_Model_Resource_Abst
         Magento_Profiler::stop('__MATCH_PRODUCTS__');
 
         $customerGroupIds = $rule->getCustomerGroupIds();
-        $fromTime         = strtotime($rule->getFromDate());
-        $toTime           = strtotime($rule->getToDate());
-        $toTime           = $toTime ? ($toTime + self::SECONDS_IN_DAY - 1) : 0;
-        $sortOrder        = (int)$rule->getSortOrder();
-        $actionOperator   = $rule->getSimpleAction();
-        $actionAmount     = $rule->getDiscountAmount();
-        $actionStop       = $rule->getStopRulesProcessing();
+        $fromTime = strtotime($rule->getFromDate());
+        $toTime = strtotime($rule->getToDate());
+        $toTime = $toTime ? ($toTime + self::SECONDS_IN_DAY - 1) : 0;
+        $sortOrder = (int)$rule->getSortOrder();
+        $actionOperator = $rule->getSimpleAction();
+        $actionAmount = $rule->getDiscountAmount();
+        $subActionOperator = $rule->getSubIsEnable() ? $rule->getSubSimpleAction() : '';
+        $subActionAmount = $rule->getSubDiscountAmount();
+        $actionStop = $rule->getStopRulesProcessing();
 
         $rows = array();
 
@@ -168,16 +169,18 @@ class Mage_CatalogRule_Model_Resource_Rule extends Mage_Rule_Model_Resource_Abst
                 foreach ($websiteIds as $websiteId) {
                     foreach ($customerGroupIds as $customerGroupId) {
                         $rows[] = array(
-                            'rule_id'           => $ruleId,
-                            'from_time'         => $fromTime,
-                            'to_time'           => $toTime,
-                            'website_id'        => $websiteId,
+                            'rule_id' => $ruleId,
+                            'from_time' => $fromTime,
+                            'to_time' => $toTime,
+                            'website_id' => $websiteId,
                             'customer_group_id' => $customerGroupId,
-                            'product_id'        => $productId,
-                            'action_operator'   => $actionOperator,
-                            'action_amount'     => $actionAmount,
-                            'action_stop'       => $actionStop,
-                            'sort_order'        => $sortOrder
+                            'product_id' => $productId,
+                            'action_operator' => $actionOperator,
+                            'action_amount' => $actionAmount,
+                            'action_stop' => $actionStop,
+                            'sort_order' => $sortOrder,
+                            'sub_simple_action' => $subActionOperator,
+                            'sub_discount_amount' => $subActionAmount,
                         );
 
                         if (count($rows) == 1000) {
@@ -190,12 +193,14 @@ class Mage_CatalogRule_Model_Resource_Rule extends Mage_Rule_Model_Resource_Abst
             if (!empty($rows)) {
                $write->insertMultiple($this->getTable('catalogrule_product'), $rows);
             }
+
+            $write->commit();
         } catch (Exception $e) {
             $write->rollback();
             throw $e;
         }
 
-        $write->commit();
+
         return $this;
     }
 
@@ -315,7 +320,8 @@ class Mage_CatalogRule_Model_Resource_Rule extends Mage_Rule_Model_Resource_Abst
         $priceTable = $priceAttr->getBackend()->getTable();
         $attributeId= $priceAttr->getId();
 
-        $joinCondition = '%1$s.entity_id=rp.product_id AND (%1$s.attribute_id='.$attributeId.') and %1$s.store_id=%2$s';
+        $joinCondition = '%1$s.entity_id=rp.product_id AND (%1$s.attribute_id=' . $attributeId
+            . ') and %1$s.store_id=%2$s';
 
         $select->join(
             array('pp_default'=>$priceTable),
@@ -508,8 +514,10 @@ class Mage_CatalogRule_Model_Resource_Rule extends Mage_Rule_Model_Resource_Abst
 
             $select = $write->select()
                 ->distinct(true)
-                ->from($this->getTable('catalogrule_product'), array('rule_id', 'customer_group_id', 'website_id'))
-                ->where("{$timestamp} >= from_time AND (({$timestamp} <= to_time AND to_time > 0) OR to_time = 0)");
+                ->from(
+                    $this->getTable('catalogrule_product'),
+                    array('rule_id', 'customer_group_id', 'website_id')
+                )->where("{$timestamp} >= from_time AND (({$timestamp} <= to_time AND to_time > 0) OR to_time = 0)");
             $query = $select->insertFromSelect($this->getTable('catalogrule_group_website'));
             $write->query($query);
 
@@ -579,19 +587,12 @@ class Mage_CatalogRule_Model_Resource_Rule extends Mage_Rule_Model_Resource_Abst
         $adapter->beginTransaction();
         try {
             foreach ($arrData as $key => $data) {
-                $productIds[$data['product_id']] = true; // to avoid dupes
-                $arrData[$key]['rule_date']          = $this->formatDate($data['rule_date'], false);
-                $arrData[$key]['latest_start_date']  = $this->formatDate($data['latest_start_date'], false);
-                $arrData[$key]['earliest_end_date']  = $this->formatDate($data['earliest_end_date'], false);
+                $productIds['product_id'] = $data['product_id'];
+                $arrData[$key]['rule_date'] = $this->formatDate($data['rule_date'], false);
+                $arrData[$key]['latest_start_date'] = $this->formatDate($data['latest_start_date'], false);
+                $arrData[$key]['earliest_end_date'] = $this->formatDate($data['earliest_end_date'], false);
             }
-
-            foreach ($productIds as $id => $v) {
-                $adapter->delete($this->getTable('catalogrule_affected_product'),
-                    array("product_id = $id"));
-                $adapter->insert($this->getTable('catalogrule_affected_product'),
-                    array('product_id' => $id));
-            }
-
+            $adapter->insertOnDuplicate($this->getTable('catalogrule_affected_product'), array_unique($productIds));
             $adapter->insertOnDuplicate($this->getTable('catalogrule_product_price'), $arrData);
 
         } catch (Exception $e) {
@@ -660,22 +661,17 @@ class Mage_CatalogRule_Model_Resource_Rule extends Mage_Rule_Model_Resource_Abst
     public function getRulesFromProduct($date, $websiteId, $customerGroupId, $productId)
     {
         $adapter = $this->_getReadAdapter();
-        $dateQuoted = $adapter->quote($this->formatDate($date, false));
-        $joinCondsQuoted[] = 'main_table.rule_id = rp.rule_id';
-        $joinCondsQuoted[] = $adapter->quoteInto('rp.website_id = ?', $websiteId);
-        $joinCondsQuoted[] = $adapter->quoteInto('rp.customer_group_id = ?', $customerGroupId);
-        $joinCondsQuoted[] = $adapter->quoteInto('rp.product_id = ?', $productId);
-        $fromDate = $adapter->getIfNullSql('main_table.from_date', $dateQuoted);
-        $toDate = $adapter->getIfNullSql('main_table.to_date', $dateQuoted);
+        if (is_string($date)) {
+            $date = strtotime($date);
+        }
         $select = $adapter->select()
-            ->from(array('main_table' => $this->getTable('catalogrule')))
-            ->joinInner(
-                array('rp' => $this->getTable('catalogrule_product')),
-                implode(' AND ', $joinCondsQuoted),
-                array())
-            ->where(new Zend_Db_Expr("{$dateQuoted} BETWEEN {$fromDate} AND {$toDate}"))
-            ->where('main_table.is_active = ?', 1)
-            ->order('main_table.sort_order');
+            ->from($this->getTable('catalogrule_product'))
+            ->where('website_id = ?', $websiteId)
+            ->where('customer_group_id = ?', $customerGroupId)
+            ->where('product_id = ?', $productId)
+            ->where('from_time = 0 or from_time < ?', $date)
+            ->where('to_time = 0 or to_time > ?', $date);
+
         return $adapter->fetchAll($select);
     }
 
@@ -735,30 +731,34 @@ class Mage_CatalogRule_Model_Resource_Rule extends Mage_Rule_Model_Resource_Abst
         }
 
         $customerGroupIds = $rule->getCustomerGroupIds();
-        $fromTime         = strtotime($rule->getFromDate());
-        $toTime           = strtotime($rule->getToDate());
-        $toTime           = $toTime ? $toTime+self::SECONDS_IN_DAY-1 : 0;
-        $sortOrder        = (int)$rule->getSortOrder();
-        $actionOperator   = $rule->getSimpleAction();
-        $actionAmount     = $rule->getDiscountAmount();
-        $actionStop       = $rule->getStopRulesProcessing();
+        $fromTime = strtotime($rule->getFromDate());
+        $toTime = strtotime($rule->getToDate());
+        $toTime = $toTime ? $toTime + self::SECONDS_IN_DAY - 1 : 0;
+        $sortOrder = (int)$rule->getSortOrder();
+        $actionOperator = $rule->getSimpleAction();
+        $actionAmount = $rule->getDiscountAmount();
+        $actionStop = $rule->getStopRulesProcessing();
+        $subActionOperator = $rule->getSubIsEnable() ? $rule->getSubSimpleAction() : '';
+        $subActionAmount = $rule->getSubDiscountAmount();
 
         $rows = array();
         try {
             foreach ($websiteIds as $websiteId) {
                 foreach ($customerGroupIds as $customerGroupId) {
                     $rows[] = array(
-                        'rule_id'           => $ruleId,
-                        'from_time'         => $fromTime,
-                        'to_time'           => $toTime,
-                        'website_id'        => $websiteId,
+                        'rule_id' => $ruleId,
+                        'from_time' => $fromTime,
+                        'to_time' => $toTime,
+                        'website_id' => $websiteId,
                         'customer_group_id' => $customerGroupId,
-                        'product_id'        => $productId,
-                        'action_operator'   => $actionOperator,
-                        'action_amount'     => $actionAmount,
-                        'action_stop'       => $actionStop,
-                        'sort_order'        => $sortOrder,
-                        );
+                        'product_id' => $productId,
+                        'action_operator' => $actionOperator,
+                        'action_amount' => $actionAmount,
+                        'action_stop' => $actionStop,
+                        'sort_order' => $sortOrder,
+                        'sub_simple_action' => $subActionOperator,
+                        'sub_discount_amount' => $subActionAmount,
+                    );
 
                     if (count($rows) == 1000) {
                         $write->insertMultiple($this->getTable('catalogrule_product'), $rows);
@@ -768,7 +768,7 @@ class Mage_CatalogRule_Model_Resource_Rule extends Mage_Rule_Model_Resource_Abst
             }
 
             if (!empty($rows)) {
-               $write->insertMultiple($this->getTable('catalogrule_product'), $rows);
+                $write->insertMultiple($this->getTable('catalogrule_product'), $rows);
             }
         } catch (Exception $e) {
             $write->rollback();
diff --git a/app/code/core/Mage/CatalogRule/Model/Rule.php b/app/code/core/Mage/CatalogRule/Model/Rule.php
index 0ec31299f4f62f633fac6474452935360ea80702..1b064ac174e6b537e6c1ca3cef17e4d72be3be3e 100644
--- a/app/code/core/Mage/CatalogRule/Model/Rule.php
+++ b/app/code/core/Mage/CatalogRule/Model/Rule.php
@@ -315,7 +315,7 @@ class Mage_CatalogRule_Model_Rule extends Mage_Rule_Model_Abstract
             if ($rulesData) {
                 foreach ($rulesData as $ruleData) {
                     if ($product->getParentId()) {
-                        if ($ruleData['sub_is_enable']) {
+                        if (!empty($ruleData['sub_simple_action'])) {
                             $priceRules = Mage::helper('Mage_CatalogRule_Helper_Data')->calcPriceRule(
                                 $ruleData['sub_simple_action'],
                                 $ruleData['sub_discount_amount'],
@@ -324,16 +324,16 @@ class Mage_CatalogRule_Model_Rule extends Mage_Rule_Model_Abstract
                         } else {
                             $priceRules = $price;
                         }
-                        if ($ruleData['stop_rules_processing']) {
+                        if ($ruleData['action_stop']) {
                             break;
                         }
                     } else {
                         $priceRules = Mage::helper('Mage_CatalogRule_Helper_Data')->calcPriceRule(
-                            $ruleData['simple_action'],
-                            $ruleData['discount_amount'],
-                            $priceRules ? $priceRules :$price
+                            $ruleData['action_operator'],
+                            $ruleData['action_amount'],
+                            $priceRules ? $priceRules : $price
                         );
-                        if ($ruleData['stop_rules_processing']) {
+                        if ($ruleData['action_stop']) {
                             break;
                         }
                     }
diff --git a/app/code/core/Mage/CatalogRule/etc/config.xml b/app/code/core/Mage/CatalogRule/etc/config.xml
index 9cf6fd46df091e81d0015002ec02ce49519cb20f..10d0d75eb73460f7cb7e3dc9ac254259a73ffea5 100644
--- a/app/code/core/Mage/CatalogRule/etc/config.xml
+++ b/app/code/core/Mage/CatalogRule/etc/config.xml
@@ -28,7 +28,7 @@
 <config>
     <modules>
         <Mage_CatalogRule>
-            <version>1.6.0.2</version>
+            <version>1.6.0.3</version>
         </Mage_CatalogRule>
     </modules>
     <global>
diff --git a/app/code/core/Mage/CatalogRule/sql/catalogrule_setup/upgrade-1.6.0.2-1.6.0.3.php b/app/code/core/Mage/CatalogRule/sql/catalogrule_setup/upgrade-1.6.0.2-1.6.0.3.php
new file mode 100644
index 0000000000000000000000000000000000000000..56e75ca1a05b26e98723e499923798ffdfbb47df
--- /dev/null
+++ b/app/code/core/Mage/CatalogRule/sql/catalogrule_setup/upgrade-1.6.0.2-1.6.0.3.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    Mage
+ * @package     Mage_CatalogRule
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/* @var $installer Mage_Core_Model_Resource_Setup */
+$installer = $this;
+
+$installer->startSetup();
+
+$ruleProductTable = $installer->getTable('catalogrule_product');
+
+$columnOptions = array(
+    'TYPE' => Varien_Db_Ddl_Table::TYPE_TEXT,
+    'LENGTH' => 32,
+    'COMMENT' => 'Simple Action For Subitems',
+);
+$installer->getConnection()->addColumn($ruleProductTable, 'sub_simple_action', $columnOptions);
+
+$columnOptions = array(
+    'TYPE' => Varien_Db_Ddl_Table::TYPE_DECIMAL,
+    'SCALE' => 4,
+    'PRECISION' => 12,
+    'NULLABLE' => false,
+    'DEFAULT' => '0.0000',
+    'COMMENT' => 'Discount Amount For Subitems',
+);
+$installer->getConnection()->addColumn($ruleProductTable, 'sub_discount_amount', $columnOptions);
+
+$installer->endSetup();
diff --git a/app/code/core/Mage/CatalogSearch/Block/Advanced/Result.php b/app/code/core/Mage/CatalogSearch/Block/Advanced/Result.php
index 15ab41f47541d8a4a9ea75fe505f12faa0e845a5..b4ed40c38d375eca7ba457ef424faa888f011225 100644
--- a/app/code/core/Mage/CatalogSearch/Block/Advanced/Result.php
+++ b/app/code/core/Mage/CatalogSearch/Block/Advanced/Result.php
@@ -58,12 +58,12 @@ class Mage_CatalogSearch_Block_Advanced_Result extends Mage_Core_Block_Template
         $availableOrders = $category->getAvailableSortByOptions();
         unset($availableOrders['position']);
 
-        $this->getChild('search_result_list')
+        $this->getChildBlock('search_result_list')
             ->setAvailableOrders($availableOrders);
     }
 
     public function setListModes() {
-        $this->getChild('search_result_list')
+        $this->getChildBlock('search_result_list')
             ->setModes(array(
                 'grid' => Mage::helper('Mage_CatalogSearch_Helper_Data')->__('Grid'),
                 'list' => Mage::helper('Mage_CatalogSearch_Helper_Data')->__('List'))
@@ -71,7 +71,7 @@ class Mage_CatalogSearch_Block_Advanced_Result extends Mage_Core_Block_Template
     }
 
     public function setListCollection() {
-        $this->getChild('search_result_list')
+        $this->getChildBlock('search_result_list')
            ->setCollection($this->_getProductCollection());
     }
 
diff --git a/app/code/core/Mage/CatalogSearch/Block/Result.php b/app/code/core/Mage/CatalogSearch/Block/Result.php
index 13e6d644c1c2a9ab3b9c5d6967fc99aaf591a8b8..4ac6e07df736799530e4f85cf26cc97603da5e9a 100644
--- a/app/code/core/Mage/CatalogSearch/Block/Result.php
+++ b/app/code/core/Mage/CatalogSearch/Block/Result.php
@@ -97,7 +97,7 @@ class Mage_CatalogSearch_Block_Result extends Mage_Core_Block_Template
      */
     public function getListBlock()
     {
-        return $this->getChild('search_result_list');
+        return $this->getChildBlock('search_result_list');
     }
 
     /**
diff --git a/app/code/core/Mage/CatalogSearch/Model/Resource/Advanced/Collection.php b/app/code/core/Mage/CatalogSearch/Model/Resource/Advanced/Collection.php
index 57fa0fc90b4b5f13cc258012abcb78a224c17154..6aa6a0093aa25c805917223ff723cc49bf160f59 100755
--- a/app/code/core/Mage/CatalogSearch/Model/Resource/Advanced/Collection.php
+++ b/app/code/core/Mage/CatalogSearch/Model/Resource/Advanced/Collection.php
@@ -99,6 +99,9 @@ class Mage_CatalogSearch_Model_Resource_Advanced_Collection extends Mage_Catalog
                                 if (!is_numeric($conditionValue['from'])){
                                     $conditionValue['from'] = Mage::getSingleton('Mage_Core_Model_Date')
                                         ->gmtDate(null, $conditionValue['from']);
+                                    if (!$conditionValue['from']) {
+                                        $conditionValue['from'] = Mage::getSingleton('Mage_Core_Model_Date')->gmtDate();
+                                    }
                                 }
                                 $conditionData[] = array('gteq' => $conditionValue['from']);
                             }
@@ -109,6 +112,9 @@ class Mage_CatalogSearch_Model_Resource_Advanced_Collection extends Mage_Catalog
                                 if (!is_numeric($conditionValue['to'])){
                                     $conditionValue['to'] = Mage::getSingleton('Mage_Core_Model_Date')
                                         ->gmtDate(null, $conditionValue['to']);
+                                    if (!$conditionValue['to']) {
+                                        $conditionValue['to'] = Mage::getSingleton('Mage_Core_Model_Date')->gmtDate();
+                                    }
                                 }
                                 $conditionData[] = array('lteq' => $conditionValue['to']);
                             }
diff --git a/app/code/core/Mage/CatalogSearch/Model/Resource/Fulltext.php b/app/code/core/Mage/CatalogSearch/Model/Resource/Fulltext.php
index 532ad0692877652631b47239518c9c781380e3d7..02d011b0de0d6588aff75f4fec1a9f192f04a1b2 100755
--- a/app/code/core/Mage/CatalogSearch/Model/Resource/Fulltext.php
+++ b/app/code/core/Mage/CatalogSearch/Model/Resource/Fulltext.php
@@ -62,6 +62,13 @@ class Mage_CatalogSearch_Model_Resource_Fulltext extends Mage_Core_Model_Resourc
      */
     protected $_productTypes             = array();
 
+    /**
+     * Product Emulators cache
+     *
+     * @var array
+     */
+    protected $_productEmulators         = array();
+
     /**
      * Store search engine instance
      *
@@ -469,16 +476,16 @@ class Mage_CatalogSearch_Model_Resource_Fulltext extends Mage_Core_Model_Resourc
      *
      * @param int $storeId
      * @param array $productIds
-     * @param array $atributeTypes
+     * @param array $attributeTypes
      * @return array
      */
-    protected function _getProductAttributes($storeId, array $productIds, array $atributeTypes)
+    protected function _getProductAttributes($storeId, array $productIds, array $attributeTypes)
     {
         $result  = array();
         $selects = array();
-        $adapter = $this->_getReadAdapter();
+        $adapter = $this->_getWriteAdapter();
         $ifStoreValue = $adapter->getCheckSql('t_store.value_id > 0', 't_store.value', 't_default.value');
-        foreach ($atributeTypes as $backendType => $attributeIds) {
+        foreach ($attributeTypes as $backendType => $attributeIds) {
             if ($attributeIds) {
                 $tableName = $this->getTable('catalog_product_entity_' . $backendType);
                 $selects[] = $adapter->select()
@@ -519,8 +526,7 @@ class Mage_CatalogSearch_Model_Resource_Fulltext extends Mage_Core_Model_Resourc
     protected function _getProductTypeInstance($typeId)
     {
         if (!isset($this->_productTypes[$typeId])) {
-            $productEmulator = $this->_getProductEmulator();
-            $productEmulator->setTypeId($typeId);
+            $productEmulator = $this->_getProductEmulator($typeId);
 
             $this->_productTypes[$typeId] = Mage::getSingleton('Mage_Catalog_Model_Product_Type')
                 ->factory($productEmulator);
@@ -538,7 +544,7 @@ class Mage_CatalogSearch_Model_Resource_Fulltext extends Mage_Core_Model_Resourc
     protected function _getProductChildIds($productId, $typeId)
     {
         $typeInstance = $this->_getProductTypeInstance($typeId);
-        $relation = $typeInstance->isComposite()
+        $relation = $typeInstance->isComposite($this->_getProductEmulator($typeId))
             ? $typeInstance->getRelationInfo()
             : false;
 
@@ -560,14 +566,18 @@ class Mage_CatalogSearch_Model_Resource_Fulltext extends Mage_Core_Model_Resourc
     /**
      * Retrieve Product Emulator (Varien Object)
      *
+     * @param string $typeId
      * @return Varien_Object
      */
-    protected function _getProductEmulator()
+    protected function _getProductEmulator($typeId)
     {
-        $productEmulator = new Varien_Object();
-        $productEmulator->setIdFieldName('entity_id');
-
-        return $productEmulator;
+        if (!isset($this->_productEmulators[$typeId])) {
+            $productEmulator = new Varien_Object();
+            $productEmulator->setIdFieldName('entity_id')
+                ->setTypeId($typeId);
+            $this->_productEmulators[$typeId] = $productEmulator;
+        }
+        return $this->_productEmulators[$typeId];
     }
 
     /**
@@ -619,9 +629,8 @@ class Mage_CatalogSearch_Model_Resource_Fulltext extends Mage_Core_Model_Resourc
         }
 
         if (!$this->_engine->allowAdvancedIndex()) {
-            $product = $this->_getProductEmulator()
+            $product = $this->_getProductEmulator($productData['type_id'])
                 ->setId($productData['entity_id'])
-                ->setTypeId($productData['type_id'])
                 ->setStoreId($storeId);
             $typeInstance = $this->_getProductTypeInstance($productData['type_id']);
             if ($data = $typeInstance->getSearchableData($product)) {
@@ -683,8 +692,6 @@ class Mage_CatalogSearch_Model_Resource_Fulltext extends Mage_Core_Model_Resourc
                     return null;
                 }
             }
-
-            $value = preg_replace("#\s+#siu", ' ', trim(strip_tags($value)));
         } elseif ($attribute->getBackendType() == 'datetime') {
             $value = $this->_getStoreDate($storeId, $value);
         } else {
@@ -694,6 +701,8 @@ class Mage_CatalogSearch_Model_Resource_Fulltext extends Mage_Core_Model_Resourc
             }
         }
 
+        $value = preg_replace("#\s+#siu", ' ', trim(strip_tags($value)));
+
         return $value;
     }
 
diff --git a/app/code/core/Mage/CatalogSearch/controllers/AjaxController.php b/app/code/core/Mage/CatalogSearch/controllers/AjaxController.php
index 0999c3cfb3128962a09694b158b01d552c1792d5..9ff10a9f0658baa93854939e7b51f99d029f56da 100644
--- a/app/code/core/Mage/CatalogSearch/controllers/AjaxController.php
+++ b/app/code/core/Mage/CatalogSearch/controllers/AjaxController.php
@@ -39,8 +39,7 @@ class Mage_CatalogSearch_AjaxController extends Mage_Core_Controller_Front_Actio
             $this->getResponse()->setRedirect(Mage::getSingleton('Mage_Core_Model_Url')->getBaseUrl());
         }
 
-        $this->getResponse()->setBody(
-            $this->getLayout()->createBlock('Mage_CatalogSearch_Block_Autocomplete')->toHtml()
-        );
+        $this->addPageLayoutHandles();
+        $this->loadLayout(false)->renderLayout();
     }
 }
diff --git a/app/code/core/Mage/CatalogSearch/view/frontend/layout.xml b/app/code/core/Mage/CatalogSearch/view/frontend/layout.xml
index 1eeb6d0f8e496b77ce90ed1f76c3ee24f78b1e96..47b33e428c349c680e25beaffb08f8930ae0a094 100644
--- a/app/code/core/Mage/CatalogSearch/view/frontend/layout.xml
+++ b/app/code/core/Mage/CatalogSearch/view/frontend/layout.xml
@@ -46,7 +46,7 @@
         </reference>
     </default>
 
-    <catalogsearch_result_index translate="label" module="Mage_CatalogSearch">
+    <catalogsearch_result_index translate="label" module="Mage_CatalogSearch" type="page" parent="default">
         <label>Quick Search Form</label>
         <reference name="root">
             <action method="setTemplate"><template>3columns.phtml</template></action>
@@ -74,7 +74,7 @@
         </reference>
     </catalogsearch_result_index>
 
-    <catalogsearch_advanced_index translate="label" module="Mage_CatalogSearch">
+    <catalogsearch_advanced_index translate="label" module="Mage_CatalogSearch" type="page" parent="default">
         <label>Advanced Search Form</label>
         <!-- Mage_Catalogsearch -->
         <reference name="root">
@@ -96,7 +96,7 @@
 Advanced search results
 -->
 
-    <catalogsearch_advanced_result translate="label" module="Mage_CatalogSearch">
+    <catalogsearch_advanced_result translate="label" module="Mage_CatalogSearch" type="page" parent="catalogsearch_advanced_index">
         <label>Advanced Search Result</label>
         <update handle="page_two_columns_right" />
         <!-- Mage_Catalogsearch -->
@@ -123,7 +123,7 @@ Advanced search results
         </reference>
     </catalogsearch_advanced_result>
 
-    <catalogsearch_term_popular translate="label" module="Mage_CatalogSearch">
+    <catalogsearch_term_popular translate="label" module="Mage_CatalogSearch" type="page" parent="default">
         <label>Popular Search Terms</label>
         <remove name="right"/>
         <remove name="left"/>
@@ -139,4 +139,10 @@ Advanced search results
         </reference>
     </catalogsearch_term_popular>
 
+    <catalogsearch_ajax_suggest translate="label" module="Mage_CatalogSearch" type="page" parent="ajax_index">
+        <label>Catalog Quick Search Form Suggestions</label>
+        <reference name="root">
+            <block type="Mage_CatalogSearch_Block_Autocomplete" name="autocomplete" />
+        </reference>
+    </catalogsearch_ajax_suggest>
 </layout>
diff --git a/app/code/core/Mage/Centinel/view/adminhtml/layout.xml b/app/code/core/Mage/Centinel/view/adminhtml/layout.xml
index 905bb6d663bb653aae18d85de34df6d5bbeabb18..5b34b169833930d6a1691c8bd6961f1cc49792c4 100644
--- a/app/code/core/Mage/Centinel/view/adminhtml/layout.xml
+++ b/app/code/core/Mage/Centinel/view/adminhtml/layout.xml
@@ -29,11 +29,11 @@
 <layout version="0.1.0">
 
     <adminhtml_centinel_index_authenticationstart>
-        <block type="Mage_Centinel_Block_Authentication_Start" name="root" output="toHtml" template="authentication/start.phtml"/>
+        <block type="Mage_Centinel_Block_Authentication_Start" name="root" output="1" template="authentication/start.phtml"/>
     </adminhtml_centinel_index_authenticationstart>
     
     <adminhtml_centinel_index_authenticationcomplete>
-        <block type="Mage_Centinel_Block_Authentication_Complete" name="root" output="toHtml" template="authentication/complete.phtml"/>
+        <block type="Mage_Centinel_Block_Authentication_Complete" name="root" output="1" template="authentication/complete.phtml"/>
     </adminhtml_centinel_index_authenticationcomplete>
 
     <adminhtml_sales_order_create_index>
diff --git a/app/code/core/Mage/Centinel/view/frontend/layout.xml b/app/code/core/Mage/Centinel/view/frontend/layout.xml
index 17520b97b1998726d6499f87e108f58e9c1df93a..e13bf23742199ec219994c0da1cc3957d476cd2a 100644
--- a/app/code/core/Mage/Centinel/view/frontend/layout.xml
+++ b/app/code/core/Mage/Centinel/view/frontend/layout.xml
@@ -27,12 +27,14 @@
 
 -->
 <layout version="0.1.0">
-    <centinel_index_authenticationstart>
-        <block type="Mage_Centinel_Block_Authentication_Start" name="root" output="toHtml" template="authentication/start.phtml"/>
+    <centinel_index_authenticationstart translate="label" type="page" parent="checkout_onepage_paymentmethod">
+        <label>Centinel Authentication Start</label>
+        <block type="Mage_Centinel_Block_Authentication_Start" name="root" output="1" template="authentication/start.phtml"/>
     </centinel_index_authenticationstart>
 
-    <centinel_index_authenticationcomplete>
-        <block type="Mage_Centinel_Block_Authentication_Complete" name="root" output="toHtml" template="authentication/complete.phtml"/>
+    <centinel_index_authenticationcomplete translate="label" type="page" parent="centinel_index_authenticationstart">
+        <label>Centinel Authentication Finish</label>
+        <block type="Mage_Centinel_Block_Authentication_Complete" name="root" output="1" template="authentication/complete.phtml"/>
     </centinel_index_authenticationcomplete>
 
     <checkout_multishipping_overview>
diff --git a/app/code/core/Mage/Checkout/Block/Cart.php b/app/code/core/Mage/Checkout/Block/Cart.php
index 037884f8f6e8ad5f1a106e2eeac09513341fee4c..15789a94c66b5817fb357bc057153538da1de1f2 100644
--- a/app/code/core/Mage/Checkout/Block/Cart.php
+++ b/app/code/core/Mage/Checkout/Block/Cart.php
@@ -140,13 +140,14 @@ class Mage_Checkout_Block_Cart extends Mage_Checkout_Block_Cart_Abstract
     /**
      * Return list of available checkout methods
      *
-     * @param string $nameInLayout Container block alias in layout
+     * @param string $alias Container block alias in layout
      * @return array
      */
-    public function getMethods($nameInLayout)
+    public function getMethods($alias)
     {
-        if ($this->getChild($nameInLayout) instanceof Mage_Core_Block_Abstract) {
-            return $this->getChild($nameInLayout)->getSortedChildren();
+        $childName = $this->getLayout()->getChildName($this->getNameInLayout(), $alias);
+        if ($childName) {
+            return $this->getLayout()->getChildNames($childName);
         }
         return array();
     }
diff --git a/app/code/core/Mage/Checkout/Block/Cart/Item/Renderer.php b/app/code/core/Mage/Checkout/Block/Cart/Item/Renderer.php
index 426c7d5063f96f57a2ded16fc293aae32a824a7c..cb314d3455581b2a99081841eb64171086bc8b01 100644
--- a/app/code/core/Mage/Checkout/Block/Cart/Item/Renderer.php
+++ b/app/code/core/Mage/Checkout/Block/Cart/Item/Renderer.php
@@ -42,6 +42,20 @@ class Mage_Checkout_Block_Cart_Item_Renderer extends Mage_Core_Block_Template
     protected $_productUrl = null;
     protected $_productThumbnail = null;
 
+    /**
+     * Whether qty will be converted to number
+     *
+     * @var bool
+     */
+    protected $_strictQtyMode = true;
+
+    /**
+     * Check, whether product URL rendering should be ignored
+     *
+     * @var bool
+     */
+    protected $_ignoreProductUrl = false;
+
     /**
      * Set item for render
      *
@@ -144,10 +158,14 @@ class Mage_Checkout_Block_Cart_Item_Renderer extends Mage_Core_Block_Template
     /**
      * Check Product has URL
      *
-     * @return this
+     * @return bool
      */
     public function hasProductUrl()
     {
+        if ($this->_ignoreProductUrl) {
+            return false;
+        }
+
         if ($this->_productUrl || $this->getItem()->getRedirectUrl()) {
             return true;
         }
@@ -255,6 +273,7 @@ class Mage_Checkout_Block_Cart_Item_Renderer extends Mage_Core_Block_Template
             return $this->getData('delete_url');
         }
 
+        $encodedUrl = $this->helper('Mage_Core_Helper_Url')->getEncodedUrl();
         return $this->getUrl(
             'checkout/cart/delete',
             array(
@@ -267,11 +286,14 @@ class Mage_Checkout_Block_Cart_Item_Renderer extends Mage_Core_Block_Template
     /**
      * Get quote item qty
      *
-     * @return mixed
+     * @return float|int|string
      */
     public function getQty()
     {
-        return $this->getItem()->getQty()*1;
+        if (!$this->_strictQtyMode && (string)$this->getItem()->getQty() == '') {
+            return '';
+        }
+        return $this->getItem()->getQty() * 1;
     }
 
     /**
@@ -396,4 +418,28 @@ class Mage_Checkout_Block_Cart_Item_Renderer extends Mage_Core_Block_Template
             ->setProduct($item->getProduct())
             ->toHtml();
     }
+
+    /**
+     * Set qty mode to be strict or not
+     *
+     * @param bool $strict
+     * @return Mage_Checkout_Block_Cart_Item_Renderer
+     */
+    public function setQtyMode($strict)
+    {
+        $this->_strictQtyMode = $strict;
+        return $this;
+    }
+
+    /**
+     * Set ignore product URL rendering
+     *
+     * @param bool $ignore
+     * @return Mage_Checkout_Block_Cart_Item_Renderer
+     */
+    public function setIgnoreProductUrl($ignore = true)
+    {
+        $this->_ignoreProductUrl = $ignore;
+        return $this;
+    }
 }
diff --git a/app/code/core/Mage/Checkout/Block/Multishipping/Overview.php b/app/code/core/Mage/Checkout/Block/Multishipping/Overview.php
index 1539f285208d1cf79ecaf68d544de0e1eff48f15..8d6faedc03c712d856d40bbf18419b0fb346b2c6 100644
--- a/app/code/core/Mage/Checkout/Block/Multishipping/Overview.php
+++ b/app/code/core/Mage/Checkout/Block/Multishipping/Overview.php
@@ -243,8 +243,8 @@ class Mage_Checkout_Block_Multishipping_Overview extends Mage_Sales_Block_Items_
         if ($colspan === null) {
             $colspan = $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices() ? 5 : 3;
         }
-        $totals = $this->getChild('totals')->setTotals($totals)->renderTotals('', $colspan)
-            . $this->getChild('totals')->setTotals($totals)->renderTotals('footer', $colspan);
+        $totals = $this->getChildBlock('totals')->setTotals($totals)->renderTotals('', $colspan)
+            . $this->getChildBlock('totals')->setTotals($totals)->renderTotals('footer', $colspan);
         return $totals;
     }
 
diff --git a/app/code/core/Mage/Checkout/Block/Multishipping/Payment/Info.php b/app/code/core/Mage/Checkout/Block/Multishipping/Payment/Info.php
index 3f63239bf5f367f800d4293b8ea1d644bfe67f06..ac69f14fc4ff0f481084e0a740037c4aeaf62d2b 100644
--- a/app/code/core/Mage/Checkout/Block/Multishipping/Payment/Info.php
+++ b/app/code/core/Mage/Checkout/Block/Multishipping/Payment/Info.php
@@ -46,7 +46,7 @@ class Mage_Checkout_Block_Multishipping_Payment_Info extends Mage_Payment_Block_
     protected function _toHtml()
     {
         $html = '';
-        if ($block = $this->getChild($this->_getInfoBlockName())) {
+        if ($block = $this->getChildBlock($this->_getInfoBlockName())) {
             $html = $block->toHtml();
         }
         return $html;
diff --git a/app/code/core/Mage/Checkout/Block/Onepage/Payment/Info.php b/app/code/core/Mage/Checkout/Block/Onepage/Payment/Info.php
index 5594171800251b1e31e36c24e467e02c82b8dda1..e4ec09416475842ca81b27d7607a0b6435113948 100644
--- a/app/code/core/Mage/Checkout/Block/Onepage/Payment/Info.php
+++ b/app/code/core/Mage/Checkout/Block/Onepage/Payment/Info.php
@@ -50,7 +50,7 @@ class Mage_Checkout_Block_Onepage_Payment_Info extends Mage_Payment_Block_Info_C
     protected function _toHtml()
     {
         $html = '';
-        if ($block = $this->getChild($this->_getInfoBlockName())) {
+        if ($block = $this->getChildBlock($this->_getInfoBlockName())) {
             $html = $block->toHtml();
         }
         return $html;
diff --git a/app/code/core/Mage/Checkout/Block/Onepage/Payment/Methods.php b/app/code/core/Mage/Checkout/Block/Onepage/Payment/Methods.php
index dda4358eb6b24189551a67b8afcca380c1020603..998a84502e37e4dd9c52e0bcfc94598b485b0260 100644
--- a/app/code/core/Mage/Checkout/Block/Onepage/Payment/Methods.php
+++ b/app/code/core/Mage/Checkout/Block/Onepage/Payment/Methods.php
@@ -81,7 +81,7 @@ class Mage_Checkout_Block_Onepage_Payment_Methods extends Mage_Payment_Block_For
      */
     public function getMethodTitle(Mage_Payment_Model_Method_Abstract $method)
     {
-        $form = $this->getChild('payment.method.' . $method->getCode());
+        $form = $this->getChildBlock('payment.method.' . $method->getCode());
         if ($form && $form->hasMethodTitle()) {
             return $form->getMethodTitle();
         }
@@ -94,7 +94,7 @@ class Mage_Checkout_Block_Onepage_Payment_Methods extends Mage_Payment_Block_For
      */
     public function getMethodLabelAfterHtml(Mage_Payment_Model_Method_Abstract $method)
     {
-        if ($form = $this->getChild('payment.method.' . $method->getCode())) {
+        if ($form = $this->getChildBlock('payment.method.' . $method->getCode())) {
             return $form->getMethodLabelAfterHtml();
         }
     }
diff --git a/app/code/core/Mage/Checkout/Helper/Data.php b/app/code/core/Mage/Checkout/Helper/Data.php
index 896b85656642ac09ff01990d3d042f2473e9860f..30372bab8f3464f5dea9706cbba0ab449a386ccf 100644
--- a/app/code/core/Mage/Checkout/Helper/Data.php
+++ b/app/code/core/Mage/Checkout/Helper/Data.php
@@ -103,7 +103,8 @@ class Mage_Checkout_Helper_Data extends Mage_Core_Helper_Abstract
             return $item->getPriceInclTax();
         }
         $qty = ($item->getQty() ? $item->getQty() : ($item->getQtyOrdered() ? $item->getQtyOrdered() : 1));
-        $price = (floatval($qty)) ? ($item->getRowTotal() + $item->getTaxAmount())/$qty : 0;
+        $taxAmount = $item->getTaxAmount() + $item->getDiscountTaxCompensation();
+        $price = (floatval($qty)) ? ($item->getRowTotal() + $taxAmount)/$qty : 0;
         return Mage::app()->getStore()->roundPrice($price);
     }
 
@@ -118,20 +119,21 @@ class Mage_Checkout_Helper_Data extends Mage_Core_Helper_Abstract
         if ($item->getRowTotalInclTax()) {
             return $item->getRowTotalInclTax();
         }
-        $tax = $item->getTaxAmount();
+        $tax = $item->getTaxAmount() + $item->getDiscountTaxCompensation();
         return $item->getRowTotal() + $tax;
     }
 
     public function getBasePriceInclTax($item)
     {
         $qty = ($item->getQty() ? $item->getQty() : ($item->getQtyOrdered() ? $item->getQtyOrdered() : 1));
-        $price = (floatval($qty)) ? ($item->getBaseRowTotal() + $item->getBaseTaxAmount())/$qty : 0;
+        $taxAmount = $item->getBaseTaxAmount() + $item->getBaseDiscountTaxCompensation();
+        $price = (floatval($qty)) ? ($item->getBaseRowTotal() + $taxAmount)/$qty : 0;
         return Mage::app()->getStore()->roundPrice($price);
     }
 
     public function getBaseSubtotalInclTax($item)
     {
-        $tax = ($item->getBaseTaxBeforeDiscount() ? $item->getBaseTaxBeforeDiscount() : $item->getBaseTaxAmount());
+        $tax = $item->getBaseTaxAmount() + $item->getBaseDiscountTaxCompensation();
         return $item->getBaseRowTotal()+$tax;
     }
 
diff --git a/app/code/core/Mage/Checkout/Model/Cart.php b/app/code/core/Mage/Checkout/Model/Cart.php
index bb5d4502602ab2e703c82832caa650e78352a546..c92e1a8b8d1c528aec7310edee6a91ed7f8ffa67 100644
--- a/app/code/core/Mage/Checkout/Model/Cart.php
+++ b/app/code/core/Mage/Checkout/Model/Cart.php
@@ -25,7 +25,7 @@
  */
 
 /**
- * Shoping cart model
+ * Shopping cart model
  *
  * @category    Mage
  * @package     Mage_Checkout
@@ -33,11 +33,24 @@
  */
 class Mage_Checkout_Model_Cart extends Varien_Object implements Mage_Checkout_Model_Cart_Interface
 {
-    protected $_summaryQty = null;
-    protected $_productIds = null;
+    /**
+     * Shopping cart items summary quantity(s)
+     *
+     * @var int|null
+     */
+    protected $_summaryQty;
+
+    /**
+     * List of product ids in shopping cart
+     *
+     * @var array|null
+     */
+    protected $_productIds;
 
     /**
      * Get shopping cart resource model
+     *
+     * @return Mage_Checkout_Model_Resource_Cart
      */
     protected function _getResource()
     {
@@ -64,6 +77,11 @@ class Mage_Checkout_Model_Cart extends Varien_Object implements Mage_Checkout_Mo
         return Mage::getSingleton('Mage_Customer_Model_Session');
     }
 
+    /**
+     * List of shopping cart items
+     *
+     * @return Mage_Eav_Model_Entity_Collection_Abstract|array
+     */
     public function getItems()
     {
         if (!$this->getQuote()->getId()) {
@@ -117,6 +135,8 @@ class Mage_Checkout_Model_Cart extends Varien_Object implements Mage_Checkout_Mo
 
     /**
      * Initialize cart quote state to be able use it on cart page
+     *
+     * @return Mage_Checkout_Model_Cart
      */
     public function init()
     {
@@ -210,8 +230,7 @@ class Mage_Checkout_Model_Cart extends Varien_Object implements Mage_Checkout_Mo
         if ($requestInfo instanceof Varien_Object) {
             $request = $requestInfo;
         } elseif (is_numeric($requestInfo)) {
-            $request = new Varien_Object();
-            $request->setQty($requestInfo);
+            $request = new Varien_Object(array('qty' => $requestInfo));
         } else {
             $request = new Varien_Object($requestInfo);
         }
@@ -219,6 +238,7 @@ class Mage_Checkout_Model_Cart extends Varien_Object implements Mage_Checkout_Mo
         if (!$request->hasQty()) {
             $request->setQty(1);
         }
+
         return $request;
     }
 
@@ -393,7 +413,10 @@ class Mage_Checkout_Model_Cart extends Varien_Object implements Mage_Checkout_Mo
             $qty = isset($itemInfo['qty']) ? (float) $itemInfo['qty'] : false;
             if ($qty > 0) {
                 $item->setQty($qty);
-                if ($item->getHasError()) {
+
+                $itemInQuote = $this->getQuote()->getItemById($item->getId());
+
+                if (!$itemInQuote && $item->getHasError()) {
                     Mage::throwException($item->getMessage());
                 }
 
@@ -483,9 +506,9 @@ class Mage_Checkout_Model_Cart extends Varien_Object implements Mage_Checkout_Mo
     }
 
     /**
-     * Get shopping cart items summary (inchlude config settings)
+     * Get shopping cart items summary (includes config settings)
      *
-     * @return decimal
+     * @return int|float
      */
     public function getSummaryQty()
     {
@@ -522,7 +545,7 @@ class Mage_Checkout_Model_Cart extends Varien_Object implements Mage_Checkout_Mo
     /**
      * Get shopping cart summary qty
      *
-     * @return decimal
+     * @return int|float
      */
     public function getItemsQty()
     {
@@ -534,7 +557,7 @@ class Mage_Checkout_Model_Cart extends Varien_Object implements Mage_Checkout_Mo
      * $requestInfo - either qty (int) or buyRequest in form of array or Varien_Object
      * $updatingParams - information on how to perform update, passed to Quote->updateItem() method
      *
-     * @param int $id
+     * @param int $itemId
      * @param int|array|Varien_Object $requestInfo
      * @param null|array|Varien_Object $updatingParams
      * @return Mage_Sales_Model_Quote_Item|string
diff --git a/app/code/core/Mage/Checkout/Model/Cart/Product/Api.php b/app/code/core/Mage/Checkout/Model/Cart/Product/Api.php
index a2afb1c1ab30dea61c929d5781e5fa284b292bd3..c9e317859480fffae770cf202c1b22745fe34278 100644
--- a/app/code/core/Mage/Checkout/Model/Cart/Product/Api.php
+++ b/app/code/core/Mage/Checkout/Model/Cart/Product/Api.php
@@ -188,7 +188,8 @@ class Mage_Checkout_Model_Cart_Product_Api extends Mage_Checkout_Model_Api_Resou
 
             try {
                 /** @var $quoteItem Mage_Sales_Model_Quote_Item */
-                $quoteItem = $this->_getQuoteItemByProduct($quote, $productByItem, $this->_getProductRequest($productItem));
+                $quoteItem = $this->_getQuoteItemByProduct($quote, $productByItem,
+                    $this->_getProductRequest($productItem));
                 if (is_null($quoteItem->getId())) {
                     $errors[] = Mage::helper('Mage_Checkout_Helper_Data')->__("One item of products is not belong any of quote item");
                     continue;
@@ -233,12 +234,13 @@ class Mage_Checkout_Model_Cart_Product_Api extends Mage_Checkout_Model_Api_Resou
             /** @var $item Mage_Sales_Model_Quote_Item */
             $product = $item->getProduct();
             $productsResult[] = array( // Basic product data
-                'product_id' => $product->getId(),
-                'sku'        => $product->getSku(),
-                'set'        => $product->getAttributeSetId(),
-                'type'       => $product->getTypeId(),
-                'categories' => $product->getCategoryIds(),
-                'websites'   => $product->getWebsiteIds()
+                'product_id'   => $product->getId(),
+                'sku'          => $product->getSku(),
+                'name'         => $product->getName(),
+                'set'          => $product->getAttributeSetId(),
+                'type'         => $product->getTypeId(),
+                'category_ids' => $product->getCategoryIds(),
+                'website_ids'  => $product->getWebsiteIds()
             );
         }
 
@@ -295,7 +297,8 @@ class Mage_Checkout_Model_Cart_Product_Api extends Mage_Checkout_Model_Api_Resou
 
             try {
                 /** @var $quoteItem Mage_Sales_Model_Quote_Item */
-                $quoteItem = $this->_getQuoteItemByProduct($quote, $productByItem, $this->_getProductRequest($productItem));
+                $quoteItem = $this->_getQuoteItemByProduct($quote, $productByItem,
+                    $this->_getProductRequest($productItem));
                 if($quoteItem->getId()){
                     $customerQuote->addItem($quoteItem);
                     $quote->removeItem($quoteItem->getId());
diff --git a/app/code/core/Mage/Checkout/Model/Type/Onepage.php b/app/code/core/Mage/Checkout/Model/Type/Onepage.php
index 32cd4d3cacb0913a0fec3c69fc7423d9505fb123..8e3b055754bc67b95ad924578e1196c88a747141 100644
--- a/app/code/core/Mage/Checkout/Model/Type/Onepage.php
+++ b/app/code/core/Mage/Checkout/Model/Type/Onepage.php
@@ -41,7 +41,7 @@ class Mage_Checkout_Model_Type_Onepage
      *
      * @var string
      */
-    private $_customerEmailExistsMessage = '';
+    protected $_customerEmailExistsMessage = '';
 
     /**
      * @var Mage_Customer_Model_Session
@@ -253,7 +253,7 @@ class Mage_Checkout_Model_Type_Onepage
             $addressData    = $addressForm->extractData($addressForm->prepareRequest($data));
             $addressErrors  = $addressForm->validateData($addressData);
             if ($addressErrors !== true) {
-                return array('error' => 1, 'message' => $addressErrors);
+                return array('error' => 1, 'message' => array_values($addressErrors));
             }
             $addressForm->compactData($addressData);
             //unset billing address attributes which were not shown in form
diff --git a/app/code/core/Mage/Checkout/controllers/CartController.php b/app/code/core/Mage/Checkout/controllers/CartController.php
index 1e9d64cf14a78f8116b4b58a41fcee82b70ef564..0aa3118705e7faf41d05006d8cb4400bfedc39c9 100644
--- a/app/code/core/Mage/Checkout/controllers/CartController.php
+++ b/app/code/core/Mage/Checkout/controllers/CartController.php
@@ -141,6 +141,8 @@ class Mage_Checkout_CartController extends Mage_Core_Controller_Front_Action
         $messages = array();
         foreach ($cart->getQuote()->getMessages() as $message) {
             if ($message) {
+                // Escape HTML entities in quote message to prevent XSS
+                $message->setCode(Mage::helper('Mage_Core_Helper_Data')->escapeHtml($message->getCode()));
                 $messages[] = $message;
             }
         }
@@ -213,11 +215,11 @@ class Mage_Checkout_CartController extends Mage_Core_Controller_Front_Action
             }
         } catch (Mage_Core_Exception $e) {
             if ($this->_getSession()->getUseNotice(true)) {
-                $this->_getSession()->addNotice($e->getMessage());
+                $this->_getSession()->addNotice(Mage::helper('Mage_Core_Helper_Data')->escapeHtml($e->getMessage()));
             } else {
                 $messages = array_unique(explode("\n", $e->getMessage()));
                 foreach ($messages as $message) {
-                    $this->_getSession()->addError($message);
+                    $this->_getSession()->addError(Mage::helper('Mage_Core_Helper_Data')->escapeHtml($message));
                 }
             }
 
@@ -423,7 +425,7 @@ class Mage_Checkout_CartController extends Mage_Core_Controller_Front_Action
             }
             $this->_getSession()->setCartWasUpdated(true);
         } catch (Mage_Core_Exception $e) {
-            $this->_getSession()->addError($e->getMessage());
+            $this->_getSession()->addError(Mage::helper('Mage_Core_Helper_Data')->escapeHtml($e->getMessage()));
         } catch (Exception $e) {
             $this->_getSession()->addException($e, $this->__('Cannot update shopping cart.'));
             Mage::logException($e);
diff --git a/app/code/core/Mage/Checkout/controllers/OnepageController.php b/app/code/core/Mage/Checkout/controllers/OnepageController.php
index 2c436e9f7acd2d70934388a48db5a09103754f1d..19cdbca55f35d386108a46ea00945382605baf73 100644
--- a/app/code/core/Mage/Checkout/controllers/OnepageController.php
+++ b/app/code/core/Mage/Checkout/controllers/OnepageController.php
@@ -92,21 +92,34 @@ class Mage_Checkout_OnepageController extends Mage_Checkout_Controller_Action
     }
 
     /**
-     * Get shipping method step html
+     * Render HTML based on requested layout handle name
      *
+     * @param string $handle
      * @return string
      */
-    protected function _getShippingMethodsHtml()
+    protected function _getHtmlByHandle($handle)
     {
         $layout = $this->getLayout();
-        $update = $layout->getUpdate();
-        $update->load('checkout_onepage_shippingmethod');
+        $layout->getUpdate()->addPageHandles(array($handle));
+        $layout->getUpdate()->load();
         $layout->generateXml();
         $layout->generateBlocks();
         $output = $layout->getOutput();
+        Mage::getSingleton('Mage_Core_Model_Translate_Inline')->processResponseBody($output);
         return $output;
     }
 
+
+    /**
+     * Get shipping method step html
+     *
+     * @return string
+     */
+    protected function _getShippingMethodsHtml()
+    {
+        return $this->_getHtmlByHandle('checkout_onepage_shippingmethod');
+    }
+
     /**
      * Get payment method step html
      *
@@ -114,25 +127,12 @@ class Mage_Checkout_OnepageController extends Mage_Checkout_Controller_Action
      */
     protected function _getPaymentMethodsHtml()
     {
-        $layout = $this->getLayout();
-        $update = $layout->getUpdate();
-        $update->load('checkout_onepage_paymentmethod');
-        $layout->generateXml();
-        $layout->generateBlocks();
-        $output = $layout->getOutput();
-        return $output;
+        return $this->_getHtmlByHandle('checkout_onepage_paymentmethod');
     }
 
     protected function _getAdditionalHtml()
     {
-        $layout = $this->getLayout();
-        $update = $layout->getUpdate();
-        $update->load('checkout_onepage_additional');
-        $layout->generateXml();
-        $layout->generateBlocks();
-        $output = $layout->getOutput();
-        Mage::getSingleton('Mage_Core_Model_Translate_Inline')->processResponseBody($output);
-        return $output;
+        return $this->_getHtmlByHandle('checkout_onepage_additional');
     }
 
     /**
@@ -142,7 +142,7 @@ class Mage_Checkout_OnepageController extends Mage_Checkout_Controller_Action
      */
     protected function _getReviewHtml()
     {
-        return $this->getLayout()->getBlock('root')->toHtml();
+        return $this->_getHtmlByHandle('checkout_onepage_review');
     }
 
     /**
@@ -196,6 +196,7 @@ class Mage_Checkout_OnepageController extends Mage_Checkout_Controller_Action
         if ($this->_expireAjax()) {
             return;
         }
+        $this->addPageLayoutHandles();
         $this->loadLayout(false);
         $this->renderLayout();
     }
@@ -205,6 +206,7 @@ class Mage_Checkout_OnepageController extends Mage_Checkout_Controller_Action
         if ($this->_expireAjax()) {
             return;
         }
+        $this->addPageLayoutHandles();
         $this->loadLayout(false);
         $this->renderLayout();
     }
@@ -214,6 +216,7 @@ class Mage_Checkout_OnepageController extends Mage_Checkout_Controller_Action
         if ($this->_expireAjax()) {
             return;
         }
+        $this->addPageLayoutHandles();
         $this->loadLayout(false);
         $this->renderLayout();
     }
@@ -425,7 +428,6 @@ class Mage_Checkout_OnepageController extends Mage_Checkout_Controller_Action
             // get section and redirect data
             $redirectUrl = $this->getOnepage()->getQuote()->getPayment()->getCheckoutRedirectUrl();
             if (empty($result['error']) && !$redirectUrl) {
-                $this->loadLayout('checkout_onepage_review');
                 $result['goto_section'] = 'review';
                 $result['update_section'] = array(
                     'name' => 'review',
diff --git a/app/code/core/Mage/Checkout/etc/translater.xml b/app/code/core/Mage/Checkout/etc/jstranslator.xml
similarity index 98%
rename from app/code/core/Mage/Checkout/etc/translater.xml
rename to app/code/core/Mage/Checkout/etc/jstranslator.xml
index fb4f010a26755b1f766287b0cdecade46c1b0a4f..ec0dd7e76b0a695614f6f2c1d548b87f7fab40cf 100644
--- a/app/code/core/Mage/Checkout/etc/translater.xml
+++ b/app/code/core/Mage/Checkout/etc/jstranslator.xml
@@ -25,7 +25,7 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 -->
-<translater>
+<jstranslator>
     <!-- opcheckout.js -->
     <validate-guest translate="message" module="Mage_Checkout">
         <message>Please choose to register or to checkout as a guest</message>
@@ -43,4 +43,4 @@
         <message>Please specify payment method.</message>
     </validate-shipping-methods-required>
     <!-- end opcheckout.js -->
-</translater>
+</jstranslator>
diff --git a/app/code/core/Mage/Checkout/view/frontend/cart/item/configure/updatecart.phtml b/app/code/core/Mage/Checkout/view/frontend/cart/item/configure/updatecart.phtml
index 8f587723afc34aacb5d81eb727c92490ae331b38..d4d49635b8901ef2d9cea375f759c868a2867117 100644
--- a/app/code/core/Mage/Checkout/view/frontend/cart/item/configure/updatecart.phtml
+++ b/app/code/core/Mage/Checkout/view/frontend/cart/item/configure/updatecart.phtml
@@ -34,6 +34,6 @@
         <input type="text" name="qty" id="qty" maxlength="12" value="<?php echo $this->getProductDefaultQty() * 1 ?>" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />
         <?php endif; ?>
         <button type="button" title="<?php echo $buttonTitle ?>" class="button btn-cart" onclick="productAddToCartForm.submit(this)"><span><span><?php echo $buttonTitle ?></span></span></button>
-        <?php echo $this->getChildHtml('', true, true) ?>
+        <?php echo $this->getChildHtml('', true) ?>
     </div>
 <?php endif; ?>
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 f3b538d71296f3981f336d4412ee18a6d4cd58a4..94cf58be48ebf5eee37d629466cc8172254fe204 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
@@ -62,9 +62,9 @@ $canApplyMsrp = Mage::helper('Mage_Catalog_Helper_Data')->canApplyMsrp($_item->g
             <p class="item-msg <?php echo $message['type'] ?>">* <?php echo $message['text'] ?></p>
         <?php endforeach; ?>
         <?php endif; ?>
-        <?php $addtInfoBlock = $this->getProductAdditionalInformationBlock(); ?>
-        <?php if ($addtInfoBlock): ?>
-            <?php echo $addtInfoBlock->setItem($_item)->toHtml() ?>
+        <?php $addInfoBlock = $this->getProductAdditionalInformationBlock(); ?>
+        <?php if ($addInfoBlock): ?>
+            <?php echo $addInfoBlock->setItem($_item)->toHtml() ?>
         <?php endif;?>
     </td>
     <td class="a-center">
@@ -75,7 +75,7 @@ $canApplyMsrp = Mage::helper('Mage_Catalog_Helper_Data')->canApplyMsrp($_item->g
     <?php if ($this->helper('Mage_Wishlist_Helper_Data')->isAllowInCart()) : ?>
     <td class="a-center">
         <?php if ($isVisibleProduct): ?>
-        <input type="checkbox" value="1" name="cart[<?php echo $_item->getId() ?>][wishlist]" title="<?php echo $this->__('Move to Wishlist') ?>" class="checkbox" />
+        <a href="<?php echo $this->helper('Mage_Wishlist_Helper_Data')->getMoveFromCartUrl($_item->getId()); ?>" class="link-wishlist use-ajax"><?php echo $this->__('Move'); ?></a>
         <?php endif ?>
     </td>
     <?php endif ?>
@@ -181,7 +181,7 @@ $canApplyMsrp = Mage::helper('Mage_Catalog_Helper_Data')->canApplyMsrp($_item->g
     <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" />
     </td>
-    <?php if ($this->helper('Mage_Tax_Helper_Data')->displayCartPriceExclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()): ?>
+    <?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');">
@@ -226,7 +226,7 @@ $canApplyMsrp = Mage::helper('Mage_Catalog_Helper_Data')->canApplyMsrp($_item->g
         <?php endif; ?>
     </td>
     <?php endif; ?>
-    <?php if ($this->helper('Mage_Tax_Helper_Data')->displayCartPriceInclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()): ?>
+    <?php if (($this->helper('Mage_Tax_Helper_Data')->displayCartPriceInclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()) && !$_item->getNoSubtotal()): ?>
     <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()): ?>
diff --git a/app/code/core/Mage/Checkout/view/frontend/cart/shipping.phtml b/app/code/core/Mage/Checkout/view/frontend/cart/shipping.phtml
index 5a779e9e96f05bca799563d1d33422516b9d68fe..90662ce189282d7af68e4ec103137ceb763560da 100644
--- a/app/code/core/Mage/Checkout/view/frontend/cart/shipping.phtml
+++ b/app/code/core/Mage/Checkout/view/frontend/cart/shipping.phtml
@@ -24,11 +24,7 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 ?>
-<?php
-/**
- * @see Mage_Checkout_Block_Cart_Shipping
- */
-?>
+<?php /** @var $this Mage_Checkout_Block_Cart_Shipping */ ?>
 <div class="shipping">
     <h2><?php echo $this->__('Estimate Shipping and Tax') ?></h2>
     <div class="shipping-form">
@@ -86,16 +82,16 @@
         <form id="co-shipping-method-form" action="<?php echo $this->getUrl('checkout/cart/estimateUpdatePost') ?>">
             <dl class="sp-methods">
                 <?php foreach ($_shippingRateGroups as $code => $_rates): ?>
-                    <dt><?php echo $this->getCarrierName($code) ?></dt>
+                    <dt><?php echo $this->escapeHtml($this->getCarrierName($code)) ?></dt>
                     <dd>
                         <ul>
                         <?php foreach ($_rates as $_rate): ?>
                             <li<?php if ($_rate->getErrorMessage()) echo ' class="error-msg"';?>>
                                <?php if ($_rate->getErrorMessage()): ?>
-                                    <?php echo $_rate->getErrorMessage() ?>
+                                    <?php echo $this->escapeHtml($_rate->getErrorMessage()) ?>
                                <?php else: ?>
                                     <input name="estimate_method" type="radio" value="<?php echo $this->escapeHtml($_rate->getCode()) ?>" id="s_method_<?php echo $_rate->getCode() ?>"<?php if($_rate->getCode()===$this->getAddressShippingMethod()) echo ' checked="checked"' ?> class="radio" />
-                                    <label for="s_method_<?php echo $_rate->getCode() ?>"><?php echo $_rate->getMethodTitle() ?>
+                                    <label for="s_method_<?php echo $_rate->getCode() ?>"><?php echo $this->escapeHtml($_rate->getMethodTitle()) ?>
                                     <?php $_excl = $this->getShippingPrice($_rate->getPrice(), $this->helper('Mage_Tax_Helper_Data')->displayShippingPriceIncludingTax()); ?>
                                     <?php $_incl = $this->getShippingPrice($_rate->getPrice(), true); ?>
                                     <?php echo $_excl; ?>
diff --git a/app/code/core/Mage/Checkout/view/frontend/layout.xml b/app/code/core/Mage/Checkout/view/frontend/layout.xml
index dd0e7f4545b83d2edf214f7149f9a38e40909eb5..4c84168b6ecd925799601b10419db6e18956fcdc 100644
--- a/app/code/core/Mage/Checkout/view/frontend/layout.xml
+++ b/app/code/core/Mage/Checkout/view/frontend/layout.xml
@@ -46,14 +46,12 @@ Default layout, loads most of the pages
                 <action method="addItemRender"><type>simple</type><block>Mage_Checkout_Block_Cart_Item_Renderer</block><template>cart/sidebar/default.phtml</template></action>
                 <action method="addItemRender"><type>grouped</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Grouped</block><template>cart/sidebar/default.phtml</template></action>
                 <action method="addItemRender"><type>configurable</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Configurable</block><template>cart/sidebar/default.phtml</template></action>
-                <block type="Mage_Core_Block_Text_List" name="cart_sidebar.extra_actions" as="extra_actions" translate="label" module="Mage_Checkout">
-                    <label>Shopping Cart Sidebar Extra Actions</label>
-                </block>
+                <container name="cart_sidebar.extra_actions" as="extra_actions" label="Shopping Cart Sidebar Extra Actions" module="Mage_Checkout"/>
             </block>
         </reference>
     </default>
 
-    <checkout_cart_index translate="label">
+    <checkout_cart_index translate="label" type="page" parent="default">
         <label>Shopping Cart</label>
         <remove name="right"/>
         <remove name="left"/>
@@ -70,20 +68,16 @@ Default layout, loads most of the pages
                 <action method="addItemRender"><type>grouped</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Grouped</block><template>cart/item/default.phtml</template></action>
                 <action method="addItemRender"><type>configurable</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Configurable</block><template>cart/item/default.phtml</template></action>
 
-                <block type="Mage_Core_Block_Text_List" name="checkout.cart.top_methods" as="top_methods" translate="label">
-                    <label>Payment Methods Before Checkout Button</label>
+                <container name="checkout.cart.top_methods" as="top_methods" label="Payment Methods Before Checkout Button">
                     <block type="Mage_Checkout_Block_Onepage_Link" name="checkout.cart.methods.onepage" template="onepage/link.phtml"/>
-                </block>
+                </container>
 
-                <block type="Mage_Page_Block_Html_Wrapper" name="checkout.cart.form.before" as="form_before" translate="label">
-                    <label>Shopping Cart Form Before</label>
-                </block>
+                <container name="checkout.cart.form.before" as="form_before" label="Shopping Cart Form Before" htmlTag="div"/>
 
-                <block type="Mage_Core_Block_Text_List" name="checkout.cart.methods" as="methods" translate="label">
-                    <label>Payment Methods After Checkout Button</label>
+                <container name="checkout.cart.methods" as="methods" label="Payment Methods After Checkout Button">
                     <block type="Mage_Checkout_Block_Onepage_Link" name="checkout.cart.methods.onepage" template="onepage/link.phtml"/>
                     <block type="Mage_Checkout_Block_Multishipping_Link" name="checkout.cart.methods.multishipping" template="multishipping/link.phtml"/>
-                </block>
+                </container>
 
                 <block type="Mage_Checkout_Block_Cart_Coupon" name="checkout.cart.coupon" as="coupon" template="cart/coupon.phtml"/>
                 <block type="Mage_Checkout_Block_Cart_Shipping" name="checkout.cart.shipping" as="shipping" template="cart/shipping.phtml"/>
@@ -92,12 +86,10 @@ Default layout, loads most of the pages
                 <block type="Mage_Checkout_Block_Cart_Totals" name="checkout.cart.totals" as="totals" template="cart/totals.phtml"/>
             </block>
         </reference>
-        <block type="Mage_Core_Block_Text_List" name="additional.product.info" translate="label">
-            <label>Additional Product Info</label>
-        </block>
+        <container name="additional.product.info" label="Additional Product Info"/>
     </checkout_cart_index>
 
-    <checkout_cart_configure translate="label">
+    <checkout_cart_configure translate="label" type="page" parent="catalog_product_view">
         <label>Configure Cart Item</label>
         <update handle="catalog_product_view"/>
         <reference name="product.info">
@@ -110,7 +102,7 @@ Multi address shipping checkout main layout,
 will be rendered on all checkout pages
 -->
 
-    <checkout_multishipping translate="label">
+    <checkout_multishipping translate="label" type="page" parent="checkout_cart_index">
         <label>Multishipping Checkout</label>
         <!-- Mage_Checkout -->
         <remove name="right"/>
@@ -124,11 +116,13 @@ will be rendered on all checkout pages
         </reference>
     </checkout_multishipping>
 
-    <checkout_multishipping_login>
+    <checkout_multishipping_login translate="label" type="page" parent="customer_account_login">
+        <label>Multishipping Checkout Login User Form</label>
         <update handle="customer_account_login"/>
     </checkout_multishipping_login>
 
-    <checkout_multishipping_register>
+    <checkout_multishipping_register translate="label" type="page" parent="customer_account_create">
+        <label>Multishipping Checkout Register User Form</label>
         <update handle="customer_account_create"/>
     </checkout_multishipping_register>
 
@@ -136,7 +130,7 @@ will be rendered on all checkout pages
 Multi address shipping checkout selection of address per item page
 -->
 
-    <checkout_multishipping_address_select translate="label">
+    <checkout_multishipping_address_select translate="label" type="page" parent="checkout_multishipping_addresses">
         <label>Multishipping Checkout Shipping Address Selection</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -145,7 +139,7 @@ Multi address shipping checkout selection of address per item page
         </reference>
     </checkout_multishipping_address_select>
 
-    <checkout_multishipping_address_selectbilling translate="label">
+    <checkout_multishipping_address_selectbilling translate="label" type="page" parent="checkout_multishipping_address_select">
         <label>Multishipping Checkout Billing Address Selection</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -155,36 +149,37 @@ Multi address shipping checkout selection of address per item page
     </checkout_multishipping_address_selectbilling>
 
 
-    <checkout_multishipping_address_newshipping translate="label">
+    <checkout_multishipping_address_newshipping translate="label" type="page" parent="checkout_multishipping_shipping">
         <label>Multishipping Checkout Shipping Address Creation</label>
         <update handle="checkout_multishipping"/>
         <update handle="checkout_multishipping_customer_address"/>
     </checkout_multishipping_address_newshipping>
 
-    <checkout_multishipping_address_newbilling translate="label">
+    <checkout_multishipping_address_newbilling translate="label" type="page" parent="checkout_multishipping_billing">
         <label>Multishipping Checkout Billing Address Creation</label>
         <update handle="checkout_multishipping"/>
         <update handle="checkout_multishipping_customer_address"/>
     </checkout_multishipping_address_newbilling>
 
-    <checkout_multishipping_address_editshipping translate="label">
+    <checkout_multishipping_address_editshipping translate="label" type="page" parent="checkout_multishipping_shipping">
         <label>Multishipping Checkout Shipping Address Edit Form</label>
         <update handle="checkout_multishipping"/>
         <update handle="checkout_multishipping_customer_address"/>
     </checkout_multishipping_address_editshipping>
 
-    <checkout_multishipping_address_editaddress>
+    <checkout_multishipping_address_editaddress translate="label" type="page" parent="checkout_multishipping_customer_address">
+        <label>Multishipping Checkout One Address Edit Form</label>
         <update handle="checkout_multishipping"/>
         <update handle="checkout_multishipping_customer_address"/>
     </checkout_multishipping_address_editaddress>
 
-    <checkout_multishipping_address_editbilling translate="label">
+    <checkout_multishipping_address_editbilling translate="label" type="page" parent="checkout_multishipping_billing">
         <label>Multishipping Checkout Billing Address Edit Form</label>
         <update handle="checkout_multishipping"/>
         <update handle="checkout_multishipping_customer_address"/>
     </checkout_multishipping_address_editbilling>
 
-    <checkout_multishipping_customer_address translate="label">
+    <checkout_multishipping_customer_address translate="label" type="page" parent="customer_address_form">
         <label>Multishipping Checkout Customer Address Edit Form</label>
         <reference name="content">
             <block type="Mage_Customer_Block_Address_Edit" name="customer_address_edit" template="address/edit.phtml"/>
@@ -195,7 +190,7 @@ Multi address shipping checkout selection of address per item page
 Multi address shipping checkout address page
 -->
 
-    <checkout_multishipping_addresses translate="label">
+    <checkout_multishipping_addresses translate="label" type="page" parent="checkout_multishipping">
         <label>Multishipping Checkout Address (Any) Form</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -212,7 +207,7 @@ Multi address shipping checkout address page
 Multi address shipping checkout shipping information
 -->
 
-    <checkout_multishipping_shipping translate="label">
+    <checkout_multishipping_shipping translate="label" type="page" parent="checkout_multishipping">
         <label>Multishipping Checkout Shipping Information Step</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -235,7 +230,7 @@ Multi address shipping checkout shipping information
 Multi address shipping checkout billing information
 -->
 
-    <checkout_multishipping_billing translate="label">
+    <checkout_multishipping_billing translate="label" type="page" parent="checkout_multishipping">
         <label>Multishipping Checkout Billing Information Step</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -257,7 +252,7 @@ Multi address shipping checkout billing information
 Multi address shipping checkout overview
 -->
 
-    <checkout_multishipping_overview translate="label">
+    <checkout_multishipping_overview translate="label" type="page" parent="checkout_multishipping">
         <label>Multishipping Checkout Overview</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -273,9 +268,7 @@ Multi address shipping checkout overview
                 </block>
                 <block type="Mage_Checkout_Block_Agreements" name="checkout.multishipping.agreements" as="agreements" template="multishipping/agreements.phtml"/>
                 <block type="Mage_Checkout_Block_Cart_Totals" name="totals" />
-                <block type="Mage_Core_Block_Text_List" name="checkout.multishipping.overview.items.after" as="items_after" translate="label">
-                    <label>Overview Items After</label>
-                </block>
+                <container name="checkout.multishipping.overview.items.after" as="items_after" label="Overview Items After"/>
             </block>
         </reference>
     </checkout_multishipping_overview>
@@ -284,7 +277,7 @@ Multi address shipping checkout overview
 Multi address shipping checkout success
 -->
 
-    <checkout_multishipping_success translate="label">
+    <checkout_multishipping_success translate="label" type="page" parent="checkout_multishipping">
         <label>Multishipping Checkout Success</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -297,7 +290,7 @@ Multi address shipping checkout success
 One page checkout main layout
 -->
 
-    <checkout_onepage_index translate="label">
+    <checkout_onepage_index translate="label" type="page" parent="checkout_cart_index">
         <label>One Page Checkout</label>
         <!-- Mage_Checkout -->
         <remove name="left"/>
@@ -307,19 +300,14 @@ One page checkout main layout
         </reference>
         <reference name="right">
             <action method="unsetChildren"></action>
-            <block type="Mage_Page_Block_Html_Wrapper" name="checkout.progress.wrapper" translate="label">
-                <label>Checkout Progress Wrapper</label>
-                <action method="setElementId"><value>checkout-progress-wrapper</value></action>
+            <container name="checkout.progress.wrapper" label="Checkout Progress Wrapper" htmlTag="div" htmlId="checkout-progress-wrapper">
                 <block type="Mage_Checkout_Block_Onepage_Progress" name="checkout.progress" before="-" template="onepage/progress.phtml"/>
-            </block>
+            </container>
         </reference>
         <reference name="content">
             <block type="Mage_Checkout_Block_Onepage" name="checkout.onepage" template="onepage.phtml">
                 <block type="Mage_Checkout_Block_Onepage_Login" name="checkout.onepage.login" as="login" template="onepage/login.phtml">
-                    <block type="Mage_Page_Block_Html_Wrapper" name="checkout.onepage.login.before" as="login_before" translate="label">
-                        <label>Login/Registration Before</label>
-                        <action method="setMayBeInvisible"><value>1</value></action>
-                    </block>
+                    <container name="checkout.onepage.login.before" as="login_before" label="Login/Registration Before" htmlTag="div"/>
                 </block>
                 <block type="Mage_Checkout_Block_Onepage_Billing" name="checkout.onepage.billing" as="billing" template="onepage/billing.phtml"/>
                 <block type="Mage_Checkout_Block_Onepage_Shipping" name="checkout.onepage.shipping" as="shipping" template="onepage/shipping.phtml"/>
@@ -341,28 +329,27 @@ One page checkout main layout
 One page checkout progress block
 -->
 
-    <checkout_onepage_progress>
-        <!-- Mage_Checkout -->
-        <remove name="right"/>
-        <remove name="left"/>
-
-        <block type="Mage_Checkout_Block_Onepage_Progress" name="root" output="toHtml" template="onepage/progress.phtml">
-            <block type="Mage_Checkout_Block_Onepage_Payment_Info" name="payment_info">
-                <action method="setInfoTemplate"><method></method><template></template></action>
+    <checkout_onepage_progress translate="label" type="page" parent="ajax_index">
+        <label>One Page Checkout Progress</label>
+        <reference name="root">
+            <block type="Mage_Checkout_Block_Onepage_Progress" name="progress" template="onepage/progress.phtml">
+                <block type="Mage_Checkout_Block_Onepage_Payment_Info" name="payment_info">
+                    <action method="setInfoTemplate"><method></method><template></template></action>
+                </block>
             </block>
-        </block>
+        </reference>
     </checkout_onepage_progress>
 
 <!--
 One page checkout payment methods block
 -->
-    <checkout_onepage_paymentmethod>
-        <remove name="right"/>
-        <remove name="left"/>
-
-        <block type="Mage_Checkout_Block_Onepage_Payment_Methods" name="root" output="toHtml" template="onepage/payment/methods.phtml">
-            <action method="setMethodFormTemplate"><method>purchaseorder</method><template>Mage_Payment::form/purchaseorder.phtml</template></action>
-        </block>
+    <checkout_onepage_paymentmethod translate="label" type="page" parent="ajax_index">
+        <label>One Page Checkout Choose Payment Method</label>
+        <reference name="root">
+            <block type="Mage_Checkout_Block_Onepage_Payment_Methods" name="payment_method" template="onepage/payment/methods.phtml">
+                <action method="setMethodFormTemplate"><method>purchaseorder</method><template>Mage_Payment::form/purchaseorder.phtml</template></action>
+            </block>
+        </reference>
     </checkout_onepage_paymentmethod>
 
 
@@ -370,51 +357,43 @@ One page checkout payment methods block
 One page checkout shipping methods block
 -->
 
-    <checkout_onepage_shippingmethod>
-        <!-- Mage_Checkout -->
-        <remove name="right"/>
-        <remove name="left"/>
-
-        <block type="Mage_Checkout_Block_Onepage_Shipping_Method_Available" name="root" output="toHtml" template="onepage/shipping_method/available.phtml"/>
+    <checkout_onepage_shippingmethod translate="label" type="page" parent="ajax_index">
+        <label>One Page Checkout Choose Shipping Method</label>
+        <reference name="root">
+            <block type="Mage_Checkout_Block_Onepage_Shipping_Method_Available" name="shipping_method" template="onepage/shipping_method/available.phtml"/>
+        </reference>
     </checkout_onepage_shippingmethod>
 
-    <checkout_onepage_additional>
-        <!-- Mage_Checkout -->
-        <remove name="right"/>
-        <remove name="left"/>
-
-        <block type="Mage_Checkout_Block_Onepage_Shipping_Method_Additional" name="root" output="toHtml" template="onepage/shipping_method/additional.phtml">
-            <action method="setDontDisplayContainer"><param>1</param></action>
-        </block>
+    <checkout_onepage_additional translate="label" type="page" parent="ajax_index">
+        <label>One Page Checkout Additional Address Form</label>
+        <reference name="root">
+            <block type="Mage_Checkout_Block_Onepage_Shipping_Method_Additional" name="shipping_method_additional" template="onepage/shipping_method/additional.phtml">
+                <action method="setDontDisplayContainer"><param>1</param></action>
+            </block>
+        </reference>
     </checkout_onepage_additional>
 
 <!--
 One page checkout order review block
 -->
 
-    <checkout_onepage_review translate="label">
+    <checkout_onepage_review translate="label" type="page" parent="ajax_index">
         <label>One Page Checkout Overview</label>
-        <!-- Mage_Checkout -->
-        <remove name="right"/>
-        <remove name="left"/>
-
-        <block type="Mage_Checkout_Block_Onepage_Review_Info" name="root" output="toHtml" template="onepage/review/info.phtml">
-            <action method="addItemRender"><type>default</type><block>Mage_Checkout_Block_Cart_Item_Renderer</block><template>onepage/review/item.phtml</template></action>
-            <action method="addItemRender"><type>grouped</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Grouped</block><template>onepage/review/item.phtml</template></action>
-            <action method="addItemRender"><type>configurable</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Configurable</block><template>onepage/review/item.phtml</template></action>
-            <block type="Mage_Checkout_Block_Cart_Totals" name="checkout.onepage.review.info.totals" as="totals" template="onepage/review/totals.phtml"/>
-            <block type="Mage_Core_Block_Text_List" name="checkout.onepage.review.info.items.before" as="items_before" translate="label">
-                <label>Items Before</label>
-            </block>
-            <block type="Mage_Core_Block_Text_List" name="checkout.onepage.review.info.items.after" as="items_after" translate="label">
-                <label>Items After</label>
+        <reference name="root">
+            <block type="Mage_Checkout_Block_Onepage_Review_Info" name="order_review" template="onepage/review/info.phtml">
+                <action method="addItemRender"><type>default</type><block>Mage_Checkout_Block_Cart_Item_Renderer</block><template>onepage/review/item.phtml</template></action>
+                <action method="addItemRender"><type>grouped</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Grouped</block><template>onepage/review/item.phtml</template></action>
+                <action method="addItemRender"><type>configurable</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Configurable</block><template>onepage/review/item.phtml</template></action>
+                <block type="Mage_Checkout_Block_Cart_Totals" name="checkout.onepage.review.info.totals" as="totals" template="onepage/review/totals.phtml"/>
+                <container name="checkout.onepage.review.info.items.before" as="items_before" label="Items Before"/>
+                <container name="checkout.onepage.review.info.items.after" as="items_after" label="Items After"/>
+                <block type="Mage_Checkout_Block_Agreements" name="checkout.onepage.agreements" as="agreements" template="onepage/agreements.phtml"/>
+                <block type="Mage_Core_Block_Template" name="checkout.onepage.review.button" as="button" template="Mage_Checkout::onepage/review/button.phtml"/>
             </block>
-            <block type="Mage_Checkout_Block_Agreements" name="checkout.onepage.agreements" as="agreements" template="onepage/agreements.phtml"/>
-            <block type="Mage_Core_Block_Template" name="checkout.onepage.review.button" as="button" template="Mage_Checkout::onepage/review/button.phtml"/>
-        </block>
+        </reference>
     </checkout_onepage_review>
 
-    <checkout_onepage_success translate="label">
+    <checkout_onepage_success translate="label" type="page" parent="checkout_onepage_index">
         <label>One Page Checkout Success</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-right.phtml</template></action>
@@ -423,7 +402,7 @@ One page checkout order review block
             <block type="Mage_Checkout_Block_Onepage_Success" name="checkout.success" template="success.phtml"/>
         </reference>
     </checkout_onepage_success>
-    <checkout_onepage_failure translate="label">
+    <checkout_onepage_failure translate="label" type="page" parent="checkout_onepage_index">
         <label>One Page Checkout Failure</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-right.phtml</template></action>
@@ -432,4 +411,12 @@ One page checkout order review block
             <block type="Mage_Checkout_Block_Onepage_Failure" name="checkout.failure" template="onepage/failure.phtml"/>
         </reference>
     </checkout_onepage_failure>
+
+    <checkout_onepage_savepayment translate="label">
+        <label>One Page Checkout Save Payment</label>
+    </checkout_onepage_savepayment>
+
+    <checkout_onepage_reorder translate="label">
+        <label>One Page Checkout Reorder</label>
+    </checkout_onepage_reorder>
 </layout>
diff --git a/app/code/core/Mage/Checkout/view/frontend/multishipping/overview.phtml b/app/code/core/Mage/Checkout/view/frontend/multishipping/overview.phtml
index d7da0ab266b38cea0cd7b9cfbc2eb7d3bfc09d84..2227f55415d4a19d950714c65e424b306228a9cb 100644
--- a/app/code/core/Mage/Checkout/view/frontend/multishipping/overview.phtml
+++ b/app/code/core/Mage/Checkout/view/frontend/multishipping/overview.phtml
@@ -24,6 +24,7 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 ?>
+<?php /** @var $this Mage_Checkout_Block_Multishipping_Overview */ ?>
 <div class="multiple-checkout">
     <div class="page-title">
         <h1><?php echo $this->__('Review Order') ?></h1>
@@ -81,7 +82,7 @@
                         <div class="box-content">
                             <?php if($_rate=$this->getShippingAddressRate($_address)): ?>
                             <p>
-                            <?php echo $_rate->getCarrierTitle() ?> - <?php echo $_rate->getMethodTitle() ?>
+                            <?php echo $this->escapeHtml($_rate->getCarrierTitle()) ?> - <?php echo $this->escapeHtml($_rate->getMethodTitle()) ?>
                             <?php $_excl = $this->getShippingPriceExclTax($_address); ?>
                             <?php $_incl = $this->getShippingPriceInclTax($_address); ?>
                             <?php echo $_excl; ?>
diff --git a/app/code/core/Mage/Checkout/view/frontend/multishipping/shipping.phtml b/app/code/core/Mage/Checkout/view/frontend/multishipping/shipping.phtml
index 84ec7188c4baae83a8cf9f4e120ada63128086e5..2765b76b0a5db7fa47e498b85cb15927a661bd63 100644
--- a/app/code/core/Mage/Checkout/view/frontend/multishipping/shipping.phtml
+++ b/app/code/core/Mage/Checkout/view/frontend/multishipping/shipping.phtml
@@ -29,6 +29,7 @@
  * Multishipping checkout shipping template
  *
  * @see Mage_Checkout_Block_Multishipping_Shipping
+ * @var $this Mage_Checkout_Block_Multishipping_Shipping
  */
 ?>
 <div class="multiple-checkout">
@@ -60,20 +61,20 @@
                         <?php else: ?>
                         <dl class="sp-methods">
                             <?php $_sole = count($_shippingRateGroups) == 1; foreach ($_shippingRateGroups as $code => $_rates): ?>
-                                <dt><?php echo $this->getCarrierName($code) ?></dt>
+                                <dt><?php echo $this->escapeHtml($this->getCarrierName($code)) ?></dt>
                                 <dd>
                                     <ul>
                                     <?php $_sole = $_sole && count($_rates) == 1; foreach ($_rates as $_rate): ?>
                                         <li<?php if ($_rate->getErrorMessage()) echo ' class="error-msg"' ?>>
                                            <?php if ($_rate->getErrorMessage()): ?>
-                                                <?php echo $_rate->getCarrierTitle() ?>: <?php echo $_rate->getErrorMessage() ?>
+                                                <?php echo $this->escapeHtml($_rate->getCarrierTitle()) ?>: <?php echo $this->escapeHtml($_rate->getErrorMessage()) ?>
                                            <?php else: ?>
                                                 <?php if ($_sole) : ?>
                                                 <span class="no-display"><input type="radio" name="shipping_method[<?php echo $_address->getId() ?>]" value="<?php echo $this->escapeHtml($_rate->getCode()) ?>" id="s_method_<?php echo $_address->getId() ?>_<?php echo $_rate->getCode() ?>" checked="checked"/></span>
                                                 <?php else: ?>
-                                                <input type="radio" name="shipping_method[<?php echo $_address->getId() ?>]" value="<?php echo $this->escapeHtml($_rate->getCode()) ?>" id="s_method_<?php echo $_address->getId() ?>_<?php echo $_rate->getCode() ?>"<?php if($_rate->getCode()===$this->getAddressShippingMethod($_address)) echo ' checked="checked"' ?> class="radio" />
+                                                <input type="radio" name="shipping_method[<?php echo $_address->getId() ?>]" value="<?php echo $_rate->getCode() ?>" id="s_method_<?php echo $_address->getId() ?>_<?php echo $_rate->getCode() ?>"<?php if($_rate->getCode()===$this->getAddressShippingMethod($_address)) echo ' checked="checked"' ?> class="radio" />
                                                 <?php endif; ?>
-                                                <label for="s_method_<?php echo $_address->getId() ?>_<?php echo $_rate->getCode() ?>"><?php echo $_rate->getMethodTitle() ?>
+                                                <label for="s_method_<?php echo $_address->getId() ?>_<?php echo $_rate->getCode() ?>"><?php echo $this->escapeHtml($_rate->getMethodTitle()) ?>
                                                 <?php $_excl = $this->getShippingPrice($_address, $_rate->getPrice(), $this->helper('Mage_Tax_Helper_Data')->displayShippingPriceIncludingTax()); ?>
                                                 <?php $_incl = $this->getShippingPrice($_address, $_rate->getPrice(), true); ?>
                                                 <?php echo $_excl; ?>
diff --git a/app/code/core/Mage/Checkout/view/frontend/onepage.phtml b/app/code/core/Mage/Checkout/view/frontend/onepage.phtml
index d8a6eddc50a1b2786994f9a27295075b9620d462..6f6cf8ca1df2dca6c49bb85b8c73760769b725ab 100644
--- a/app/code/core/Mage/Checkout/view/frontend/onepage.phtml
+++ b/app/code/core/Mage/Checkout/view/frontend/onepage.phtml
@@ -29,10 +29,9 @@
 </div>
 <script type="text/javascript" src="<?php echo $this->getSkinUrl('Mage_Checkout::onepage/accordion.js') ?>"></script>
 <script type="text/javascript" src="<?php echo $this->getSkinUrl('Mage_Checkout::opcheckout.js') ?>"></script>
-<script type="text/javascript">countryRegions = <?php echo $this->helper('Mage_Directory_Helper_Data')->getRegionJson() ?></script>
 <ol class="opc" id="checkoutSteps">
 <?php $i=0; foreach($this->getSteps() as $_stepId => $_stepInfo): ?>
-<?php if (!$this->getChild($_stepId) || !$this->getChild($_stepId)->isShow()): continue; endif; $i++ ?>
+<?php if (!$this->getChildBlock($_stepId) || !$this->getChildBlock($_stepId)->isShow()): continue; endif; $i++ ?>
     <li id="opc-<?php echo $_stepId ?>" class="section<?php echo !empty($_stepInfo['allow'])?' allow':'' ?><?php echo !empty($_stepInfo['complete'])?' saved':'' ?>">
         <div class="step-title">
             <span class="number"><?php echo $i ?></span>
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 751277fc7a2f75ecc74e2a0650f1d6e29b17065a..7cb6b4b063be6f8734c4907cb7440afd2e2da6ac 100644
--- a/app/code/core/Mage/Checkout/view/frontend/onepage/billing.phtml
+++ b/app/code/core/Mage/Checkout/view/frontend/onepage/billing.phtml
@@ -44,7 +44,7 @@
                     <div class="field">
                         <label for="billing:company"><?php echo $this->__('Company') ?></label>
                         <div class="input-box">
-                            <input type="text" id="billing:company" name="billing[company]" value="<?php echo $this->escapeHtml($this->getAddress()->getCompany()) ?>" title="<?php echo $this->__('Company') ?>" class="input-text" />
+                            <input type="text" id="billing:company" name="billing[company]" value="<?php echo $this->escapeHtml($this->getAddress()->getCompany()) ?>" title="<?php echo $this->__('Company') ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('company') ?>" />
                         </div>
                     </div>
         <?php if(!$this->isCustomerLoggedIn()): ?>
@@ -59,7 +59,7 @@
                 <li class="wide">
                     <label for="billing:street1" class="required"><em>*</em><?php echo $this->__('Address') ?></label>
                     <div class="input-box">
-                        <input type="text" title="<?php echo $this->__('Street Address') ?>" name="billing[street][]" id="billing:street1" value="<?php echo $this->escapeHtml($this->getAddress()->getStreet(1)) ?>" class="input-text required-entry" />
+                        <input type="text" title="<?php echo $this->__('Street Address') ?>" name="billing[street][]" id="billing:street1" value="<?php echo $this->escapeHtml($this->getAddress()->getStreet(1)) ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('street') ?>" />
                     </div>
                 </li>
         <?php for ($_i=2, $_n=$this->helper('Mage_Customer_Helper_Address')->getStreetLines(); $_i<=$_n; $_i++): ?>
@@ -72,14 +72,14 @@
                 <li class="wide">
                     <label for="billing:vat_id"><?php echo $this->__('VAT Number') ?></label>
                     <div class="input-box">
-                        <input type="text" id="billing:vat_id" name="billing[vat_id]" value="<?php echo $this->escapeHtml($this->getAddress()->getVatId()) ?>" title="<?php echo $this->__('VAT Number') ?>" class="input-text" />
+                        <input type="text" id="billing:vat_id" name="billing[vat_id]" value="<?php echo $this->escapeHtml($this->getAddress()->getVatId()) ?>" title="<?php echo $this->__('VAT Number') ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('vat_id') ?>" />
                     </div>
                 </li>
                 <li class="fields">
                     <div class="field">
                         <label for="billing:city" class="required"><em>*</em><?php echo $this->__('City') ?></label>
                         <div class="input-box">
-                            <input type="text" title="<?php echo $this->__('City') ?>" name="billing[city]" value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>" class="input-text required-entry" id="billing:city" />
+                            <input type="text" title="<?php echo $this->__('City') ?>" name="billing[city]" value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('city') ?>" id="billing:city" />
                         </div>
                     </div>
                     <div class="field">
@@ -93,7 +93,7 @@
                                 $('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" style="display:none;" />
+                            <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>
                 </li>
@@ -101,7 +101,7 @@
                     <div class="field">
                         <label for="billing:postcode" class="required"><em>*</em><?php echo $this->__('Zip/Postal Code') ?></label>
                         <div class="input-box">
-                            <input type="text" title="<?php echo $this->__('Zip/Postal Code') ?>" name="billing[postcode]" id="billing:postcode" value="<?php echo $this->escapeHtml($this->getAddress()->getPostcode()) ?>" class="input-text validate-zip-international required-entry" />
+                            <input type="text" title="<?php echo $this->__('Zip/Postal Code') ?>" name="billing[postcode]" id="billing:postcode" value="<?php echo $this->escapeHtml($this->getAddress()->getPostcode()) ?>" class="input-text validate-zip-international <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('postcode') ?>" />
                         </div>
                     </div>
                     <div class="field">
@@ -115,13 +115,13 @@
                     <div class="field">
                         <label for="billing:telephone" class="required"><em>*</em><?php echo $this->__('Telephone') ?></label>
                         <div class="input-box">
-                            <input type="text" name="billing[telephone]" value="<?php echo $this->escapeHtml($this->getAddress()->getTelephone()) ?>" title="<?php echo $this->__('Telephone') ?>" class="input-text required-entry" id="billing:telephone" />
+                            <input type="text" name="billing[telephone]" value="<?php echo $this->escapeHtml($this->getAddress()->getTelephone()) ?>" title="<?php echo $this->__('Telephone') ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('telephone') ?>" id="billing:telephone" />
                         </div>
                     </div>
                     <div class="field">
                         <label for="billing:fax"><?php echo $this->__('Fax') ?></label>
                         <div class="input-box">
-                            <input type="text" name="billing[fax]" value="<?php echo $this->escapeHtml($this->getAddress()->getFax()) ?>" title="<?php echo $this->__('Fax') ?>" class="input-text" id="billing:fax" />
+                            <input type="text" name="billing[fax]" value="<?php echo $this->escapeHtml($this->getAddress()->getFax()) ?>" title="<?php echo $this->__('Fax') ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('fax') ?>" id="billing:fax" />
                         </div>
                     </div>
                 </li>
@@ -205,6 +205,6 @@
     //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', countryRegions, undefined, 'billing:postcode');
+    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>
diff --git a/app/code/core/Mage/Checkout/view/frontend/onepage/payment.phtml b/app/code/core/Mage/Checkout/view/frontend/onepage/payment.phtml
index 94e51a966ef57c41c8f62c82cf48aaac9e573966..23b2413774f451ccd7611a9d6b4eeed2a2361675 100644
--- a/app/code/core/Mage/Checkout/view/frontend/onepage/payment.phtml
+++ b/app/code/core/Mage/Checkout/view/frontend/onepage/payment.phtml
@@ -68,6 +68,6 @@
 </script>
 <script type="text/javascript">
 //<![CDATA[
-    payment.currentMethod = "<?php echo $this->getChild('methods')->getSelectedMethodCode() ?>";
+    payment.currentMethod = "<?php echo $this->getChildBlock('methods')->getSelectedMethodCode() ?>";
 //]]>
 </script>
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 8c1e116ab946b256b4dfe39ddf9a9bbb6489c918..80e0d644ac83f91dd69faf022574636cd696952d 100644
--- a/app/code/core/Mage/Checkout/view/frontend/onepage/shipping.phtml
+++ b/app/code/core/Mage/Checkout/view/frontend/onepage/shipping.phtml
@@ -43,22 +43,14 @@
                         <div class="fields">
                             <label for="shipping:company"><?php echo $this->__('Company') ?></label>
                             <div class="input-box">
-                                <input type="text" id="shipping:company" name="shipping[company]" value="<?php echo $this->escapeHtml($this->getAddress()->getCompany()) ?>" title="<?php echo $this->__('Company') ?>" class="input-text" onchange="shipping.setSameAsBilling(false);" />
+                                <input type="text" id="shipping:company" name="shipping[company]" value="<?php echo $this->escapeHtml($this->getAddress()->getCompany()) ?>" title="<?php echo $this->__('Company') ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('company') ?>" onchange="shipping.setSameAsBilling(false);" />
                             </div>
                         </div>
-            <?php if(false): ?>
-                        <div class="fields">
-                            <label for="shipping:email" class="required"><em>*</em><?php echo $this->__('Email Address') ?></label>
-                            <div class="input-box">
-                                <input type="text" name="shipping[email]" id="shipping:email" value="<?php echo $this->escapeHtml($this->getAddress()->getEmail()) ?>" title="<?php echo $this->__('Email Address') ?>" class="input-text validate-email required-entry" />
-                            </div>
-                        </div>
-            <?php endif ?>
                     </li>
                     <li class="wide">
                         <label for="shipping:street1" class="required"><em>*</em><?php echo $this->__('Address') ?></label>
                         <div class="input-box">
-                            <input type="text" title="<?php echo $this->__('Street Address') ?>" name="shipping[street][]" id="shipping:street1" value="<?php echo $this->escapeHtml($this->getAddress()->getStreet(1)) ?>" class="input-text required-entry" onchange="shipping.setSameAsBilling(false);" />
+                            <input type="text" title="<?php echo $this->__('Street Address') ?>" name="shipping[street][]" id="shipping:street1" value="<?php echo $this->escapeHtml($this->getAddress()->getStreet(1)) ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('street') ?>" onchange="shipping.setSameAsBilling(false);" />
                         </div>
                         </li>
             <?php for ($_i=2, $_n=$this->helper('Mage_Customer_Helper_Address')->getStreetLines(); $_i<=$_n; $_i++): ?>
@@ -71,14 +63,14 @@
                     <li class="wide">
                         <label for="billing:vat_id"><?php echo $this->__('VAT Number'); ?></label>
                         <div class="input-box">
-                            <input type="text" id="shipping:vat_id" name="shipping[vat_id]" value="<?php echo $this->escapeHtml($this->getAddress()->getVatId()); ?>" title="<?php echo $this->__('VAT Number'); ?>" class="input-text" />
+                            <input type="text" id="shipping:vat_id" name="shipping[vat_id]" value="<?php echo $this->escapeHtml($this->getAddress()->getVatId()); ?>" title="<?php echo $this->__('VAT Number'); ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('vat_id') ?>" />
                         </div>
                     </li>
                     <li class="fields">
                         <div class="field">
                             <label for="shipping:city" class="required"><em>*</em><?php echo $this->__('City') ?></label>
                             <div class="input-box">
-                                <input type="text" title="<?php echo $this->__('City') ?>" name="shipping[city]" value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>" class="input-text required-entry" id="shipping:city" onchange="shipping.setSameAsBilling(false);" />
+                                <input type="text" title="<?php echo $this->__('City') ?>" name="shipping[city]" value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('city') ?>" id="shipping:city" onchange="shipping.setSameAsBilling(false);" />
                             </div>
                         </div>
                         <div class="field">
@@ -92,7 +84,7 @@
                                     $('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" style="display:none;" />
+                                <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>
                     </li>
@@ -100,7 +92,7 @@
                         <div class="field">
                             <label for="shipping:postcode" class="required"><em>*</em><?php echo $this->__('Zip/Postal Code') ?></label>
                             <div class="input-box">
-                                <input type="text" title="<?php echo $this->__('Zip/Postal Code') ?>" name="shipping[postcode]" id="shipping:postcode" value="<?php echo $this->escapeHtml($this->getAddress()->getPostcode()) ?>" class="input-text validate-zip-international required-entry" onchange="shipping.setSameAsBilling(false);" />
+                                <input type="text" title="<?php echo $this->__('Zip/Postal Code') ?>" name="shipping[postcode]" id="shipping:postcode" value="<?php echo $this->escapeHtml($this->getAddress()->getPostcode()) ?>" class="input-text validate-zip-international <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('postcode') ?>" onchange="shipping.setSameAsBilling(false);" />
                             </div>
                         </div>
                         <div class="field">
@@ -114,13 +106,13 @@
                         <div class="field">
                             <label for="shipping:telephone" class="required"><em>*</em><?php echo $this->__('Telephone') ?></label>
                             <div class="input-box">
-                                <input type="text" name="shipping[telephone]" value="<?php echo $this->escapeHtml($this->getAddress()->getTelephone()) ?>" title="<?php echo $this->__('Telephone') ?>" class="input-text required-entry" id="shipping:telephone" onchange="shipping.setSameAsBilling(false);" />
+                                <input type="text" name="shipping[telephone]" value="<?php echo $this->escapeHtml($this->getAddress()->getTelephone()) ?>" title="<?php echo $this->__('Telephone') ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('telephone') ?>" id="shipping:telephone" onchange="shipping.setSameAsBilling(false);" />
                             </div>
                         </div>
                         <div class="field">
                             <label for="shipping:fax"><?php echo $this->__('Fax') ?></label>
                             <div class="input-box">
-                                <input type="text" name="shipping[fax]" value="<?php echo $this->escapeHtml($this->getAddress()->getFax()) ?>" title="<?php echo $this->__('Fax') ?>" class="input-text" id="shipping:fax" onchange="shipping.setSameAsBilling(false);" />
+                                <input type="text" name="shipping[fax]" value="<?php echo $this->escapeHtml($this->getAddress()->getFax()) ?>" title="<?php echo $this->__('Fax') ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('fax') ?>" id="shipping:fax" onchange="shipping.setSameAsBilling(false);" />
                             </div>
                         </div>
                     </li>
@@ -155,6 +147,6 @@
     //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', countryRegions, undefined, 'shipping:postcode');
+    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>
diff --git a/app/code/core/Mage/Checkout/view/frontend/onepage/shipping_method/available.phtml b/app/code/core/Mage/Checkout/view/frontend/onepage/shipping_method/available.phtml
index 436d9dbc3df0d3c0080791e9e41f4f640d578284..66a0e7b735fbd28848d27673391ce75525fc3e54 100644
--- a/app/code/core/Mage/Checkout/view/frontend/onepage/shipping_method/available.phtml
+++ b/app/code/core/Mage/Checkout/view/frontend/onepage/shipping_method/available.phtml
@@ -24,20 +24,22 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 ?>
-<?php if (!($_shippingRateGroups = $this->getShippingRates())): ?>
+<?php /** @var $this Mage_Checkout_Block_Onepage_Shipping_Method_Available */ ?>
+<?php $_shippingRateGroups = $this->getShippingRates(); ?>
+<?php if (!$_shippingRateGroups): ?>
     <p><?php echo $this->__('Sorry, no quotes are available for this order at this time.') ?></p>
 <?php else: ?>
     <dl class="sp-methods">
     <?php $shippingCodePrice = array(); ?>
     <?php $_sole = count($_shippingRateGroups) == 1; foreach ($_shippingRateGroups as $code => $_rates): ?>
-        <dt><?php echo $this->getCarrierName($code) ?></dt>
+        <dt><?php echo $this->escapeHtml($this->getCarrierName($code)) ?></dt>
         <dd>
             <ul>
             <?php $_sole = $_sole && count($_rates) == 1; foreach ($_rates as $_rate): ?>
                 <?php $shippingCodePrice[] = "'".$_rate->getCode()."':".(float)$_rate->getPrice(); ?>
                 <li>
                    <?php if ($_rate->getErrorMessage()): ?>
-                    <ul class="messages"><li class="error-msg"><ul><li><?php echo $_rate->getErrorMessage() ?></li></ul></li></ul>
+                    <ul class="messages"><li class="error-msg"><ul><li><?php echo $this->escapeHtml($_rate->getErrorMessage()) ?></li></ul></li></ul>
                    <?php else: ?>
                         <?php if ($_sole) : ?>
                         <span class="no-display"><input name="shipping_method" type="radio" value="<?php echo $_rate->getCode() ?>" id="s_method_<?php echo $_rate->getCode() ?>" checked="checked" /></span>
@@ -53,7 +55,7 @@
                         <?php endif; ?>
 
                         <?php endif; ?>
-                        <label for="s_method_<?php echo $_rate->getCode() ?>"><?php echo $_rate->getMethodTitle() ?>
+                        <label for="s_method_<?php echo $_rate->getCode() ?>"><?php echo $this->escapeHtml($_rate->getMethodTitle()) ?>
                         <?php $_excl = $this->getShippingPrice($_rate->getPrice(), $this->helper('Mage_Tax_Helper_Data')->displayShippingPriceIncludingTax()); ?>
                         <?php $_incl = $this->getShippingPrice($_rate->getPrice(), true); ?>
                         <?php echo $_excl; ?>
diff --git a/app/code/core/Mage/Checkout/view/frontend/opcheckout.js b/app/code/core/Mage/Checkout/view/frontend/opcheckout.js
index d792a8cda8ae7d3cf487b0bdc0c9cda59949783f..115db07a0ae2d533d1d0813fc70da369c8930d07 100644
--- a/app/code/core/Mage/Checkout/view/frontend/opcheckout.js
+++ b/app/code/core/Mage/Checkout/view/frontend/opcheckout.js
@@ -136,7 +136,7 @@ Checkout.prototype = {
             this.gotoSection('billing');
         }
         else{
-            alert(Translator.translate('Please choose to register or to checkout as a guest'));
+            alert(Translator.translate('Please choose to register or to checkout as a guest').stripTags());
             return false;
         }
         document.body.fire('login:setMethod', {method : this.method});
@@ -545,7 +545,7 @@ ShippingMethod.prototype = {
     validate: function() {
         var methods = document.getElementsByName('shipping_method');
         if (methods.length==0) {
-            alert(Translator.translate('Your order cannot be completed at this time as there is no shipping methods available for it. Please make necessary changes in your shipping address.'));
+            alert(Translator.translate('Your order cannot be completed at this time as there is no shipping methods available for it. Please make necessary changes in your shipping address.').stripTags());
             return false;
         }
 
@@ -558,7 +558,7 @@ ShippingMethod.prototype = {
                 return true;
             }
         }
-        alert(Translator.translate('Please specify shipping method.'));
+        alert(Translator.translate('Please specify shipping method.').stripTags());
         return false;
     },
 
@@ -732,7 +732,7 @@ Payment.prototype = {
         }
         var methods = document.getElementsByName('payment[method]');
         if (methods.length==0) {
-            alert(Translator.translate('Your order cannot be completed at this time as there is no payment methods available for it.'));
+            alert(Translator.translate('Your order cannot be completed at this time as there is no payment methods available for it.').stripTags());
             return false;
         }
         for (var i=0; i<methods.length; i++) {
@@ -744,7 +744,7 @@ Payment.prototype = {
         if (result) {
             return true;
         }
-        alert(Translator.translate('Please specify payment method.'));
+        alert(Translator.translate('Please specify payment method.').stripTags());
         return false;
     },
 
diff --git a/app/code/core/Mage/Checkout/view/frontend/total/tax.phtml b/app/code/core/Mage/Checkout/view/frontend/total/tax.phtml
index 5a4c01e829196e71b609bab8829e643a91e9217f..ec3308684e93561659dcfe49b0b486d3f68033c1 100644
--- a/app/code/core/Mage/Checkout/view/frontend/total/tax.phtml
+++ b/app/code/core/Mage/Checkout/view/frontend/total/tax.phtml
@@ -37,7 +37,7 @@
                 <?php foreach ($rates as $rate): ?>
                 <tr class="summary-details-<?php echo $taxIter; ?> summary-details<?php if ($isTop): echo ' summary-details-first'; endif; ?>" style="display:none;">
                     <td class="a-right" style="<?php echo $this->getTotal()->getStyle() ?>" colspan="<?php echo $this->getColspan(); ?>">
-                        <?php echo $rate['title']; ?>
+                        <?php echo $this->escapeHtml($rate['title']); ?>
                         <?php if (!is_null($rate['percent'])): ?>
                             (<?php echo (float)$rate['percent']; ?>%)
                         <?php endif; ?>
diff --git a/app/code/core/Mage/Cms/Helper/Page.php b/app/code/core/Mage/Cms/Helper/Page.php
index 5cb46256381ea0d974347cdc02efbe33afa62e4a..feada094239bee3ee438326841d156de4b5603e5 100644
--- a/app/code/core/Mage/Cms/Helper/Page.php
+++ b/app/code/core/Mage/Cms/Helper/Page.php
@@ -88,10 +88,7 @@ class Mage_Cms_Helper_Page extends Mage_Core_Helper_Abstract
                 Mage::getDesign()->setDesignTheme($page->getCustomTheme());
             }
         }
-
-        $action->getLayout()->getUpdate()
-            ->addHandle('default')
-            ->addHandle('cms_page');
+        $action->addPageLayoutHandles(array('id' => $page->getIdentifier()));
 
         $action->addActionLayoutHandles();
         if ($page->getRootTemplate()) {
diff --git a/app/code/core/Mage/Cms/Model/Resource/Block.php b/app/code/core/Mage/Cms/Model/Resource/Block.php
index 51e135031feeed2a012d4a9e8d29ab96dff09732..5f77a3e3b35f91897545878292bd149c5557b4a8 100755
--- a/app/code/core/Mage/Cms/Model/Resource/Block.php
+++ b/app/code/core/Mage/Cms/Model/Resource/Block.php
@@ -148,6 +148,7 @@ class Mage_Cms_Model_Resource_Block extends Mage_Core_Model_Resource_Db_Abstract
         if ($object->getId()) {
             $stores = $this->lookupStoreIds($object->getId());
             $object->setData('store_id', $stores);
+            $object->setData('stores', $stores);
         }
 
         return parent::_afterLoad($object);
diff --git a/app/code/core/Mage/Cms/data/cms_setup/data-upgrade-1.6.0.0.0-1.6.0.0.1.php b/app/code/core/Mage/Cms/data/cms_setup/data-upgrade-1.6.0.0.0-1.6.0.0.1.php
new file mode 100644
index 0000000000000000000000000000000000000000..6f251c416058a6e22de9d8c7b660098edaf238dd
--- /dev/null
+++ b/app/code/core/Mage/Cms/data/cms_setup/data-upgrade-1.6.0.0.0-1.6.0.0.1.php
@@ -0,0 +1,270 @@
+<?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_Cms
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+
+$pageContent = <<<EOD
+<p>
+    <b>
+        Please replace this text with you Privacy Policy.
+        Please add any additional cookies your website uses below (e.g., Google Analytics)
+    </b>
+</p>
+<p>
+    This privacy policy sets out how {{config path="general/store_information/name"}} uses and protects any information
+    that you give {{config path="general/store_information/name"}} when you use this website.
+    {{config path="general/store_information/name"}} is committed to ensuring that your privacy is protected.
+    Should we ask you to provide certain information by which you can be identified when using this website,
+    then you can be assured that it will only be used in accordance with this privacy statement.
+    {{config path="general/store_information/name"}} may change this policy from time to time by updating this page.
+    You should check this page from time to time to ensure that you are happy with any changes.
+</p>
+<h2>What we collect</h2>
+<p>We may collect the following information:</p>
+<ul>
+    <li>name</li>
+    <li>contact information including email address</li>
+    <li>demographic information such as postcode, preferences and interests</li>
+    <li>other information relevant to customer surveys and/or offers</li>
+</ul>
+<p>
+    For the exhaustive list of cookies we collect see the <a href="#list">List of cookies we collect</a> section.
+</p>
+<h2>What we do with the information we gather</h2>
+<p>
+    We require this information to understand your needs and provide you with a better service,
+    and in particular for the following reasons:
+</p>
+<ul>
+    <li>Internal record keeping.</li>
+    <li>We may use the information to improve our products and services.</li>
+    <li>
+        We may periodically send promotional emails about new products, special offers or other information which we
+        think you may find interesting using the email address which you have provided.
+    </li>
+    <li>
+        From time to time, we may also use your information to contact you for market research purposes.
+        We may contact you by email, phone, fax or mail. We may use the information to customise the website
+        according to your interests.
+    </li>
+</ul>
+<h2>Security</h2>
+<p>
+    We are committed to ensuring that your information is secure. In order to prevent unauthorised access or disclosure,
+    we have put in place suitable physical, electronic and managerial procedures to safeguard and secure
+    the information we collect online.
+</p>
+<h2>How we use cookies</h2>
+<p>
+    A cookie is a small file which asks permission to be placed on your computer's hard drive.
+    Once you agree, the file is added and the cookie helps analyse web traffic or lets you know when you visit
+    a particular site. Cookies allow web applications to respond to you as an individual. The web application
+    can tailor its operations to your needs, likes and dislikes by gathering and remembering information about
+    your preferences.
+</p>
+<p>
+    We use traffic log cookies to identify which pages are being used. This helps us analyse data about web page traffic
+    and improve our website in order to tailor it to customer needs. We only use this information for statistical
+    analysis purposes and then the data is removed from the system.
+</p>
+<p>
+    Overall, cookies help us provide you with a better website, by enabling us to monitor which pages you find useful
+    and which you do not. A cookie in no way gives us access to your computer or any information about you,
+    other than the data you choose to share with us. You can choose to accept or decline cookies.
+    Most web browsers automatically accept cookies, but you can usually modify your browser setting
+    to decline cookies if you prefer. This may prevent you from taking full advantage of the website.
+</p>
+<h2>Links to other websites</h2>
+<p>
+    Our website may contain links to other websites of interest. However, once you have used these links
+    to leave our site, you should note that we do not have any control over that other website.
+    Therefore, we cannot be responsible for the protection and privacy of any information which you provide whilst
+    visiting such sites and such sites are not governed by this privacy statement.
+    You should exercise caution and look at the privacy statement applicable to the website in question.
+</p>
+<h2>Controlling your personal information</h2>
+<p>You may choose to restrict the collection or use of your personal information in the following ways:</p>
+<ul>
+    <li>
+        whenever you are asked to fill in a form on the website, look for the box that you can click to indicate
+        that you do not want the information to be used by anybody for direct marketing purposes
+    </li>
+    <li>
+        if you have previously agreed to us using your personal information for direct marketing purposes,
+        you may change your mind at any time by writing to or emailing us at
+        {{config path="trans_email/ident_general/email"}}
+    </li>
+</ul>
+<p>
+    We will not sell, distribute or lease your personal information to third parties unless we have your permission
+    or are required by law to do so. We may use your personal information to send you promotional information
+    about third parties which we think you may find interesting if you tell us that you wish this to happen.
+</p>
+<p>
+    You may request details of personal information which we hold about you under the Data Protection Act 1998.
+    A small fee will be payable. If you would like a copy of the information held on you please write to
+    {{config path="general/store_information/address"}}.
+</p>
+<p>
+    If you believe that any information we are holding on you is incorrect or incomplete,
+    please write to or email us as soon as possible, at the above address.
+    We will promptly correct any information found to be incorrect.
+</p>
+<h2><a name="list"></a>List of cookies we collect</h2>
+<p>The table below lists the cookies we collect and what information they store.</p>
+<table class="data-table">
+    <thead>
+        <tr>
+            <th>COOKIE name</th>
+            <th>COOKIE Description</th>
+        </tr>
+    </thead>
+    <tbody>
+        <tr>
+            <th>CART</th>
+            <td>The association with your shopping cart.</td>
+        </tr>
+        <tr>
+            <th>CATEGORY_INFO</th>
+            <td></td>
+        </tr>
+        <tr>
+            <th>COMPARE</th>
+            <td>The items that you have in the Compare Products list.</td>
+        </tr>
+        <tr>
+            <th>CURRENCY</th>
+            <td>Your preferred currency</td>
+        </tr>
+        <tr>
+            <th>CUSTOMER</th>
+            <td>An encrypted version of your customer id with the store.</td>
+        </tr>
+        <tr>
+            <th>CUSTOMER_AUTH</th>
+            <td>An indicator if you are currently logged into the store.</td>
+        </tr>
+        <tr>
+            <th>CUSTOMER_INFO</th>
+            <td>An encrypted version of the customer group you belong to.</td>
+        </tr>
+        <tr>
+            <th>EXTERNAL_NO_CACHE</th>
+            <td></td>
+        </tr>
+        <tr>
+            <th>FRONTEND</th>
+            <td>You sesssion ID on the server.</td>
+        </tr>
+        <tr>
+            <th>GUEST-VIEW</th>
+            <td></td>
+        </tr>
+        <tr>
+            <th>LAST_CATEGORY</th>
+            <td>The last category you visited.</td>
+        </tr>
+        <tr>
+            <th>LAST_PRODUCT</th>
+            <td>The most recent product you have viewed.</td>
+        </tr>
+        <tr>
+            <th>NEWMESSAGE</th>
+            <td></td>
+        </tr>
+        <tr>
+            <th>NO_CACHE</th>
+            <td></td>
+        </tr>
+        <tr>
+            <th>PERSISTENT_SHOPPING_CART</th>
+            <td>A link to information about your cart and viewing history if you have asked the site.</td>
+        </tr>
+        <tr>
+            <th>POLL</th>
+            <td>The ID of any polls you have recently voted in.</td>
+        </tr>
+        <tr>
+            <th>POLLN</th>
+            <td>Information on what polls you have voted on.</td>
+        </tr>
+        <tr>
+            <th>RECENTLYCOMPARED</th>
+            <td>The items that you have recently compared.            </td>
+        </tr>
+        <tr>
+            <th>STF</th>
+            <td>Information on products you have emailed to friends.</td>
+        </tr>
+        <tr>
+            <th>STORE</th>
+            <td>The store view or language you have selected.</td>
+        </tr>
+        <tr>
+            <th>USER_ALLOWED_SAVE_COOKIE</th>
+            <td>Indicates whether a customer allowed to use cookies.</td>
+        </tr>
+        <tr>
+            <th>VIEWED_PRODUCT_IDS</th>
+            <td>The products that you have recently viewed.</td>
+        </tr>
+        <tr>
+            <th>WISHLIST</th>
+            <td>An encrypted list of products added to your Wishlist.</td>
+        </tr>
+        <tr>
+            <th>WISHLIST_CNT</th>
+            <td>The number of items in your Wishlist.</td>
+        </tr>
+    </tbody>
+</table>
+EOD;
+
+$privacyPageData = array(
+    'title'           => 'Privacy Policy',
+    'content_heading' => 'Privacy Policy',
+    'root_template'   => 'one_column',
+    'identifier'      => 'privacy-policy-cookie-restriction-mode',
+    'content'         => $pageContent,
+    'is_active'       => 1,
+    'stores'          => array(0),
+    'sort_order'      => 0
+);
+
+Mage::getModel('Mage_Cms_Model_Page')->setData($privacyPageData)->save();
+
+$footerLinksBlock = Mage::getModel('Mage_Cms_Model_Block')->load('footer_links','identifier');
+
+if ($footerLinksBlock->getId()) {
+    $content = $footerLinksBlock->getContent();
+    if (preg_match('/<ul>(.*?)<\\/ul>/ims',$content, $matches)) {
+        $content = preg_replace('/<li class="last">/ims', '<li>',$content);
+        $replacment = '<li class="last privacy">'
+            . "<a href=\"{{store direct_url=\"privacy-policy-cookie-restriction-mode\"}}\">"
+            . "Privacy Policy</a></li>\r\n</ul>";
+        $content = preg_replace('/<\\/ul>/ims', $replacment, $content);
+        $footerLinksBlock->setContent($content)->save();
+    }
+}
diff --git a/app/code/core/Mage/Cms/etc/config.xml b/app/code/core/Mage/Cms/etc/config.xml
index 431d8766863a12f6845b654efcdda80a01d35e42..b6f7d1f2eaa65b7fb4d5a131d2f937efe47fd76d 100644
--- a/app/code/core/Mage/Cms/etc/config.xml
+++ b/app/code/core/Mage/Cms/etc/config.xml
@@ -28,7 +28,7 @@
 <config>
     <modules>
         <Mage_Cms>
-            <version>1.6.0.0</version>
+            <version>1.6.0.0.1</version>
         </Mage_Cms>
     </modules>
     <frontend>
diff --git a/app/code/core/Mage/Cms/view/frontend/layout.xml b/app/code/core/Mage/Cms/view/frontend/layout.xml
index 8ccd42c0924f0a267c9b97e3b05de378bfbb0b53..3153795d911d9daef94ee34fb3bca776229b7835 100644
--- a/app/code/core/Mage/Cms/view/frontend/layout.xml
+++ b/app/code/core/Mage/Cms/view/frontend/layout.xml
@@ -51,23 +51,22 @@ Default layout, loads most of the pages
         </reference>
     </print>
 
-    <cms_page translate="label">
+    <cms_page_view translate="label" type="page" parent="default">
         <label>CMS Pages (All)</label>
         <reference name="content">
             <block type="Mage_Core_Block_Template" name="page_content_heading" template="Mage_Cms::content_heading.phtml"/>
-            <block type="Mage_Page_Block_Html_Wrapper" name="cms.wrapper" translate="label">
-                <label>CMS Content Wrapper</label>
-                <action method="setElementClass"><value>std</value></action>
+            <container name="cms.wrapper" label="CMS Content Wrapper" htmlTag="div" htmlClass="std">
                 <block type="Mage_Cms_Block_Page" name="cms_page"/>
-            </block>
+            </container>
         </reference>
-    </cms_page>
+    </cms_page_view>
 
-    <cms_index_index translate="label">
+    <cms_index_index translate="label" type="page" parent="cms_page_view">
         <label>CMS Home Page</label>
     </cms_index_index>
 
-    <cms_index_defaultindex>
+    <cms_index_defaultindex translate="label" type="page" parent="cms_page_view">
+        <label>CMS Home Default Page</label>
         <remove name="right"/>
         <remove name="left"/>
 
@@ -79,11 +78,12 @@ Default layout, loads most of the pages
         </reference>
     </cms_index_defaultindex>
 
-    <cms_index_noroute translate="label">
+    <cms_index_noroute translate="label" type="page" parent="cms_page_view">
         <label>CMS No-Route Page</label>
     </cms_index_noroute>
 
-    <cms_index_defaultnoroute>
+    <cms_index_defaultnoroute translate="label" type="page" parent="cms_page_view">
+        <label>CMS No-Route Default Page</label>
         <remove name="right"/>
         <remove name="left"/>
 
@@ -94,5 +94,4 @@ Default layout, loads most of the pages
             <block type="Mage_Core_Block_Template" name="default_no_route" template="Mage_Cms::default/no-route.phtml"/>
         </reference>
     </cms_index_defaultnoroute>
-
 </layout>
diff --git a/app/code/core/Mage/Connect/view/adminhtml/layout.xml b/app/code/core/Mage/Connect/view/adminhtml/layout.xml
index c15baeb25e7fa2ce52b234d33ee82f5acb1770a9..298618bf5ede241950d76977939c8733fc156c41 100644
--- a/app/code/core/Mage/Connect/view/adminhtml/layout.xml
+++ b/app/code/core/Mage/Connect/view/adminhtml/layout.xml
@@ -56,18 +56,18 @@
     </adminhtml_extension_custom_edit>
     
     <adminhtml_extension_custom_loadtab>
-        <block type="Mage_Core_Block_Text_List" name="root">
+        <container name="root" label="Root">
             <block type="Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Load" name="connect_extension_load_local_package_grid"
                 template="extension/custom/load.phtml">
                 <block type="Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Grid" name="local_package_grid" />
             </block>
-        </block>
+        </container>
     </adminhtml_extension_custom_loadtab>
     
     <adminhtml_extension_custom_grid>
-        <block type="Mage_Core_Block_Text_List" name="root">
+        <container name="root" label="Root">
             <block type="Mage_Connect_Block_Adminhtml_Extension_Custom_Edit_Tab_Grid" name="connect_extension_edit_local_package_grid" />
-        </block>
+        </container>
     </adminhtml_extension_custom_grid>
 </layout>
 
diff --git a/app/code/core/Mage/Contacts/view/frontend/layout.xml b/app/code/core/Mage/Contacts/view/frontend/layout.xml
index 6d6d5073f8afe9aaf0e0da0172a7cf64cde1fc95..8301d359d23c1300738e0e22b8b43b69a3d7ee89 100644
--- a/app/code/core/Mage/Contacts/view/frontend/layout.xml
+++ b/app/code/core/Mage/Contacts/view/frontend/layout.xml
@@ -32,7 +32,7 @@
         </reference>
     </default>
 
-    <contacts_index_index translate="label">
+    <contacts_index_index translate="label" type="page" parent="cms_page_view">
         <label>Contact Us Form</label>
         <reference name="head">
             <action method="setTitle" translate="title" module="Mage_Contacts"><title>Contact Us</title></action>
diff --git a/app/code/core/Mage/Core/Block/Abstract.php b/app/code/core/Mage/Core/Block/Abstract.php
index a86fae89842d554430d9303b3f7da1b50a493d9c..b4cd02cf489756080ef54144a9ae4e8cafa805d4 100644
--- a/app/code/core/Mage/Core/Block/Abstract.php
+++ b/app/code/core/Mage/Core/Block/Abstract.php
@@ -1,5 +1,5 @@
-<?php
-/**
+<?php
+/**
  * Magento
  *
  * NOTICE OF LICENSE
@@ -17,1319 +17,1005 @@
  * 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
+ *
+ * @category    Mage
+ * @package     Mage_Core
  * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
- */
-
-
-/**
- * Base Content Block class
- *
- * For block generation you must define Data source class, data source class method,
- * parameters array and block template
- *
- * @category   Mage
- * @package    Mage_Core
- * @author      Magento Core Team <core@magentocommerce.com>
- */
-abstract class Mage_Core_Block_Abstract extends Varien_Object
-{
-    /**
-     * Cache group Tag
-     */
-    const CACHE_GROUP = 'block_html';
-    /**
-     * Block name in layout
-     *
-     * @var string
-     */
-    protected $_nameInLayout;
-
-    /**
-     * Parent layout of the block
-     *
-     * @var Mage_Core_Model_Layout
-     */
-    protected $_layout;
-
-    /**
-     * Parent block
-     *
-     * @var Mage_Core_Block_Abstract
-     */
-    protected $_parent;
-
-    /**
-     * Short alias of this block that was refered from parent
-     *
-     * @var string
-     */
-    protected $_alias;
-
-    /**
-     * Suffix for name of anonymous block
-     *
-     * @var string
-     */
-    protected $_anonSuffix;
-
-    /**
-     * Contains references to child block objects
-     *
-     * @var array
-     */
-    protected $_children                    = array();
-
-    /**
-     * Sorted children list
-     *
-     * @var array
-     */
-    protected $_sortedChildren              = array();
-
-    /**
-     * Children blocks HTML cache array
-     *
-     * @var array
-     */
-    protected $_childrenHtmlCache           = array();
-
-    /**
-     * Arbitrary groups of child blocks
-     *
-     * @var array
-     */
-    protected $_childGroups                 = array();
-
-    /**
-     * Request object
-     *
-     * @var Zend_Controller_Request_Http
-     */
-    protected $_request;
-
-    /**
-     * Messages block instance
-     *
-     * @var Mage_Core_Block_Messages
-     */
-    protected $_messagesBlock               = null;
-
-    /**
-     * Whether this block was not explicitly named
-     *
-     * @var boolean
-     */
-    protected $_isAnonymous                 = false;
-
-    /**
-     * Parent block
-     *
-     * @var Mage_Core_Block_Abstract
-     */
-    protected $_parentBlock;
-
-    /**
-     * Block html frame open tag
-     * @var string
-     */
-    protected $_frameOpenTag;
-
-    /**
-     * Block html frame close tag
-     * @var string
-     */
-    protected $_frameCloseTag;
-
-    /**
-     * Url object
-     *
-     * @var Mage_Core_Model_Url
-     */
-    protected static $_urlModel;
-
-    /**
-     * @var Varien_Object
-     */
-    private static $_transportObject;
-
-    /**
-     * Array of block sort priority instructions
-     *
-     * @var array
-     */
-    protected $_sortInstructions = array();
-
-    /**
-     * Constructor
-     */
-    public function __construct(array $data= array())
-    {
-        parent::__construct($data);
-        $this->_construct();
-
-    }
-
-    /**
-     * Internal constructor, that is called from real constructor
-     *
-     * Please override this one instead of overriding real __construct constructor
-     *
-     */
-    protected function _construct()
-    {
-        /**
-         * Please override this one instead of overriding real __construct constructor
-         */
-    }
-
-    /**
-     * Retrieve request object
-     *
-     * @return Mage_Core_Controller_Request_Http
-     * @throws Exception
-     */
-    public function getRequest()
-    {
-        $controller = Mage::app()->getFrontController();
-        if ($controller) {
-            $this->_request = $controller->getRequest();
-        } else {
-            throw new Exception(Mage::helper('Mage_Core_Helper_Data')->__("Can't retrieve request object"));
-        }
-        return $this->_request;
-    }
-
-    /**
-     * Retrieve parent block
-     *
-     * @return Mage_Core_Block_Abstract
-     */
-    public function getParentBlock()
-    {
-        return $this->_parentBlock;
-    }
-
-    /**
-     * Set parent block
-     *
-     * @param   Mage_Core_Block_Abstract $block
-     * @return  Mage_Core_Block_Abstract
-     */
-    public function setParentBlock(Mage_Core_Block_Abstract $block)
-    {
-        $this->_parentBlock = $block;
-        return $this;
-    }
-
-    /**
-     * Retrieve current action object
-     *
-     * @return Mage_Core_Controller_Varien_Action
-     */
-    public function getAction()
-    {
-        return Mage::app()->getFrontController()->getAction();
-    }
-
-    /**
-     * Set layout object
-     *
-     * @param   Mage_Core_Model_Layout $layout
-     * @return  Mage_Core_Block_Abstract
-     */
-    public function setLayout(Mage_Core_Model_Layout $layout)
-    {
-        $this->_layout = $layout;
-        Mage::dispatchEvent('core_block_abstract_prepare_layout_before', array('block' => $this));
-        $this->_prepareLayout();
-        Mage::dispatchEvent('core_block_abstract_prepare_layout_after', array('block' => $this));
-        return $this;
-    }
-
-    /**
-     * Preparing global layout
-     *
-     * You can redefine this method in child classes for changing layout
-     *
-     * @return Mage_Core_Block_Abstract
-     */
-    protected function _prepareLayout()
-    {
-        return $this;
-    }
-
-    /**
-     * Retrieve layout object
-     *
-     * @return Mage_Core_Model_Layout
-     */
-    public function getLayout()
-    {
-        return $this->_layout;
-    }
-
-    /**
-     * Check if block is using auto generated (Anonymous) name
-     * @return bool
-     */
-    public function getIsAnonymous()
-    {
-        return $this->_isAnonymous;
-    }
-
-    /**
-     * Set the anonymous flag
-     *
-     * @param  bool $flag
-     * @return Mage_Core_Block_Abstract
-     */
-    public function setIsAnonymous($flag)
-    {
-        $this->_isAnonymous = (bool)$flag;
-        return $this;
-    }
-
-    /**
-     * Returns anonymous block suffix
-     *
-     * @return string
-     */
-    public function getAnonSuffix()
-    {
-        return $this->_anonSuffix;
-    }
-
-    /**
-     * Set anonymous suffix for current block
-     *
-     * @param string $suffix
-     * @return Mage_Core_Block_Abstract
-     */
-    public function setAnonSuffix($suffix)
-    {
-        $this->_anonSuffix = $suffix;
-        return $this;
-    }
-
-    /**
-     * Returns block alias
-     *
-     * @return string
-     */
-    public function getBlockAlias()
-    {
-        return $this->_alias;
-    }
-
-    /**
-     * Set block alias
-     *
-     * @param string $alias
-     * @return Mage_Core_Block_Abstract
-     */
-    public function setBlockAlias($alias)
-    {
-        $this->_alias = $alias;
-        return $this;
-    }
-
-    /**
-     * Set block's name in layout and unsets previous link if such exists.
-     *
-     * @param string $name
-     * @return Mage_Core_Block_Abstract
-     */
-    public function setNameInLayout($name)
-    {
-        if (!empty($this->_nameInLayout) && $this->getLayout()) {
-            $this->getLayout()->unsetBlock($this->_nameInLayout)
-                ->setBlock($name, $this);
-        }
-        $this->_nameInLayout = $name;
-        return $this;
-    }
-
-    /**
-     * Retrieve sorted list of children.
-     *
-     * @return array
-     */
-    public function getSortedChildren()
-    {
-        $this->sortChildren();
-        return $this->_sortedChildren;
-    }
-
-    /**
-     * Set block attribute value
-     *
-     * Wrapper for method "setData"
-     *
-     * @param   string $name
-     * @param   mixed $value
-     * @return  Mage_Core_Block_Abstract
-     */
-    public function setAttribute($name, $value = null)
-    {
-        return $this->setData($name, $value);
-    }
-
-    /**
-     * Set child block
-     *
-     * @param   string $alias
-     * @param   Mage_Core_Block_Abstract $block
-     * @return  Mage_Core_Block_Abstract
-     */
-    public function setChild($alias, $block)
-    {
-        if (is_string($block)) {
-            $block = $this->getLayout()->getBlock($block);
-        }
-        if (!$block) {
-            return $this;
-        }
-
-        if ($block->getIsAnonymous()) {
-            $suffix = $block->getAnonSuffix();
-            if (empty($suffix)) {
-                $suffix = 'child' . sizeof($this->_children);
-            }
-            $blockName = $this->getNameInLayout() . '.' . $suffix;
-
-            if ($this->getLayout()) {
-                $this->getLayout()->unsetBlock($block->getNameInLayout())
-                    ->setBlock($blockName, $block);
-            }
-
-            $block->setNameInLayout($blockName);
-            $block->setIsAnonymous(false);
-
-            if (empty($alias)) {
-                $alias = $blockName;
-            }
-        }
-
-        $block->setParentBlock($this);
-        $block->setBlockAlias($alias);
-        $this->_children[$alias] = $block;
-        return $this;
-    }
-
-    /**
-     * Unset child block
-     *
-     * @param  string $alias
-     * @return Mage_Core_Block_Abstract
-     */
-    public function unsetChild($alias)
-    {
-        if (isset($this->_children[$alias])) {
-            /** @var Mage_Core_Block_Abstract $block */
-            $block = $this->_children[$alias];
-            $name = $block->getNameInLayout();
-            unset($this->_children[$alias]);
-            $key = array_search($name, $this->_sortedChildren);
-            if ($key !== false) {
-                unset($this->_sortedChildren[$key]);
-            }
-        }
-
-        return $this;
-    }
-
-    /**
-     * Call a child and unset it, if callback matched result
-     *
-     * $params will pass to child callback
-     * $params may be array, if called from layout with elements with same name, for example:
-     * ...<foo>value_1</foo><foo>value_2</foo><foo>value_3</foo>
-     *
-     * Or, if called like this:
-     * ...<foo>value_1</foo><bar>value_2</bar><baz>value_3</baz>
-     * - then it will be $params1, $params2, $params3
-     *
-     * It is no difference anyway, because they will be transformed in appropriate way.
-     *
-     * @param string $alias
-     * @param string $callback
-     * @param mixed $result
-     * @param array $params
-     * @return Mage_Core_Block_Abstract
-     */
-    public function unsetCallChild($alias, $callback, $result, $params)
-    {
-        $child = $this->getChild($alias);
-        if ($child) {
-            $args     = func_get_args();
-            $alias    = array_shift($args);
-            $callback = array_shift($args);
-            $result   = (string)array_shift($args);
-            if (!is_array($params)) {
-                $params = $args;
-            }
-
-            if ($result == call_user_func_array(array(&$child, $callback), $params)) {
-                $this->unsetChild($alias);
-            }
-        }
-        return $this;
-    }
-
-    /**
-     * Unset all children blocks
-     *
-     * @return Mage_Core_Block_Abstract
-     */
-    public function unsetChildren()
-    {
-        $this->_children       = array();
-        $this->_sortedChildren = array();
-        return $this;
-    }
-
-    /**
-     * Retrieve child block by name
-     *
-     * @param string $alias
-     * @return array|Mage_Core_Block_Abstract|false
-     */
-    public function getChild($alias = '')
-    {
-        if ($alias === '') {
-            return $this->_children;
-        } elseif (isset($this->_children[$alias])) {
-            return $this->_children[$alias];
-        }
-        return false;
-    }
-
-    /**
-     * Retrieve child block HTML
-     *
-     * @param   string $name
-     * @param   boolean $useCache
-     * @param   boolean $sorted
-     * @return  string
-     */
-    public function getChildHtml($name = '', $useCache = true, $sorted = false)
-    {
-        if ($name === '') {
-            if ($sorted) {
-                $children = array();
-                foreach ($this->getSortedChildren() as $childName) {
-                    $children[$childName] = $this->getLayout()->getBlock($childName);
-                }
-            } else {
-                $children = $this->getChild();
-            }
-            $out = '';
-            foreach ($children as $child) {
-                $out .= $this->_getChildHtml($child->getBlockAlias(), $useCache);
-            }
-            return $out;
-        } else {
-            return $this->_getChildHtml($name, $useCache);
-        }
-    }
-
-    /**
-     * @param string $name          Parent block name
-     * @param string $childName     OPTIONAL Child block name
-     * @param bool $useCache        OPTIONAL Use cache flag
-     * @param bool $sorted          OPTIONAL @see getChildHtml()
-     * @return string
-     */
-    public function getChildChildHtml($name, $childName = '', $useCache = true, $sorted = false)
-    {
-        if (empty($name)) {
-            return '';
-        }
-        $child = $this->getChild($name);
-        if (!$child) {
-            return '';
-        }
-        return $child->getChildHtml($childName, $useCache, $sorted);
-    }
-
-    /**
-     * Obtain sorted child blocks
-     *
-     * @return array
-     */
-    public function getSortedChildBlocks()
-    {
-        $children = array();
-        foreach ($this->getSortedChildren() as $childName) {
-            $children[$childName] = $this->getLayout()->getBlock($childName);
-        }
-        return $children;
-    }
-
-    /**
-     * Retrieve child block HTML
-     *
-     * @param   string $name
-     * @param   boolean $useCache
-     * @return  string
-     */
-    protected function _getChildHtml($name, $useCache = true)
-    {
-        if ($useCache && isset($this->_childrenHtmlCache[$name])) {
-            return $this->_childrenHtmlCache[$name];
-        }
-
-        $child = $this->getChild($name);
-
-        if (!$child) {
-            $html = '';
-        } else {
-            $this->_beforeChildToHtml($name, $child);
-            $html = $child->toHtml();
-        }
-
-        $this->_childrenHtmlCache[$name] = $html;
-        return $html;
-    }
-
-    /**
-     * Prepare child block before generate html
-     *
-     * @param   string $name
-     * @param   Mage_Core_Block_Abstract $child
-     */
-    protected function _beforeChildToHtml($name, $child)
-    {
-    }
-
-    /**
-     * Retrieve block html
-     *
-     * @param   string $name
-     * @return  string
-     */
-    public function getBlockHtml($name)
-    {
-        if (!($layout = $this->getLayout()) && !($layout = $this->getAction()->getLayout())) {
-            return '';
-        }
-        if (!($block = $layout->getBlock($name))) {
-            return '';
-        }
-        return $block->toHtml();
-    }
-
-    /**
-     * Insert child block
-     *
-     * @param   Mage_Core_Block_Abstract|string $block
-     * @param   string $siblingName
-     * @param   boolean $after
-     * @param   string $alias
-     * @return  object $this
-     */
-    public function insert($block, $siblingName = '', $after = false, $alias = '')
-    {
-        if (is_string($block)) {
-            $block = $this->getLayout()->getBlock($block);
-        }
-        if (!$block) {
-            /*
-             * if we don't have block - don't throw exception because
-             * block can simply removed using layout method remove
-             */
-            //Mage::throwException(Mage::helper('Mage_Core_Helper_Data')->__('Invalid block name to set child %s: %s', $alias, $block));
-            return $this;
-        }
-        if ($block->getIsAnonymous()) {
-            $this->setChild('', $block);
-            $name = $block->getNameInLayout();
-        } elseif ('' != $alias) {
-            $this->setChild($alias, $block);
-            $name = $block->getNameInLayout();
-        } else {
-            $name = $block->getNameInLayout();
-            $this->setChild($name, $block);
-        }
-
-        if ($siblingName === '') {
-            if ($after) {
-                array_push($this->_sortedChildren, $name);
-            } else {
-                array_unshift($this->_sortedChildren, $name);
-            }
-        } else {
-            $key = array_search($siblingName, $this->_sortedChildren);
-            if (false !== $key) {
-                if ($after) {
-                    $key++;
-                }
-                array_splice($this->_sortedChildren, $key, 0, $name);
-            } else {
-                if ($after) {
-                    array_push($this->_sortedChildren, $name);
-                } else {
-                    array_unshift($this->_sortedChildren, $name);
-                }
-            }
-
-            $this->_sortInstructions[$name] = array($siblingName, (bool)$after, false !== $key);
-        }
-
-        return $this;
-    }
-
-    /**
-     * Sort block's children
-     *
-     * @param boolean $force force re-sort all children
-     * @return Mage_Core_Block_Abstract
-     */
-    public function sortChildren($force = false)
-    {
-        foreach ($this->_sortInstructions as $name => $list) {
-            list($siblingName, $after, $exists) = $list;
-            if ($exists && !$force) {
-                continue;
-            }
-            $this->_sortInstructions[$name][2] = true;
-
-            $index      = array_search($name, $this->_sortedChildren);
-            $siblingKey = array_search($siblingName, $this->_sortedChildren);
-
-            if ($index === false || $siblingKey === false) {
-                continue;
-            }
-
-            if ($after) {
-                // insert after block
-                if ($index == $siblingKey + 1) {
-                    continue;
-                }
-                // remove sibling from array
-                array_splice($this->_sortedChildren, $index, 1, array());
-                // insert sibling after
-                array_splice($this->_sortedChildren, $siblingKey + 1, 0, array($name));
-            } else {
-                // insert before block
-                if ($index == $siblingKey - 1) {
-                    continue;
-                }
-                // remove sibling from array
-                array_splice($this->_sortedChildren, $index, 1, array());
-                // insert sibling after
-                array_splice($this->_sortedChildren, $siblingKey, 0, array($name));
-            }
-        }
-
-        return $this;
-    }
-
-    /**
-     * Append child block
-     *
-     * @param   Mage_Core_Block_Abstract|string $block
-     * @param   string $alias
-     * @return  Mage_Core_Block_Abstract
-     */
-    public function append($block, $alias = '')
-    {
-        $this->insert($block, '', true, $alias);
-        return $this;
-    }
-
-    /**
-     * Make sure specified block will be registered in the specified child groups
-     *
-     * @param string $groupName
-     * @param Mage_Core_Block_Abstract $child
-     */
-    public function addToChildGroup($groupName, Mage_Core_Block_Abstract $child)
-    {
-        if (!isset($this->_childGroups[$groupName])) {
-            $this->_childGroups[$groupName] = array();
-        }
-        if (!in_array($child->getBlockAlias(), $this->_childGroups[$groupName])) {
-            $this->_childGroups[$groupName][] = $child->getBlockAlias();
-        }
-    }
-
-    /**
-     * Add self to the specified group of parent block
-     *
-     * @param string $groupName
-     * @return Mage_Core_Block_Abstract
-     */
-    public function addToParentGroup($groupName)
-    {
-        $this->getParentBlock()->addToChildGroup($groupName, $this);
-        return $this;
-    }
-
-    /**
-     * Get a group of child blocks
-     *
-     * Returns an array of <alias> => <block>
-     * or an array of <alias> => <callback_result>
-     * The callback currently supports only $this methods and passes the alias as parameter
-     *
-     * @param string $groupName
-     * @param string $callback
-     * @param bool $skipEmptyResults
-     * @return array
-     */
-    public function getChildGroup($groupName, $callback = null, $skipEmptyResults = true)
-    {
-        $result = array();
-        if (!isset($this->_childGroups[$groupName])) {
-            return $result;
-        }
-        foreach ($this->getSortedChildBlocks() as $block) {
-            $alias = $block->getBlockAlias();
-            if (in_array($alias, $this->_childGroups[$groupName])) {
-                if ($callback) {
-                    $row = $this->$callback($alias);
-                    if (!$skipEmptyResults || $row) {
-                        $result[$alias] = $row;
-                    }
-                } else {
-                    $result[$alias] = $block;
-                }
-
-            }
-        }
-        return $result;
-    }
-
-    /**
-     * Get a value from child block by specified key
-     *
-     * @param string $alias
-     * @param string $key
-     * @return mixed
-     */
-    public function getChildData($alias, $key = '')
-    {
-        $child = $this->getChild($alias);
-        if ($child) {
-            return $child->getData($key);
-        }
-    }
-
-    /**
-     * Before rendering html, but after trying to load cache
-     *
-     * @return Mage_Core_Block_Abstract
-     */
-    protected function _beforeToHtml()
-    {
-        return $this;
-    }
-
-    /**
-     * Specify block output frame tags
-     *
-     * @param $openTag
-     * @param $closeTag
-     * @return Mage_Core_Block_Abstract
-     */
-    public function setFrameTags($openTag, $closeTag = null)
-    {
-        $this->_frameOpenTag = $openTag;
-        if ($closeTag) {
-            $this->_frameCloseTag = $closeTag;
-        } else {
-            $this->_frameCloseTag = '/' . $openTag;
-        }
-        return $this;
-    }
-
-    /**
-     * Produce and return block's html output
-     *
-     * It is a final method, but you can override _toHtml() method in descendants if needed.
-     *
-     * @return string
-     */
-    final public function toHtml()
-    {
-        Mage::dispatchEvent('core_block_abstract_to_html_before', array('block' => $this));
-        if (Mage::getStoreConfig('advanced/modules_disable_output/' . $this->getModuleName())) {
-            return '';
-        }
-        $html = $this->_loadCache();
-        if ($html === false) {
-            $translate = Mage::getSingleton('Mage_Core_Model_Translate');
-            /** @var $translate Mage_Core_Model_Translate */
-            if ($this->hasData('translate_inline')) {
-                $translate->setTranslateInline($this->getData('translate_inline'));
-            }
-
-            $this->_beforeToHtml();
-            $html = $this->_toHtml();
-            $this->_saveCache($html);
-
-            if ($this->hasData('translate_inline')) {
-                $translate->setTranslateInline(true);
-            }
-        }
-        $html = $this->_afterToHtml($html);
-
-        /**
-         * Check framing options
-         */
-        if ($this->_frameOpenTag) {
-            $html = '<'.$this->_frameOpenTag.'>'.$html.'<'.$this->_frameCloseTag.'>';
-        }
-
-        /**
-         * Use single transport object instance for all blocks
-         */
-        if (self::$_transportObject === null) {
-            self::$_transportObject = new Varien_Object;
-        }
-        self::$_transportObject->setHtml($html);
-        Mage::dispatchEvent('core_block_abstract_to_html_after',
-                array('block' => $this, 'transport' => self::$_transportObject));
-        $html = self::$_transportObject->getHtml();
-
-        return $html;
-    }
-
-    /**
-     * Processing block html after rendering
-     *
-     * @param   string $html
-     * @return  string
-     */
-    protected function _afterToHtml($html)
-    {
-        return $html;
-    }
-
-    /**
-     * Override this method in descendants to produce html
-     *
-     * @return string
-     */
-    protected function _toHtml()
-    {
-        return '';
-    }
-
-    /**
-     * Returns url model class name
-     *
-     * @return string
-     */
-    protected function _getUrlModelClass()
-    {
-        return 'Mage_Core_Model_Url';
-    }
-
-    /**
-     * Create and return url object
-     *
-     * @return Mage_Core_Model_Url
-     */
-    protected function _getUrlModel()
-    {
-        return Mage::getModel($this->_getUrlModelClass());
-    }
-
-    /**
-     * Generate url by route and parameters
-     *
-     * @param   string $route
-     * @param   array $params
-     * @return  string
-     */
-    public function getUrl($route = '', $params = array())
-    {
-        return $this->_getUrlModel()->getUrl($route, $params);
-    }
-
-    /**
-     * Generate base64-encoded url by route and parameters
-     *
-     * @param   string $route
-     * @param   array $params
-     * @return  string
-     */
-    public function getUrlBase64($route = '', $params = array())
-    {
-        return Mage::helper('Mage_Core_Helper_Data')->urlEncode($this->getUrl($route, $params));
-    }
-
-    /**
-     * Generate url-encoded url by route and parameters
-     *
-     * @param   string $route
-     * @param   array $params
-     * @return  string
-     */
-    public function getUrlEncoded($route = '', $params = array())
-    {
-        return Mage::helper('Mage_Core_Helper_Data')->urlEncode($this->getUrl($route, $params));
-    }
-
-    /**
-     * Retrieve url of skins file
-     *
-     * @param   string $file path to file in skin
-     * @param   array $params
-     * @return  string
-     */
-    public function getSkinUrl($file = null, array $params = array())
-    {
-        return Mage::getDesign()->getSkinUrl($file, $params);
-    }
-
-    /**
-     * Retrieve messages block
-     *
-     * @return Mage_Core_Block_Messages
-     */
-    public function getMessagesBlock()
-    {
-        if (is_null($this->_messagesBlock)) {
-            return $this->getLayout()->getMessagesBlock();
-        }
-        return $this->_messagesBlock;
-    }
-
-    /**
-     * Set messages block
-     *
-     * @param   Mage_Core_Block_Messages $block
-     * @return  Mage_Core_Block_Abstract
-     */
-    public function setMessagesBlock(Mage_Core_Block_Messages $block)
-    {
-        $this->_messagesBlock = $block;
-        return $this;
-    }
-
-    /**
-     * Return block helper
-     *
-     * @param string $type
-     * @return Mage_Core_Block_Abstract
-     */
-    public function getHelper($type)
-    {
-        return $this->getLayout()->getBlockSingleton($type);
-    }
-
-    /**
-     * Returns helper object
-     *
-     * @param string $name
-     * @return Mage_Core_Block_Abstract
-     */
-    public function helper($name)
-    {
-        if ($this->getLayout()) {
-            return $this->getLayout()->helper($name);
-        }
-        return Mage::helper($name);
-    }
-
-    /**
-     * Retrieve formatting date
-     *
-     * @param   string $date
-     * @param   string $format
-     * @param   bool $showTime
-     * @return  string
-     */
-    public function formatDate($date = null, $format =  Mage_Core_Model_Locale::FORMAT_TYPE_SHORT, $showTime = false)
-    {
-        return $this->helper('Mage_Core_Helper_Data')->formatDate($date, $format, $showTime);
-    }
-
-    /**
-     * Retrieve formatting time
-     *
-     * @param   string $time
-     * @param   string $format
-     * @param   bool $showDate
-     * @return  string
-     */
-    public function formatTime($time = null, $format =  Mage_Core_Model_Locale::FORMAT_TYPE_SHORT, $showDate = false)
-    {
-        return $this->helper('Mage_Core_Helper_Data')->formatTime($time, $format, $showDate);
-    }
-
-    /**
-     * Retrieve module name of block
-     *
-     * @return string
-     */
-    public function getModuleName()
-    {
-        $module = $this->getData('module_name');
-        if (is_null($module)) {
-            $class = get_class($this);
-            $module = substr($class, 0, strpos($class, '_Block'));
-            $this->setData('module_name', $module);
-        }
-        return $module;
-    }
-
-    /**
-     * Translate block sentence
-     *
-     * @return string
-     */
-    public function __()
-    {
-        $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);
-    }
-
-    /**
-     * Escape html entities
-     *
-     * @param   string|array $data
-     * @param   array $allowedTags
-     * @return  string
-     */
-    public function escapeHtml($data, $allowedTags = null)
-    {
-        return $this->helper('Mage_Core_Helper_Data')->escapeHtml($data, $allowedTags);
-    }
-
-    /**
-     * Wrapper for standard strip_tags() function with extra functionality for html entities
-     *
-     * @param string $data
-     * @param string $allowableTags
-     * @param bool $allowHtmlEntities
-     * @return string
-     */
-    public function stripTags($data, $allowableTags = null, $allowHtmlEntities = false)
-    {
-        return $this->helper('Mage_Core_Helper_Data')->stripTags($data, $allowableTags, $allowHtmlEntities);
-    }
-
-    /**
-     * Escape html entities in url
-     *
-     * @param string $data
-     * @return string
-     */
-    public function escapeUrl($data)
-    {
-        return $this->helper('Mage_Core_Helper_Data')->escapeUrl($data);
-    }
-
-    /**
-     * Escape quotes in java scripts
-     *
-     * @param mixed $data
-     * @param string $quote
-     * @return mixed
-     */
-    public function jsQuoteEscape($data, $quote = '\'')
-    {
-        return $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape($data, $quote);
-    }
-
-    /**
-     * Alias for getName method.
-     *
-     * @return string
-     */
-    public function getNameInLayout()
-    {
-        return $this->_nameInLayout;
-    }
-
-    /**
-     * Get chilren blocks count
-     * @return int
-     */
-    public function countChildren()
-    {
-        return count($this->_children);
-    }
-
-    /**
-     * Prepare url for save to cache
-     *
-     * @return Mage_Core_Block_Abstract
-     */
-    protected function _beforeCacheUrl()
-    {
-        if (Mage::app()->useCache(self::CACHE_GROUP)) {
-            Mage::app()->setUseSessionVar(true);
-        }
-        return $this;
-    }
-
-    /**
-     * Replace URLs from cache
-     *
-     * @param string $html
-     * @return string
-     */
-    protected function _afterCacheUrl($html)
-    {
-        if (Mage::app()->useCache(self::CACHE_GROUP)) {
-            Mage::app()->setUseSessionVar(false);
-            Magento_Profiler::start('CACHE_URL');
-            $html = Mage::getSingleton($this->_getUrlModelClass())->sessionUrlVar($html);
-            Magento_Profiler::stop('CACHE_URL');
-        }
-        return $html;
-    }
-
-    /**
-     * Get cache key informative items
-     * Provide string array key to share specific info item with FPC placeholder
-     *
-     * @return array
-     */
-    public function getCacheKeyInfo()
-    {
-        return array(
-            $this->getNameInLayout()
-        );
-    }
-
-    /**
-     * Get Key for caching block content
-     *
-     * @return string
-     */
-    public function getCacheKey()
-    {
-        if ($this->hasData('cache_key')) {
-            return $this->getData('cache_key');
-        }
-        /**
-         * don't prevent recalculation by saving generated cache key
-         * because of ability to render single block instance with different data
-         */
-        $key = $this->getCacheKeyInfo();
-        //ksort($key);  // ignore order
-        $key = array_values($key);  // ignore array keys
-        $key = implode('|', $key);
-        $key = sha1($key);
-        return $key;
-    }
-
-    /**
-     * Get tags array for saving cache
-     *
-     * @return array
-     */
-    public function getCacheTags()
-    {
-        if (!$this->hasData('cache_tags')) {
-            $tags = array();
-        } else {
-            $tags = $this->getData('cache_tags');
-        }
-        $tags[] = self::CACHE_GROUP;
-        return $tags;
-    }
-
-    /**
-     * Get block cache life time
-     *
-     * @return int
-     */
-    public function getCacheLifetime()
-    {
-        if (!$this->hasData('cache_lifetime')) {
-            return null;
-        }
-        return $this->getData('cache_lifetime');
-    }
-
-    /**
-     * Load block html from cache storage
-     *
-     * @return string | false
-     */
-    protected function _loadCache()
-    {
-        if (is_null($this->getCacheLifetime()) || !Mage::app()->useCache(self::CACHE_GROUP)) {
-            return false;
-        }
-        $cacheKey = $this->getCacheKey();
-        /** @var $session Mage_Core_Model_Session */
-        $session = Mage::getSingleton('Mage_Core_Model_Session');
-        $cacheData = Mage::app()->loadCache($cacheKey);
-        if ($cacheData) {
-            $cacheData = str_replace(
-                $this->_getSidPlaceholder($cacheKey),
-                $session->getSessionIdQueryParam() . '=' . $session->getEncryptedSessionId(),
-                $cacheData
-            );
-        }
-        return $cacheData;
-    }
-
-    /**
-     * Save block content to cache storage
-     *
-     * @param string $data
-     * @return Mage_Core_Block_Abstract
-     */
-    protected function _saveCache($data)
-    {
-        if (is_null($this->getCacheLifetime()) || !Mage::app()->useCache(self::CACHE_GROUP)) {
-            return false;
-        }
-        $cacheKey = $this->getCacheKey();
-        /** @var $session Mage_Core_Model_Session */
-        $session = Mage::getSingleton('Mage_Core_Model_Session');
-        $data = str_replace(
-            $session->getSessionIdQueryParam() . '=' . $session->getEncryptedSessionId(),
-            $this->_getSidPlaceholder($cacheKey),
-            $data
-        );
-
-        Mage::app()->saveCache($data, $cacheKey, $this->getCacheTags(), $this->getCacheLifetime());
-        return $this;
-    }
-
-    /**
-     * Get SID placeholder for cache
-     *
-     * @param null|string $cacheKey
-     * @return string
-     */
-    protected function _getSidPlaceholder($cacheKey = null)
-    {
-        if (is_null($cacheKey)) {
-            $cacheKey = $this->getCacheKey();
-        }
-
-        return '<!--SID=' . $cacheKey . '-->';
-    }
-
-    /**
-     * Get variable value from view configuration
-     *
-     * Module name can be omitted. If omitted, it will be determined automatically.
-     *
-     * @param string $name variable name
-     * @param string $module optional module name
-     * @return string|false
-     */
-    public function getVar($name, $module = null)
-    {
-        $module = $module ?: $this->getModuleName();
-        return Mage::getDesign()->getViewConfig()->getVarValue($module, $name);
-    }
-}
+ */
+
+
+/**
+ * Base Content Block class
+ *
+ * For block generation you must define Data source class, data source class method,
+ * parameters array and block template
+ *
+ * @category   Mage
+ * @package    Mage_Core
+ * @author      Magento Core Team <core@magentocommerce.com>
+ * @SuppressWarnings(PHPMD.ExcessivePublicCount)
+ * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
+ */
+abstract class Mage_Core_Block_Abstract extends Varien_Object
+{
+    /**
+     * Cache group Tag
+     */
+    const CACHE_GROUP = 'block_html';
+    /**
+     * Block name in layout
+     *
+     * @var string
+     */
+    protected $_nameInLayout;
+
+    /**
+     * Parent layout of the block
+     *
+     * @var Mage_Core_Model_Layout
+     */
+    protected $_layout;
+
+    /**
+     * Request object
+     *
+     * @var Zend_Controller_Request_Http
+     */
+    protected $_request;
+
+    /**
+     * Messages block instance
+     *
+     * @var Mage_Core_Block_Messages
+     */
+    protected $_messagesBlock               = null;
+
+    /**
+     * Block html frame open tag
+     * @var string
+     */
+    protected $_frameOpenTag;
+
+    /**
+     * Block html frame close tag
+     * @var string
+     */
+    protected $_frameCloseTag;
+
+    /**
+     * Url object
+     *
+     * @var Mage_Core_Model_Url
+     */
+    protected static $_urlModel;
+
+    /**
+     * Class constructor
+     *
+     * @param array $data
+     */
+    public function __construct(array $data= array())
+    {
+        parent::__construct($data);
+        $this->_construct();
+
+    }
+
+    /**
+     * Internal constructor, that is called from real constructor
+     *
+     * Please override this one instead of overriding real __construct constructor
+     *
+     */
+    protected function _construct()
+    {
+        /**
+         * Please override this one instead of overriding real __construct constructor
+         */
+    }
+
+    /**
+     * Retrieve request object
+     *
+     * @return Mage_Core_Controller_Request_Http
+     * @throws Exception
+     */
+    public function getRequest()
+    {
+        $controller = Mage::app()->getFrontController();
+        if ($controller) {
+            $this->_request = $controller->getRequest();
+        } else {
+            throw new Exception(Mage::helper('Mage_Core_Helper_Data')->__("Can't retrieve request object"));
+        }
+        return $this->_request;
+    }
+
+    /**
+     * Retrieve parent block
+     *
+     * @return Mage_Core_Block_Abstract|bool
+     */
+    public function getParentBlock()
+    {
+        $layout = $this->getLayout();
+        if (!$layout) {
+            return false;
+        }
+        $parentName = $layout->getParentName($this->getNameInLayout());
+        if ($parentName) {
+            return $layout->getBlock($parentName);
+        }
+        return false;
+    }
+
+    /**
+     * Retrieve current action object
+     *
+     * @return Mage_Core_Controller_Varien_Action
+     */
+    public function getAction()
+    {
+        return Mage::app()->getFrontController()->getAction();
+    }
+
+    /**
+     * Set layout object
+     *
+     * @param   Mage_Core_Model_Layout $layout
+     * @return  Mage_Core_Block_Abstract
+     */
+    public function setLayout(Mage_Core_Model_Layout $layout)
+    {
+        $this->_layout = $layout;
+        Mage::dispatchEvent('core_block_abstract_prepare_layout_before', array('block' => $this));
+        $this->_prepareLayout();
+        Mage::dispatchEvent('core_block_abstract_prepare_layout_after', array('block' => $this));
+        return $this;
+    }
+
+    /**
+     * Preparing global layout
+     *
+     * You can redefine this method in child classes for changing layout
+     *
+     * @return Mage_Core_Block_Abstract
+     */
+    protected function _prepareLayout()
+    {
+        return $this;
+    }
+
+    /**
+     * Retrieve layout object
+     *
+     * @return Mage_Core_Model_Layout
+     */
+    public function getLayout()
+    {
+        return $this->_layout;
+    }
+
+    /**
+     * Returns block alias
+     *
+     * @return string
+     */
+    public function getBlockAlias()
+    {
+        $layout = $this->getLayout();
+        if (!$layout) {
+            return '';
+        }
+        return $layout->getElementAlias($this->getNameInLayout());
+    }
+
+    /**
+     * Sets/changes name of a block in layout
+     *
+     * @param string $name
+     * @return Mage_Core_Block_Abstract
+     */
+    public function setNameInLayout($name)
+    {
+        $layout = $this->getLayout();
+        if (!empty($this->_nameInLayout) && $layout) {
+            $layout->renameElement($this->_nameInLayout, $name);
+        }
+        $this->_nameInLayout = $name;
+        return $this;
+    }
+
+    /**
+     * Retrieves sorted list of child names
+     *
+     * @return array
+     */
+    public function getChildNames()
+    {
+        $layout = $this->getLayout();
+        if (!$layout) {
+            return array();
+        }
+        return $layout->getChildNames($this->getNameInLayout());
+    }
+
+    /**
+     * Set block attribute value
+     *
+     * Wrapper for method "setData"
+     *
+     * @param   string $name
+     * @param   mixed $value
+     * @return  Mage_Core_Block_Abstract
+     */
+    public function setAttribute($name, $value = null)
+    {
+        return $this->setData($name, $value);
+    }
+
+    /**
+     * Set child block
+     *
+     * @param   string $alias
+     * @param   Mage_Core_Block_Abstract|string $block
+     * @return  Mage_Core_Block_Abstract
+     */
+    public function setChild($alias, $block)
+    {
+        $layout = $this->getLayout();
+        if (!$layout) {
+            return $this;
+        }
+        if (!is_string($block)) {
+            $block = $block->getNameInLayout();
+        }
+        $layout->setChild($this->getNameInLayout(), $block, $alias);
+
+        return $this;
+    }
+
+    /**
+     * Unset child block
+     *
+     * @param  string $alias
+     * @return Mage_Core_Block_Abstract
+     */
+    public function unsetChild($alias)
+    {
+        $layout = $this->getLayout();
+        if (!$layout) {
+            return $this;
+        }
+        $layout->unsetChild($this->getNameInLayout(), $alias);
+        return $this;
+    }
+
+    /**
+     * Call a child and unset it, if callback matched result
+     *
+     * $params will pass to child callback
+     * $params may be array, if called from layout with elements with same name, for example:
+     * ...<foo>value_1</foo><foo>value_2</foo><foo>value_3</foo>
+     *
+     * Or, if called like this:
+     * ...<foo>value_1</foo><bar>value_2</bar><baz>value_3</baz>
+     * - then it will be $params1, $params2, $params3
+     *
+     * It is no difference anyway, because they will be transformed in appropriate way.
+     *
+     * @param string $alias
+     * @param string $callback
+     * @param mixed $result
+     * @param array $params
+     * @return Mage_Core_Block_Abstract
+     */
+    public function unsetCallChild($alias, $callback, $result, $params)
+    {
+        $child = $this->getChildBlock($alias);
+        if ($child) {
+            $args     = func_get_args();
+            $alias    = array_shift($args);
+            $callback = array_shift($args);
+            $result   = (string)array_shift($args);
+            if (!is_array($params)) {
+                $params = $args;
+            }
+
+            if ($result == call_user_func_array(array(&$child, $callback), $params)) {
+                $this->unsetChild($alias);
+            }
+        }
+        return $this;
+    }
+
+    /**
+     * Unset all children blocks
+     *
+     * @return Mage_Core_Block_Abstract
+     */
+    public function unsetChildren()
+    {
+        $layout = $this->getLayout();
+        if (!$layout) {
+            return $this;
+        }
+        $name = $this->getNameInLayout();
+        $children = $layout->getChildNames($name);
+        foreach ($children as $childName) {
+            $layout->unsetChild($name, $childName);
+        }
+        return $this;
+    }
+
+    /**
+     * Retrieve child block by name
+     *
+     * @param string $alias
+     * @return Mage_Core_Block_Abstract|bool
+     */
+    public function getChildBlock($alias)
+    {
+        $layout = $this->getLayout();
+        if (!$layout) {
+            return false;
+        }
+        $name = $layout->getChildName($this->getNameInLayout(), $alias);
+        if ($name) {
+            return $layout->getBlock($name);
+        }
+        return false;
+    }
+
+    /**
+     * Retrieve child block HTML
+     *
+     * @param   string $alias
+     * @param   boolean $useCache
+     * @return  string
+     */
+    public function getChildHtml($alias = '', $useCache = true)
+    {
+        $layout = $this->getLayout();
+        if (!$layout) {
+            return '';
+        }
+        $name = $this->getNameInLayout();
+        $out = '';
+        if ($alias) {
+            $childName = $layout->getChildName($name, $alias);
+            $out = $layout->renderElement($childName, $useCache);
+        } else {
+            foreach ($layout->getChildNames($name) as $child) {
+                $out .= $layout->renderElement($child, $useCache);
+            }
+        }
+
+        return $out;
+    }
+
+    /**
+     * Render output of child child element
+     *
+     * @param string $alias
+     * @param string $childChildAlias
+     * @param bool $useCache
+     * @return string
+     */
+    public function getChildChildHtml($alias, $childChildAlias = '', $useCache = true)
+    {
+        $layout = $this->getLayout();
+        if (!$layout) {
+            return '';
+        }
+        $childName = $layout->getChildName($this->getNameInLayout(), $alias);
+        $out = '';
+        if ($childChildAlias) {
+            $childChildName = $layout->getChildName($childName, $childChildAlias);
+            $out = $layout->renderElement($childChildName, $useCache);
+        } else {
+            foreach ($layout->getChildNames($childName) as $childChild) {
+                $out .= $layout->renderElement($childChild, $useCache);
+            }
+        }
+        return $out;
+    }
+
+    /**
+     * Retrieve block html
+     *
+     * @param   string $name
+     * @return  string
+     */
+    public function getBlockHtml($name)
+    {
+        if (($layout = $this->getLayout()) || ($this->getAction() && ($layout = $this->getAction()->getLayout()))) {
+            $block = $layout->getBlock($name);
+            if ($block) {
+                return $block->toHtml();
+            }
+        }
+        return '';
+    }
+
+    /**
+     * @param Mage_Core_Block_Abstract|string $block
+     * @param string $siblingName
+     * @param bool $after
+     * @param string $alias
+     * @return Mage_Core_Block_Abstract|bool
+     */
+    public function insert($block, $siblingName = '', $after = false, $alias = '')
+    {
+        $layout = $this->getLayout();
+        if (!$layout) {
+            return false;
+        }
+        if ($block instanceof Mage_Core_Block_Abstract) {
+            $block = $block->getNameInLayout();
+        }
+        $this->getLayout()->insertBlock($this->getNameInLayout(), $block, $alias, $after, $siblingName);
+        return $this;
+    }
+
+    /**
+     * @param Mage_Core_Block_Abstract|string $block
+     * @param string $alias
+     * @return Mage_Core_Block_Abstract
+     */
+    public function append($block, $alias = '')
+    {
+        return $this->insert($block, '', true, $alias);
+    }
+
+    /**
+     * Add self to the specified group of parent block
+     *
+     * @param string $groupName
+     * @return Mage_Core_Block_Abstract|bool
+     */
+    public function addToParentGroup($groupName)
+    {
+        $layout = $this->getLayout();
+        if (!$layout) {
+            return false;
+        }
+        $layout->addToParentGroup($this->getNameInLayout(), $groupName);
+
+        return $this;
+    }
+
+    /**
+     * Get a group of child blocks
+     *
+     * Returns an array of <alias> => <block>
+     * or an array of <alias> => <callback_result>
+     * The callback currently supports only $this methods and passes the alias as parameter
+     *
+     * @param string $groupName
+     * @return array
+     */
+    public function getGroupChildNames($groupName)
+    {
+        return $this->getLayout()->getGroupChildNames($this->getNameInLayout(), $groupName);
+    }
+
+    /**
+     * Get a value from child block by specified key
+     *
+     * @param string $alias
+     * @param string $key
+     * @return mixed
+     */
+    public function getChildData($alias, $key = '')
+    {
+        $child = $this->getChildBlock($alias);
+        if ($child) {
+            return $child->getData($key);
+        }
+        return null;
+    }
+
+    /**
+     * Before rendering html, but after trying to load cache
+     *
+     * @return Mage_Core_Block_Abstract
+     */
+    protected function _beforeToHtml()
+    {
+        return $this;
+    }
+
+    /**
+     * Specify block output frame tags
+     *
+     * @param $openTag
+     * @param $closeTag
+     * @return Mage_Core_Block_Abstract
+     */
+    public function setFrameTags($openTag, $closeTag = null)
+    {
+        $this->_frameOpenTag = $openTag;
+        if ($closeTag) {
+            $this->_frameCloseTag = $closeTag;
+        } else {
+            $this->_frameCloseTag = '/' . $openTag;
+        }
+        return $this;
+    }
+
+    /**
+     * Produce and return block's html output
+     *
+     * It is a final method, but you can override _toHtml() method in descendants if needed.
+     *
+     * @return string
+     */
+    final public function toHtml()
+    {
+        Mage::dispatchEvent('core_block_abstract_to_html_before', array('block' => $this));
+        if (Mage::getStoreConfig('advanced/modules_disable_output/' . $this->getModuleName())) {
+            return '';
+        }
+        $html = $this->_loadCache();
+        if ($html === false) {
+            $translate = Mage::getSingleton('Mage_Core_Model_Translate');
+            /** @var $translate Mage_Core_Model_Translate */
+            if ($this->hasData('translate_inline')) {
+                $translate->setTranslateInline($this->getData('translate_inline'));
+            }
+
+            $this->_beforeToHtml();
+            $html = $this->_toHtml();
+            $this->_saveCache($html);
+
+            if ($this->hasData('translate_inline')) {
+                $translate->setTranslateInline(true);
+            }
+        }
+        $html = $this->_afterToHtml($html);
+
+        /**
+         * Check framing options
+         */
+        if ($this->_frameOpenTag) {
+            $html = '<'.$this->_frameOpenTag.'>'.$html.'<'.$this->_frameCloseTag.'>';
+        }
+
+        return $html;
+    }
+
+    /**
+     * Processing block html after rendering
+     *
+     * @param   string $html
+     * @return  string
+     */
+    protected function _afterToHtml($html)
+    {
+        return $html;
+    }
+
+    /**
+     * Override this method in descendants to produce html
+     *
+     * @return string
+     */
+    protected function _toHtml()
+    {
+        return '';
+    }
+
+    /**
+     * Returns url model class name
+     *
+     * @return string
+     */
+    protected function _getUrlModelClass()
+    {
+        return 'Mage_Core_Model_Url';
+    }
+
+    /**
+     * Create and return url object
+     *
+     * @return Mage_Core_Model_Url
+     */
+    protected function _getUrlModel()
+    {
+        return Mage::getModel($this->_getUrlModelClass());
+    }
+
+    /**
+     * Generate url by route and parameters
+     *
+     * @param   string $route
+     * @param   array $params
+     * @return  string
+     */
+    public function getUrl($route = '', $params = array())
+    {
+        return $this->_getUrlModel()->getUrl($route, $params);
+    }
+
+    /**
+     * Generate base64-encoded url by route and parameters
+     *
+     * @param   string $route
+     * @param   array $params
+     * @return  string
+     */
+    public function getUrlBase64($route = '', $params = array())
+    {
+        return Mage::helper('Mage_Core_Helper_Data')->urlEncode($this->getUrl($route, $params));
+    }
+
+    /**
+     * Generate url-encoded url by route and parameters
+     *
+     * @param   string $route
+     * @param   array $params
+     * @return  string
+     */
+    public function getUrlEncoded($route = '', $params = array())
+    {
+        return Mage::helper('Mage_Core_Helper_Data')->urlEncode($this->getUrl($route, $params));
+    }
+
+    /**
+     * Retrieve url of skins file
+     *
+     * @param   string $file path to file in skin
+     * @param   array $params
+     * @return  string
+     */
+    public function getSkinUrl($file = null, array $params = array())
+    {
+        return Mage::getDesign()->getSkinUrl($file, $params);
+    }
+
+    /**
+     * Retrieve messages block
+     *
+     * @return Mage_Core_Block_Messages
+     */
+    public function getMessagesBlock()
+    {
+        if (is_null($this->_messagesBlock)) {
+            return $this->getLayout()->getMessagesBlock();
+        }
+        return $this->_messagesBlock;
+    }
+
+    /**
+     * Set messages block
+     *
+     * @param   Mage_Core_Block_Messages $block
+     * @return  Mage_Core_Block_Abstract
+     */
+    public function setMessagesBlock(Mage_Core_Block_Messages $block)
+    {
+        $this->_messagesBlock = $block;
+        return $this;
+    }
+
+    /**
+     * Return block helper
+     *
+     * @param string $type
+     * @return Mage_Core_Block_Abstract
+     */
+    public function getHelper($type)
+    {
+        return $this->getLayout()->getBlockSingleton($type);
+    }
+
+    /**
+     * Returns helper object
+     *
+     * @param string $name
+     * @return Mage_Core_Block_Abstract
+     */
+    public function helper($name)
+    {
+        if ($this->getLayout()) {
+            return $this->getLayout()->helper($name);
+        }
+        return Mage::helper($name);
+    }
+
+    /**
+     * Retrieve formatting date
+     *
+     * @param   string $date
+     * @param   string $format
+     * @param   bool $showTime
+     * @return  string
+     */
+    public function formatDate($date = null, $format =  Mage_Core_Model_Locale::FORMAT_TYPE_SHORT, $showTime = false)
+    {
+        return $this->helper('Mage_Core_Helper_Data')->formatDate($date, $format, $showTime);
+    }
+
+    /**
+     * Retrieve formatting time
+     *
+     * @param   string $time
+     * @param   string $format
+     * @param   bool $showDate
+     * @return  string
+     */
+    public function formatTime($time = null, $format =  Mage_Core_Model_Locale::FORMAT_TYPE_SHORT, $showDate = false)
+    {
+        return $this->helper('Mage_Core_Helper_Data')->formatTime($time, $format, $showDate);
+    }
+
+    /**
+     * Retrieve module name of block
+     *
+     * @return string
+     */
+    public function getModuleName()
+    {
+        if (!$this->_getData('module_name')) {
+            $this->setData('module_name', self::extractModuleName(get_class($this)));
+        }
+        return $this->_getData('module_name');
+    }
+
+    /**
+     * Extract module name from specified block class name
+     *
+     * @param string $className
+     * @return string
+     */
+    public static function extractModuleName($className)
+    {
+        return substr($className, 0, strpos($className, '_Block'));
+    }
+
+    /**
+     * Translate block sentence
+     *
+     * @return string
+     * @SuppressWarnings(PHPMD.ShortMethodName)
+     */
+    public function __()
+    {
+        $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);
+    }
+
+    /**
+     * Escape html entities
+     *
+     * @param   string|array $data
+     * @param   array $allowedTags
+     * @return  string
+     */
+    public function escapeHtml($data, $allowedTags = null)
+    {
+        return $this->helper('Mage_Core_Helper_Data')->escapeHtml($data, $allowedTags);
+    }
+
+    /**
+     * Wrapper for standard strip_tags() function with extra functionality for html entities
+     *
+     * @param string $data
+     * @param string $allowableTags
+     * @param bool $allowHtmlEntities
+     * @return string
+     */
+    public function stripTags($data, $allowableTags = null, $allowHtmlEntities = false)
+    {
+        return $this->helper('Mage_Core_Helper_Data')->stripTags($data, $allowableTags, $allowHtmlEntities);
+    }
+
+    /**
+     * Escape html entities in url
+     *
+     * @param string $data
+     * @return string
+     */
+    public function escapeUrl($data)
+    {
+        return $this->helper('Mage_Core_Helper_Data')->escapeUrl($data);
+    }
+
+    /**
+     * Escape quotes in java scripts
+     *
+     * @param mixed $data
+     * @param string $quote
+     * @return mixed
+     */
+    public function jsQuoteEscape($data, $quote = '\'')
+    {
+        return $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape($data, $quote);
+    }
+
+    /**
+     * Get block name
+     *
+     * @return string
+     */
+    public function getNameInLayout()
+    {
+        return $this->_nameInLayout;
+    }
+
+    /**
+     * Prepare url for save to cache
+     *
+     * @return Mage_Core_Block_Abstract
+     */
+    protected function _beforeCacheUrl()
+    {
+        if (Mage::app()->useCache(self::CACHE_GROUP)) {
+            Mage::app()->setUseSessionVar(true);
+        }
+        return $this;
+    }
+
+    /**
+     * Replace URLs from cache
+     *
+     * @param string $html
+     * @return string
+     */
+    protected function _afterCacheUrl($html)
+    {
+        if (Mage::app()->useCache(self::CACHE_GROUP)) {
+            Mage::app()->setUseSessionVar(false);
+            Magento_Profiler::start('CACHE_URL');
+            $html = Mage::getSingleton($this->_getUrlModelClass())->sessionUrlVar($html);
+            Magento_Profiler::stop('CACHE_URL');
+        }
+        return $html;
+    }
+
+    /**
+     * Get cache key informative items
+     * Provide string array key to share specific info item with FPC placeholder
+     *
+     * @return array
+     */
+    public function getCacheKeyInfo()
+    {
+        return array(
+            $this->getNameInLayout()
+        );
+    }
+
+    /**
+     * Get Key for caching block content
+     *
+     * @return string
+     */
+    public function getCacheKey()
+    {
+        if ($this->hasData('cache_key')) {
+            return $this->getData('cache_key');
+        }
+        /**
+         * don't prevent recalculation by saving generated cache key
+         * because of ability to render single block instance with different data
+         */
+        $key = $this->getCacheKeyInfo();
+        //ksort($key);  // ignore order
+        $key = array_values($key);  // ignore array keys
+        $key = implode('|', $key);
+        $key = sha1($key);
+        return $key;
+    }
+
+    /**
+     * Get tags array for saving cache
+     *
+     * @return array
+     */
+    public function getCacheTags()
+    {
+        if (!$this->hasData('cache_tags')) {
+            $tags = array();
+        } else {
+            $tags = $this->getData('cache_tags');
+        }
+        $tags[] = self::CACHE_GROUP;
+        return $tags;
+    }
+
+    /**
+     * Get block cache life time
+     *
+     * @return int
+     */
+    public function getCacheLifetime()
+    {
+        if (!$this->hasData('cache_lifetime')) {
+            return null;
+        }
+        return $this->getData('cache_lifetime');
+    }
+
+    /**
+     * Load block html from cache storage
+     *
+     * @return string | false
+     */
+    protected function _loadCache()
+    {
+        if (is_null($this->getCacheLifetime()) || !Mage::app()->useCache(self::CACHE_GROUP)) {
+            return false;
+        }
+        $cacheKey = $this->getCacheKey();
+        /** @var $session Mage_Core_Model_Session */
+        $session = Mage::getSingleton('Mage_Core_Model_Session');
+        $cacheData = Mage::app()->loadCache($cacheKey);
+        if ($cacheData) {
+            $cacheData = str_replace(
+                $this->_getSidPlaceholder($cacheKey),
+                $session->getSessionIdQueryParam() . '=' . $session->getEncryptedSessionId(),
+                $cacheData
+            );
+        }
+        return $cacheData;
+    }
+
+    /**
+     * Save block content to cache storage
+     *
+     * @param string $data
+     * @return Mage_Core_Block_Abstract
+     */
+    protected function _saveCache($data)
+    {
+        if (is_null($this->getCacheLifetime()) || !Mage::app()->useCache(self::CACHE_GROUP)) {
+            return false;
+        }
+        $cacheKey = $this->getCacheKey();
+        /** @var $session Mage_Core_Model_Session */
+        $session = Mage::getSingleton('Mage_Core_Model_Session');
+        $data = str_replace(
+            $session->getSessionIdQueryParam() . '=' . $session->getEncryptedSessionId(),
+            $this->_getSidPlaceholder($cacheKey),
+            $data
+        );
+
+        Mage::app()->saveCache($data, $cacheKey, $this->getCacheTags(), $this->getCacheLifetime());
+        return $this;
+    }
+
+    /**
+     * Get SID placeholder for cache
+     *
+     * @param null|string $cacheKey
+     * @return string
+     */
+    protected function _getSidPlaceholder($cacheKey = null)
+    {
+        if (is_null($cacheKey)) {
+            $cacheKey = $this->getCacheKey();
+        }
+
+        return '<!--SID=' . $cacheKey . '-->';
+    }
+
+    /**
+     * Get variable value from view configuration
+     *
+     * Module name can be omitted. If omitted, it will be determined automatically.
+     *
+     * @param string $name variable name
+     * @param string $module optional module name
+     * @return string|false
+     */
+    public function getVar($name, $module = null)
+    {
+        $module = $module ?: $this->getModuleName();
+        return Mage::getDesign()->getViewConfig()->getVarValue($module, $name);
+    }
+}
diff --git a/app/code/core/Mage/Core/Block/Flush.php b/app/code/core/Mage/Core/Block/Flush.php
index 3b936a2157b62f1c917c3de044c5de5b380191a9..6f899bc8fb2ce6e420068d86157a2c4599e92a33 100644
--- a/app/code/core/Mage/Core/Block/Flush.php
+++ b/app/code/core/Mage/Core/Block/Flush.php
@@ -41,12 +41,9 @@ class Mage_Core_Block_Flush extends Mage_Core_Block_Abstract
 
         ob_implicit_flush();
 
-        foreach ($this->getSortedChildren() as $name) {
-            $block = $this->getLayout()->getBlock($name);
-            if (!$block) {
-                Mage::exception('Mage_Core', Mage::helper('Mage_Core_Helper_Data')->__('Invalid block: %s', $name));
-            }
-            echo $block->toHtml();
+        $layout = $this->getLayout();
+        foreach ($this->getChildNames() as $name) {
+            echo $layout->renderElement($name);
         }
     }
 
diff --git a/app/code/core/Mage/Core/Block/Template.php b/app/code/core/Mage/Core/Block/Template.php
index 7c66af87330f344746c4e506a70c460162a1cc72..ff7966b5155769f42ac3c7c8e314bca8f01d9d5e 100644
--- a/app/code/core/Mage/Core/Block/Template.php
+++ b/app/code/core/Mage/Core/Block/Template.php
@@ -184,7 +184,7 @@ class Mage_Core_Block_Template extends Mage_Core_Block_Abstract
     public function getDirectOutput()
     {
         if ($this->getLayout()) {
-            return $this->getLayout()->getDirectOutput();
+            return $this->getLayout()->isDirectOutput();
         }
         return false;
     }
diff --git a/app/code/core/Mage/Core/Block/Text/List.php b/app/code/core/Mage/Core/Block/Text/List.php
index 47f8c1c2888f9240a7395cadc1ce53f1dd90e687..e56004d6c9b4a6aafa07153bfbd1b282cb90a9dd 100644
--- a/app/code/core/Mage/Core/Block/Text/List.php
+++ b/app/code/core/Mage/Core/Block/Text/List.php
@@ -35,12 +35,9 @@ class Mage_Core_Block_Text_List extends Mage_Core_Block_Text
     protected function _toHtml()
     {
         $this->setText('');
-        foreach ($this->getSortedChildren() as $name) {
-            $block = $this->getLayout()->getBlock($name);
-            if (!$block) {
-                Mage::throwException(Mage::helper('Mage_Core_Helper_Data')->__('Invalid block: %s', $name));
-            }
-            $this->addText($block->toHtml());
+        $layout = $this->getLayout();
+        foreach ($this->getChildNames() as $child) {
+            $this->addText($layout->renderElement($child));
         }
         return parent::_toHtml();
     }
diff --git a/app/code/core/Mage/Core/Controller/Front/Action.php b/app/code/core/Mage/Core/Controller/Front/Action.php
old mode 100644
new mode 100755
index 6d3043ca2a416efdb73f425b641e42a3fb453b93..b0b8059b1a550e1a6946c7104add5f8355458bd4
--- a/app/code/core/Mage/Core/Controller/Front/Action.php
+++ b/app/code/core/Mage/Core/Controller/Front/Action.php
@@ -24,15 +24,16 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
 /**
- * Base front controller
- *
- * @category   Mage
- * @package    Mage_Core
+ * Generic frontend controller
  */
 class Mage_Core_Controller_Front_Action extends Mage_Core_Controller_Varien_Action
 {
+    /**
+     * Session namespace to refer in other places
+     */
+    const SESSION_NAMESPACE = 'frontend';
+
     /**
      * Currently used area
      *
@@ -45,23 +46,10 @@ class Mage_Core_Controller_Front_Action extends Mage_Core_Controller_Varien_Acti
      *
      * @var string
      */
-    protected $_sessionNamespace = 'frontend';
+    protected $_sessionNamespace = self::SESSION_NAMESPACE;
 
     /**
-     * Predispatch: should set layout area
-     *
-     * @return Mage_Core_Controller_Front_Action
-     */
-    public function preDispatch()
-    {
-        $this->getLayout()->setArea($this->_currentArea);
-
-        parent::preDispatch();
-        return $this;
-    }
-
-    /**
-     * Postdispatch: should set last visited url
+     * Remember the last visited url in the session
      *
      * @return Mage_Core_Controller_Front_Action
      */
@@ -69,7 +57,7 @@ class Mage_Core_Controller_Front_Action extends Mage_Core_Controller_Varien_Acti
     {
         parent::postDispatch();
         if (!$this->getFlag('', self::FLAG_NO_START_SESSION )) {
-            Mage::getSingleton('Mage_Core_Model_Session')->setLastUrl(Mage::getUrl('*/*/*', array('_current'=>true)));
+            Mage::getSingleton('Mage_Core_Model_Session')->setLastUrl(Mage::getUrl('*/*/*', array('_current' => true)));
         }
         return $this;
     }
@@ -88,7 +76,7 @@ class Mage_Core_Controller_Front_Action extends Mage_Core_Controller_Varien_Acti
     }
 
     /**
-     * Declare headers and content file in responce for file download
+     * Declare headers and content file in response for file download
      *
      * @param string $fileName
      * @param string|array $content set to null to avoid starting output, $contentLength should be set explicitly in
@@ -146,6 +134,8 @@ class Mage_Core_Controller_Front_Action extends Mage_Core_Controller_Varien_Acti
                 if (!empty($content['rm'])) {
                     $ioAdapter->rm($file);
                 }
+
+                exit(0);
             } else {
                 $this->getResponse()->setBody($content);
             }
diff --git a/app/code/core/Mage/Core/Controller/Request/Http.php b/app/code/core/Mage/Core/Controller/Request/Http.php
index 346aacc495d78aa409e40f5e351d265f75f19adc..f6b758eed2767ea193cb3cce54edc2038b924056 100644
--- a/app/code/core/Mage/Core/Controller/Request/Http.php
+++ b/app/code/core/Mage/Core/Controller/Request/Http.php
@@ -296,7 +296,7 @@ class Mage_Core_Controller_Request_Http extends Zend_Controller_Request_Http
     /**
      * Set a member of the $_POST superglobal
      *
-     * @param striing|array $key
+     * @param string|array $key
      * @param mixed $value
      *
      * @return Mage_Core_Controller_Request_Http
diff --git a/app/code/core/Mage/Core/Controller/Response/Http.php b/app/code/core/Mage/Core/Controller/Response/Http.php
index 7b0c7a644127bffbf13e849721f65e81fd21fd2a..db9796e9c2463ec9ba3737ea47a208d52bea3341 100644
--- a/app/code/core/Mage/Core/Controller/Response/Http.php
+++ b/app/code/core/Mage/Core/Controller/Response/Http.php
@@ -44,6 +44,7 @@ class Mage_Core_Controller_Response_Http extends Zend_Controller_Response_Http
      *
      * @link  http://bugs.php.net/bug.php?id=36705
      *
+     * @return Mage_Core_Controller_Response_Http
      */
     public function sendHeaders()
     {
@@ -73,7 +74,7 @@ class Mage_Core_Controller_Response_Http extends Zend_Controller_Response_Http
                 }
             }
         }
-        parent::sendHeaders();
+        return parent::sendHeaders();
     }
 
     public function sendResponse()
diff --git a/app/code/core/Mage/Core/Controller/Varien/Action.php b/app/code/core/Mage/Core/Controller/Varien/Action.php
old mode 100644
new mode 100755
index e772dbeb048917cf6c7aae765a5f1a8d2235d037..2defe83f7d5d9c42fe02ac023513a9f07eeb97a8
--- a/app/code/core/Mage/Core/Controller/Varien/Action.php
+++ b/app/code/core/Mage/Core/Controller/Varien/Action.php
@@ -152,7 +152,6 @@ abstract class Mage_Core_Controller_Varien_Action
 
     protected function _construct()
     {
-
     }
 
     public function hasAction($action)
@@ -241,18 +240,18 @@ abstract class Mage_Core_Controller_Varien_Action
      */
     public function getLayout()
     {
-        return Mage::getSingleton('Mage_Core_Model_Layout');
+        return Mage::getSingleton('Mage_Core_Model_Layout', array('area' => $this->_currentArea));
     }
 
     /**
      * Load layout by handles(s)
      *
-     * @param   string $handles
-     * @param   string $cacheId
-     * @param   boolean $generateBlocks
+     * @param   string|null|bool $handles
+     * @param   bool $generateBlocks
+     * @param   bool $generateXml
      * @return  Mage_Core_Controller_Varien_Action
      */
-    public function loadLayout($handles=null, $generateBlocks=true, $generateXml=true)
+    public function loadLayout($handles = null, $generateBlocks = true, $generateXml = true)
     {
         // if handles were specified in arguments load them first
         if (false!==$handles && ''!==$handles) {
@@ -278,25 +277,46 @@ abstract class Mage_Core_Controller_Varien_Action
         return $this;
     }
 
-    public function addActionLayoutHandles()
+    /**
+     * Retrieve the default layout handle name for the current action
+     *
+     * @return string
+     */
+    public function getDefaultLayoutHandle()
     {
-        $update = $this->getLayout()->getUpdate();
-
-        // load store handle
-        $update->addHandle('STORE_'.Mage::app()->getStore()->getCode());
-
-        // load theme handle
-        $package = Mage::getSingleton('Mage_Core_Model_Design_Package');
-        $update->addHandle(
-            'THEME_'.$package->getArea().'_'.$package->getPackageName().'_'.$package->getTheme()
-        );
-
-        // load action handle
-        $update->addHandle(strtolower($this->getFullActionName()));
+        return strtolower($this->getFullActionName());
+    }
 
+    /**
+     * Add layout handle by full controller action name
+     *
+     * @return Mage_Core_Controller_Varien_Action
+     */
+    public function addActionLayoutHandles()
+    {
+        /*
+         * @todo Use addPageLayoutHandles() as soon as page type inheritance declarations are correct
+         */
+        $this->getLayout()->getUpdate()->addHandle($this->getDefaultLayoutHandle());
         return $this;
     }
 
+    /**
+     * Add layout updates handles associated with the action page
+     *
+     * @param array $parameters page parameters
+     * @return bool
+     */
+    public function addPageLayoutHandles(array $parameters = array())
+    {
+        $handle = $this->getDefaultLayoutHandle();
+        $pageHandles = array($handle);
+        foreach ($parameters as $key => $value) {
+            $pageHandles[] = $handle . '_' . $key . '_' . $value;
+        }
+        return $this->getLayout()->getUpdate()->addPageHandles(array_reverse($pageHandles));
+    }
+
     public function loadLayoutUpdates()
     {
         Magento_Profiler::start('LAYOUT');
@@ -387,9 +407,8 @@ abstract class Mage_Core_Controller_Varien_Action
 
         Magento_Profiler::start('layout_render');
 
-
         if (''!==$output) {
-            $this->getLayout()->addOutputBlock($output);
+            $this->getLayout()->addOutputElement($output);
         }
 
         Mage::dispatchEvent('controller_action_layout_render_before');
@@ -480,7 +499,7 @@ abstract class Mage_Core_Controller_Varien_Action
     /**
      * Dispatch event before action
      *
-     * @return null
+     * @return void
      */
     public function preDispatch()
     {
@@ -502,13 +521,24 @@ abstract class Mage_Core_Controller_Varien_Action
         }
 
         if (!$this->getFlag('', self::FLAG_NO_START_SESSION)) {
-            $checkCookie = in_array($this->getRequest()->getActionName(), $this->_cookieCheckActions);
-            $checkCookie = $checkCookie && !$this->getRequest()->getParam('nocookie', false);
+            $checkCookie = in_array($this->getRequest()->getActionName(), $this->_cookieCheckActions)
+                && !$this->getRequest()->getParam('nocookie', false);
             $cookies = Mage::getSingleton('Mage_Core_Model_Cookie')->get();
-            if ($checkCookie && empty($cookies)) {
-                $this->setFlag('', self::FLAG_NO_COOKIES_REDIRECT, true);
+            /** @var $session Mage_Core_Model_Session */
+            $session = Mage::getSingleton('Mage_Core_Model_Session', array('name' => $this->_sessionNamespace))->start();
+
+            if (empty($cookies)) {
+                if ($session->getCookieShouldBeReceived()) {
+                    $this->setFlag('', self::FLAG_NO_COOKIES_REDIRECT, true);
+                    $session->unsCookieShouldBeReceived();
+                } else {
+                    if (isset($_GET[$session->getSessionIdQueryParam()]) && Mage::app()->getUseSessionInUrl()) {
+                        $session->setCookieShouldBeReceived(true);
+                    } elseif ($checkCookie) {
+                        $this->setFlag('', self::FLAG_NO_COOKIES_REDIRECT, true);
+                    }
+                }
             }
-            Mage::getSingleton('Mage_Core_Model_Session', array('name' => $this->_sessionNamespace))->start();
         }
 
         Mage::app()->loadArea($this->getLayout()->getArea());
@@ -607,7 +637,6 @@ abstract class Mage_Core_Controller_Varien_Action
             $this->renderLayout();
         } else {
             $status->setForwarded(true);
-            #$this->_forward('cmsNoRoute', 'index', 'cms');
             $this->_forward(
                 $status->getForwardAction(),
                 $status->getForwardController(),
@@ -644,7 +673,7 @@ abstract class Mage_Core_Controller_Varien_Action
      * @param string $action
      * @param string|null $controller
      * @param string|null $module
-     * @param string|null $params
+     * @param array|null $params
      */
     protected function _forward($action, $controller = null, $module = null, array $params = null)
     {
@@ -652,15 +681,15 @@ abstract class Mage_Core_Controller_Varien_Action
 
         $request->initForward();
 
-        if (!is_null($params)) {
+        if (isset($params)) {
             $request->setParams($params);
         }
 
-        if (!is_null($controller)) {
+        if (isset($controller)) {
             $request->setControllerName($controller);
 
             // Module should only be reset if controller has been specified
-            if (!is_null($module)) {
+            if (isset($module)) {
                 $request->setModuleName($module);
             }
         }
@@ -670,7 +699,7 @@ abstract class Mage_Core_Controller_Varien_Action
     }
 
     /**
-     * Inits layout messages by message storage(s), loading and adding messages to layout messages block
+     * Initializing layout messages by message storage(s), loading and adding messages to layout messages block
      *
      * @param string|array $messagesStorage
      * @return Mage_Core_Controller_Varien_Action
@@ -698,7 +727,7 @@ abstract class Mage_Core_Controller_Varien_Action
     }
 
     /**
-     * Inits layout messages by message storage(s), loading and adding messages to layout messages block
+     * Initializing layout messages by message storage(s), loading and adding messages to layout messages block
      *
      * @param string|array $messagesStorage
      * @return Mage_Core_Controller_Varien_Action
@@ -725,17 +754,40 @@ abstract class Mage_Core_Controller_Varien_Action
      *
      * @param   string $path
      * @param   array $arguments
+     * @return  Mage_Core_Controller_Varien_Action
      */
-    protected function _redirect($path, $arguments=array())
+    protected function _redirect($path, $arguments = array())
     {
+        return $this->setRedirectWithCookieCheck($path, $arguments);
+    }
+
+    /**
+     * Set redirect into response with session id in URL if it is enabled.
+     * It allows to distinguish primordial request from browser with cookies disabled.
+     *
+     * @param   string $path
+     * @param   array $arguments
+     * @return  Mage_Core_Controller_Varien_Action
+     */
+    public function setRedirectWithCookieCheck($path, array $arguments = array())
+    {
+        /** @var $session Mage_Core_Model_Session */
+        $session = Mage::getSingleton('Mage_Core_Model_Session', array('name' => $this->_sessionNamespace));
+        if ($session->getCookieShouldBeReceived() && Mage::app()->getUseSessionInUrl()) {
+            $arguments += array('_query' => array(
+                $session->getSessionIdQueryParam() => $session->getSessionId()
+            ));
+        }
         $this->getResponse()->setRedirect(Mage::getUrl($path, $arguments));
         return $this;
     }
 
+
     /**
      * Redirect to success page
      *
      * @param string $defaultUrl
+     * @return Mage_Core_Controller_Varien_Action
      */
     protected function _redirectSuccess($defaultUrl)
     {
@@ -754,6 +806,7 @@ abstract class Mage_Core_Controller_Varien_Action
      * Redirect to error page
      *
      * @param string $defaultUrl
+     * @return  Mage_Core_Controller_Varien_Action
      */
     protected function _redirectError($defaultUrl)
     {
@@ -769,7 +822,7 @@ abstract class Mage_Core_Controller_Varien_Action
     }
 
     /**
-     * Set referer url for redirect in responce
+     * Set referer url for redirect in response
      *
      * @param   string $defaultUrl
      * @return  Mage_Core_Controller_Varien_Action
@@ -939,6 +992,7 @@ abstract class Mage_Core_Controller_Varien_Action
      *
      * @see self::_renderTitles()
      * @param string|false|-1|null $text
+     * @param bool $resetIfExists
      * @return Mage_Core_Controller_Varien_Action
      */
     protected function _title($text = null, $resetIfExists = true)
@@ -1044,7 +1098,7 @@ abstract class Mage_Core_Controller_Varien_Action
     }
 
     /**
-     * Declare headers and content file in responce for file download
+     * Declare headers and content file in response for file download
      *
      * @param string $fileName
      * @param string|array $content set to null to avoid starting output, $contentLength should be set explicitly in
@@ -1102,6 +1156,8 @@ abstract class Mage_Core_Controller_Varien_Action
                 if (!empty($content['rm'])) {
                     $ioAdapter->rm($file);
                 }
+
+                exit(0);
             } else {
                 $this->getResponse()->setBody($content);
             }
diff --git a/app/code/core/Mage/Core/Controller/Varien/Front.php b/app/code/core/Mage/Core/Controller/Varien/Front.php
index 87f41660c7bcf90c7dfcc27756414c38cb97e78f..b31a07a73dada03ee03d1f87823636f64fea5690 100644
--- a/app/code/core/Mage/Core/Controller/Varien/Front.php
+++ b/app/code/core/Mage/Core/Controller/Varien/Front.php
@@ -119,7 +119,7 @@ class Mage_Core_Controller_Varien_Front extends Varien_Object
     }
 
     /**
-     * Init Fron Controller
+     * Init Front Controller
      *
      * @return Mage_Core_Controller_Varien_Front
      */
@@ -187,7 +187,7 @@ class Mage_Core_Controller_Varien_Front extends Varien_Object
         if ($i>100) {
             Mage::throwException('Front controller reached 100 router match iterations');
         }
-        //This event give possibility to launch smth before sending ouptut(Allow cookie setting)
+        // 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');
         $this->getResponse()->sendResponse();
@@ -305,13 +305,9 @@ class Mage_Core_Controller_Varien_Front extends Varien_Object
             return;
         }
 
-        $adminPath = (string)Mage::getConfig()->getNode(Mage_Adminhtml_Helper_Data::XML_PATH_CUSTOM_ADMIN_PATH);
-        if (!$adminPath) {
-            $adminPath = (string)Mage::getConfig()
-                ->getNode(Mage_Adminhtml_Helper_Data::XML_PATH_ADMINHTML_ROUTER_FRONTNAME);
-        }
-        if (preg_match('#^' . $adminPath . '(\/.*)?$#', ltrim($request->getPathInfo(), '/'))
-            && (string)Mage::getConfig()->getNode(Mage_Adminhtml_Helper_Data::XML_PATH_USE_CUSTOM_ADMIN_URL)) {
+        if ($this->_isAdminFrontNameMatched($request)
+            && (string)Mage::getConfig()->getNode(Mage_Adminhtml_Helper_Data::XML_PATH_USE_CUSTOM_ADMIN_URL)
+        ) {
             return;
         }
 
@@ -338,4 +334,39 @@ class Mage_Core_Controller_Varien_Front extends Varien_Object
             exit;
         }
     }
+
+    /**
+     * Check if requested path starts with one of the admin front names
+     *
+     * @param Zend_Controller_Request_Http $request
+     * @return boolean
+     */
+    protected function _isAdminFrontNameMatched($request)
+    {
+        $adminPath = (string)Mage::getConfig()->getNode(Mage_Adminhtml_Helper_Data::XML_PATH_CUSTOM_ADMIN_PATH);
+        if (!$adminPath) {
+            $adminPath = (string)Mage::getConfig()
+                ->getNode(Mage_Adminhtml_Helper_Data::XML_PATH_ADMINHTML_ROUTER_FRONTNAME);
+        }
+        $adminFrontNames = array($adminPath);
+
+        // Check for other modules that can use admin router (a lot of Magento extensions do that)
+        $adminFrontNameNodes = Mage::getConfig()->getNode('admin/routers')
+            ->xpath('*[not(self::adminhtml) and use = "admin"]/args/frontName');
+
+        if (is_array($adminFrontNameNodes)) {
+            foreach ($adminFrontNameNodes as $frontNameNode) {
+                /** @var $frontNameNode SimpleXMLElement */
+                array_push($adminFrontNames, (string)$frontNameNode);
+            }
+        }
+
+        $pathPrefix = ltrim($request->getPathInfo(), '/');
+        $urlDelimiterPos = strpos($pathPrefix, '/');
+        if ($urlDelimiterPos) {
+            $pathPrefix = substr($pathPrefix, 0, $urlDelimiterPos);
+        }
+
+        return in_array($pathPrefix, $adminFrontNames);
+    }
 }
diff --git a/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php b/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php
index 1a1bfca45771d3b1ccf5fa899b45162917c8423e..9eba4c3810aba16439ca985a5ef57ec60ef06e5a 100644
--- a/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php
+++ b/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php
@@ -154,7 +154,7 @@ class Mage_Core_Controller_Varien_Router_Standard extends Mage_Core_Controller_V
             return false;
         }
 
-        //checkings after we foundout that this router should be used for current module
+        // checks after we found out that this router should be used for current module
         if (!$this->_afterModuleMatch()) {
             return false;
         }
@@ -210,7 +210,7 @@ class Mage_Core_Controller_Varien_Router_Standard extends Mage_Core_Controller_V
         }
 
         /**
-         * if we did not found any siutibul
+         * if we did not found any suitable
          */
         if (!$found) {
             if ($this->_noRouteShouldBeApplied()) {
@@ -407,13 +407,12 @@ class Mage_Core_Controller_Varien_Router_Standard extends Mage_Core_Controller_V
     }
 
     /**
-     * Check if request URL should be secure
-     *
-     * Function redirects user to correct URL if needed
+     * Check that request uses https protocol if it should.
+     * Function redirects user to correct URL if needed.
      *
      * @param Mage_Core_Controller_Request_Http $request
      * @param string $path
-     * @return null
+     * @return void
      */
     protected function _checkShouldBeSecure($request, $path = '')
     {
@@ -423,11 +422,14 @@ class Mage_Core_Controller_Varien_Router_Standard extends Mage_Core_Controller_V
 
         if ($this->_shouldBeSecure($path) && !$request->isSecure()) {
             $url = $this->_getCurrentSecureUrl($request);
+            if ($request->getRouteName() != 'adminhtml' && Mage::app()->getUseSessionInUrl()) {
+                $url = Mage::getSingleton('Mage_Core_Model_Url')->getRedirectUrl($url);
+            }
 
             Mage::app()->getFrontController()->getResponse()
                 ->setRedirect($url)
                 ->sendResponse();
-            exit();
+            exit;
         }
     }
 
diff --git a/app/code/core/Mage/Core/Helper/Abstract.php b/app/code/core/Mage/Core/Helper/Abstract.php
old mode 100644
new mode 100755
index 1e8cc108455e3a9523ce5774dc2f2c970a9511f9..3f9cb29f243f139cc6c3aaf9fa1ae79199073796
--- a/app/code/core/Mage/Core/Helper/Abstract.php
+++ b/app/code/core/Mage/Core/Helper/Abstract.php
@@ -206,10 +206,10 @@ abstract class Mage_Core_Helper_Abstract
                 if (is_array($allowedTags) and !empty($allowedTags)) {
                     $allowed = implode('|', $allowedTags);
                     $result = preg_replace('/<([\/\s\r\n]*)(' . $allowed . ')([\/\s\r\n]*)>/si', '##$1$2$3##', $data);
-                    $result = htmlspecialchars($result);
+                    $result = htmlspecialchars($result, ENT_COMPAT, 'UTF-8', false);
                     $result = preg_replace('/##([\/\s\r\n]*)(' . $allowed . ')([\/\s\r\n]*)##/si', '<$1$2$3>', $result);
                 } else {
-                    $result = htmlspecialchars($data);
+                    $result = htmlspecialchars($data, ENT_COMPAT, 'UTF-8', false);
                 }
             } else {
                 $result = $data;
diff --git a/app/code/core/Mage/Core/Helper/Data.php b/app/code/core/Mage/Core/Helper/Data.php
index d6bd6941b080e74c970f40223e1a9809bf48b7f8..8404ab31adf35c27e9bc881f29a34e1648b3d356 100644
--- a/app/code/core/Mage/Core/Helper/Data.php
+++ b/app/code/core/Mage/Core/Helper/Data.php
@@ -55,6 +55,11 @@ class Mage_Core_Helper_Data extends Mage_Core_Helper_Abstract
     const XML_PATH_MERCHANT_VAT_NUMBER = 'general/store_information/merchant_vat_number';
     const XML_PATH_EU_COUNTRIES_LIST = 'general/country/eu_countries';
 
+    /**
+     * Const for correct dividing decimal values
+     */
+    const DIVIDE_EPSILON = 10000;
+
     /**
      * @var Mage_Core_Model_Encryption
      */
@@ -762,4 +767,23 @@ XML;
         $euCountries = explode(',', Mage::getStoreConfig(self::XML_PATH_EU_COUNTRIES_LIST, $storeId));
         return in_array($countryCode, $euCountries);
     }
+
+    /**
+     * Returns the floating point remainder (modulo) of the division of the arguments
+     *
+     * @param float|int $dividend
+     * @param float|int $divisor
+     * @return float|int
+     */
+    public function getExactDivision($dividend, $divisor)
+    {
+        $epsilon = $divisor / self::DIVIDE_EPSILON;
+
+        $remainder = fmod($dividend, $divisor);
+        if (abs($remainder - $divisor) < $epsilon || abs($remainder) < $epsilon) {
+            $remainder = 0;
+        }
+
+        return $remainder;
+    }
 }
diff --git a/app/code/core/Mage/Core/Helper/Js.php b/app/code/core/Mage/Core/Helper/Js.php
index 5e416ea93c18e8eb9d3cbc17a943e8aad67f7648..957a3a164b9398157ab41c09c68bb91576eb0876 100644
--- a/app/code/core/Mage/Core/Helper/Js.php
+++ b/app/code/core/Mage/Core/Helper/Js.php
@@ -39,7 +39,7 @@ class Mage_Core_Helper_Js extends Mage_Core_Helper_Abstract
     /**
      * Translate file name
      */
-    const JAVASCRIPT_TRANSLATE_CONFIG_FILENAME = 'translater.xml';
+    const JAVASCRIPT_TRANSLATE_CONFIG_FILENAME = 'jstranslator.xml';
 
     /**
      * Array of senteces of JS translations
@@ -84,7 +84,7 @@ class Mage_Core_Helper_Js extends Mage_Core_Helper_Abstract
      */
     public function getScript($script)
     {
-        return '<script type="text/javascript">'.$script.'</script>';
+        return '<script type="text/javascript">//<![CDATA[' . "\n{$script}\n" . '//]]></script>';
     }
 
     /**
@@ -107,11 +107,14 @@ class Mage_Core_Helper_Js extends Mage_Core_Helper_Abstract
     {
         if ($this->_translateData === null) {
             $this->_translateData = array();
-
-            foreach ($this->_getXmlConfig()->getXpath('*/message') as $message) {
-                $messageText = (string)$message;
-                $module = $message->getParent()->getAttribute("module");
-                $this->_translateData[$messageText] = Mage::helper(empty($module) ? 'Mage_Core' : $module)->__($messageText);
+            $messages = $this->_getXmlConfig()->getXpath('*/message');
+            if (!empty($messages)) {
+                foreach ($messages as $message) {
+                    $messageText = (string)$message;
+                    $module = $message->getParent()->getAttribute("module");
+                    $this->_translateData[$messageText] = Mage::helper(empty($module) ? 'Mage_Core' : $module
+                    )->__($messageText);
+                }
             }
 
             foreach ($this->_translateData as $key => $value) {
@@ -137,7 +140,7 @@ class Mage_Core_Helper_Js extends Mage_Core_Helper_Abstract
                 $xmlConfig = new Varien_Simplexml_Config($cachedXml);
             } else {
                 $xmlConfig = new Varien_Simplexml_Config();
-                $xmlConfig->loadString('<?xml version="1.0"?><translater></translater>');
+                $xmlConfig->loadString('<?xml version="1.0"?><jstranslator></jstranslator>');
                 Mage::getConfig()->loadModulesConfiguration(self::JAVASCRIPT_TRANSLATE_CONFIG_FILENAME, $xmlConfig);
 
                 if ($canUsaCache) {
diff --git a/app/code/core/Mage/Core/Model/App.php b/app/code/core/Mage/Core/Model/App.php
index eeea0d0b7a4daed74bbcfa745f0dc8fbf2740b5c..c7768d2538dc552fd271c6c7cc7ae8f065807a80 100644
--- a/app/code/core/Mage/Core/Model/App.php
+++ b/app/code/core/Mage/Core/Model/App.php
@@ -138,7 +138,7 @@ class Mage_Core_Model_App
     /**
      * Cache object
      *
-     * @var Zend_Cache_Core
+     * @var Mage_Core_Model_Cache
      */
     protected $_cache;
 
diff --git a/app/code/core/Mage/Core/Model/Cache.php b/app/code/core/Mage/Core/Model/Cache.php
index 882420fa1bf493756243daac0cff4d5580f652a9..4323d0a22d04445970c52d0d1ddc8faacf429d59 100644
--- a/app/code/core/Mage/Core/Model/Cache.php
+++ b/app/code/core/Mage/Core/Model/Cache.php
@@ -510,6 +510,7 @@ class Mage_Core_Model_Cache
 
     /**
      * Disable cache usage for specific data type
+     *
      * @param string $typeCode
      * @return Mage_Core_Model_Cache
      */
@@ -519,6 +520,18 @@ class Mage_Core_Model_Cache
         return $this;
     }
 
+    /**
+     * Enable cache usage for specific data type
+     *
+     * @param string $typeCode
+     * @return Mage_Core_Model_Cache
+     */
+    public function allowUse($typeCode)
+    {
+        $this->_allowedCacheOptions[$typeCode] = true;
+        return $this;
+    }
+
     /**
      * Get cache tags by cache type from configuration
      *
diff --git a/app/code/core/Mage/Core/Model/Date.php b/app/code/core/Mage/Core/Model/Date.php
index 9edb4618eca7efcafa9fbea0fa102568cb8e82b9..b3c2dc95bf807d416be52fd2fede70d93a5a4ea8 100644
--- a/app/code/core/Mage/Core/Model/Date.php
+++ b/app/code/core/Mage/Core/Model/Date.php
@@ -106,7 +106,13 @@ class Mage_Core_Model_Date
             $format = 'Y-m-d H:i:s';
         }
 
-        $result = date($format, $this->gmtTimestamp($input));
+        $date = $this->gmtTimestamp($input);
+
+        if ($date === false) {
+            return false;
+        }
+
+        $result = date($format, $date);
         return $result;
     }
 
@@ -144,6 +150,11 @@ class Mage_Core_Model_Date
             $result = strtotime($input);
         }
 
+        if ($result === false) {
+            // strtotime() unable to parse string (it's not a date or has incorrect format)
+            return false;
+        }
+
         $date      = Mage::app()->getLocale()->date($result);
         $timestamp = $date->get(Zend_Date::TIMESTAMP) - $date->get(Zend_Date::TIMEZONE_SECS);
 
diff --git a/app/code/core/Mage/Core/Model/Email/Template.php b/app/code/core/Mage/Core/Model/Email/Template.php
index 5ba293b0e82e8f676135562143f52d57ac5df782..1b1fb319fbfa8468e9a403d6090b8771a87cf2e3 100644
--- a/app/code/core/Mage/Core/Model/Email/Template.php
+++ b/app/code/core/Mage/Core/Model/Email/Template.php
@@ -71,11 +71,12 @@ class Mage_Core_Model_Email_Template extends Mage_Core_Model_Template
 {
     /**
      * Configuration path for default email templates
-     *
      */
-    const XML_PATH_TEMPLATE_EMAIL          = 'global/template/email';
-    const XML_PATH_SENDING_SET_RETURN_PATH = 'system/smtp/set_return_path';
-    const XML_PATH_SENDING_RETURN_PATH_EMAIL = 'system/smtp/return_path_email';
+    const XML_PATH_TEMPLATE_EMAIL               = 'global/template/email';
+    const XML_PATH_SENDING_SET_RETURN_PATH      = 'system/smtp/set_return_path';
+    const XML_PATH_SENDING_RETURN_PATH_EMAIL    = 'system/smtp/return_path_email';
+    const XML_PATH_DESIGN_EMAIL_LOGO            = 'design/email/logo';
+    const XML_PATH_DESIGN_EMAIL_LOGO_ALT        = 'design/email/logo_alt';
 
     protected $_templateFilter;
     protected $_preprocessFlag = false;
@@ -100,7 +101,44 @@ class Mage_Core_Model_Email_Template extends Mage_Core_Model_Template
     }
 
     /**
-     * Get new Zend_Mail instance
+     * Return logo URL for emails
+     * Take logo from skin if custom logo is undefined
+     *
+     * @param  Mage_Core_Model_Store|int|string $store
+     * @return string
+     */
+    protected function _getLogoUrl($store)
+    {
+        $store = Mage::app()->getStore($store);
+        $fileName = $store->getConfig(self::XML_PATH_DESIGN_EMAIL_LOGO);
+        if ($fileName) {
+            $uploadDir = Mage_Adminhtml_Model_System_Config_Backend_Email_logo::UPLOAD_DIR;
+            $fullFileName = Mage::getBaseDir('media') . DS . $uploadDir . DS . $fileName;
+            if (file_exists($fullFileName)) {
+                return Mage::getBaseUrl('media') . $uploadDir . '/' . $fileName;
+            }
+        }
+        return Mage::getDesign()->getSkinUrl('Mage_Core::logo_email.gif');
+    }
+
+    /**
+     * Return logo alt for emails
+     *
+     * @param  Mage_Core_Model_Store|int|string $store
+     * @return string
+     */
+    protected function _getLogoAlt($store)
+    {
+        $store = Mage::app()->getStore($store);
+        $alt = $store->getConfig(self::XML_PATH_DESIGN_EMAIL_LOGO_ALT);
+        if ($alt) {
+            return $alt;
+        }
+        return $store->getFrontendName();
+    }
+
+    /**
+     * Retrieve mail object instance
      *
      * @return Zend_Mail
      */
@@ -307,14 +345,21 @@ class Mage_Core_Model_Email_Template extends Mage_Core_Model_Template
         $processor->setUseSessionInUrl(false)
             ->setPlainTemplateMode($this->isPlain());
 
-        if(!$this->_preprocessFlag) {
+        if (!$this->_preprocessFlag) {
             $variables['this'] = $this;
         }
 
-        if(isset($variables['subscriber']) && ($variables['subscriber'] instanceof Mage_Newsletter_Model_Subscriber)) {
+        if (isset($variables['subscriber']) && ($variables['subscriber'] instanceof Mage_Newsletter_Model_Subscriber)) {
             $processor->setStoreId($variables['subscriber']->getStoreId());
         }
 
+        if (!isset($variables['logo_url'])) {
+            $variables['logo_url'] = $this->_getLogoUrl($processor->getStoreId());
+        }
+        if (!isset($variables['logo_alt'])) {
+            $variables['logo_alt'] = $this->_getLogoAlt($processor->getStoreId());
+        }
+
         $processor->setIncludeProcessor(array($this, 'getInclude'))
             ->setVariables($variables);
 
@@ -493,8 +538,8 @@ class Mage_Core_Model_Email_Template extends Mage_Core_Model_Template
         }
 
         if (!is_array($sender)) {
-            $this->setSenderName(Mage::getStoreConfig('trans_email/ident_'.$sender.'/name', $storeId));
-            $this->setSenderEmail(Mage::getStoreConfig('trans_email/ident_'.$sender.'/email', $storeId));
+            $this->setSenderName(Mage::getStoreConfig('trans_email/ident_' . $sender . '/name', $storeId));
+            $this->setSenderEmail(Mage::getStoreConfig('trans_email/ident_' . $sender . '/email', $storeId));
         } else {
             $this->setSenderName($sender['name']);
             $this->setSenderEmail($sender['email']);
@@ -503,7 +548,6 @@ class Mage_Core_Model_Email_Template extends Mage_Core_Model_Template
         if (!isset($vars['store'])) {
             $vars['store'] = Mage::app()->getStore($storeId);
         }
-
         $this->setSentSuccess($this->send($email, $name, $vars));
         return $this;
     }
diff --git a/app/code/core/Mage/Core/Model/Email/Template/Filter.php b/app/code/core/Mage/Core/Model/Email/Template/Filter.php
index dd1e77414dce3792926cda3956b7d6c70bdac77f..4916eba121b1ecd02fa84ea193dc8c0364c76819 100644
--- a/app/code/core/Mage/Core/Model/Email/Template/Filter.php
+++ b/app/code/core/Mage/Core/Model/Email/Template/Filter.php
@@ -228,7 +228,7 @@ class Mage_Core_Model_Email_Template_Filter extends Varien_Filter_Template
         $allBlocks = $layout->getAllBlocks();
         $firstBlock = reset($allBlocks);
         if ($firstBlock) {
-            $layout->addOutputBlock($firstBlock->getNameInLayout());
+            $layout->addOutputElement($firstBlock->getNameInLayout());
         }
 
         $layout->setDirectOutput(false);
diff --git a/app/code/core/Mage/Core/Model/Layout.php b/app/code/core/Mage/Core/Model/Layout.php
index 43f1b33c2058e863317cd9cd9980d56ce23c7540..2d71354be006fc601c8cbcde312626614780a45d 100644
--- a/app/code/core/Mage/Core/Model/Layout.php
+++ b/app/code/core/Mage/Core/Model/Layout.php
@@ -30,9 +30,18 @@
  *
  * @category   Mage
  * @package    Mage_Core
+ * @SuppressWarnings(PHPMD.ExcessiveClassComplexity)
+ * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  */
 class Mage_Core_Model_Layout extends Varien_Simplexml_Config
 {
+    /**
+     * Names of container options in layout
+     */
+    const CONTAINER_OPT_HTML_TAG   = 'htmlTag';
+    const CONTAINER_OPT_HTML_CLASS = 'htmlClass';
+    const CONTAINER_OPT_HTML_ID    = 'htmlId';
+    const CONTAINER_OPT_LABEL      = 'label';
 
     /**
      * Layout Update module
@@ -49,7 +58,7 @@ class Mage_Core_Model_Layout extends Varien_Simplexml_Config
     protected $_blocks = array();
 
     /**
-     * Cache of block callbacks to output during rendering
+     * Cache of elements to output during rendering
      *
      * @var array
      */
@@ -76,41 +85,74 @@ class Mage_Core_Model_Layout extends Varien_Simplexml_Config
      */
     protected $_directOutput = false;
 
+    /**
+     * A vairable for transporting output into observer during rendering
+     *
+     * @var Varien_Object
+     */
+    protected $_renderingOutput = null;
+
+    /**
+     * Available options for containers in layout
+     *
+     * @var array
+     */
+    protected $_containerOptions = array(
+        self::CONTAINER_OPT_HTML_CLASS,
+        self::CONTAINER_OPT_HTML_ID,
+        self::CONTAINER_OPT_HTML_TAG,
+        self::CONTAINER_OPT_LABEL,
+    );
+
+    /**
+     * Cache of generated elements' HTML
+     *
+     * @var array
+     */
+    protected $_renderElementCache = array();
+
+    /**
+     * Layout structure model
+     *
+     * @var Mage_Core_Model_Layout_Structure
+     */
+    protected $_structure;
+
     /**
      * Class constructor
      *
-     * @param array $data
+     * @param array $arguments
      */
-    public function __construct($data=array())
+    public function __construct(array $arguments = array())
     {
+        $this->_area = isset($arguments['area']) ? $arguments['area'] : Mage_Core_Model_Design_Package::DEFAULT_AREA;
+        if (isset($arguments['structure'])) {
+            if ($arguments['structure'] instanceof Mage_Core_Model_Layout_Structure) {
+                $this->_structure = $arguments['structure'];
+            } else {
+                throw new Magento_Exception('Expected instance of Mage_Core_Model_Layout_Structure.');
+            }
+        } else {
+            $this->_structure = Mage::getModel('Mage_Core_Model_Layout_Structure');
+        }
         $this->_elementClass = Mage::getConfig()->getModelClassName('Mage_Core_Model_Layout_Element');
         $this->setXml(simplexml_load_string('<layout/>', $this->_elementClass));
-        $this->_update = Mage::getModel('Mage_Core_Model_Layout_Update');
-        parent::__construct($data);
+        $this->_renderingOutput = new Varien_Object;
     }
 
     /**
-     * Layout update instance
+     * Retrieve the layout update instance
      *
      * @return Mage_Core_Model_Layout_Update
      */
     public function getUpdate()
     {
+        if (!$this->_update) {
+            $this->_update = Mage::getModel('Mage_Core_Model_Layout_Update', array('area' => $this->getArea()));
+        }
         return $this->_update;
     }
 
-    /**
-     * Set layout area
-     *
-     * @param   string $area
-     * @return  Mage_Core_Model_Layout
-     */
-    public function setArea($area)
-    {
-        $this->_area = $area;
-        return $this;
-    }
-
     /**
      * Retrieve layout area
      *
@@ -134,49 +176,44 @@ class Mage_Core_Model_Layout extends Varien_Simplexml_Config
     }
 
     /**
-     * Retrieve derect output flag
+     * Retrieve direct output flag
      *
      * @return bool
      */
-    public function getDirectOutput()
+    public function isDirectOutput()
     {
         return $this->_directOutput;
     }
 
     /**
-     * Loyout xml generation
+     * Layout xml generation
      *
      * @return Mage_Core_Model_Layout
      */
     public function generateXml()
     {
         $xml = $this->getUpdate()->asSimplexml();
-        $removeInstructions = $xml->xpath("//remove");
-        if (is_array($removeInstructions)) {
-            foreach ($removeInstructions as $infoNode) {
-                $attributes = $infoNode->attributes();
-                $blockName = (string)$attributes->name;
-                if ($blockName) {
-                    $ignoreNodes = $xml->xpath("//block[@name='".$blockName."']");
-                    if (!is_array($ignoreNodes)) {
-                        continue;
-                    }
-                    $ignoreReferences = $xml->xpath("//reference[@name='".$blockName."']");
-                    if (is_array($ignoreReferences)) {
-                        $ignoreNodes = array_merge($ignoreNodes, $ignoreReferences);
-                    }
+        $removeInstructions = (array)$xml->xpath("//remove[@name]");
+        foreach ($removeInstructions as $infoNode) {
+            $attributes = $infoNode->attributes();
+            $blockName = (string)$attributes->name;
+            $ignoreNodes = $xml->xpath("//block[@name='" . $blockName . "']");
+            if (!is_array($ignoreNodes)) {
+                continue;
+            }
+            $ignoreReferences = $xml->xpath("//reference[@name='" . $blockName . "']");
+            if (is_array($ignoreReferences)) {
+                $ignoreNodes = array_merge($ignoreNodes, $ignoreReferences);
+            }
 
-                    foreach ($ignoreNodes as $block) {
-                        if ($block->getAttribute('ignore') !== null) {
-                            continue;
-                        }
-                        if (($acl = (string)$attributes->acl) && Mage::getSingleton('Mage_Admin_Model_Session')->isAllowed($acl)) {
-                            continue;
-                        }
-                        if (!isset($block->attributes()->ignore)) {
-                            $block->addAttribute('ignore', true);
-                        }
-                    }
+            foreach ($ignoreNodes as $block) {
+                $acl = (string)$attributes->acl;
+                if ($block->getAttribute('ignore') !== null || ($acl
+                    && Mage::getSingleton('Mage_Admin_Model_Session')->isAllowed($acl))) {
+                    continue;
+                }
+                if (!isset($block->attributes()->ignore)) {
+                    $block->addAttribute('ignore', true);
                 }
             }
         }
@@ -187,21 +224,23 @@ class Mage_Core_Model_Layout extends Varien_Simplexml_Config
     /**
      * Create layout blocks hierarchy from layout xml configuration
      *
-     * @param Mage_Core_Layout_Element|null $parent
+     * @param Mage_Core_Model_Layout_Element|null $parent
      */
     public function generateBlocks($parent=null)
     {
         if (empty($parent)) {
             $parent = $this->getNode();
         }
+        /** @var Mage_Core_Model_Layout_Element $node  */
         foreach ($parent as $node) {
             $attributes = $node->attributes();
             if ((bool)$attributes->ignore) {
                 continue;
             }
             switch ($node->getName()) {
+                case 'container':
                 case 'block':
-                    $this->_generateBlock($node, $parent);
+                    $this->_generateElement($node, $parent);
                     $this->generateBlocks($node);
                     break;
 
@@ -217,144 +256,458 @@ class Mage_Core_Model_Layout extends Varien_Simplexml_Config
     }
 
     /**
-     * Add block object to layout based on xml node data
+     * Creates block/container object based on xml node data
      *
-     * @param Varien_Simplexml_Element $node
-     * @param Varien_Simplexml_Element $parent
+     * @param Mage_Core_Model_Layout_Element $node
+     * @param Mage_Core_Model_Layout_Element $parent
+     * @return Mage_Core_Model_Layout
+     * @throws Magento_Exception
+     */
+    protected function _generateElement($node, $parent)
+    {
+        $elementType = $node->getName();
+        $name = $node->getAttribute('name');
+
+        $profilerKey = strtoupper($elementType) . ':' . $name;
+        Magento_Profiler::start($profilerKey);
+
+        $parentName = $node->getAttribute('parent');
+        if (is_null($parentName)) {
+            $parentName = $parent->getElementName();
+        }
+
+        $alias = $node->getAttribute('as');
+        if (!$alias) {
+            $alias = $name;
+        }
+
+        $sibling = $node->getSibling();
+        $after = !isset($node['before']);
+
+        $options = $this->_extractContainerOptions($node);
+        $elementName = $this->_structure
+            ->insertElement($parentName, $name, $elementType, $alias, $after, $sibling, $options);
+
+        if ($this->_structure->isBlock($elementName)) {
+            $block = $this->_generateBlock($node);
+            $updatedName = $block->getNameInLayout();
+            if (empty($name)) {
+                if (empty($alias)) {
+                    $this->_structure->setElementAlias($elementName, $updatedName);
+                }
+                $this->_structure->renameElement($elementName, $updatedName);
+            }
+        } else {
+            $this->_removeBlock($name);
+        }
+
+        if (isset($node['output'])) {
+            $this->addOutputElement($elementName);
+        }
+
+        Magento_Profiler::stop($profilerKey);
+
+        return $this;
+    }
+
+    /**
+     * Remove block from blocks list
+     *
+     * @param $name
      * @return Mage_Core_Model_Layout
      */
-    protected function _generateBlock($node, $parent)
+    protected function _removeBlock($name)
+    {
+        if (isset($this->_blocks[$name])) {
+            unset($this->_blocks[$name]);
+        }
+        return $this;
+    }
+
+    /**
+     * Extract appropriate options from a node if it is a container
+     *
+     * @param Mage_Core_Model_Layout_Element $node
+     * @return array
+     */
+    protected function _extractContainerOptions(Mage_Core_Model_Layout_Element $node)
+    {
+        $options = array();
+        if ('container' == $node->getName()) {
+            foreach ($this->_containerOptions as $optName) {
+                if ($value = $node->getAttribute($optName)) {
+                    $options[$optName] = $value;
+                }
+            }
+        }
+
+        return $options;
+    }
+
+    /**
+     * Creates block object based on xml node data and add it to the layout
+     *
+     * @param Mage_Core_Model_Layout_Element $node
+     * @return Mage_Core_Block_Abstract
+     */
+    protected function _generateBlock(Mage_Core_Model_Layout_Element $node)
     {
         if (!empty($node['class'])) {
             $className = (string)$node['class'];
         } else {
             $className = (string)$node['type'];
         }
+        $elementName = $node->getAttribute('name');
+
+        $block = $this->_createBlock($className, $elementName);
+        if (!empty($node['template'])) {
+            $block->setTemplate((string)$node['template']);
+        }
 
-        $blockName = (string)$node['name'];
-        $_profilerKey = 'BLOCK:' . $blockName;
-        Magento_Profiler::start($_profilerKey);
+        return $block;
+    }
 
-        $block = $this->addBlock($className, $blockName);
-        if (!$block) {
+    /**
+     * Run action defined in layout update
+     *
+     * @param Mage_Core_Model_Layout_Element $node
+     * @param Mage_Core_Model_Layout_Element $parent
+     * @return Mage_Core_Model_Layout
+     * @throws Magento_Exception
+     */
+    protected function _generateAction($node, $parent)
+    {
+        $configPath = $node->getAttribute('ifconfig');
+        if ($configPath && !Mage::getStoreConfigFlag($configPath)) {
             return $this;
         }
 
-        if (!empty($node['parent'])) {
-            $parentBlock = $this->getBlock((string)$node['parent']);
-        } else {
-            $parentName = $parent->getBlockName();
-            if (!empty($parentName)) {
-                $parentBlock = $this->getBlock($parentName);
-            }
+        if (Mage_Core_Model_Layout_Structure::ELEMENT_TYPE_CONTAINER === $parent->getName()) {
+            throw new Magento_Exception('Action can not be placed inside container');
         }
-        if (!empty($parentBlock)) {
-            $alias = isset($node['as']) ? (string)$node['as'] : '';
-            if (isset($node['before'])) {
-                $sibling = (string)$node['before'];
-                if ('-'===$sibling) {
-                    $sibling = '';
-                }
-                $parentBlock->insert($block, $sibling, false, $alias);
-            } elseif (isset($node['after'])) {
-                $sibling = (string)$node['after'];
-                if ('-'===$sibling) {
-                    $sibling = '';
-                }
-                $parentBlock->insert($block, $sibling, true, $alias);
-            } else {
-                $parentBlock->append($block, $alias);
-            }
+
+        $method = $node->getAttribute('method');
+        $parentName = $node->getAttribute('block');
+        if (empty($parentName)) {
+            $parentName = $parent->getElementName();
         }
-        if (!empty($node['template'])) {
-            $block->setTemplate((string)$node['template']);
+
+        $profilerKey = 'BLOCK_ACTION:' . $parentName . '>' . $method;
+        Magento_Profiler::start($profilerKey);
+
+        $block = $this->getBlock($parentName);
+        if (!empty($block)) {
+
+            $args = $this->_extractArgs($node);
+
+            $this->_translateLayoutNode($node, $args);
+            call_user_func_array(array($block, $method), $args);
         }
 
-        if (!empty($node['output'])) {
-            $method = (string)$node['output'];
-            $this->addOutputBlock($blockName, $method);
+        Magento_Profiler::stop($profilerKey);
+
+        return $this;
+    }
+
+    /**
+     * Insert block into layout structure
+     *
+     * @param string $parentName
+     * @param string $name
+     * @param string $alias
+     * @param bool $after
+     * @param string $sibling
+     * @return bool|string
+     */
+    public function insertBlock($parentName, $name, $alias = '', $after = true, $sibling = '')
+    {
+        return $this->_structure->insertBlock($parentName, $name, $alias, $after, $sibling);
+    }
+
+    /**
+     * Insert container into layout structure
+     *
+     * @param string $parentName
+     * @param string $name
+     * @param string $alias
+     * @param bool $after
+     * @param string $sibling
+     * @return bool|string
+     */
+    public function insertContainer($parentName, $name, $alias = '', $after = true, $sibling = '')
+    {
+        return $this->_structure->insertContainer($parentName, $name, $alias, $after, $sibling);
+    }
+
+    /**
+     * Get child block if exists
+     *
+     * @param string $parentName
+     * @param string $alias
+     * @return bool|Mage_Core_Block_Abstract
+     */
+    public function getChildBlock($parentName, $alias)
+    {
+        $name = $this->_structure->getChildName($parentName, $alias);
+        if ($this->_structure->isBlock($name)) {
+            return $this->getBlock($name);
         }
-        Magento_Profiler::stop($_profilerKey);
+        return false;
+    }
 
+    /**
+     * Set child element into layout structure
+     *
+     * @param string $parentName
+     * @param string $elementName
+     * @param string $alias
+     * @return Mage_Core_Model_Layout
+     */
+    public function setChild($parentName, $elementName, $alias)
+    {
+        $this->_structure->setChild($parentName, $elementName, $alias);
         return $this;
     }
 
     /**
-     * Enter description here...
+     * Remove child element from parent
      *
-     * @param Varien_Simplexml_Element $node
-     * @param Varien_Simplexml_Element $parent
+     * @param string $parentName
+     * @param string $alias
      * @return Mage_Core_Model_Layout
      */
-    protected function _generateAction($node, $parent)
+    public function unsetChild($parentName, $alias)
+    {
+        $this->_structure->unsetChild($parentName, $alias);
+        return $this;
+    }
+
+    /**
+     * Get list of child names
+     *
+     * @param string $parentName
+     * @return array
+     */
+    public function getChildNames($parentName)
+    {
+        return $this->_structure->getChildNames($parentName);
+    }
+
+    /**
+     * Get list of child blocks
+     *
+     * @param string $parentName
+     * @return array
+     */
+    public function getChildBlocks($parentName)
     {
-        if (isset($node['ifconfig']) && ($configPath = (string)$node['ifconfig'])) {
-            if (!Mage::getStoreConfigFlag($configPath)) {
-                return $this;
+        $blocks = array();
+        foreach ($this->getChildNames($parentName) as $name) {
+            $block = $this->getBlock($name);
+            if ($block) {
+                $blocks[] = $block;
             }
         }
+        return $blocks;
+    }
 
-        $method = (string)$node['method'];
-        if (!empty($node['block'])) {
-            $parentName = (string)$node['block'];
-        } else {
-            $parentName = $parent->getBlockName();
+    /**
+     * Get child name by alias
+     *
+     * @param string $parentName
+     * @param string $alias
+     * @return bool|string
+     */
+    public function getChildName($parentName, $alias)
+    {
+        return $this->_structure->getChildName($parentName, $alias);
+    }
+
+    /**
+     * Find an element in layout, render it and return string with its output
+     *
+     * @param string $name
+     * @param bool $useCache
+     * @return string
+     */
+    public function renderElement($name, $useCache = true)
+    {
+        if (!isset($this->_renderElementCache[$name]) || !$useCache) {
+            if ($this->_structure->isBlock($name)) {
+                $result = $this->_renderBlock($name);
+            } else {
+                $result = $this->_renderContainer($name);
+            }
+            $this->_renderElementCache[$name] = $result;
+        }
+        $this->_renderingOutput->setData('output', $this->_renderElementCache[$name]);
+        Mage::dispatchEvent('core_layout_render_element', array(
+            'element_name' => $name,
+            'structure'    => $this->_structure,
+            'layout'       => $this,
+            'transport'    => $this->_renderingOutput,
+        ));
+        return $this->_renderingOutput->getData('output');
+    }
+
+    /**
+     * Gets HTML of block element
+     *
+     * @param string $name
+     * @return string
+     * @throws Magento_Exception
+     */
+    protected function _renderBlock($name)
+    {
+        $block = $this->getBlock($name);
+        return $block ? $block->toHtml() : '';
+    }
+
+    /**
+     * Gets HTML of container element
+     *
+     * @param string $name
+     * @return string
+     */
+    protected function _renderContainer($name)
+    {
+        $html = '';
+        $children = $this->_structure->getChildNames($name);
+        foreach ($children as $child) {
+            $html .= $this->renderElement($child);
+        }
+        if ($html == '' || !$this->_structure->getElementAttribute($name, self::CONTAINER_OPT_HTML_TAG)) {
+            return $html;
         }
 
-        $_profilerKey = 'BLOCK_ACTION:' . $parentName . '>' . $method;
-        Magento_Profiler::start($_profilerKey);
+        $htmlId = $this->_structure->getElementAttribute($name, self::CONTAINER_OPT_HTML_ID);
+        if ($htmlId) {
+            $htmlId = ' id="' . $htmlId . '"';
+        }
 
-        if (!empty($parentName)) {
-            $block = $this->getBlock($parentName);
+        $htmlClass = $this->_structure->getElementAttribute($name, self::CONTAINER_OPT_HTML_CLASS);
+        if ($htmlClass) {
+            $htmlClass = ' class="'. $htmlClass . '"';
         }
-        if (!empty($block)) {
 
-            $args = (array)$node->children();
-            unset($args['@attributes']);
-
-            foreach ($args as $key => $arg) {
-                if (($arg instanceof Mage_Core_Model_Layout_Element)) {
-                    if (isset($arg['helper'])) {
-                        $helper = (string)$arg['helper'];
-                        if (strpos($helper, '::') === false) {
-                            $helperName = explode('/', $helper);
-                            $helperMethod = array_pop($helperName);
-                            $helperName = implode('/', $helperName);
-                        } else {
-                            list($helperName, $helperMethod) = explode('::', $helper);
-                        }
-                        $arg = $arg->asArray();
-                        unset($arg['@']);
-                        $args[$key] = call_user_func_array(array(Mage::helper($helperName), $helperMethod), $arg);
-                    } else {
-                        /**
-                         * if there is no helper we hope that this is assoc array
-                         */
-                        $arr = array();
-                        foreach($arg as $subkey => $value) {
-                            $arr[(string)$subkey] = $value->asArray();
-                        }
-                        if (!empty($arr)) {
-                            $args[$key] = $arr;
-                        }
+        $htmlTag = $this->_structure->getElementAttribute($name, self::CONTAINER_OPT_HTML_TAG);
+
+        $html = sprintf('<%1$s%2$s%3$s>%4$s</%1$s>', $htmlTag, $htmlId, $htmlClass, $html);
+
+        return $html;
+    }
+
+    /**
+     * Add element to parent group
+     *
+     * @param string $blockName
+     * @param string $parentGroupName
+     * @return bool
+     */
+    public function addToParentGroup($blockName, $parentGroupName)
+    {
+        return $this->_structure->addToParentGroup($blockName, $parentGroupName);
+    }
+
+    /**
+     * Get element names for specified group
+     *
+     * @param string $blockName
+     * @param string $groupName
+     * @return array
+     */
+    public function getGroupChildNames($blockName, $groupName)
+    {
+        return $this->_structure->getGroupChildNames($blockName, $groupName);
+    }
+
+    /**
+     * Update args according to its type
+     *
+     * @param Mage_Core_Model_Layout_Element $node
+     * @return array
+     */
+    protected function _extractArgs($node)
+    {
+        $args = (array)$node->children();
+        unset($args['@attributes']);
+
+        foreach ($args as $key => $arg) {
+            if (($arg instanceof Mage_Core_Model_Layout_Element)) {
+                if (isset($arg['helper'])) {
+                    $args[$key] = $this->_getArgsByHelper($arg);
+                } else {
+                    /**
+                     * if there is no helper we hope that this is assoc array
+                     */
+                    $arr = $this->_getArgsFromAssoc($arg);
+                    if (!empty($arr)) {
+                        $args[$key] = $arr;
                     }
                 }
             }
+        }
 
-            if (isset($node['json'])) {
-                $json = explode(' ', (string)$node['json']);
-                foreach ($json as $arg) {
-                    $args[$arg] = Mage::helper('Mage_Core_Helper_Data')->jsonDecode($args[$arg]);
-                }
+        if (isset($node['json'])) {
+            $json = explode(' ', (string)$node['json']);
+            foreach ($json as $arg) {
+                $args[$arg] = Mage::helper('Mage_Core_Helper_Data')->jsonDecode($args[$arg]);
             }
+        }
 
-            $this->_translateLayoutNode($node, $args);
-            call_user_func_array(array($block, $method), $args);
+        return $args;
+    }
+
+    /**
+     * Gets arguments using helper method
+     *
+     * @param Mage_Core_Model_Layout_Element $arg
+     * @return mixed
+     */
+    protected function _getArgsByHelper(Mage_Core_Model_Layout_Element $arg)
+    {
+        $helper = (string)$arg['helper'];
+        list($helperName, $helperMethod) = explode('::', $helper);
+        $arg = $arg->asArray();
+        unset($arg['@']);
+        return call_user_func_array(array(Mage::helper($helperName), $helperMethod), $arg);
+    }
+
+    /**
+     * Converts input array to arguments array
+     *
+     * @param array $array
+     * @return array
+     */
+    protected function _getArgsFromAssoc($array)
+    {
+        $arr = array();
+        foreach ($array as $key => $value) {
+            $arr[(string)$key] = $value->asArray();
         }
+        return $arr;
+    }
 
-        Magento_Profiler::stop($_profilerKey);
+    /**
+     * Check if element exists in layout structure
+     *
+     * @param string $name
+     * @return bool
+     */
+    public function hasElement($name)
+    {
+        return $this->_structure->hasElement($name);
+    }
 
-        return $this;
+    /**
+     * Checks if element with specified name is container
+     *
+     * @param string $name
+     * @return bool
+     */
+    public function isContainer($name)
+    {
+        return $this->_structure->isContainer($name);
     }
 
     /**
@@ -366,13 +719,38 @@ class Mage_Core_Model_Layout extends Varien_Simplexml_Config
     protected function _translateLayoutNode($node, &$args)
     {
         if (isset($node['translate'])) {
-            $items = explode(' ', (string)$node['translate']);
-            foreach ($items as $arg) {
-                if (isset($node['module'])) {
-                    $args[$arg] = Mage::helper($node['module'])->__($args[$arg]);
+            // Translate value by core module if module attribute was not set
+            $moduleName = (isset($node['module'])) ? (string)$node['module'] : 'Mage_Core';
+
+            // Handle translations in arrays if needed
+            $translatableArgs = explode(' ', (string)$node['translate']);
+            foreach ($translatableArgs as $translatableArg) {
+                /*
+                 * .(dot) character is used as a path separator in nodes hierarchy
+                 * e.g. info.title means that Magento needs to translate value of <title> node
+                 * that is a child of <info> node
+                 */
+                // @var $argumentHierarhy array - path to translatable item in $args array
+                $argumentHierarchy = explode('.', $translatableArg);
+                $argumentStack = &$args;
+                $canTranslate = true;
+                while (is_array($argumentStack) && count($argumentStack) > 0) {
+                    $argumentName = array_shift($argumentHierarchy);
+                    if (isset($argumentStack[$argumentName])) {
+                        /*
+                         * Move to the next element in arguments hieracrhy
+                         * in order to find target translatable argument
+                         */
+                        $argumentStack = &$argumentStack[$argumentName];
+                    } else {
+                        // Target argument cannot be found
+                        $canTranslate = false;
+                        break;
+                    }
                 }
-                else {
-                    $args[$arg] = Mage::helper('Mage_Core_Helper_Data')->__($args[$arg]);
+                if ($canTranslate && is_string($argumentStack)) {
+                    // $argumentStack is now a reference to target translatable argument so it can be translated
+                    $argumentStack = Mage::helper($moduleName)->__($argumentStack);
                 }
             }
         }
@@ -382,7 +760,8 @@ class Mage_Core_Model_Layout extends Varien_Simplexml_Config
      * Save block in blocks registry
      *
      * @param string $name
-     * @param Mage_Core_Model_Layout $block
+     * @param Mage_Core_Block_abstract $block
+     * @return Mage_Core_Model_Layout
      */
     public function setBlock($name, $block)
     {
@@ -394,40 +773,45 @@ class Mage_Core_Model_Layout extends Varien_Simplexml_Config
      * Remove block from registry
      *
      * @param string $name
+     * @return Mage_Core_Model_Layout
      */
-    public function unsetBlock($name)
+    public function unsetElement($name)
     {
-        $this->_blocks[$name] = null;
-        unset($this->_blocks[$name]);
+        if (isset($this->_blocks[$name])) {
+            $this->_blocks[$name] = null;
+            unset($this->_blocks[$name]);
+        }
+        $this->_structure->unsetElement($name);
+
         return $this;
     }
 
     /**
      * Block Factory
      *
-     * @param     string $type
-     * @param     string $name
-     * @param     array $attributes
-     * @return    Mage_Core_Block_Abstract
+     * @param  string $type
+     * @param  string $name
+     * @param  array $attributes
+     * @return Mage_Core_Block_Abstract
      */
-    public function createBlock($type, $name='', array $attributes = array())
+    public function createBlock($type, $name = '', array $attributes = array())
     {
-        try {
-            $block = $this->_getBlockInstance($type, $attributes);
-        } catch (Exception $e) {
-            Mage::logException($e);
-            return false;
-        }
+        $name = $this->_structure->insertBlock('', $name);
+        $type = $this->_createBlock($type, $name, $attributes);
+        return $type;
+    }
 
-        if (empty($name) || '.'===$name{0}) {
-            $block->setIsAnonymous(true);
-            if (!empty($name)) {
-                $block->setAnonSuffix(substr($name, 1));
-            }
-            $name = 'ANONYMOUS_'.sizeof($this->_blocks);
-        } elseif (isset($this->_blocks[$name]) && Mage::getIsDeveloperMode()) {
-            //Mage::throwException(Mage::helper('Mage_Core_Helper_Data')->__('Block with name "%s" already exists', $name));
-        }
+    /**
+     * Creates block and add to layout
+     *
+     * @param string $type
+     * @param string $name
+     * @param array $attributes
+     * @return Mage_Core_Block_Abstract
+     */
+    protected function _createBlock($type, $name='', array $attributes = array())
+    {
+        $block = $this->_getBlockInstance($type, $attributes);
 
         $block->setType($type);
         $block->setNameInLayout($name);
@@ -442,13 +826,42 @@ class Mage_Core_Model_Layout extends Varien_Simplexml_Config
     /**
      * Add a block to registry, create new object if needed
      *
-     * @param string|Mage_Core_Block_Abstract $blockClass
-     * @param string $blockName
+     * @param string|Mage_Core_Block_Abstract $block
+     * @param string $name
+     * @param string $parent
+     * @param string $alias
+     * @param bool $after
+     * @param string $sibling
      * @return Mage_Core_Block_Abstract
      */
-    public function addBlock($block, $blockName)
+    public function addBlock($block, $name = '', $parent = '', $alias = '', $after = true, $sibling = '')
+    {
+        if (empty($name) && $block instanceof Mage_Core_Block_Abstract) {
+            $name = $block->getNameInLayout();
+        }
+        $name = $this->_structure->insertBlock($parent, $name, $alias, $after, $sibling);
+        $block = $this->_createBlock($block, $name);
+        return $block;
+    }
+
+    /**
+     * Rename element in layout and layout structure
+     *
+     * @param string $oldName
+     * @param string $newName
+     * @return bool
+     */
+    public function renameElement($oldName, $newName)
     {
-        return $this->createBlock($block, $blockName);
+        if (isset($this->_blocks[$oldName])) {
+            $block = $this->_blocks[$oldName];
+            $this->_blocks[$oldName] = null;
+            unset($this->_blocks[$oldName]);
+            $this->_blocks[$newName] = $block;
+        }
+        $this->_structure->renameElement($oldName, $newName);
+
+        return $this;
     }
 
     /**
@@ -487,7 +900,7 @@ class Mage_Core_Model_Layout extends Varien_Simplexml_Config
      * Get block object by name
      *
      * @param string $name
-     * @return Mage_Core_Block_Abstract
+     * @return Mage_Core_Block_Abstract|bool
      */
     public function getBlock($name)
     {
@@ -499,21 +912,50 @@ class Mage_Core_Model_Layout extends Varien_Simplexml_Config
     }
 
     /**
-     * Add a block to output
+     * Gets parent name of an element with specified name
      *
-     * @param string $blockName
-     * @param string $method
+     * @param string $childName
+     * @return bool|string
      */
-    public function addOutputBlock($blockName, $method='toHtml')
+    public function getParentName($childName)
     {
-        //$this->_output[] = array($blockName, $method);
-        $this->_output[$blockName] = array($blockName, $method);
+        return $this->_structure->getParentName($childName);
+    }
+
+    /**
+     * Get element alias by name
+     *
+     * @param string $name
+     * @return string
+     */
+    public function getElementAlias($name)
+    {
+        return $this->_structure->getElementAlias($name);
+    }
+
+    /**
+     * Add an element to output
+     *
+     * @param string $name
+     * @return Mage_Core_Model_Layout
+     */
+    public function addOutputElement($name)
+    {
+        $this->_output[$name] = $name;
         return $this;
     }
 
-    public function removeOutputBlock($blockName)
+    /**
+     * Remove an element from output
+     *
+     * @param string $name
+     * @return Mage_Core_Model_Layout
+     */
+    public function removeOutputElement($name)
     {
-        unset($this->_output[$blockName]);
+        if (false !== ($key = array_search($name, $this->_output))) {
+            unset($this->_output[$key]);
+        }
         return $this;
     }
 
@@ -525,10 +967,8 @@ class Mage_Core_Model_Layout extends Varien_Simplexml_Config
     public function getOutput()
     {
         $out = '';
-        if (!empty($this->_output)) {
-            foreach ($this->_output as $callback) {
-                $out .= $this->getBlock($callback[0])->$callback[1]();
-            }
+        foreach ($this->_output as $name) {
+            $out .= $this->renderElement($name);
         }
 
         return $out;
@@ -615,12 +1055,12 @@ class Mage_Core_Model_Layout extends Varien_Simplexml_Config
             }
         }
         foreach ($node->xpath('ancestor-or-self::*[last()-1]') as $handle) {
-            $name = Mage::getConfig()->determineOmittedNamespace($handle->getName());
+            $name = Mage::getConfig()->determineOmittedNamespace($handle->getName(), true);
             if ($name) {
                 //return Mage::getConfig()->getModuleConfig($name) ? $name : 'core';
                 return $name;
             }
         }
-        return 'core';
+        return 'Mage_Core';
     }
 }
diff --git a/app/code/core/Mage/Core/Model/Layout/Element.php b/app/code/core/Mage/Core/Model/Layout/Element.php
index d9c727ab7bfa5a8177f41d4fe5c78c7392c1759b..0bedfad9bfdab692e25af7fc1206a4c83d5501cd 100644
--- a/app/code/core/Mage/Core/Model/Layout/Element.php
+++ b/app/code/core/Mage/Core/Model/Layout/Element.php
@@ -74,6 +74,42 @@ class Mage_Core_Model_Layout_Element extends Varien_Simplexml_Element
         return (string)$this['name'];
     }
 
+    /**
+     * Get element name
+     *
+     * Advanced version of getBlockName() method: gets name for container as well as for block
+     *
+     * @return string|bool
+     */
+    public function getElementName()
+    {
+        $tagName = $this->getName();
+        if (!in_array($tagName, array('block', 'reference', 'container'))) {
+            return false;
+        }
+        return $this->getAttribute('name');
+    }
+
+    /**
+     * Extracts sibling from 'before' and 'after' attributes
+     *
+     * @return string
+     */
+    public function getSibling()
+    {
+        $sibling = '';
+        if ($this->getAttribute('before')) {
+            $sibling = $this->getAttribute('before');
+        } elseif ($this->getAttribute('after')) {
+            $sibling = $this->getAttribute('after');
+        }
+        if ('-' === $sibling) {
+            $sibling = '';
+        }
+
+        return $sibling;
+    }
+
     public function prepareBlock($args)
     {
         $type = (string)$this['type'];
diff --git a/app/code/core/Mage/Core/Model/Layout/Structure.php b/app/code/core/Mage/Core/Model/Layout/Structure.php
new file mode 100644
index 0000000000000000000000000000000000000000..6472b3a58839885665b142532881e3b9569291c9
--- /dev/null
+++ b/app/code/core/Mage/Core/Model/Layout/Structure.php
@@ -0,0 +1,659 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Layout structure model
+ *
+ * @category   Mage
+ * @package    Mage_Core
+ */
+class Mage_Core_Model_Layout_Structure
+{
+    /**
+     * Available element types
+     */
+    const ELEMENT_TYPE_BLOCK = 'block';
+    const ELEMENT_TYPE_CONTAINER = 'container';
+
+    /**
+     * Prefix for temporary names of elements
+     */
+    const TMP_NAME_PREFIX = 'ANONYMOUS_';
+
+    /**
+     * Page structure as DOM document
+     *
+     * @var DOMDocument
+     */
+    protected $_dom;
+
+    /**
+     * Xpath object
+     *
+     * @var DOMXPath
+     */
+    protected $_xpath;
+
+    /**
+     * Increment for temporary names of elements
+     *
+     * @var int
+     */
+    protected $_nameIncrement = 0;
+
+    /**
+     * Class constructor
+     *
+     */
+    public function __construct()
+    {
+        $this->_dom = new DOMDocument();
+        $this->_dom->formatOutput = true;
+        $this->_dom->loadXML("<layout/>");
+        $this->_xpath = new DOMXPath($this->_dom);
+    }
+
+    /**
+     * Get parent element by name
+     *
+     * @param string $name
+     * @return bool|string
+     */
+    public function getParentName($name)
+    {
+        $elements = $this->_getElementsByName($name);
+        $length = $elements->length;
+        if ($length) {
+            if ($length > 1) {
+                Mage::logException(new Magento_Exception("Too many parents found for element [$name]: " . $length));
+            }
+            $element = $elements->item($length - 1);
+            return $element->parentNode->getAttribute('name');
+        }
+        return false;
+    }
+
+    /**
+     * Get sorted list of child aliases by parent name
+     *
+     * @param string $parentName
+     * @return array
+     */
+    public function getChildNames($parentName)
+    {
+        $children = array();
+        /** @var $child DOMElement */
+        foreach ($this->_findByXpath("//element[@name='$parentName']/element") as $child) {
+            $children[] = $child->getAttribute('name');
+        }
+        return $children;
+    }
+
+    /**
+     * Move node to necessary parent node. If node doesn't exist, creates it
+     *
+     * @param string $parentName
+     * @param string $elementName
+     * @param string $alias
+     * @return Mage_Core_Model_Layout_Structure
+     */
+    public function setChild($parentName, $elementName, $alias)
+    {
+        if (empty($alias)) {
+            $alias = $elementName;
+        }
+        $element = $this->_getElementByName($elementName);
+        if (!$element) {
+            $this->insertBlock($parentName, $elementName, $alias);
+            return $this;
+        } else {
+            $element->setAttribute('alias', $alias);
+        }
+
+        $this->_move($element, $parentName);
+
+        return $this;
+    }
+
+    /**
+     * Sets alias for an element with specified name
+     *
+     * @param string $name
+     * @param string $alias
+     * @return Mage_Core_Model_Layout_Structure|string
+     */
+    public function setElementAlias($name, $alias)
+    {
+        $this->_setElementAttribute($name, 'alias', $alias);
+        return $this;
+    }
+
+    /**
+     * Get element alias by name
+     *
+     * @param string $name
+     * @return string
+     */
+    public function getElementAlias($name)
+    {
+        return $this->getElementAttribute($name, 'alias');
+    }
+
+    /**
+     * Change element's name
+     *
+     * @param string $oldName
+     * @param string $newName
+     * @return Mage_Core_Model_Layout_Structure|string
+     */
+    public function renameElement($oldName, $newName)
+    {
+        $this->_setElementAttribute($oldName, 'name', $newName);
+        return $this;
+    }
+
+    /**
+     * Set element attribute
+     *
+     * @param string $name
+     * @param string $attribute
+     * @return string
+     */
+    public function getElementAttribute($name, $attribute)
+    {
+        $element = $this->_getElementByName($name);
+        if ($element && $element->hasAttribute($attribute)) {
+            return $element->getAttribute($attribute);
+        }
+
+        return '';
+    }
+
+    /**
+     * Set element attribute
+     *
+     * @param string $name
+     * @param string $attribute
+     * @param string $value
+     * @return bool
+     */
+    protected function _setElementAttribute($name, $attribute, $value)
+    {
+        $element = $this->_getElementByName($name);
+        if (!$element) {
+            return false;
+        }
+        $element->setAttribute($attribute, $value);
+
+        return true;
+    }
+
+    /**
+     * Move child element to new parent
+     *
+     * @param string $childName
+     * @param string $parent
+     * @return Mage_Core_Model_Layout_Structure
+     */
+    public function move($childName, $parent)
+    {
+        $child = $this->_getElementByName($childName);
+        if ($child) {
+            $this->_move($child, $parent);
+        }
+
+        return $this;
+    }
+
+    /**
+     * Remove child from parent element
+     *
+     * @param string $parentName
+     * @param string $alias
+     * @return Mage_Core_Model_Layout_Structure
+     */
+    public function unsetChild($parentName, $alias)
+    {
+        $parent = $this->_getElementByXpath("//element[@name='$parentName']");
+        if ($parent) {
+            $child = $this->_getElementByXpath("element[@alias='$alias']", $parent);
+            if ($child) {
+                $parent->removeChild($child);
+            }
+        }
+
+        return $this;
+    }
+
+    /**
+     * Remove elements with specified name from the structure
+     *
+     * @param string $name
+     * @return Mage_Core_Model_Layout_Structure
+     */
+    public function unsetElement($name)
+    {
+        foreach ($this->_getElementsByName($name) as $element) {
+            $element->parentNode->removeChild($element);
+        }
+
+        return $this;
+    }
+
+    /**
+     * Get child name by parent name and alias
+     *
+     * @param string $parentName
+     * @param string $alias
+     * @return string|bool
+     */
+    public function getChildName($parentName, $alias)
+    {
+        $child = $this->_getChildElement($parentName, $alias);
+        if (!$child) {
+            return false;
+        }
+        return $child->getAttribute('name');
+    }
+
+    /**
+     * Add new element to necessary position in the structure
+     *
+     * @param string $parentName
+     * @param string $name
+     * @param string $type
+     * @param string $alias
+     * @param string $sibling
+     * @param bool $after
+     * @param array $options
+     * @return string|bool
+     */
+    public function insertElement($parentName, $name, $type, $alias = '', $after = true, $sibling = '',
+        $options = array()
+    ) {
+        if (!in_array($type, array(self::ELEMENT_TYPE_BLOCK, self::ELEMENT_TYPE_CONTAINER))) {
+            return false;
+        }
+
+        if (empty($name) || '.' === $name{0}) {
+            $name = self::TMP_NAME_PREFIX . ($this->_nameIncrement++);
+        }
+        if ($alias == '') {
+            $alias = $name;
+        }
+
+        $child = $this->_getTempOrNewNode($name);
+        $child->setAttribute('type', $type);
+        $child->setAttribute('alias', $alias);
+        foreach ($options as $optName => $value) {
+            $child->setAttribute($optName, $value);
+        }
+
+        $parentNode = $this->_findOrCreateParentNode($parentName);
+        $this->_clearExistingChild($parentNode, $alias);
+
+        $siblingNode = $this->_getSiblingElement($parentNode, $after, $sibling);
+        if ($siblingNode) {
+            $parentNode->insertBefore($child, $siblingNode);
+        } else {
+            $parentNode->appendChild($child);
+        }
+
+        return $name;
+    }
+
+    /**
+     * Gets temporary node with specified name, creates new node if it doesn't exist
+     *
+     * @param string $name
+     * @return DOMElement|null
+     */
+    protected function _getTempOrNewNode($name)
+    {
+        $child = $this->_getElementByXpath("//element[not(@type) and @name='$name']");
+        if (!$child) {
+            if ($length = $this->_getElementsByName($name)->length) {
+                Mage::logException(new Magento_Exception("Element with name [$name] already exists (" . $length . ')'));
+            }
+            $child = $this->_dom->createElement('element');
+            $child->setAttribute('name', $name);
+        }
+        return $child;
+    }
+
+    /**
+     * Gets parent node with specified name, creates new if it doesn't exist
+     * If $parentNode is not specified, returns root document node
+     *
+     * @param string $parentName
+     * @return bool|DOMElement|DOMNode
+     */
+    protected function _findOrCreateParentNode($parentName)
+    {
+        if ($parentName) {
+            $parentNode = $this->_getElementByName($parentName);
+            if (!$parentNode) {
+                $parentNode = $this->_dom->createElement('element');
+                $parentNode->setAttribute('name', $parentName);
+                $this->_dom->appendChild($parentNode);
+            }
+        } else {
+            $parentNode = $this->_dom->firstChild;
+        }
+        return $parentNode;
+    }
+
+    /**
+     * Get sibling element based on after and siblingName parameter
+     *
+     * @param DOMElement $parentNode
+     * @param string $after
+     * @param string $sibling
+     * @return DOMElement|bool
+     */
+    protected function _getSiblingElement(DOMElement $parentNode, $after, $sibling)
+    {
+        if (!$parentNode->hasChildNodes()) {
+            $sibling = '';
+        }
+        $siblingNode = false;
+        if ('' !== $sibling) {
+            $siblingNode = $this->_getChildElement($parentNode->getAttribute('name'), $sibling);
+            if ($siblingNode && $after) {
+                if (isset($siblingNode->nextSibling)) {
+                    $siblingNode = $siblingNode->nextSibling;
+                } else {
+                    $siblingNode = false;
+                }
+            }
+        }
+        if (!$after && !$siblingNode && isset($parentNode->firstChild)) {
+            $siblingNode = $parentNode->firstChild;
+        }
+
+        return $siblingNode;
+    }
+
+    /**
+     * Remove existing child element
+     *
+     * @param DOMElement $parentNode
+     * @param string $alias
+     * @return bool
+     */
+    protected function _clearExistingChild(DOMElement $parentNode, $alias)
+    {
+        $existent = $this->_getElementByXpath("element[@alias='$alias']", $parentNode);
+        if ($existent) {
+            $parentNode->removeChild($existent);
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Add new block to necessary position in the structure
+     *
+     * @param string $parentName
+     * @param string $name
+     * @param string $alias
+     * @param string $sibling
+     * @param bool $after
+     * @param array $options
+     * @return string|bool
+     */
+    public function insertBlock($parentName, $name, $alias = '', $after = true, $sibling = '', $options = array())
+    {
+        return $this->insertElement($parentName, $name, self::ELEMENT_TYPE_BLOCK, $alias, $after, $sibling, $options);
+    }
+
+    /**
+     * Add new container to necessary position in the structure
+     *
+     * @param string $parentName
+     * @param string $name
+     * @param string $alias
+     * @param string $sibling
+     * @param bool $after
+     * @param array $options
+     * @return string|bool
+     */
+    public function insertContainer($parentName, $name, $alias = '', $after = true, $sibling = '', $options = array())
+    {
+        return $this->insertElement(
+            $parentName, $name, self::ELEMENT_TYPE_CONTAINER, $alias, $after, $sibling, $options
+        );
+    }
+
+    /**
+     * Check if element with specified name exists in the structure
+     *
+     * @param string $name
+     * @return bool
+     */
+    public function hasElement($name)
+    {
+        return $this->_getElementsByName($name)->length > 0;
+    }
+
+    /**
+     * Get children count
+     *
+     * @param string $name
+     * @return int
+     */
+    public function getChildrenCount($name)
+    {
+        return $this->_findByXpath("//element[@name='$name']/element")->length;
+    }
+
+    /**
+     * Add element to parent group
+     *
+     * @param string $name
+     * @param string $groupName
+     * @return bool
+     */
+    public function addToParentGroup($name, $groupName)
+    {
+        $parentName = $this->getParentName($name);
+        if (!$parentName) {
+            return false;
+        }
+        $parentElement = $this->_getElementByName($parentName);
+        if (!$parentElement
+            || $this->_getElementByXpath("groups/group[@name='$groupName']/child[@name='$name']", $parentElement)) {
+            return false;
+        }
+
+        $group = $this->_getElementByXpath("groups/group[@name='$groupName']", $parentElement);
+        if (!$group) {
+            $groups = $this->_getElementByXpath('groups', $parentElement);
+            if (!$groups) {
+                $groups = $this->_dom->createElement('groups');
+                $parentElement->appendChild($groups);
+            }
+            $group = $this->_dom->createElement('group');
+            $groups->appendChild($group);
+            $group->setAttribute('name', $groupName);
+        }
+
+        $child = $this->_dom->createElement('child');
+        $group->appendChild($child);
+        $child->setAttribute('name', $name);
+
+        return true;
+    }
+
+    /**
+     * Get element names for specified group
+     *
+     * @param string $name Name of an element containing group
+     * @param string $groupName
+     * @return array
+     */
+    public function getGroupChildNames($name, $groupName)
+    {
+        $children = array();
+        $elements = $this->_findByXpath("//element[@name='$name']/groups/group[@name='$groupName']/child");
+        /** @var $element DOMElement */
+        foreach ($elements as $element) {
+            $children[] = $element->getAttribute('name');
+        }
+
+        return $children;
+    }
+
+    /**
+     * Check if element with specified name is block
+     *
+     * @param string $name
+     * @return bool
+     */
+    public function isBlock($name)
+    {
+        return $this->_findByXpath("//element[@name='$name' and @type='" .self::ELEMENT_TYPE_BLOCK. "']")->length > 0;
+    }
+
+    /**
+     * Check if element with specified name is container
+     *
+     * @param string $name
+     * @return bool
+     */
+    public function isContainer($name)
+    {
+        return $this->_findByXpath("//element[@name='$name' and @type='" .self::ELEMENT_TYPE_CONTAINER. "']")
+            ->length > 0;
+    }
+
+    /**
+     * Whether the specified element may be manipulated externally
+     *
+     * @param string $name
+     * @return bool
+     */
+    public function isManipulationAllowed($name)
+    {
+        $element = $this->_getElementByName($name);
+        $parent = isset($element->parentNode) ? $element->parentNode : null;
+        if ($parent && self::ELEMENT_TYPE_CONTAINER == $parent->getAttribute('type')) {
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Get child node from a parent
+     *
+     * @param string $parentName
+     * @param string $alias
+     * @return DOMElement|null
+     */
+    protected function _getChildElement($parentName, $alias)
+    {
+        if (!$alias) {
+            return null;
+        }
+        return $this->_getElementByXpath("//element[@name='$parentName']/element[@alias='$alias']");
+    }
+
+    /**
+     * Move element to new parent node
+     *
+     * @param DOMElement $element
+     * @param string $newParent
+     * @return Mage_Core_Model_Layout_Structure
+     * @throws Magento_Exception
+     */
+    protected function _move($element, $newParent)
+    {
+        $parentNode = $this->_findOrCreateParentNode($newParent);
+        if (!$parentNode) {
+            throw new Magento_Exception(
+                "Can not move element [" . $element->getAttribute('name') . "]: parent is not found"
+            );
+        }
+
+        $this->_clearExistingChild($parentNode, $element->getAttribute('alias'));
+        $parentNode->appendChild($element);
+        return $this;
+    }
+
+    /**
+     * Get element by name
+     *
+     * @param string $name
+     * @return DOMElement
+     */
+    protected function _getElementByName($name)
+    {
+        return $this->_getElementByXpath("//element[@name='$name']");
+    }
+
+    /**
+     * @param string $name
+     * @return DOMNodeList
+     */
+    protected function _getElementsByName($name)
+    {
+        return $this->_findByXpath("//element[@name='$name']");
+    }
+
+    /**
+     * Find element(s) by xpath
+     *
+     * @param string $xpath
+     * @param DOMElement $context
+     * @return DOMNodeList
+     */
+    protected function _findByXpath($xpath, $context = null)
+    {
+        if (is_null($context)) {
+            return $this->_xpath->query($xpath);
+        }
+        return $this->_xpath->query($xpath, $context);
+    }
+
+    /**
+     * Get first element by xpath
+     *
+     * Gets element by xpath
+     *
+     * @param string $xpath
+     * @param null|DOMElement $context
+     * @return null|DOMElement
+     */
+    protected function _getElementByXpath($xpath, $context = null)
+    {
+        $elements = $this->_findByXpath($xpath, $context);
+        if ($elements->length) {
+            return $elements->item(0);
+        } else {
+            return null;
+        }
+    }
+}
diff --git a/app/code/core/Mage/Core/Model/Layout/Update.php b/app/code/core/Mage/Core/Model/Layout/Update.php
index 8edf38f82d2475edc8021ee8e7184b6fc411d821..4a215a5d116115c552d8f7e382a3a12c5573fecb 100644
--- a/app/code/core/Mage/Core/Model/Layout/Update.php
+++ b/app/code/core/Mage/Core/Model/Layout/Update.php
@@ -33,30 +33,38 @@ class Mage_Core_Model_Layout_Update
     const LAYOUT_GENERAL_CACHE_TAG = 'LAYOUT_GENERAL_CACHE_TAG';
 
     /**
-     * Layout Update Simplexml Element Class Name
-     *
      * @var string
      */
-    protected $_elementClass;
+    private $_area;
 
     /**
-     * @var Simplexml_Element
+     * @var string
      */
-    protected $_packageLayout;
+    private $_package;
 
     /**
-     * Cache key
-     *
      * @var string
      */
-    protected $_cacheId;
+    private $_theme;
+
+    /**
+     * @var int
+     */
+    private $_storeId;
 
     /**
-     * Cache prefix
+     * Layout Update Simplexml Element Class Name
      *
      * @var string
      */
-    protected $_cachePrefix;
+    protected $_elementClass;
+
+    /**
+     * In-memory cache for loaded layout updates
+     *
+     * @var Mage_Core_Model_Layout_Element
+     */
+    protected $_layoutUpdatesCache;
 
     /**
      * Cumulative array of update XML strings
@@ -72,6 +80,13 @@ class Mage_Core_Model_Layout_Update
      */
     protected $_handles = array();
 
+    /**
+     * Page handle names sorted by from parent to child
+     *
+     * @var array
+     */
+    protected $_pageHandles = array();
+
     /**
      * Substitution values in structure array('from'=>array(), 'to'=>array())
      *
@@ -79,15 +94,35 @@ class Mage_Core_Model_Layout_Update
      */
     protected $_subst = array();
 
-    public function __construct()
+    /**
+     * Constructor
+     *
+     * @param array $arguments
+     */
+    public function __construct(array $arguments = array())
     {
-        $subst = Mage::getConfig()->getPathVars();
-        foreach ($subst as $k=>$v) {
-            $this->_subst['from'][] = '{{'.$k.'}}';
-            $this->_subst['to'][] = $v;
+        /* Default values */
+        $arguments += array(
+            'area'    => Mage::getDesign()->getArea(),
+            'package' => Mage::getDesign()->getPackageName(),
+            'theme'   => Mage::getDesign()->getTheme(),
+            'store'   => null,
+        );
+        $this->_area    = $arguments['area'];
+        $this->_package = $arguments['package'];
+        $this->_theme   = $arguments['theme'];
+        $this->_storeId = Mage::app()->getStore($arguments['store'])->getId();
+        foreach (Mage::getConfig()->getPathVars() as $key => $value) {
+            $this->_subst['from'][] = '{{' . $key . '}}';
+            $this->_subst['to'][] = $value;
         }
     }
 
+    /**
+     * Retrieve XML element class name
+     *
+     * @return string
+     */
     public function getElementClass()
     {
         if (!$this->_elementClass) {
@@ -96,34 +131,44 @@ class Mage_Core_Model_Layout_Update
         return $this->_elementClass;
     }
 
-    public function resetUpdates()
-    {
-        $this->_updates = array();
-        return $this;
-    }
-
+    /**
+     * Add XML update instruction
+     *
+     * @param string $update
+     * @return Mage_Core_Model_Layout_Update
+     */
     public function addUpdate($update)
     {
         $this->_updates[] = $update;
         return $this;
     }
 
+    /**
+     * Get all registered updates as array
+     *
+     * @return array
+     */
     public function asArray()
     {
         return $this->_updates;
     }
 
+    /**
+     * Get all registered updates as string
+     *
+     * @return string
+     */
     public function asString()
     {
         return implode('', $this->_updates);
     }
 
-    public function resetHandles()
-    {
-        $this->_handles = array();
-        return $this;
-    }
-
+    /**
+     * Add handle(s) to update
+     *
+     * @param array|string $handle
+     * @return Mage_Core_Model_Layout_Update
+     */
     public function addHandle($handle)
     {
         if (is_array($handle)) {
@@ -148,54 +193,154 @@ class Mage_Core_Model_Layout_Update
     }
 
     /**
-     * Get cache id
+     * Add the first existing (declared in layout updates) page handle along with all parents to the update.
+     * Return whether any page handles have been added or not.
      *
-     * @return string
+     * @param array $handlesToTry
+     * @return bool
      */
-    public function getCacheId()
+    public function addPageHandles(array $handlesToTry)
     {
-        if (!$this->_cacheId) {
-            $this->_cacheId = 'LAYOUT_'.Mage::app()->getStore()->getId().md5(join('__', $this->getHandles()));
+        foreach ($handlesToTry as $pageHandle) {
+            $handleWithParents = $this->getPageLayoutHandles($pageHandle);
+            if ($handleWithParents) {
+                /* replace existing page handles with the new ones */
+                foreach ($this->_pageHandles as $pageHandle) {
+                    $this->removeHandle($pageHandle);
+                }
+                $this->_pageHandles = $handleWithParents;
+                $this->addHandle($handleWithParents);
+                return true;
+            }
         }
-        return $this->_cacheId;
+        return false;
     }
 
     /**
-     * Set cache id
+     * Retrieve page handle names sorted from parent to child
      *
-     * @param string $cacheId
-     * @return Mage_Core_Model_Layout_Update
+     * @return array
      */
-    public function setCacheId($cacheId)
+    public function getPageHandles()
     {
-        $this->_cacheId = $cacheId;
-        return $this;
+        return $this->_pageHandles;
     }
 
-    public function loadCache()
+    /**
+     * Retrieve the page layout handle along with all parent handles ordered from parent to child
+     *
+     * @param string $pageHandle
+     * @return array
+     */
+    public function getPageLayoutHandles($pageHandle)
     {
-        if (!Mage::app()->useCache('layout')) {
-            return false;
+        $result = array();
+        while ($this->pageTypeExists($pageHandle)) {
+            array_unshift($result, $pageHandle);
+            $pageHandle = $this->getPageTypeParent($pageHandle);
         }
+        return $result;
+    }
 
-        if (!$result = Mage::app()->loadCache($this->getCacheId())) {
-            return false;
+    /**
+     * Retrieve recursively all children of a page type
+     *
+     * @param string $parentName
+     * @return array
+     */
+    protected function _getPageTypeChildren($parentName)
+    {
+        $result = array();
+        $xpath = '/layouts/*[@type="page" and ' . ($parentName ? "@parent='$parentName'" : 'not(@parent)') . ']';
+        $pageTypeNodes = $this->getFileLayoutUpdatesXml()->xpath($xpath) ?: array();
+        /** @var $pageTypeNode Varien_Simplexml_Element */
+        foreach ($pageTypeNodes as $pageTypeNode) {
+            $pageTypeName = $pageTypeNode->getName();
+            $result[$pageTypeName] = array(
+                'name'     => $pageTypeName,
+                'label'    => (string)$pageTypeNode->label,
+                'children' => $this->_getPageTypeChildren($pageTypeName),
+            );
         }
+        return $result;
+    }
 
-        $this->addUpdate($result);
+    /**
+     * @param string $pageTypeName
+     * @return Varien_Simplexml_Element
+     */
+    protected function _getPageTypeNode($pageTypeName)
+    {
+        /* quick validation for non-existing page types */
+        if (!$pageTypeName || !isset($this->getFileLayoutUpdatesXml()->$pageTypeName)) {
+            return null;
+        }
+        $nodes = $this->getFileLayoutUpdatesXml()->xpath("/layouts/{$pageTypeName}[@type='page'][1]");
+        return $nodes ? reset($nodes) : null;
+    }
 
-        return true;
+    /**
+     * Retrieve all page types in the system represented as a hierarchy
+     *
+     * Result format:
+     * array(
+     *     'page_type_1' => array(
+     *         'name'     => 'page_type_1',
+     *         'label'    => 'Page Type 1',
+     *         'children' => array(
+     *             'page_type_2' => array(
+     *                 'name'     => 'page_type_2',
+     *                 'label'    => 'Page Type 2',
+     *                 'children' => array(
+     *                     // ...
+     *                 )
+     *             ),
+     *             // ...
+     *         )
+     *     ),
+     *     // ...
+     * )
+     *
+     * @return array
+     */
+    public function getPageTypesHierarchy()
+    {
+        return $this->_getPageTypeChildren('');
     }
 
-    public function saveCache()
+    /**
+     * Whether a page type is declared in the system or not
+     *
+     * @param string $pageType
+     * @return bool
+     */
+    public function pageTypeExists($pageType)
     {
-        if (!Mage::app()->useCache('layout')) {
-            return false;
-        }
-        $str = $this->asString();
-        $tags = $this->getHandles();
-        $tags[] = self::LAYOUT_GENERAL_CACHE_TAG;
-        return Mage::app()->saveCache($str, $this->getCacheId(), $tags, null);
+        return (bool)$this->_getPageTypeNode($pageType);
+    }
+
+    /**
+     * Retrieve the label for a page type
+     *
+     * @param string $pageType
+     * @return string|bool
+     */
+    public function getPageTypeLabel($pageType)
+    {
+        $pageTypeNode = $this->_getPageTypeNode($pageType);
+        return $pageTypeNode ? (string)$pageTypeNode->label : false;
+    }
+
+    /**
+     * Retrieve the name of the parent for a page type
+     *
+     * @param string $pageType
+     * @return string|null|false
+     */
+    public function getPageTypeParent($pageType)
+    {
+        $pageTypeNode = $this->_getPageTypeNode($pageType);
+        return $pageTypeNode ? $pageTypeNode->getAttribute('parent') : false;
     }
 
     /**
@@ -205,27 +350,28 @@ class Mage_Core_Model_Layout_Update
      * @return Mage_Core_Model_Layout_Update
      * @throws Magento_Exception
      */
-    public function load($handles=array())
+    public function load($handles = array())
     {
         if (is_string($handles)) {
             $handles = array($handles);
-        } elseif (!is_array($handles)) {
+        } else if (!is_array($handles)) {
             throw new Magento_Exception('Invalid layout update handle');
         }
 
-        foreach ($handles as $handle) {
-            $this->addHandle($handle);
-        }
+        $this->addHandle($handles);
 
-        if ($this->loadCache()) {
+        $cacheId = $this->_getCacheId(md5(implode('|', $this->getHandles())));
+        $result = $this->_loadCache($cacheId);
+        if ($result) {
+            $this->addUpdate($result);
             return $this;
         }
 
         foreach ($this->getHandles() as $handle) {
-            $this->merge($handle);
+            $this->_merge($handle);
         }
 
-        $this->saveCache();
+        $this->_saveCache($this->asString(), $cacheId, $this->getHandles());
         return $this;
     }
 
@@ -242,114 +388,28 @@ class Mage_Core_Model_Layout_Update
      * @param string $handle
      * @return Mage_Core_Model_Layout_Update
      */
-    public function merge($handle)
+    protected function _merge($handle)
     {
-        $packageUpdatesStatus = $this->fetchPackageLayoutUpdates($handle);
+        $this->_fetchPackageLayoutUpdates($handle);
         if (Mage::isInstalled()) {
-            $this->fetchDbLayoutUpdates($handle);
+            $this->_fetchDbLayoutUpdates($handle);
         }
-//        if (!$this->fetchPackageLayoutUpdates($handle)
-//            && !$this->fetchDbLayoutUpdates($handle)) {
-//            #$this->removeHandle($handle);
-//        }
         return $this;
     }
 
-    public function fetchFileLayoutUpdates()
-    {
-        $storeId = Mage::app()->getStore()->getId();
-        $elementClass = $this->getElementClass();
-        $design = Mage::getSingleton('Mage_Core_Model_Design_Package');
-        $cacheKey = 'LAYOUT_' . $design->getArea() . '_STORE' . $storeId . '_' . $design->getPackageName() . '_'
-            . $design->getTheme('layout');
-
-        $cacheTags = array(self::LAYOUT_GENERAL_CACHE_TAG);
-        if (Mage::app()->useCache('layout') && ($layoutStr = Mage::app()->loadCache($cacheKey))) {
-            $this->_packageLayout = simplexml_load_string($layoutStr, $elementClass);
-        }
-        if (empty($layoutStr)) {
-            $this->_packageLayout = $this->getFileLayoutUpdatesXml(
-                $design->getArea(),
-                $design->getPackageName(),
-                $design->getTheme('layout'),
-                $storeId
-            );
-            if (Mage::app()->useCache('layout')) {
-                Mage::app()->saveCache($this->_packageLayout->asXml(), $cacheKey, $cacheTags, null);
-            }
-        }
-
-
-
-//        $elementClass = $this->getElementClass();
-//
-//        $design = Mage::getSingleton('Mage_Core_Model_Design_Package');
-//        $area = $design->getArea();
-//        $storeId = Mage::app()->getStore()->getId();
-//        $cacheKey = 'LAYOUT_'.$area.'_STORE'.$storeId.'_'.$design->getPackageName().'_'.$design->getTheme('layout');
-//#echo "TEST:".$cacheKey;
-//        $cacheTags = array('layout');
-//
-//        if (Mage::app()->useCache('layout') && ($layoutStr = Mage::app()->loadCache($cacheKey))) {
-//            $this->_packageLayout = simplexml_load_string($layoutStr, $elementClass);
-//        }
-//
-//        if (empty($layoutStr)) {
-//            $updatesRoot = Mage::app()->getConfig()->getNode($area.'/layout/updates');
-//            Mage::dispatchEvent('core_layout_update_updates_get_after', array('updates' => $updatesRoot));
-//            $updateFiles = array();
-//            foreach ($updatesRoot->children() as $updateNode) {
-//                if ($updateNode->file) {
-//                    $module = $updateNode->getAttribute('module');
-//                    if ($module && Mage::getStoreConfigFlag('advanced/modules_disable_output/' . $module)) {
-//                        continue;
-//                    }
-//                    $updateFiles[] = (string)$updateNode->file;
-//                }
-//            }
-//
-//            // custom local layout updates file - load always last
-//            $updateFiles[] = 'local.xml';
-//
-//            $layoutStr = '';
-//            #$layoutXml = new $elementClass('<layouts/>');
-//            foreach ($updateFiles as $file) {
-//                $filename = $design->getLayoutFilename($file);
-//                if (!is_readable($filename)) {
-//                    continue;
-//                }
-//                $fileStr = file_get_contents($filename);
-//                $fileStr = str_replace($this->_subst['from'], $this->_subst['to'], $fileStr);
-//                $fileXml = simplexml_load_string($fileStr, $elementClass);
-//                if (!$fileXml instanceof SimpleXMLElement) {
-//                    continue;
-//                }
-//                $layoutStr .= $fileXml->innerXml();
-//
-//                #$layoutXml->appendChild($fileXml);
-//            }
-//            $layoutXml = simplexml_load_string('<layouts>'.$layoutStr.'</layouts>', $elementClass);
-//
-//            $this->_packageLayout = $layoutXml;
-//
-//            if (Mage::app()->useCache('layout')) {
-//                Mage::app()->saveCache($this->_packageLayout->asXml(), $cacheKey, $cacheTags, null);
-//            }
-//        }
-
-        return $this;
-    }
-
-    public function fetchPackageLayoutUpdates($handle)
+    /**
+     * Add updates for the specified handle
+     *
+     * @param string $handle
+     * @return bool
+     */
+    protected function _fetchPackageLayoutUpdates($handle)
     {
         $_profilerKey = 'layout_package_update:' . $handle;
         Magento_Profiler::start($_profilerKey);
-        if (empty($this->_packageLayout)) {
-            $this->fetchFileLayoutUpdates();
-        }
-        foreach ($this->_packageLayout->$handle as $updateXml) {
-#echo '<textarea style="width:600px; height:400px;">'.$handle.':'.print_r($updateXml,1).'</textarea>';
-            $this->fetchRecursiveUpdates($updateXml);
+        $layout = $this->getFileLayoutUpdatesXml();
+        foreach ($layout->$handle as $updateXml) {
+            $this->_fetchRecursiveUpdates($updateXml);
             $this->addUpdate($updateXml->innerXml());
         }
         Magento_Profiler::stop($_profilerKey);
@@ -357,14 +417,27 @@ class Mage_Core_Model_Layout_Update
         return true;
     }
 
-    public function fetchDbLayoutUpdates($handle)
+    /**
+     * Fetch & add layout updates for the specified handle from the database
+     *
+     * @param string $handle
+     * @return bool
+     */
+    protected function _fetchDbLayoutUpdates($handle)
     {
-        $_profilerKey = 'layout_db_update: '.$handle;
+        $_profilerKey = 'layout_db_update: ' . $handle;
         Magento_Profiler::start($_profilerKey);
         $updateStr = $this->_getUpdateString($handle);
         if (!$updateStr) {
+            Magento_Profiler::stop($_profilerKey);
             return false;
         }
+        $updateStr = '<update_xml>' . $updateStr . '</update_xml>';
+        $updateStr = str_replace($this->_subst['from'], $this->_subst['to'], $updateStr);
+        $updateXml = simplexml_load_string($updateStr, $this->getElementClass());
+        $this->_fetchRecursiveUpdates($updateXml);
+        $this->addUpdate($updateXml->innerXml());
+
         Magento_Profiler::stop($_profilerKey);
         return (bool)$updateStr;
     }
@@ -380,12 +453,18 @@ class Mage_Core_Model_Layout_Update
         return Mage::getResourceModel('Mage_Core_Model_Resource_Layout')->fetchUpdatesByHandle($handle);
     }
 
-    public function fetchRecursiveUpdates($updateXml)
+    /**
+     * Add handles declared as '<update handle="handle_name"/>' directives
+     *
+     * @param SimpleXMLElement $updateXml
+     * @return Mage_Core_Model_Layout_Update
+     */
+    protected function _fetchRecursiveUpdates($updateXml)
     {
         foreach ($updateXml->children() as $child) {
-            if (strtolower($child->getName())=='update' && isset($child['handle'])) {
-                $this->merge((string)$child['handle']);
-                // Adding merged layout handle to the list of applied hanles
+            if (strtolower($child->getName()) == 'update' && isset($child['handle'])) {
+                $this->_merge((string)$child['handle']);
+                // Adding merged layout handle to the list of applied handles
                 $this->addHandle((string)$child['handle']);
             }
         }
@@ -393,64 +472,110 @@ class Mage_Core_Model_Layout_Update
     }
 
     /**
-     * Collect and merge layout updates from file
+     * Retrieve already merged layout updates from files for specified area/theme/package/store
      *
-     * @param string $area
-     * @param string $package
-     * @param string $theme
-     * @param integer|null $storeId
      * @return Mage_Core_Model_Layout_Element
-     * @throws Magento_Exception
      */
-    public function getFileLayoutUpdatesXml($area, $package, $theme, $storeId = null)
+    public function getFileLayoutUpdatesXml()
     {
-        if (null === $storeId) {
-            $storeId = Mage::app()->getStore()->getId();
+        if ($this->_layoutUpdatesCache) {
+            return $this->_layoutUpdatesCache;
+        }
+        $cacheId = $this->_getCacheId();
+        $result = $this->_loadCache($cacheId);
+        if ($result) {
+            $result = simplexml_load_string($result, $this->getElementClass());
+        } else {
+            $result = $this->_loadFileLayoutUpdatesXml();
+            $this->_saveCache($result->asXml(), $cacheId);
         }
-        /* @var $design Mage_Core_Model_Design_Package */
-        $design = Mage::getSingleton('Mage_Core_Model_Design_Package');
+        $this->_layoutUpdatesCache = $result;
+        return $result;
+    }
 
-        $layoutParams = array(
-            '_area'    => $area,
-            '_package' => $package,
-            '_theme'   => $theme,
-        );
+    /**
+     * Retrieve cache identifier taking into account current area/package/theme/store
+     *
+     * @param string $suffix
+     * @return string
+     */
+    protected function _getCacheId($suffix = '')
+    {
+        return "LAYOUT_{$this->_area}_STORE{$this->_storeId}_{$this->_package}_{$this->_theme}{$suffix}";
+    }
+
+    /**
+     * Retrieve data from the cache, if the layout caching is allowed, or FALSE otherwise
+     *
+     * @param string $cacheId
+     * @return string|false
+     */
+    protected function _loadCache($cacheId)
+    {
+        if (!Mage::app()->useCache('layout')) {
+            return false;
+        }
+        return Mage::app()->loadCache($cacheId);
+    }
+
+    /**
+     * Save data to the cache, if the layout caching is allowed
+     *
+     * @param string $data
+     * @param string $cacheId
+     * @param array $cacheTags
+     */
+    protected function _saveCache($data, $cacheId, array $cacheTags = array())
+    {
+        if (!Mage::app()->useCache('layout')) {
+            return;
+        }
+        $cacheTags[] = self::LAYOUT_GENERAL_CACHE_TAG;
+        Mage::app()->saveCache($data, $cacheId, $cacheTags, null);
+    }
+
+    /**
+     * Collect and merge layout updates from files
+     *
+     * @return Mage_Core_Model_Layout_Element
+     * @throws Magento_Exception
+     */
+    protected function _loadFileLayoutUpdatesXml()
+    {
+        $layoutParams = array('_area' => $this->_area, '_package' => $this->_package, '_theme' => $this->_theme);
 
         /*
          * Allow to modify declared layout updates.
          * For example, the module can remove all its updates to not participate in rendering depending on settings.
          */
-        $updatesRoot = Mage::app()->getConfig()->getNode($area . '/layout/updates');
+        $updatesRootPath = $this->_area . '/layout/updates';
+        $updatesRoot = Mage::app()->getConfig()->getNode($updatesRootPath);
         Mage::dispatchEvent('core_layout_update_updates_get_after', array('updates' => $updatesRoot));
 
         /* Layout update files declared in configuration */
         $updateFiles = array();
         foreach ($updatesRoot->children() as $updateNode) {
-            if ($updateNode->file) {
-                $module = $updateNode->getAttribute('module');
-                if (!$module) {
-                    $updateNodePath = $area . '/layout/updates/' . $updateNode->getName();
-                    throw new Magento_Exception(
-                        "Layout update instruction '{$updateNodePath}' must specify the module."
-                    );
-                }
-                if ($module && Mage::getStoreConfigFlag('advanced/modules_disable_output/' . $module, $storeId)) {
-                    continue;
-                }
-                /* Resolve layout update filename with fallback to the module */
-                $filename = $design->getLayoutFilename(
-                    (string)$updateNode->file,
-                    $layoutParams + array('_module' => $module)
+            $module = $updateNode->getAttribute('module');
+            $file = (string)$updateNode->file;
+            if (!$module || !$file) {
+                $updateNodePath = $updatesRootPath . '/' . $updateNode->getName();
+                throw new Magento_Exception(
+                    "Layout update instruction '{$updateNodePath}' must specify module and file."
                 );
-                if (!is_readable($filename)) {
-                    throw new Magento_Exception("Layout update file '{$filename}' doesn't exist or isn't readable.");
-                }
-                $updateFiles[] = $filename;
             }
+            if (Mage::getStoreConfigFlag("advanced/modules_disable_output/$module", $this->_storeId)) {
+                continue;
+            }
+            /* Resolve layout update filename with fallback to the module */
+            $filename = Mage::getDesign()->getLayoutFilename($file, $layoutParams + array('_module' => $module));
+            if (!is_readable($filename)) {
+                throw new Magento_Exception("Layout update file '{$filename}' doesn't exist or isn't readable.");
+            }
+            $updateFiles[] = $filename;
         }
 
         /* Custom local layout updates file for the current theme */
-        $filename = $design->getLayoutFilename('local.xml', $layoutParams);
+        $filename = Mage::getDesign()->getLayoutFilename('local.xml', $layoutParams);
         if (is_readable($filename)) {
             $updateFiles[] = $filename;
         }
@@ -459,15 +584,35 @@ class Mage_Core_Model_Layout_Update
         foreach ($updateFiles as $filename) {
             $fileStr = file_get_contents($filename);
             $fileStr = str_replace($this->_subst['from'], $this->_subst['to'], $fileStr);
+            /** @var $fileXml Varien_Simplexml_Element */
             $fileXml = simplexml_load_string($fileStr, $this->getElementClass());
-            if (!$fileXml instanceof SimpleXMLElement) {
-                continue;
-            }
             $layoutStr .= $fileXml->innerXml();
         }
         $layoutStr = '<layouts>' . $layoutStr . '</layouts>';
-
         $layoutXml = simplexml_load_string($layoutStr, $this->getElementClass());
         return $layoutXml;
     }
+
+    /**
+     * Retrieve containers from the update handles that have been already loaded
+     *
+     * Result format:
+     * array(
+     *     'container_name' => 'Container Label',
+     *     // ...
+     * )
+     *
+     * @return array
+     */
+    public function getContainers()
+    {
+        $result = array();
+        $containerNodes = $this->asSimplexml()->xpath('//container');
+        /** @var $oneContainerNode Mage_Core_Model_Layout_Element */
+        foreach ($containerNodes as $oneContainerNode) {
+            $helper = Mage::helper(Mage_Core_Model_Layout::findTranslationModuleName($oneContainerNode));
+            $result[$oneContainerNode->getAttribute('name')] = $helper->__($oneContainerNode->getAttribute('label'));
+        }
+        return $result;
+    }
 }
diff --git a/app/code/core/Mage/Core/Model/Locale.php b/app/code/core/Mage/Core/Model/Locale.php
index 39738d875d9b2efb35688d82db67ea2360aa0fc5..320bc352e7ade3a4b62220a37cd3e8eb9ad7c5d2 100644
--- a/app/code/core/Mage/Core/Model/Locale.php
+++ b/app/code/core/Mage/Core/Model/Locale.php
@@ -564,18 +564,23 @@ class Mage_Core_Model_Locale
     {
         Magento_Profiler::start('locale/currency');
         if (!isset(self::$_currencyCache[$this->getLocaleCode()][$currency])) {
+            $options = array();
             try {
                 $currencyObject = new Zend_Currency($currency, $this->getLocale());
             } catch (Exception $e) {
                 $currencyObject = new Zend_Currency($this->getCurrency(), $this->getLocale());
-                $options = array(
-                        'name'      => $currency,
-                        'currency'  => $currency,
-                        'symbol'    => $currency
-                );
-                $currencyObject->setFormat($options);
+                $options['name'] = $currency;
+                $options['currency'] = $currency;
+                $options['symbol'] = $currency;
             }
 
+            $options = new Varien_Object($options);
+            Mage::dispatchEvent('currency_display_options_forming', array(
+                'currency_options' => $options,
+                'base_code' => $currency
+            ));
+
+            $currencyObject->setFormat($options->toArray());
             self::$_currencyCache[$this->getLocaleCode()][$currency] = $currencyObject;
         }
         Magento_Profiler::stop('locale/currency');
@@ -596,8 +601,8 @@ class Mage_Core_Model_Locale
      * '2'054.52' = 2054.52
      * '2,46 GB' = 2.46
      *
-     * @param string|int $value
-     * @return float
+     * @param string|float|int $value
+     * @return float|null
      */
     public function getNumber($value)
     {
@@ -609,9 +614,8 @@ class Mage_Core_Model_Locale
             return floatval($value);
         }
 
-        //trim space and apos
-        $value = str_replace('\'', '', $value);
-        $value = str_replace(' ', '', $value);
+        //trim spaces and apostrophes
+        $value = str_replace(array('\'', ' '), '', $value);
 
         $separatorComa = strpos($value, ',');
         $separatorDot  = strpos($value, '.');
@@ -630,11 +634,10 @@ class Mage_Core_Model_Locale
         }
 
         return floatval($value);
-        //return Zend_Locale_Format::getNumber($value, array('locale' => $this->getLocaleCode()));
     }
 
     /**
-     * Functions returns array with price formating info for js function
+     * Functions returns array with price formatting info for js function
      * formatCurrency in js/varien/js.js
      *
      * @return array
diff --git a/app/code/core/Mage/Core/Model/Message/Abstract.php b/app/code/core/Mage/Core/Model/Message/Abstract.php
index ad581ae4787901df9404666f3a82b1846353f8fb..2b009cd0a4d09c51c73b483210f68bb84ecd3f96 100644
--- a/app/code/core/Mage/Core/Model/Message/Abstract.php
+++ b/app/code/core/Mage/Core/Model/Message/Abstract.php
@@ -120,4 +120,16 @@ abstract class Mage_Core_Model_Message_Abstract
     {
         return $this->_isSticky;
     }
+
+    /**
+     * Set code
+     *
+     * @param string $code
+     * @return Mage_Core_Model_Message_Abstract
+     */
+    public function setCode($code)
+    {
+        $this->_code = $code;
+        return $this;
+    }
 }
diff --git a/app/code/core/Mage/Core/Model/Observer.php b/app/code/core/Mage/Core/Model/Observer.php
index 9ccfe39cad4846cc6714b39eaf861b64704b87b5..296980ada6f734963dd2ebc907509b85bfff0d79 100644
--- a/app/code/core/Mage/Core/Model/Observer.php
+++ b/app/code/core/Mage/Core/Model/Observer.php
@@ -94,4 +94,15 @@ class Mage_Core_Model_Observer
 
         return $this;
     }
+
+    /**
+     * Cron job method to clean old cache resources
+     *
+     * @param Mage_Cron_Model_Schedule $schedule
+     */
+    public function cleanCache(Mage_Cron_Model_Schedule $schedule)
+    {
+        Mage::app()->getCache()->clean(Zend_Cache::CLEANING_MODE_OLD);
+        Mage::dispatchEvent('core_clean_cache');
+    }
 }
diff --git a/app/code/core/Mage/Core/Model/Resource/Db/Abstract.php b/app/code/core/Mage/Core/Model/Resource/Db/Abstract.php
index c03da80b0c76060d516a974a07a813bc089a856f..fdd03a3f59988725e47c23e7a29d32384616242e 100644
--- a/app/code/core/Mage/Core/Model/Resource/Db/Abstract.php
+++ b/app/code/core/Mage/Core/Model/Resource/Db/Abstract.php
@@ -287,6 +287,11 @@ abstract class Mage_Core_Model_Resource_Db_Abstract extends Mage_Core_Model_Reso
      */
     protected function _getReadAdapter()
     {
+        $writeAdapter = $this->_getWriteAdapter();
+        if ($writeAdapter && $writeAdapter->getTransactionLevel() > 0) {
+            // if transaction is started we should use write connection for reading
+            return $writeAdapter;
+        }
         return $this->_getConnection('read');
     }
 
diff --git a/app/code/core/Mage/Core/Model/Resource/Layout.php b/app/code/core/Mage/Core/Model/Resource/Layout.php
index d48bef3210e97932639476dd61d017b254262cd6..98aecdac1aa27276a0731cb3f168a0f32d4221c5 100644
--- a/app/code/core/Mage/Core/Model/Resource/Layout.php
+++ b/app/code/core/Mage/Core/Model/Resource/Layout.php
@@ -85,4 +85,25 @@ class Mage_Core_Model_Resource_Layout extends Mage_Core_Model_Resource_Db_Abstra
         }
         return $result;
     }
+
+    /**
+     * Update a "layout update link" if relevant data is provided
+     *
+     * @param Mage_Core_Model_Abstract $object
+     * @return Mage_Core_Model_Resource_Layout
+     */
+    protected function _afterSave(Mage_Core_Model_Abstract $object)
+    {
+        $data = $object->getData();
+        if (isset($data['store_id']) && isset($data['area']) && isset($data['package']) && isset($data['theme'])) {
+            $this->_getWriteAdapter()->insertOnDuplicate($this->getTable('core_layout_link'), array(
+                'store_id' => $data['store_id'],
+                'area' => $data['area'],
+                'package' => $data['package'],
+                'theme' => $data['theme'],
+                'layout_update_id' => $object->getId(),
+            ));
+        }
+        return parent::_afterSave($object);
+    }
 }
diff --git a/app/code/core/Mage/Core/Model/Resource/Session.php b/app/code/core/Mage/Core/Model/Resource/Session.php
index 139638a02de6fc40b366293f41a275f1c053d78a..4aac11080c235fc50a78bf9ea9855ba7fb292e23 100644
--- a/app/code/core/Mage/Core/Model/Resource/Session.php
+++ b/app/code/core/Mage/Core/Model/Resource/Session.php
@@ -34,11 +34,6 @@
  */
 class Mage_Core_Model_Resource_Session implements Zend_Session_SaveHandler_Interface
 {
-    /**
-     * Session maximum cookie lifetime
-     */
-    const SEESION_MAX_COOKIE_LIFETIME = 3155692600;
-
     /**
      * Session lifetime
      *
@@ -67,15 +62,6 @@ class Mage_Core_Model_Resource_Session implements Zend_Session_SaveHandler_Inter
      */
     protected $_write;
 
-    /**
-     * Automatic cleaning factor of expired sessions
-     * value zero means no automatic cleaning, one means automatic cleaning each time a session is closed, and x>1 means
-     * cleaning once in x calls
-     *
-     * @var int
-     */
-    protected $_automaticCleaningFactor    = 50;
-
     /**
      * Constructor
      *
@@ -97,33 +83,6 @@ class Mage_Core_Model_Resource_Session implements Zend_Session_SaveHandler_Inter
         session_write_close();
     }
 
-    /**
-     * Retrieve session life time
-     *
-     * @return int
-     */
-    public function getLifeTime()
-    {
-        if (is_null($this->_lifeTime)) {
-            $configNode = Mage::app()->getStore()->isAdmin() ?
-                    'admin/security/session_cookie_lifetime' : 'web/cookie/cookie_lifetime';
-            $this->_lifeTime = (int) Mage::getStoreConfig($configNode);
-
-            if ($this->_lifeTime < 60) {
-                $this->_lifeTime = ini_get('session.gc_maxlifetime');
-            }
-
-            if ($this->_lifeTime < 60) {
-                $this->_lifeTime = 3600; //one hour
-            }
-
-            if ($this->_lifeTime > self::SEESION_MAX_COOKIE_LIFETIME) {
-                $this->_lifeTime = self::SEESION_MAX_COOKIE_LIFETIME; // 100 years
-            }
-        }
-        return $this->_lifeTime;
-    }
-
     /**
      * Check DB connection
      *
@@ -182,8 +141,6 @@ class Mage_Core_Model_Resource_Session implements Zend_Session_SaveHandler_Inter
      */
     public function close()
     {
-        $this->gc($this->getLifeTime());
-
         return true;
     }
 
@@ -197,15 +154,12 @@ class Mage_Core_Model_Resource_Session implements Zend_Session_SaveHandler_Inter
     {
         $select = $this->_read->select()
                 ->from($this->_sessionTable, array('session_data'))
-                ->where('session_id = :session_id')
-                ->where('session_expires > :session_expires');
+                ->where('session_id = :session_id');
         $bind = array(
             'session_id'      => $sessId,
-            'session_expires' => Varien_Date::toTimestamp(true)
         );
 
         $data = $this->_read->fetchOne($select, $bind);
-
         return $data;
     }
 
@@ -218,28 +172,23 @@ class Mage_Core_Model_Resource_Session implements Zend_Session_SaveHandler_Inter
      */
     public function write($sessId, $sessData)
     {
-        $bindValues = array(
-            'session_id'      => $sessId
-        );
+        $bindValues = array('session_id' => $sessId);
         $select = $this->_write->select()
                 ->from($this->_sessionTable)
                 ->where('session_id = :session_id');
         $exists = $this->_read->fetchOne($select, $bindValues);
 
         $bind = array(
-            'session_expires' => Varien_Date::toTimestamp(true) + $this->getLifeTime(),
+            'session_expires' => time(),
             'session_data' => $sessData
         );
+
         if ($exists) {
-            $where = array(
-                'session_id=?' => $sessId
-            );
-            $this->_write->update($this->_sessionTable, $bind, $where);
+            $this->_write->update($this->_sessionTable, $bind, array('session_id=?' => $sessId));
         } else {
             $bind['session_id'] = $sessId;
             $this->_write->insert($this->_sessionTable, $bind);
         }
-
         return true;
     }
 
@@ -259,18 +208,13 @@ class Mage_Core_Model_Resource_Session implements Zend_Session_SaveHandler_Inter
     /**
      * Garbage collection
      *
-     * @param int $sessMaxLifeTime ignored
+     * @param int $maxLifeTime
      * @return boolean
      */
-    public function gc($sessMaxLifeTime)
+    public function gc($maxLifeTime)
     {
-        if ($this->_automaticCleaningFactor > 0) {
-            if ($this->_automaticCleaningFactor == 1 ||
-                rand(1, $this->_automaticCleaningFactor) == 1) {
-                $where = array('session_expires < ?' => Varien_Date::toTimestamp(true));
-                $this->_write->delete($this->_sessionTable, $where);
-            }
-        }
+        $where = array('session_expires < ?' => time() - $maxLifeTime);
+        $this->_write->delete($this->_sessionTable, $where);
         return true;
     }
 }
diff --git a/app/code/core/Mage/Core/Model/Resource/Store/Group/Collection.php b/app/code/core/Mage/Core/Model/Resource/Store/Group/Collection.php
index 9d26576d41c2bcd8e97eb0752dc94c8fef1bf435..0145b3c2ed168d2e08ea908546f3858a8ff8604d 100644
--- a/app/code/core/Mage/Core/Model/Resource/Store/Group/Collection.php
+++ b/app/code/core/Mage/Core/Model/Resource/Store/Group/Collection.php
@@ -48,12 +48,12 @@ class Mage_Core_Model_Resource_Store_Group_Collection extends Mage_Core_Model_Re
      * Set flag for load default (admin) store
      *
      * @param boolean $loadDefault
+     *
      * @return Mage_Core_Model_Resource_Store_Group_Collection
      */
     public function setLoadDefault($loadDefault)
     {
-        $this->setFlag('load_default_store_group', (bool)$loadDefault);
-        return $this;
+        return $this->setFlag('load_default_store_group', (bool)$loadDefault);
     }
 
     /**
@@ -67,21 +67,28 @@ class Mage_Core_Model_Resource_Store_Group_Collection extends Mage_Core_Model_Re
     }
 
     /**
-     *  Add disable default store group filter to collection
+     * Add disable default store group filter to collection
      *
      * @return Mage_Core_Model_Resource_Store_Group_Collection
      */
     public function setWithoutDefaultFilter()
     {
-        $this->addFieldToFilter('main_table.group_id', array('gt' => 0));
-        return $this;
+        return $this->addFieldToFilter('main_table.group_id', array('gt' => 0));
+    }
+
+    /**
+     * Filter to discard stores without views
+     *
+     * @return Mage_Core_Model_Resource_Store_Group_Collection
+     */
+    public function setWithoutStoreViewFilter()
+    {
+        return $this->addFieldToFilter('main_table.default_store_id', array('gt' => 0));
     }
 
     /**
      * Load collection data
      *
-     * @param boolean $printQuery
-     * @param boolean $logQuery
      * @return Mage_Core_Model_Resource_Store_Group_Collection
      */
     public function _beforeLoad()
@@ -103,15 +110,15 @@ class Mage_Core_Model_Resource_Store_Group_Collection extends Mage_Core_Model_Re
         return $this->_toOptionArray('group_id', 'name');
     }
 
-     /**
+    /**
      * Add filter by website to collection
      *
      * @param int|array $website
-     * @return Mage_Core_Model_Resource_Store_Collection
+     *
+     * @return Mage_Core_Model_Resource_Store_Group_Collection
      */
     public function addWebsiteFilter($website)
     {
         return $this->addFieldToFilter('main_table.website_id', array('in' => $website));
     }
-
 }
diff --git a/app/code/core/Mage/Core/Model/Session.php b/app/code/core/Mage/Core/Model/Session.php
index cd9e1ee452d199b3e3c703271a5cdf7209dda2f7..34cc640b84094fbe3f4d01b60812d44cbf58d185 100644
--- a/app/code/core/Mage/Core/Model/Session.php
+++ b/app/code/core/Mage/Core/Model/Session.php
@@ -30,6 +30,9 @@
  *
  * @todo extend from Mage_Core_Model_Session_Abstract
  *
+ * @method null|bool getCookieShouldBeReceived()
+ * @method Mage_Core_Model_Session setCookieShouldBeReceived(bool $flag)
+ * @method Mage_Core_Model_Session unsCookieShouldBeReceived()
  */
 class Mage_Core_Model_Session extends Mage_Core_Model_Session_Abstract
 {
diff --git a/app/code/core/Mage/Core/Model/Session/Abstract.php b/app/code/core/Mage/Core/Model/Session/Abstract.php
index d6581184b03e8c117fbc35a1b3574d4238d7ce81..a4a28709c03951c34fed285f5ce206d095bd9cd1 100644
--- a/app/code/core/Mage/Core/Model/Session/Abstract.php
+++ b/app/code/core/Mage/Core/Model/Session/Abstract.php
@@ -32,11 +32,16 @@
  * @package    Mage_Core
  * @author     Magento Core Team <core@magentocommerce.com>
  */
-class Mage_Core_Model_Session_Abstract extends Mage_Core_Model_Session_Abstract_Varien
+class Mage_Core_Model_Session_Abstract extends Varien_Object
 {
+    const VALIDATOR_KEY                         = '_session_validator_data';
+    const VALIDATOR_HTTP_USER_AGENT_KEY         = 'http_user_agent';
+    const VALIDATOR_HTTP_X_FORVARDED_FOR_KEY    = 'http_x_forwarded_for';
+    const VALIDATOR_HTTP_VIA_KEY                = 'http_via';
+    const VALIDATOR_REMOTE_ADDR_KEY             = 'remote_addr';
+
     const XML_PATH_COOKIE_DOMAIN        = 'web/cookie/cookie_domain';
     const XML_PATH_COOKIE_PATH          = 'web/cookie/cookie_path';
-    const XML_PATH_COOKIE_LIFETIME      = 'web/cookie/cookie_lifetime';
     const XML_NODE_SESSION_SAVE         = 'global/session_save';
     const XML_NODE_SESSION_SAVE_PATH    = 'global/session_save_path';
 
@@ -49,6 +54,7 @@ class Mage_Core_Model_Session_Abstract extends Mage_Core_Model_Session_Abstract_
     const XML_NODE_USET_AGENT_SKIP      = 'global/session/validation/http_user_agent_skip';
     const XML_PATH_LOG_EXCEPTION_FILE   = 'dev/log/exception_file';
 
+    const HOST_KEY                      = '_session_hosts';
     const SESSION_ID_QUERY_PARAM        = 'SID';
 
     /**
@@ -73,7 +79,101 @@ class Mage_Core_Model_Session_Abstract extends Mage_Core_Model_Session_Abstract_
     protected $_skipSessionIdFlag   = false;
 
     /**
-     * Init session
+     * Configure session handler and start session
+     *
+     * @param string $sessionName
+     * @return Mage_Core_Model_Session_Abstract
+     */
+    public function start($sessionName=null)
+    {
+        if (isset($_SESSION)) {
+            return $this;
+        }
+
+        switch($this->getSessionSaveMethod()) {
+            case 'db':
+                ini_set('session.save_handler', 'user');
+                $sessionResource = Mage::getResourceSingleton('Mage_Core_Model_Resource_Session');
+                /* @var $sessionResource Mage_Core_Model_Resource_Session */
+                $sessionResource->setSaveHandler();
+                break;
+            case 'memcache':
+                ini_set('session.save_handler', 'memcache');
+                session_save_path($this->getSessionSavePath());
+                break;
+            case 'memcached':
+                ini_set('session.save_handler', 'memcached');
+                session_save_path($this->getSessionSavePath());
+                break;
+            case 'eaccelerator':
+                ini_set('session.save_handler', 'eaccelerator');
+                break;
+            default:
+                session_module_name($this->getSessionSaveMethod());
+                if (is_writable($this->getSessionSavePath())) {
+                    session_save_path($this->getSessionSavePath());
+                }
+                break;
+        }
+        $cookie = $this->getCookie();
+
+        // session cookie params
+        $cookieParams = array(
+            'lifetime' => 0, // 0 is browser session lifetime
+            'path'     => $cookie->getPath(),
+            'domain'   => $cookie->getConfigDomain(),
+            'secure'   => $cookie->isSecure(),
+            'httponly' => $cookie->getHttponly()
+        );
+
+        if (!$cookieParams['httponly']) {
+            unset($cookieParams['httponly']);
+            if (!$cookieParams['secure']) {
+                unset($cookieParams['secure']);
+                if (!$cookieParams['domain']) {
+                    unset($cookieParams['domain']);
+                }
+            }
+        }
+
+        if (isset($cookieParams['domain'])) {
+            $cookieParams['domain'] = $cookie->getDomain();
+        }
+
+        call_user_func_array('session_set_cookie_params', $cookieParams);
+
+        if (!empty($sessionName)) {
+            $this->setSessionName($sessionName);
+        }
+
+        // potential custom logic for session id (ex. switching between hosts)
+        $this->setSessionId();
+
+        Magento_Profiler::start('session_start');
+        $sessionCacheLimiter = Mage::getConfig()->getNode('global/session_cache_limiter');
+        if ($sessionCacheLimiter) {
+            session_cache_limiter((string)$sessionCacheLimiter);
+        }
+
+        session_start();
+
+        Magento_Profiler::stop('session_start');
+
+        return $this;
+    }
+
+    /**
+     * Retrieve cookie object
+     *
+     * @return Mage_Core_Model_Cookie
+     */
+    public function getCookie()
+    {
+        return Mage::getSingleton('Mage_Core_Model_Cookie');
+    }
+
+    /**
+     * Init session with namespace
      *
      * @param string $namespace
      * @param string $sessionName
@@ -81,106 +181,211 @@ class Mage_Core_Model_Session_Abstract extends Mage_Core_Model_Session_Abstract_
      */
     public function init($namespace, $sessionName=null)
     {
-        parent::init($namespace, $sessionName);
-        $this->addHost(true);
+        if (!isset($_SESSION)) {
+            $this->start($sessionName);
+        }
+        if (!isset($_SESSION[$namespace])) {
+            $_SESSION[$namespace] = array();
+        }
+
+        $this->_data = &$_SESSION[$namespace];
+
+        $this->validate();
+        $this->_addHost();
         return $this;
     }
 
     /**
-     * Retrieve Cookie domain
+     * Additional get data with clear mode
+     *
+     * @param string $key
+     * @param bool $clear
+     * @return mixed
+     */
+    public function getData($key='', $clear = false)
+    {
+        $data = parent::getData($key);
+        if ($clear && isset($this->_data[$key])) {
+            unset($this->_data[$key]);
+        }
+        return $data;
+    }
+
+    /**
+     * Retrieve session Id
      *
      * @return string
      */
-    public function getCookieDomain()
+    public function getSessionId()
     {
-        return $this->getCookie()->getDomain();
+        return session_id();
     }
 
     /**
-     * Retrieve cookie path
+     * Retrieve session name
      *
      * @return string
      */
-    public function getCookiePath()
+    public function getSessionName()
     {
-        return $this->getCookie()->getPath();
+        return session_name();
     }
 
     /**
-     * Retrieve cookie lifetime
+     * Set session name
      *
-     * @return int
+     * @param string $name
+     * @return Mage_Core_Model_Session_Abstract
      */
-    public function getCookieLifetime()
+    public function setSessionName($name)
     {
-        return $this->getCookie()->getLifetime();
+        session_name($name);
+        return $this;
     }
 
     /**
-     * Use REMOTE_ADDR in validator key
+     * Unset all data
      *
-     * @return bool
+     * @return Mage_Core_Model_Session_Abstract
      */
-    public function useValidateRemoteAddr()
+    public function unsetAll()
     {
-        $use = Mage::getStoreConfig(self::XML_PATH_USE_REMOTE_ADDR);
-        if (is_null($use)) {
-            return parent::useValidateRemoteAddr();
-        }
-        return (bool)$use;
+        $this->unsetData();
+        return $this;
     }
 
     /**
-     * Use HTTP_VIA in validator key
+     * Alias for unsetAll
      *
-     * @return bool
+     * @return Mage_Core_Model_Session_Abstract
      */
-    public function useValidateHttpVia()
+    public function clear()
     {
-        $use = Mage::getStoreConfig(self::XML_PATH_USE_HTTP_VIA);
-        if (is_null($use)) {
-            return parent::useValidateHttpVia();
+        return $this->unsetAll();
+    }
+
+    /**
+     * Validate session
+     *
+     * @param string $namespace
+     * @return Mage_Core_Model_Session_Abstract
+     */
+    public function validate()
+    {
+        if (!isset($_SESSION[self::VALIDATOR_KEY])) {
+            $_SESSION[self::VALIDATOR_KEY] = $this->_getSessionEnvironment();
+        } else {
+            if (!$this->_validate()) {
+                $this->getCookie()->delete(session_name());
+                // throw core session exception
+                throw new Mage_Core_Model_Session_Exception('');
+            }
         }
-        return (bool)$use;
+
+        return $this;
     }
 
     /**
-     * Use HTTP_X_FORWARDED_FOR in validator key
+     * Validate data
      *
      * @return bool
      */
-    public function useValidateHttpXForwardedFor()
+    protected function _validate()
     {
-        $use = Mage::getStoreConfig(self::XML_PATH_USE_X_FORWARDED);
-        if (is_null($use)) {
-            return parent::useValidateHttpXForwardedFor();
+        $sessionData = $_SESSION[self::VALIDATOR_KEY];
+        $validatorData = $this->_getSessionEnvironment();
+
+        if (Mage::getStoreConfig(self::XML_PATH_USE_REMOTE_ADDR)
+                && $sessionData[self::VALIDATOR_REMOTE_ADDR_KEY] != $validatorData[self::VALIDATOR_REMOTE_ADDR_KEY]) {
+            return false;
+        }
+        if (Mage::getStoreConfig(self::XML_PATH_USE_HTTP_VIA)
+                && $sessionData[self::VALIDATOR_HTTP_VIA_KEY] != $validatorData[self::VALIDATOR_HTTP_VIA_KEY]) {
+            return false;
+        }
+
+        $sessionValidateHttpXForwardedForKey = $sessionData[self::VALIDATOR_HTTP_X_FORVARDED_FOR_KEY];
+        $validatorValidateHttpXForwardedForKey = $validatorData[self::VALIDATOR_HTTP_X_FORVARDED_FOR_KEY];
+        if (Mage::getStoreConfig(self::XML_PATH_USE_X_FORWARDED)
+            && $sessionValidateHttpXForwardedForKey != $validatorValidateHttpXForwardedForKey ) {
+            return false;
+        }
+        if (Mage::getStoreConfig(self::XML_PATH_USE_USER_AGENT)
+            && $sessionData[self::VALIDATOR_HTTP_USER_AGENT_KEY] != $validatorData[self::VALIDATOR_HTTP_USER_AGENT_KEY]
+        ) {
+            $userAgentValidated = $this->getValidateHttpUserAgentSkip();
+            foreach ($userAgentValidated as $agent) {
+                if (preg_match('/' . $agent . '/iu', $validatorData[self::VALIDATOR_HTTP_USER_AGENT_KEY])) {
+                    return true;
+                }
+            }
+            return false;
         }
-        return (bool)$use;
+
+        return true;
     }
 
     /**
-     * Use HTTP_USER_AGENT in validator key
+     * Prepare session environment data for validation
      *
-     * @return bool
+     * @return array
      */
-    public function useValidateHttpUserAgent()
+    protected function _getSessionEnvironment()
     {
-        $use = Mage::getStoreConfig(self::XML_PATH_USE_USER_AGENT);
-        if (is_null($use)) {
-            return parent::useValidateHttpUserAgent();
+        $parts = array(
+            self::VALIDATOR_REMOTE_ADDR_KEY             => '',
+            self::VALIDATOR_HTTP_VIA_KEY                => '',
+            self::VALIDATOR_HTTP_X_FORVARDED_FOR_KEY    => '',
+            self::VALIDATOR_HTTP_USER_AGENT_KEY         => ''
+        );
+
+        // collect ip data
+        if (Mage::helper('Mage_Core_Helper_Http')->getRemoteAddr()) {
+            $parts[self::VALIDATOR_REMOTE_ADDR_KEY] = Mage::helper('Mage_Core_Helper_Http')->getRemoteAddr();
+        }
+        if (isset($_ENV['HTTP_VIA'])) {
+            $parts[self::VALIDATOR_HTTP_VIA_KEY] = (string)$_ENV['HTTP_VIA'];
+        }
+        if (isset($_ENV['HTTP_X_FORWARDED_FOR'])) {
+            $parts[self::VALIDATOR_HTTP_X_FORVARDED_FOR_KEY] = (string)$_ENV['HTTP_X_FORWARDED_FOR'];
         }
-        return (bool)$use;
+
+        // collect user agent data
+        if (isset($_SERVER['HTTP_USER_AGENT'])) {
+            $parts[self::VALIDATOR_HTTP_USER_AGENT_KEY] = (string)$_SERVER['HTTP_USER_AGENT'];
+        }
+
+        return $parts;
+    }
+
+    /**
+     * Retrieve Cookie domain
+     *
+     * @return string
+     */
+    public function getCookieDomain()
+    {
+        return $this->getCookie()->getDomain();
     }
 
     /**
-     * Check whether SID can be used for session initialization
-     * Admin area will always have this feature enabled
+     * Retrieve cookie path
      *
-     * @return bool
+     * @return string
+     */
+    public function getCookiePath()
+    {
+        return $this->getCookie()->getPath();
+    }
+
+    /**
+     * Retrieve cookie lifetime
+     *
+     * @return int
      */
-    public function useSid()
+    public function getCookieLifetime()
     {
-        return Mage::app()->getStore()->isAdmin() || Mage::getStoreConfig(self::XML_PATH_USE_FRONTEND_SID);
+        return $this->getCookie()->getLifetime();
     }
 
     /**
@@ -278,7 +483,7 @@ class Mage_Core_Model_Session_Abstract extends Mage_Core_Model_Session_Abstract_
     }
 
     /**
-     * Adding new nitice message
+     * Adding new notice message
      *
      * @param   string $message
      * @return  Mage_Core_Model_Session_Abstract
@@ -375,38 +580,31 @@ class Mage_Core_Model_Session_Abstract extends Mage_Core_Model_Session_Abstract_
      */
     public function setSessionId($id=null)
     {
-        if (is_null($id) && $this->useSid()) {
+
+        if (is_null($id)
+            && (Mage::app()->getStore()->isAdmin() || Mage::getStoreConfig(self::XML_PATH_USE_FRONTEND_SID))) {
             $_queryParam = $this->getSessionIdQueryParam();
             if (isset($_GET[$_queryParam]) && Mage::getSingleton('Mage_Core_Model_Url')->isOwnOriginUrl()) {
                 $id = $_GET[$_queryParam];
-                /**
-                 * No reason use crypt key for session
-                 */
-//                if ($tryId = Mage::helper('Mage_Core_Helper_Data')->decrypt($_GET[self::SESSION_ID_QUERY_PARAM])) {
-//                    $id = $tryId;
-//                }
             }
         }
 
-        $this->addHost(true);
-        return parent::setSessionId($id);
+        $this->_addHost();
+        if (!is_null($id) && preg_match('#^[0-9a-zA-Z,-]+$#', $id)) {
+            session_id($id);
+        }
+        return $this;
     }
 
     /**
-     * Get ecrypted session identifuer
-     * No reason use crypt key for session id encryption
-     * we can use session identifier as is
+     * Get encrypted session identifier.
+     * No reason use crypt key for session id encryption, we can use session identifier as is.
      *
      * @return string
      */
     public function getEncryptedSessionId()
     {
         if (!self::$_encryptedSessionId) {
-//            $helper = Mage::helper('Mage_Core_Helper_Data');
-//            if (!$helper) {
-//                return $this;
-//            }
-//            self::$_encryptedSessionId = $helper->encrypt($this->getSessionId());
             self::$_encryptedSessionId = $this->getSessionId();
         }
         return self::$_encryptedSessionId;
@@ -444,7 +642,7 @@ class Mage_Core_Model_Session_Abstract extends Mage_Core_Model_Session_Abstract_
     }
 
     /**
-     * If the host was switched but session cookie won't recognize it - add session id to query
+     * If session cookie is not applicable due to host or path mismatch - add session id to query
      *
      * @param string $urlHost can be host or url
      * @return string {session_id_key}={session_id_encrypted}
@@ -455,7 +653,8 @@ class Mage_Core_Model_Session_Abstract extends Mage_Core_Model_Session_Abstract_
             return '';
         }
 
-        if (!$httpHost = Mage::app()->getFrontController()->getRequest()->getHttpHost()) {
+        $httpHost = Mage::app()->getFrontController()->getRequest()->getHttpHost();
+        if (!$httpHost) {
             return '';
         }
 
@@ -463,23 +662,22 @@ class Mage_Core_Model_Session_Abstract extends Mage_Core_Model_Session_Abstract_
         if (!empty($urlHostArr[2])) {
             $urlHost = $urlHostArr[2];
         }
+        $urlPath = empty($urlHostArr[3]) ? '' : $urlHostArr[3];
 
         if (!isset(self::$_urlHostCache[$urlHost])) {
             $urlHostArr = explode(':', $urlHost);
             $urlHost = $urlHostArr[0];
-
-            if ($httpHost !== $urlHost && !$this->isValidForHost($urlHost)) {
-                $sessionId = $this->getEncryptedSessionId();
-            } else {
-                $sessionId = '';
-            }
+            $sessionId = $httpHost !== $urlHost && !$this->isValidForHost($urlHost)
+                ? $this->getEncryptedSessionId() : '';
             self::$_urlHostCache[$urlHost] = $sessionId;
         }
-        return self::$_urlHostCache[$urlHost];
+
+        return Mage::app()->getStore()->isAdmin() || $this->isValidForPath($urlPath) ? self::$_urlHostCache[$urlHost]
+            : $this->getEncryptedSessionId();
     }
 
     /**
-     * Check is valid session for hostname
+     * Check if session is valid for given hostname
      *
      * @param string $host
      * @return bool
@@ -487,42 +685,65 @@ class Mage_Core_Model_Session_Abstract extends Mage_Core_Model_Session_Abstract_
     public function isValidForHost($host)
     {
         $hostArr = explode(':', $host);
-        $hosts = $this->getSessionHosts();
+        $hosts = $this->_getHosts();
         return (!empty($hosts[$hostArr[0]]));
     }
 
     /**
-     * Add hostname to session
+     * Check if session is valid for given path
      *
-     * @param string $host
-     * @return Mage_Core_Model_Session_Abstract
+     * @param string $path
+     * @return bool
      */
-    public function addHost($host)
+    public function isValidForPath($path)
     {
-        if ($host === true) {
-            if (!$host = Mage::app()->getFrontController()->getRequest()->getHttpHost()) {
-                return $this;
-            }
+        $cookiePath = trim($this->getCookiePath(), '/') . '/';
+        if ($cookiePath == '/') {
+            return true;
         }
 
+        $urlPath = trim($path, '/') . '/';
+
+        return strpos($urlPath, $cookiePath) === 0;
+    }
+
+    /**
+     * Register request host name as used with session
+     *
+     * @return Mage_Core_Model_Session_Abstract
+     */
+    protected function _addHost()
+    {
+        $host = Mage::app()->getFrontController()->getRequest()->getHttpHost();
         if (!$host) {
             return $this;
         }
 
-        $hosts = $this->getSessionHosts();
+        $hosts = $this->_getHosts();
         $hosts[$host] = true;
-        $this->setSessionHosts($hosts);
+        $_SESSION[self::HOST_KEY] = $hosts;
         return $this;
     }
 
     /**
-     * Retrieve session hostnames
+     * Get all host names where session was used
      *
      * @return array
      */
-    public function getSessionHosts()
+    protected function _getHosts()
+    {
+        return isset($_SESSION[self::HOST_KEY]) ? $_SESSION[self::HOST_KEY] : array();
+    }
+
+    /**
+     * Clean all host names that were registered with session
+     *
+     * @return Mage_Core_Model_Session_Abstract
+     */
+    protected function _cleanHosts()
     {
-        return $this->getData('session_hosts');
+        unset($_SESSION[self::HOST_KEY]);
+        return $this;
     }
 
     /**
@@ -533,9 +754,9 @@ class Mage_Core_Model_Session_Abstract extends Mage_Core_Model_Session_Abstract_
     public function getSessionSaveMethod()
     {
         if (Mage::isInstalled() && $sessionSave = Mage::getConfig()->getNode(self::XML_NODE_SESSION_SAVE)) {
-            return $sessionSave;
+            return (string) $sessionSave;
         }
-        return parent::getSessionSaveMethod();
+        return 'files';
     }
 
     /**
@@ -548,7 +769,7 @@ class Mage_Core_Model_Session_Abstract extends Mage_Core_Model_Session_Abstract_
         if (Mage::isInstalled() && $sessionSavePath = Mage::getConfig()->getNode(self::XML_NODE_SESSION_SAVE_PATH)) {
             return $sessionSavePath;
         }
-        return parent::getSessionSavePath();
+        return Mage::getBaseDir('session');
     }
 
     /**
@@ -558,10 +779,13 @@ class Mage_Core_Model_Session_Abstract extends Mage_Core_Model_Session_Abstract_
      */
     public function renewSession()
     {
-        $this->getCookie()->delete($this->getSessionName());
-        $this->regenerateSessionId();
+        if (headers_sent()) {
+            Mage::log('Can not regenerate session id because HTTP headers already sent.');
+            return $this;
+        }
+        session_regenerate_id(true);
 
-        $sessionHosts = $this->getSessionHosts();
+        $sessionHosts = $this->_getHosts();
         $currentCookieDomain = $this->getCookie()->getDomain();
         if (is_array($sessionHosts)) {
             foreach (array_keys($sessionHosts) as $host) {
@@ -574,5 +798,4 @@ class Mage_Core_Model_Session_Abstract extends Mage_Core_Model_Session_Abstract_
 
         return $this;
     }
-
 }
diff --git a/app/code/core/Mage/Core/Model/Session/Abstract/Varien.php b/app/code/core/Mage/Core/Model/Session/Abstract/Varien.php
deleted file mode 100644
index f32b59a6ad48f3c032873044b27a2ab097b576bd..0000000000000000000000000000000000000000
--- a/app/code/core/Mage/Core/Model/Session/Abstract/Varien.php
+++ /dev/null
@@ -1,422 +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    Mage
- * @package     Mage_Core
- * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
- * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
- */
-
-
-class Mage_Core_Model_Session_Abstract_Varien extends Varien_Object
-{
-    const VALIDATOR_KEY                         = '_session_validator_data';
-    const VALIDATOR_HTTP_USER_AGENT_KEY         = 'http_user_agent';
-    const VALIDATOR_HTTP_X_FORVARDED_FOR_KEY    = 'http_x_forwarded_for';
-    const VALIDATOR_HTTP_VIA_KEY                = 'http_via';
-    const VALIDATOR_REMOTE_ADDR_KEY             = 'remote_addr';
-
-    /**
-     * Conigure and start session
-     *
-     * @param string $sessionName
-     * @return Mage_Core_Model_Session_Abstract_Varien
-     */
-    public function start($sessionName=null)
-    {
-        if (isset($_SESSION)) {
-            return $this;
-        }
-
-        switch($this->getSessionSaveMethod()) {
-            case 'db':
-                ini_set('session.save_handler', 'user');
-                $sessionResource = Mage::getResourceSingleton('Mage_Core_Model_Resource_Session');
-                /* @var $sessionResource Mage_Core_Model_Resource_Session */
-                $sessionResource->setSaveHandler();
-                break;
-            case 'memcache':
-                ini_set('session.save_handler', 'memcache');
-                session_save_path($this->getSessionSavePath());
-                break;
-            case 'memcached':
-                ini_set('session.save_handler', 'memcached');
-                session_save_path($this->getSessionSavePath());
-                break;
-            case 'eaccelerator':
-                ini_set('session.save_handler', 'eaccelerator');
-                break;
-            default:
-                session_module_name($this->getSessionSaveMethod());
-                if (is_writable($this->getSessionSavePath())) {
-                    session_save_path($this->getSessionSavePath());
-                }
-                break;
-        }
-        $cookie = $this->getCookie();
-        if (Mage::app()->getStore()->isAdmin()) {
-            $sessionMaxLifetime = Mage_Core_Model_Resource_Session::SEESION_MAX_COOKIE_LIFETIME;
-            $adminSessionLifetime = (int)Mage::getStoreConfig('admin/security/session_cookie_lifetime');
-            if ($adminSessionLifetime > $sessionMaxLifetime) {
-                $adminSessionLifetime = $sessionMaxLifetime;
-            }
-            if ($adminSessionLifetime > 60) {
-                $cookie->setLifetime($adminSessionLifetime);
-            }
-        }
-
-        // session cookie params
-        $cookieParams = array(
-            'lifetime' => $cookie->getLifetime(),
-            'path'     => $cookie->getPath(),
-            'domain'   => $cookie->getConfigDomain(),
-            'secure'   => $cookie->isSecure(),
-            'httponly' => $cookie->getHttponly()
-        );
-
-        if (!$cookieParams['httponly']) {
-            unset($cookieParams['httponly']);
-            if (!$cookieParams['secure']) {
-                unset($cookieParams['secure']);
-                if (!$cookieParams['domain']) {
-                    unset($cookieParams['domain']);
-                }
-            }
-        }
-
-        if (isset($cookieParams['domain'])) {
-            $cookieParams['domain'] = $cookie->getDomain();
-        }
-
-        call_user_func_array('session_set_cookie_params', $cookieParams);
-
-        if (!empty($sessionName)) {
-            $this->setSessionName($sessionName);
-        }
-
-        // potential custom logic for session id (ex. switching between hosts)
-        $this->setSessionId();
-
-        Magento_Profiler::start('session_start');
-        $sessionCacheLimiter = Mage::getConfig()->getNode('global/session_cache_limiter');
-        if ($sessionCacheLimiter) {
-            session_cache_limiter((string)$sessionCacheLimiter);
-        }
-
-        session_start();
-
-        /**
-        * Renew cookie expiration time if session id did not change
-        */
-        if ($cookie->get(session_name()) == $this->getSessionId()) {
-            $cookie->renew(session_name());
-        }
-        Magento_Profiler::stop('session_start');
-
-        return $this;
-    }
-
-    /**
-     * Retrieve cookie object
-     *
-     * @return Mage_Core_Model_Cookie
-     */
-    public function getCookie()
-    {
-        return Mage::getSingleton('Mage_Core_Model_Cookie');
-    }
-
-    /**
-     * Init session with namespace
-     *
-     * @param string $namespace
-     * @param string $sessionName
-     * @return Mage_Core_Model_Session_Abstract_Varien
-     */
-    public function init($namespace, $sessionName=null)
-    {
-        if (!isset($_SESSION)) {
-            $this->start($sessionName);
-        }
-        if (!isset($_SESSION[$namespace])) {
-            $_SESSION[$namespace] = array();
-        }
-
-        $this->_data = &$_SESSION[$namespace];
-
-        $this->validate();
-
-        return $this;
-    }
-
-    /**
-     * Additional get data with clear mode
-     *
-     * @param string $key
-     * @param bool $clear
-     * @return mixed
-     */
-    public function getData($key='', $clear = false)
-    {
-        $data = parent::getData($key);
-        if ($clear && isset($this->_data[$key])) {
-            unset($this->_data[$key]);
-        }
-        return $data;
-    }
-
-    /**
-     * Retrieve session Id
-     *
-     * @return string
-     */
-    public function getSessionId()
-    {
-        return session_id();
-    }
-
-    /**
-     * Set custom session id
-     *
-     * @param string $id
-     * @return Mage_Core_Model_Session_Abstract_Varien
-     */
-    public function setSessionId($id=null)
-    {
-        if (!is_null($id) && preg_match('#^[0-9a-zA-Z,-]+$#', $id)) {
-            session_id($id);
-        }
-        return $this;
-    }
-
-    /**
-     * Retrieve session name
-     *
-     * @return string
-     */
-    public function getSessionName()
-    {
-        return session_name();
-    }
-
-    /**
-     * Set session name
-     *
-     * @param string $name
-     * @return Mage_Core_Model_Session_Abstract_Varien
-     */
-    public function setSessionName($name)
-    {
-        session_name($name);
-        return $this;
-    }
-
-    /**
-     * Unset all data
-     *
-     * @return Mage_Core_Model_Session_Abstract_Varien
-     */
-    public function unsetAll()
-    {
-        $this->unsetData();
-        return $this;
-    }
-
-    /**
-     * Alias for unsetAll
-     *
-     * @return Mage_Core_Model_Session_Abstract_Varien
-     */
-    public function clear()
-    {
-        return $this->unsetAll();
-    }
-
-    /**
-     * Retrieve session save method
-     * Default files
-     *
-     * @return string
-     */
-    public function getSessionSaveMethod()
-    {
-        return 'files';
-    }
-
-    /**
-     * Get sesssion save path
-     *
-     * @return string
-     */
-    public function getSessionSavePath()
-    {
-        return Mage::getBaseDir('session');
-    }
-
-    /**
-     * Use REMOTE_ADDR in validator key
-     *
-     * @return bool
-     */
-    public function useValidateRemoteAddr()
-    {
-        return true;
-    }
-
-    /**
-     * Use HTTP_VIA in validator key
-     *
-     * @return bool
-     */
-    public function useValidateHttpVia()
-    {
-        return true;
-    }
-
-    /**
-     * Use HTTP_X_FORWARDED_FOR in validator key
-     *
-     * @return bool
-     */
-    public function useValidateHttpXForwardedFor()
-    {
-        return true;
-    }
-
-    /**
-     * Use HTTP_USER_AGENT in validator key
-     *
-     * @return bool
-     */
-    public function useValidateHttpUserAgent()
-    {
-        return true;
-    }
-
-    /**
-     * Retrieve skip User Agent validation strings (Flash etc)
-     *
-     * @return array
-     */
-    public function getValidateHttpUserAgentSkip()
-    {
-        return array();
-    }
-
-    /**
-     * Validate session
-     *
-     * @param string $namespace
-     * @return Mage_Core_Model_Session_Abstract_Varien
-     */
-    public function validate()
-    {
-        if (!isset($this->_data[self::VALIDATOR_KEY])) {
-            $this->_data[self::VALIDATOR_KEY] = $this->getValidatorData();
-        }
-        else {
-            if (!$this->_validate()) {
-                $this->getCookie()->delete(session_name());
-                // throw core session exception
-                throw new Mage_Core_Model_Session_Exception('');
-            }
-        }
-
-        return $this;
-    }
-
-    /**
-     * Validate data
-     *
-     * @return bool
-     */
-    protected function _validate()
-    {
-        $sessionData = $this->_data[self::VALIDATOR_KEY];
-        $validatorData = $this->getValidatorData();
-
-        if ($this->useValidateRemoteAddr()
-                && $sessionData[self::VALIDATOR_REMOTE_ADDR_KEY] != $validatorData[self::VALIDATOR_REMOTE_ADDR_KEY]) {
-            return false;
-        }
-        if ($this->useValidateHttpVia()
-                && $sessionData[self::VALIDATOR_HTTP_VIA_KEY] != $validatorData[self::VALIDATOR_HTTP_VIA_KEY]) {
-            return false;
-        }
-
-        $sessionValidateHttpXForwardedForKey = $sessionData[self::VALIDATOR_HTTP_X_FORVARDED_FOR_KEY];
-        $validatorValidateHttpXForwardedForKey = $validatorData[self::VALIDATOR_HTTP_X_FORVARDED_FOR_KEY];
-        if ($this->useValidateHttpXForwardedFor()
-            && $sessionValidateHttpXForwardedForKey != $validatorValidateHttpXForwardedForKey ) {
-            return false;
-        }
-        if ($this->useValidateHttpUserAgent()
-            && $sessionData[self::VALIDATOR_HTTP_USER_AGENT_KEY] != $validatorData[self::VALIDATOR_HTTP_USER_AGENT_KEY]
-            && !in_array($validatorData[self::VALIDATOR_HTTP_USER_AGENT_KEY], $this->getValidateHttpUserAgentSkip())) {
-            return false;
-        }
-
-        return true;
-    }
-
-    /**
-     * Retrieve unique user data for validator
-     *
-     * @return array
-     */
-    public function getValidatorData()
-    {
-        $parts = array(
-            self::VALIDATOR_REMOTE_ADDR_KEY             => '',
-            self::VALIDATOR_HTTP_VIA_KEY                => '',
-            self::VALIDATOR_HTTP_X_FORVARDED_FOR_KEY    => '',
-            self::VALIDATOR_HTTP_USER_AGENT_KEY         => ''
-        );
-
-        // collect ip data
-        if (Mage::helper('Mage_Core_Helper_Http')->getRemoteAddr()) {
-            $parts[self::VALIDATOR_REMOTE_ADDR_KEY] = Mage::helper('Mage_Core_Helper_Http')->getRemoteAddr();
-        }
-        if (isset($_ENV['HTTP_VIA'])) {
-            $parts[self::VALIDATOR_HTTP_VIA_KEY] = (string)$_ENV['HTTP_VIA'];
-        }
-        if (isset($_ENV['HTTP_X_FORWARDED_FOR'])) {
-            $parts[self::VALIDATOR_HTTP_X_FORVARDED_FOR_KEY] = (string)$_ENV['HTTP_X_FORWARDED_FOR'];
-        }
-
-        // collect user agent data
-        if (isset($_SERVER['HTTP_USER_AGENT'])) {
-            $parts[self::VALIDATOR_HTTP_USER_AGENT_KEY] = (string)$_SERVER['HTTP_USER_AGENT'];
-        }
-
-        return $parts;
-    }
-
-    /**
-     * Regenerate session Id
-     *
-     * @return Mage_Core_Model_Session_Abstract_Varien
-     */
-    public function regenerateSessionId()
-    {
-        session_regenerate_id(true);
-        return $this;
-    }
-}
diff --git a/app/code/core/Mage/Core/Model/Session/Abstract/Zend.php b/app/code/core/Mage/Core/Model/Session/Abstract/Zend.php
deleted file mode 100644
index a2a4d78c2e873151374467dfaaa185debf93b967..0000000000000000000000000000000000000000
--- a/app/code/core/Mage/Core/Model/Session/Abstract/Zend.php
+++ /dev/null
@@ -1,176 +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    Mage
- * @package     Mage_Core
- * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
- * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
- */
-
-/**
- * Session abstaract class
- *
- * @category   Mage
- * @package    Mage_Core
- * @author      Magento Core Team <core@magentocommerce.com>
- */
-abstract class Mage_Core_Model_Session_Abstract_Zend extends Varien_Object
-{
-    /**
-     * Session namespace object
-     *
-     * @var Zend_Session_Namespace
-     */
-    protected $_namespace;
-
-    public function getNamespace()
-    {
-        return $this->_namespace;
-    }
-
-    public function start()
-    {
-        Magento_Profiler::start(__METHOD__.'/setOptions');
-        $options = array(
-            'save_path'=>Mage::getBaseDir('session'),
-            'use_only_cookies'=>'off',
-            'throw_startup_exceptions' => E_ALL ^ E_NOTICE,
-        );
-        if ($this->getCookieDomain()) {
-            $options['cookie_domain'] = $this->getCookieDomain();
-        }
-        if ($this->getCookiePath()) {
-            $options['cookie_path'] = $this->getCookiePath();
-        }
-        if ($this->getCookieLifetime()) {
-            $options['cookie_lifetime'] = $this->getCookieLifetime();
-        }
-        Zend_Session::setOptions($options);
-        Magento_Profiler::stop(__METHOD__.'/setOptions');
-/*
-        Magento_Profiler::start(__METHOD__.'/setHandler');
-        $sessionResource = Mage::getResourceSingleton('Mage_Core_Model_Resource_Session');
-        if ($sessionResource->hasConnection()) {
-            Zend_Session::setSaveHandler($sessionResource);
-        }
-        Magento_Profiler::stop(__METHOD__.'/setHandler');
-*/
-        Magento_Profiler::start(__METHOD__.'/start');
-        Zend_Session::start();
-        Magento_Profiler::stop(__METHOD__.'/start');
-
-        return $this;
-    }
-
-    /**
-     * Initialization session namespace
-     *
-     * @param string $namespace
-     */
-    public function init($namespace)
-    {
-        if (!Zend_Session::sessionExists()) {
-            $this->start();
-        }
-
-        Magento_Profiler::start(__METHOD__.'/init');
-        $this->_namespace = new Zend_Session_Namespace($namespace, Zend_Session_Namespace::SINGLE_INSTANCE);
-        Magento_Profiler::stop(__METHOD__.'/init');
-        return $this;
-    }
-
-    /**
-     * Redeclaration object setter
-     *
-     * @param   string $key
-     * @param   mixed $value
-     * @return  Mage_Core_Model_Session_Abstract
-     */
-    public function setData($key, $value='', $isChanged = false)
-    {
-        if (!$this->_namespace->data) {
-            $this->_namespace->data = new Varien_Object();
-        }
-        $this->_namespace->data->setData($key, $value, $isChanged);
-        return $this;
-    }
-
-    /**
-     * Redeclaration object getter
-     *
-     * @param   string $var
-     * @param   bool $clear
-     * @return  mixed
-     */
-    public function getData($var=null, $clear=false)
-    {
-        if (!$this->_namespace->data) {
-            $this->_namespace->data = new Varien_Object();
-        }
-
-        $data = $this->_namespace->data->getData($var);
-
-        if ($clear) {
-            $this->_namespace->data->unsetData($var);
-        }
-
-        return $data;
-    }
-
-    /**
-     * Cleare session data
-     *
-     * @return Mage_Core_Model_Session_Abstract
-     */
-    public function unsetAll()
-    {
-        $this->_namespace->unsetAll();
-        return $this;
-    }
-
-    /**
-     * Retrieve current session identifier
-     *
-     * @return string
-     */
-    public function getSessionId()
-    {
-        return Zend_Session::getId();
-    }
-
-    public function setSessionId($id=null)
-    {
-        if (!is_null($id)) {
-            Zend_Session::setId($id);
-        }
-        return $this;
-    }
-
-    /**
-     * Regenerate session Id
-     *
-     * @return Mage_Core_Model_Session_Abstract_Zend
-     */
-    public function regenerateSessionId()
-    {
-        Zend_Session::regenerateId();
-        return $this;
-    }
-}
diff --git a/app/code/core/Mage/Core/Model/Translate/Inline.php b/app/code/core/Mage/Core/Model/Translate/Inline.php
index 60b9a50b6bbdaada22a67ff37153f71891cf2774..6f7e20aa6ca1757e4d254d5514876d4dd96fc36f 100644
--- a/app/code/core/Mage/Core/Model/Translate/Inline.php
+++ b/app/code/core/Mage/Core/Model/Translate/Inline.php
@@ -264,7 +264,7 @@ class Mage_Core_Model_Translate_Inline
 ?>
 <script type="text/javascript" src="<?php echo $design->getSkinUrl('prototype/window.js') ?>"></script>
 <link rel="stylesheet" type="text/css" href="<?php echo $design->getSkinUrl('prototype/windows/themes/default.css') ?>"/>
-<link rel="stylesheet" type="text/css" href="<?php echo $design->getSkinUrl('prototype/windows/themes/magento.css') ?>"/>
+<link rel="stylesheet" type="text/css" href="<?php echo $design->getSkinUrl('Mage_Core::prototype/magento.css') ?>"/>
 
 <script type="text/javascript" src="<?php echo $design->getSkinUrl('mage/translate_inline.js') ?>"></script>
 <link rel="stylesheet" type="text/css" href="<?php echo $design->getSkinUrl('mage/translate_inline.css') ?>"/>
diff --git a/app/code/core/Mage/Core/Model/Url.php b/app/code/core/Mage/Core/Model/Url.php
index ea8f81f6310e12aa1cf6111230240c5a83e654ae..68ae0fdc539f45b10294fd6720ec0a15055fdacb 100644
--- a/app/code/core/Mage/Core/Model/Url.php
+++ b/app/code/core/Mage/Core/Model/Url.php
@@ -89,7 +89,7 @@ class Mage_Core_Model_Url extends Varien_Object
     const DEFAULT_ACTION_NAME       = 'index';
 
     /**
-     * Configuration pathes
+     * Configuration paths
      */
     const XML_PATH_UNSECURE_URL     = 'web/unsecure/base_url';
     const XML_PATH_SECURE_URL       = 'web/secure/base_url';
@@ -111,7 +111,7 @@ class Mage_Core_Model_Url extends Varien_Object
     static protected $_encryptedSessionId;
 
     /**
-     * Reserved Route parametr keys
+     * Reserved Route parameter keys
      *
      * @var array
      */
@@ -136,7 +136,7 @@ class Mage_Core_Model_Url extends Varien_Object
     protected $_useSession;
 
     /**
-     * Initailize object
+     * Initialize object
      */
     protected function _construct()
     {
@@ -864,7 +864,7 @@ class Mage_Core_Model_Url extends Varien_Object
     }
 
     /**
-     * Retrurn Query Params
+     * Return Query Params
      *
      * @return array
      */
@@ -948,8 +948,8 @@ class Mage_Core_Model_Url extends Varien_Object
         $escapeQuery = false;
 
         /**
-         * All system params should be unseted before we call getRouteUrl
-         * this method has condition for ading default controller anr actions names
+         * All system params should be unset before we call getRouteUrl
+         * this method has condition for adding default controller and action names
          * in case when we have params
          */
         if (isset($routeParams['_fragment'])) {
@@ -971,7 +971,7 @@ class Mage_Core_Model_Url extends Varien_Object
 
         $noSid = null;
         if (isset($routeParams['_nosid'])) {
-            $noSid = (bool) $routeParams['_nosid'];
+            $noSid = (bool)$routeParams['_nosid'];
             unset($routeParams['_nosid']);
         }
         $url = $this->getRouteUrl($routePath, $routeParams);
@@ -1010,27 +1010,35 @@ class Mage_Core_Model_Url extends Varien_Object
      * Check and add session id to URL
      *
      * @param string $url
+     *
      * @return Mage_Core_Model_Url
      */
     protected function _prepareSessionUrl($url)
+    {
+        return $this->_prepareSessionUrlWithParams($url, array());
+    }
+
+    /**
+     * Check and add session id to URL, session is obtained with parameters
+     *
+     * @param string $url
+     * @param array $params
+     *
+     * @return Mage_Core_Model_Url
+     */
+    protected function _prepareSessionUrlWithParams($url, array $params)
     {
         if (!$this->getUseSession()) {
             return $this;
         }
-        $session = Mage::getSingleton('Mage_Core_Model_Session');
         /** @var $session Mage_Core_Model_Session */
-        if (Mage::app()->getUseSessionVar() && !$session->getSessionIdForHost($url)) {
-            // secure URL
-            if ($this->getSecure()) {
-                $this->setQueryParam('___SID', 'S');
-            } else {
-                $this->setQueryParam('___SID', 'U');
-            }
-        } else {
-            $sessionId = $session->getSessionIdForHost($url);
-            if ($sessionId) {
-                $this->setQueryParam($session->getSessionIdQueryParam(), $sessionId);
-            }
+        $session = Mage::getSingleton('Mage_Core_Model_Session', $params);
+
+        $sessionId = $session->getSessionIdForHost($url);
+        if (Mage::app()->getUseSessionVar() && !$sessionId) {
+            $this->setQueryParam('___SID', $this->getSecure() ? 'S' : 'U'); // Secure/Unsecure
+        } else if ($sessionId) {
+            $this->setQueryParam($session->getSessionIdQueryParam(), $sessionId);
         }
         return $this;
     }
@@ -1177,4 +1185,25 @@ class Mage_Core_Model_Url extends Varien_Object
         }
         return false;
     }
+
+    /**
+     * Return frontend redirect URL with SID and other session parameters if any
+     *
+     * @param string $url
+     *
+     * @return string
+     */
+    public function getRedirectUrl($url)
+    {
+        $this->_prepareSessionUrlWithParams($url, array(
+            'name' => Mage_Core_Controller_Front_Action::SESSION_NAMESPACE
+        ));
+
+        $query = $this->getQuery(false);
+        if ($query) {
+            $url .= (strpos($url, '?') === false ? '?' : '&') . $query;
+        }
+
+        return $url;
+    }
 }
diff --git a/app/code/core/Mage/Core/etc/config.xml b/app/code/core/Mage/Core/etc/config.xml
index 113756251afa5e15698ee085eebaed3e75b2c3b2..88a6f10b7746a953a28e4431f3f4a6306ea96717 100644
--- a/app/code/core/Mage/Core/etc/config.xml
+++ b/app/code/core/Mage/Core/etc/config.xml
@@ -73,8 +73,7 @@
             <validation>
                 <http_user_agent_skip>
                     <flash>Shockwave Flash</flash>
-                    <flash_9_mac>Adobe Flash Player 9</flash_9_mac>
-                    <flash_10_mac>Adobe Flash Player 10</flash_10_mac>
+                    <flash_mac><![CDATA[Adobe Flash Player\s{1,}\w{1,10}]]></flash_mac>
                 </http_user_agent_skip>
             </validation>
         </session>
@@ -271,6 +270,7 @@
             <cookie>
                 <cookie_lifetime>3600</cookie_lifetime>
                 <cookie_httponly>1</cookie_httponly>
+                <cookie_restriction>0</cookie_restriction>
             </cookie>
             <session>
                 <use_remote_addr>0</use_remote_addr>
@@ -343,4 +343,16 @@
             </web>
         </default>
     </stores>
+    <crontab>
+        <jobs>
+            <core_clean_cache>
+                <schedule>
+                    <cron_expr>30 2 * * *</cron_expr>
+                </schedule>
+                <run>
+                    <model>Mage_Core_Model_Observer::cleanCache</model>
+                </run>
+            </core_clean_cache>
+        </jobs>
+    </crontab>
 </config>
diff --git a/app/code/core/Mage/Core/etc/translater.xml b/app/code/core/Mage/Core/etc/jstranslator.xml
similarity index 99%
rename from app/code/core/Mage/Core/etc/translater.xml
rename to app/code/core/Mage/Core/etc/jstranslator.xml
index 237bd08c4c2b2f42e24b4686b26a5cba106aea3f..4168a824889f4b4bce25712636e89f04b9c8dc0b 100644
--- a/app/code/core/Mage/Core/etc/translater.xml
+++ b/app/code/core/Mage/Core/etc/jstranslator.xml
@@ -25,7 +25,7 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 -->
-<translater>
+<jstranslator>
     <!-- validation.js -->
     <validate-no-html-tags translate="message" module="Mage_Core">
         <message>HTML tags are not allowed</message>
@@ -202,4 +202,4 @@
         <message>Please enter a valid date less than or equal to %s</message>
     </validate-date-less>
     <!-- end js.js -->
-</translater>
+</jstranslator>
diff --git a/app/code/core/Mage/Core/etc/system.xml b/app/code/core/Mage/Core/etc/system.xml
index 3cfe32059a6cb5bb7844619db830794565a9b770..14cf368d37a0a1156c1b439134cf723221a087c7 100644
--- a/app/code/core/Mage/Core/etc/system.xml
+++ b/app/code/core/Mage/Core/etc/system.xml
@@ -347,6 +347,35 @@
                         </anchor_text_for_next>
                     </fields>
                 </pagination>
+                <email translate="label">
+                    <label>Transactional Emails</label>
+                    <frontend_type>text</frontend_type>
+                    <sort_order>510</sort_order>
+                    <show_in_default>1</show_in_default>
+                    <show_in_website>1</show_in_website>
+                    <show_in_store>1</show_in_store>
+                    <fields>
+                        <logo translate="label">
+                            <label>Logo Image</label>
+                            <comment>Allowed file types: jpg, jpeg, gif, png</comment>
+                            <frontend_type>image</frontend_type>
+                            <backend_model>Mage_Adminhtml_Model_System_Config_Backend_Email_Logo</backend_model>
+                            <base_url type="media" scope_info="1">email/logo</base_url>
+                            <sort_order>10</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>1</show_in_store>
+                        </logo>
+                        <logo_alt translate="label">
+                            <label>Logo Image Alt</label>
+                            <frontend_type>text</frontend_type>
+                            <sort_order>20</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>1</show_in_store>
+                        </logo_alt>
+                    </fields>
+                </email>
             </groups>
         </design>
         <dev translate="label" module="Mage_Core">
@@ -853,8 +882,8 @@
                             <source_model>Mage_Adminhtml_Model_System_Config_Source_Email_Template</source_model>
                             <sort_order>10</sort_order>
                             <show_in_default>1</show_in_default>
-                            <show_in_website>1</show_in_website>
-                            <show_in_store>1</show_in_store>
+                            <show_in_website>0</show_in_website>
+                            <show_in_store>0</show_in_store>
                         </forgot_email_template>
                         <forgot_email_identity translate="label">
                             <label>Forgot Password Email Sender</label>
@@ -862,13 +891,14 @@
                             <source_model>Mage_Adminhtml_Model_System_Config_Source_Email_Identity</source_model>
                             <sort_order>20</sort_order>
                             <show_in_default>1</show_in_default>
-                            <show_in_website>1</show_in_website>
-                            <show_in_store>1</show_in_store>
+                            <show_in_website>0</show_in_website>
+                            <show_in_store>0</show_in_store>
                         </forgot_email_identity>
                         <password_reset_link_expiration_period translate="label comment">
                             <label>Recovery Link Expiration Period (days)</label>
-                            <comment>This value must be greater than 0.</comment>
+                            <comment>Please enter a number 1 or greater in this field.</comment>
                             <frontend_type>text</frontend_type>
+                            <validate>required-entry validate-digits validate-digits-range digits-range-1-</validate>
                             <backend_model>Mage_Adminhtml_Model_System_Config_Backend_Admin_Password_Link_Expirationperiod</backend_model>
                             <sort_order>30</sort_order>
                             <show_in_default>1</show_in_default>
@@ -976,15 +1006,15 @@
                             <show_in_website>0</show_in_website>
                             <show_in_store>0</show_in_store>
                         </use_case_sensitive_login>
-                        <session_cookie_lifetime translate="label comment">
-                            <label>Session Lifetime (seconds)</label>
-                            <comment>Values less than 60 are ignored. Note that changes will apply after logout.</comment>
+                        <session_lifetime translate="label comment">
+                            <label>Admin Session Lifetime (seconds)</label>
+                            <comment>Values less than 60 are ignored.</comment>
                             <validate>validate-digits</validate>
                             <sort_order>3</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>0</show_in_website>
                             <show_in_store>0</show_in_store>
-                        </session_cookie_lifetime>
+                        </session_lifetime>
                     </fields>
                 </security>
                 <dashboard translate="label">
@@ -1224,7 +1254,7 @@
                     <show_in_store>1</show_in_store>
                 </polls>
                 <cookie translate="label">
-                    <label>Session Cookie Management</label>
+                    <label>Default Cookie Settings</label>
                     <frontend_type>text</frontend_type>
                     <sort_order>50</sort_order>
                     <show_in_default>1</show_in_default>
@@ -1264,6 +1294,15 @@
                             <show_in_website>1</show_in_website>
                             <show_in_store>1</show_in_store>
                         </cookie_httponly>
+                        <cookie_restriction translate="label">
+                            <label>Cookie Restriction Mode</label>
+                            <frontend_type>select</frontend_type>
+                            <source_model>Mage_Adminhtml_Model_System_Config_Source_Yesno</source_model>
+                            <sort_order>50</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </cookie_restriction>
                     </fields>
                 </cookie>
                 <session translate="label">
diff --git a/app/design/frontend/default/default/skin/blank/images/logo_email.gif b/app/code/core/Mage/Core/view/adminhtml/logo_email.gif
similarity index 100%
rename from app/design/frontend/default/default/skin/blank/images/logo_email.gif
rename to app/code/core/Mage/Core/view/adminhtml/logo_email.gif
diff --git a/pub/js/prototype/windows/themes/magento.css b/app/code/core/Mage/Core/view/adminhtml/prototype/magento.css
similarity index 62%
rename from pub/js/prototype/windows/themes/magento.css
rename to app/code/core/Mage/Core/view/adminhtml/prototype/magento.css
index 93fef2ad762a0ab453bc0622132d8e1d66e4ad0b..9492d511e779ce491ff1aba5893c61fc5f9f1594 100644
--- a/pub/js/prototype/windows/themes/magento.css
+++ b/app/code/core/Mage/Core/view/adminhtml/prototype/magento.css
@@ -1,3 +1,28 @@
+/**
+ * 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_Core
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+
 .dialog { border:1px solid #555; }
 .dialog .bot { display:none !important; }
 .overlay_magento { background-color:#000; filter:alpha(opacity=60); -moz-opacity:.6; opacity:.6; -webkit-opacity:.6; }
@@ -30,6 +55,7 @@
 
 .magento_buttons { padding:10px; text-align:right; }
 .magento_buttons input.button { border-width:1px; border-style:solid; border-color:#ed6502 #a04300 #a04300 #ed6502;  background:#ffac47 url(magento/btn_bg.gif) 0 100% repeat-x; padding:0 7px 1px 7px; font:bold 12px/18px Arial, Helvetica, sans-serif; color:#fff; cursor:pointer; text-align:center; white-space:nowrap; }
+.magento_buttons button.button span span span { display:inline; background:none; padding:0; height:auto; }
 
 /* FOR IE */
 * html .magento_close { background-image:none; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src="../themes/magento/window_close.png", sizingMethod="crop"); }
diff --git a/pub/js/prototype/windows/themes/magento/btn_bg.gif b/app/code/core/Mage/Core/view/adminhtml/prototype/magento/btn_bg.gif
similarity index 100%
rename from pub/js/prototype/windows/themes/magento/btn_bg.gif
rename to app/code/core/Mage/Core/view/adminhtml/prototype/magento/btn_bg.gif
diff --git a/pub/js/prototype/windows/themes/magento/content_bg.gif b/app/code/core/Mage/Core/view/adminhtml/prototype/magento/content_bg.gif
similarity index 100%
rename from pub/js/prototype/windows/themes/magento/content_bg.gif
rename to app/code/core/Mage/Core/view/adminhtml/prototype/magento/content_bg.gif
diff --git a/pub/js/prototype/windows/themes/magento/top_bg.gif b/app/code/core/Mage/Core/view/adminhtml/prototype/magento/top_bg.gif
similarity index 100%
rename from pub/js/prototype/windows/themes/magento/top_bg.gif
rename to app/code/core/Mage/Core/view/adminhtml/prototype/magento/top_bg.gif
diff --git a/pub/js/prototype/windows/themes/magento/window_close.png b/app/code/core/Mage/Core/view/adminhtml/prototype/magento/window_close.png
similarity index 100%
rename from pub/js/prototype/windows/themes/magento/window_close.png
rename to app/code/core/Mage/Core/view/adminhtml/prototype/magento/window_close.png
diff --git a/app/code/core/Mage/Core/view/frontend/layout.xml b/app/code/core/Mage/Core/view/frontend/layout.xml
index f34c4a6e50715bc524a781a493d86b363386db80..4376426a6c8aba0bf96bf52908bda6104313bfff 100644
--- a/app/code/core/Mage/Core/view/frontend/layout.xml
+++ b/app/code/core/Mage/Core/view/frontend/layout.xml
@@ -30,4 +30,8 @@
     <default>
         <block name="formkey" type="Mage_Core_Block_Template" template="Mage_Core::formkey.phtml" />
     </default>
+
+    <calendar translate="label">
+        <label>Calendar</label>
+    </calendar>
 </layout>
diff --git a/app/design/frontend/default/default/skin/blue/images/logo_email.gif b/app/code/core/Mage/Core/view/frontend/logo_email.gif
similarity index 100%
rename from app/design/frontend/default/default/skin/blue/images/logo_email.gif
rename to app/code/core/Mage/Core/view/frontend/logo_email.gif
diff --git a/app/code/core/Mage/Core/view/frontend/prototype/magento.css b/app/code/core/Mage/Core/view/frontend/prototype/magento.css
new file mode 100644
index 0000000000000000000000000000000000000000..9492d511e779ce491ff1aba5893c61fc5f9f1594
--- /dev/null
+++ b/app/code/core/Mage/Core/view/frontend/prototype/magento.css
@@ -0,0 +1,61 @@
+/**
+ * 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_Core
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+
+.dialog { border:1px solid #555; }
+.dialog .bot { display:none !important; }
+.overlay_magento { background-color:#000; filter:alpha(opacity=60); -moz-opacity:.6; opacity:.6; -webkit-opacity:.6; }
+.top.table_window { border-bottom:1px solid #e6e6e6; background:#6a838b url(magento/top_bg.gif) 0 100% repeat-x; }
+
+.magento_nw { width:6px; height:28px; }
+.magento_n { height:28px; }
+.magento_ne { width:6px; height:28px; }
+
+.magento_w { width:6px; }
+.magento_e { width:6px; }
+.magento_w,
+.magento_e,
+.magento_content { background: #fafafa url(magento/content_bg.gif) 0 0 repeat-x; }
+
+.magento_sw { background:#deebf0; width:5px; height:3px; }
+.magento_s { background:#deebf0; height:3px; }
+.magento_se,
+
+.magento_sizer { background:#deebf0; width:5px; height:3px; }
+.magento_sizer { cursor:se-resize; }
+
+.magento_close { width:16px; height:16px; background:url(magento/window_close.png) no-repeat 0 0; position:absolute; top:5px; right:7px; cursor:pointer; z-index:1000; }
+
+.magento_title { float:left; width:100%; font:bold 12px/28px Arial, Helvetica, sans-serif; color:#fff; text-align:left; }
+
+.magento_content { overflow:auto; font-size:12px; }
+.magento_content,
+.magento_content label { color:#333; font-family:Arial, sans-serif; }
+
+.magento_buttons { padding:10px; text-align:right; }
+.magento_buttons input.button { border-width:1px; border-style:solid; border-color:#ed6502 #a04300 #a04300 #ed6502;  background:#ffac47 url(magento/btn_bg.gif) 0 100% repeat-x; padding:0 7px 1px 7px; font:bold 12px/18px Arial, Helvetica, sans-serif; color:#fff; cursor:pointer; text-align:center; white-space:nowrap; }
+.magento_buttons button.button span span span { display:inline; background:none; padding:0; height:auto; }
+
+/* FOR IE */
+* html .magento_close { background-image:none; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src="../themes/magento/window_close.png", sizingMethod="crop"); }
diff --git a/app/code/core/Mage/Core/view/frontend/prototype/magento/btn_bg.gif b/app/code/core/Mage/Core/view/frontend/prototype/magento/btn_bg.gif
new file mode 100644
index 0000000000000000000000000000000000000000..32d6ca84f3f541bf3a7bf29d9eb67b7f0b403d27
Binary files /dev/null and b/app/code/core/Mage/Core/view/frontend/prototype/magento/btn_bg.gif differ
diff --git a/app/code/core/Mage/Core/view/frontend/prototype/magento/content_bg.gif b/app/code/core/Mage/Core/view/frontend/prototype/magento/content_bg.gif
new file mode 100644
index 0000000000000000000000000000000000000000..2a8c1375eb0bd58b04aab652e041237c8674f385
Binary files /dev/null and b/app/code/core/Mage/Core/view/frontend/prototype/magento/content_bg.gif differ
diff --git a/app/code/core/Mage/Core/view/frontend/prototype/magento/top_bg.gif b/app/code/core/Mage/Core/view/frontend/prototype/magento/top_bg.gif
new file mode 100644
index 0000000000000000000000000000000000000000..c9a37315deca7bf581033ad28aeeb2713a4d6e33
Binary files /dev/null and b/app/code/core/Mage/Core/view/frontend/prototype/magento/top_bg.gif differ
diff --git a/app/code/core/Mage/Core/view/frontend/prototype/magento/window_close.png b/app/code/core/Mage/Core/view/frontend/prototype/magento/window_close.png
new file mode 100644
index 0000000000000000000000000000000000000000..6e2b6dfb1d098287e6f7f87f1d2acefcd4a074ec
Binary files /dev/null and b/app/code/core/Mage/Core/view/frontend/prototype/magento/window_close.png differ
diff --git a/app/code/core/Mage/CurrencySymbol/Block/Adminhtml/System/Currencysymbol.php b/app/code/core/Mage/CurrencySymbol/Block/Adminhtml/System/Currencysymbol.php
new file mode 100644
index 0000000000000000000000000000000000000000..dbeb46682e43f424a318e6d7972083684282a4cc
--- /dev/null
+++ b/app/code/core/Mage/CurrencySymbol/Block/Adminhtml/System/Currencysymbol.php
@@ -0,0 +1,144 @@
+<?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_CurrencySymbol
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Manage currency symbols block
+ *
+ * @category   Mage
+ * @package    Mage_CurrencySymbol
+ * @author     Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_Currencysymbol_Block_Adminhtml_System_Currencysymbol extends Mage_Adminhtml_Block_Widget_Form
+{
+    /**
+     * Constructor. Initialization required variables for class instance.
+     */
+    public function __construct()
+    {
+        $this->_blockGroup = 'currencysymbol_system';
+        $this->_controller = 'adminhtml_system_currencysymbol';
+        parent::__construct();
+    }
+
+    /**
+     * Custom currency symbol properties
+     *
+     * @var array
+     */
+    protected $_symbolsData = array();
+
+    /**
+     * Prepares layout
+     *
+     * @return Mage_Core_Block_Abstract
+     */
+    protected function _prepareLayout()
+    {
+        return parent::_prepareLayout();
+    }
+
+    /**
+     * Returns page header
+     *
+     * @return bool|string
+     */
+    public function getHeader()
+    {
+        return Mage::helper('Mage_Adminhtml_Helper_Data')->__('Manage Currency Symbols');
+    }
+
+    /**
+     * Returns 'Save Currency Symbol' button's HTML code
+     *
+     * @return string
+     */
+    public function getSaveButtonHtml()
+    {
+        /** @var $block Mage_Core_Block_Abstract */
+        $block = $this->getLayout()->createBlock('Mage_Adminhtml_Block_Widget_Button');
+        $block->setData(array(
+            'label'     => Mage::helper('Mage_CurrencySymbol_Helper_Data')->__('Save Currency Symbols'),
+            'onclick'   => 'currencySymbolsForm.submit();',
+            'class'     => 'save'
+        ));
+
+        return $block->toHtml();
+    }
+
+    /**
+     * Returns URL for save action
+     *
+     * @return string
+     */
+    public function getFormActionUrl()
+    {
+        return $this->getUrl('*/*/save');
+    }
+
+    /**
+     * Returns website id
+     *
+     * @return int
+     */
+    public function getWebsiteId()
+    {
+        return $this->getRequest()->getParam('website');
+    }
+
+    /**
+     * Returns store id
+     *
+     * @return int
+     */
+    public function getStoreId()
+    {
+        return $this->getRequest()->getParam('store');
+    }
+
+    /**
+     * Returns Custom currency symbol properties
+     *
+     * @return array
+     */
+    public function getCurrencySymbolsData()
+    {
+        if(!$this->_symbolsData) {
+            $this->_symbolsData =  Mage::getModel('Mage_CurrencySymbol_Model_System_Currencysymbol')
+                ->getCurrencySymbolsData();
+        }
+        return $this->_symbolsData;
+    }
+
+    /**
+     * Returns inheritance text
+     *
+     * @return string
+     */
+    public function getInheritText()
+    {
+        return Mage::helper('Mage_CurrencySymbol_Helper_Data')->__('Use Standard');
+    }
+}
diff --git a/app/code/core/Mage/CurrencySymbol/Helper/Data.php b/app/code/core/Mage/CurrencySymbol/Helper/Data.php
new file mode 100644
index 0000000000000000000000000000000000000000..8001bb86bee1c735233945857541650975309fdf
--- /dev/null
+++ b/app/code/core/Mage/CurrencySymbol/Helper/Data.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_CurrencySymbol
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+ /**
+ * Currency Symbol helper
+ *
+ * @category   Mage
+ * @package    Mage_CurrencySymbol
+ * @author     Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_CurrencySymbol_Helper_Data extends Mage_Core_Helper_Data
+{
+
+    /**
+     * Get currency display options
+     *
+     * @param string $baseCode
+     * @return array
+     */
+    public function getCurrencyOptions($baseCode)
+    {
+        $currencyOptions = array();
+        $currencySymbol = Mage::getModel('Mage_CurrencySymbol_Model_System_Currencysymbol');
+        if($currencySymbol) {
+            $customCurrencySymbol = $currencySymbol->getCurrencySymbol($baseCode);
+
+            if ($customCurrencySymbol) {
+                $currencyOptions['symbol']  = $customCurrencySymbol;
+                $currencyOptions['display'] = Zend_Currency::USE_SYMBOL;
+            }
+        }
+
+        return $currencyOptions;
+    }
+}
diff --git a/app/code/core/Mage/CurrencySymbol/Model/Observer.php b/app/code/core/Mage/CurrencySymbol/Model/Observer.php
new file mode 100644
index 0000000000000000000000000000000000000000..235a05a7799f7a32ab821954e4510bba0f290897
--- /dev/null
+++ b/app/code/core/Mage/CurrencySymbol/Model/Observer.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_CurrencySymbol
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Currency Symbol Observer
+ *
+ * @category    Mage
+ * @package     Mage_CurrencySymbol
+ * @author      Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_CurrencySymbol_Model_Observer
+{
+    /**
+     * Generate options for currency displaying with custom currency symbol
+     *
+     * @param Varien_Event_Observer $observer
+     * @return Mage_CurrencySymbol_Model__Observer
+     */
+    public function currencyDisplayOptions(Varien_Event_Observer $observer)
+    {
+        $baseCode = $observer->getEvent()->getBaseCode();
+        $currencyOptions = $observer->getEvent()->getCurrencyOptions();
+        $currencyOptions->setData(Mage::helper('Mage_CurrencySymbol_Helper_Data')->getCurrencyOptions($baseCode));
+
+        return $this;
+    }
+}
diff --git a/app/code/core/Mage/CurrencySymbol/Model/System/Currencysymbol.php b/app/code/core/Mage/CurrencySymbol/Model/System/Currencysymbol.php
new file mode 100644
index 0000000000000000000000000000000000000000..db212a8f422fea8c48b0abe25431daa40992c6c9
--- /dev/null
+++ b/app/code/core/Mage/CurrencySymbol/Model/System/Currencysymbol.php
@@ -0,0 +1,282 @@
+<?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_CurrencySymbol
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Custom currency symbol model
+ *
+ * @category    Mage
+ * @package     Mage_CurrencySymbol
+ * @author      Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_CurrencySymbol_Model_System_Currencysymbol
+{
+    /**
+     * Custom currency symbol properties
+     *
+     * @var array
+     */
+    protected $_symbolsData = array();
+
+    /**
+     * Store id
+     *
+     * @var string | null
+     */
+    protected $_storeId;
+
+    /**
+     * Website id
+     *
+     * @var string | null
+     */
+    protected $_websiteId;
+    /**
+     * Cache types which should be invalidated
+     *
+     * @var array
+     */
+    protected $_cacheTypes = array(
+        'config',
+        'block_html',
+        'layout'
+    );
+
+    /**
+     * Config path to custom currency symbol value
+     */
+    const XML_PATH_CUSTOM_CURRENCY_SYMBOL = 'currency/options/customsymbol';
+    const XML_PATH_ALLOWED_CURRENCIES     = 'currency/options/allow';
+
+    /*
+     * Separator used in config in allowed currencies list
+     */
+    const ALLOWED_CURRENCIES_CONFIG_SEPARATOR = ',';
+
+    /**
+     * Config currency section
+     */
+    const CONFIG_SECTION = 'currency';
+
+    /**
+     * Sets store Id
+     *
+     * @param  $storeId
+     * @return Mage_CurrencySymbol_Model_System_Currencysymbol
+     */
+    public function setStoreId($storeId=null)
+    {
+        $this->_storeId = $storeId;
+        $this->_symbolsData = array();
+
+        return $this;
+    }
+
+    /**
+     * Sets website Id
+     *
+     * @param  $websiteId
+     * @return Mage_CurrencySymbol_Model_System_Currencysymbol
+     */
+    public function setWebsiteId($websiteId=null)
+    {
+        $this->_websiteId = $websiteId;
+        $this->_symbolsData = array();
+
+        return $this;
+    }
+
+    /**
+     * Returns currency symbol properties array based on config values
+     *
+     * @return array
+     */
+    public function getCurrencySymbolsData()
+    {
+        if ($this->_symbolsData) {
+            return $this->_symbolsData;
+        }
+
+        $this->_symbolsData = array();
+
+        $allowedCurrencies = explode(
+            self::ALLOWED_CURRENCIES_CONFIG_SEPARATOR,
+            Mage::getStoreConfig(self::XML_PATH_ALLOWED_CURRENCIES, null)
+        );
+
+        /* @var $storeModel Mage_Adminhtml_Model_System_Store */
+        $storeModel = Mage::getSingleton('Mage_Adminhtml_Model_System_Store');
+        foreach ($storeModel->getWebsiteCollection() as $website) {
+            $websiteShow = false;
+            foreach ($storeModel->getGroupCollection() as $group) {
+                if ($group->getWebsiteId() != $website->getId()) {
+                    continue;
+                }
+                foreach ($storeModel->getStoreCollection() as $store) {
+                    if ($store->getGroupId() != $group->getId()) {
+                        continue;
+                    }
+                    if (!$websiteShow) {
+                        $websiteShow = true;
+                        $websiteSymbols  = $website->getConfig(self::XML_PATH_ALLOWED_CURRENCIES);
+                        $allowedCurrencies = array_merge($allowedCurrencies, explode(
+                            self::ALLOWED_CURRENCIES_CONFIG_SEPARATOR,
+                            $websiteSymbols
+                        ));
+                    }
+                    $storeSymbols = Mage::getStoreConfig(self::XML_PATH_ALLOWED_CURRENCIES, $store);
+                    $allowedCurrencies = array_merge($allowedCurrencies, explode(
+                        self::ALLOWED_CURRENCIES_CONFIG_SEPARATOR,
+                        $storeSymbols
+                    ));
+                }
+            }
+        }
+        ksort($allowedCurrencies);
+
+        $currentSymbols = $this->_unserializeStoreConfig(self::XML_PATH_CUSTOM_CURRENCY_SYMBOL);
+
+        /** @var $locale Mage_Core_Model_Locale */
+        $locale = Mage::app()->getLocale();
+        foreach ($allowedCurrencies as $code) {
+            if (!$symbol = $locale->getTranslation($code, 'currencysymbol')) {
+                $symbol = $code;
+            }
+            $name = $locale->getTranslation($code, 'nametocurrency');
+            if (!$name) {
+                $name = $code;
+            }
+            $this->_symbolsData[$code] = array(
+                'parentSymbol'  => $symbol,
+                'displayName' => $name
+            );
+
+            if (isset($currentSymbols[$code]) && !empty($currentSymbols[$code])) {
+                $this->_symbolsData[$code]['displaySymbol'] = $currentSymbols[$code];
+            } else {
+                $this->_symbolsData[$code]['displaySymbol'] = $this->_symbolsData[$code]['parentSymbol'];
+            }
+            if ($this->_symbolsData[$code]['parentSymbol'] == $this->_symbolsData[$code]['displaySymbol']) {
+                $this->_symbolsData[$code]['inherited'] = true;
+            } else {
+                $this->_symbolsData[$code]['inherited'] = false;
+            }
+        }
+
+        return $this->_symbolsData;
+    }
+
+    /**
+     * Saves currency symbol to config
+     *
+     * @param  $symbols array
+     * @return Mage_CurrencySymbol_Model_System_Currencysymbol
+     */
+    public function setCurrencySymbolsData($symbols=array())
+    {
+        foreach ($this->getCurrencySymbolsData() as $code => $values) {
+            if (isset($symbols[$code])) {
+                if ($symbols[$code] == $values['parentSymbol'] || empty($symbols[$code]))
+                unset($symbols[$code]);
+            }
+        }
+        if ($symbols) {
+            $value['options']['fields']['customsymbol']['value'] = serialize($symbols);
+        } else {
+            $value['options']['fields']['customsymbol']['inherit'] = 1;
+        }
+
+        Mage::getModel('Mage_Adminhtml_Model_Config_Data')
+            ->setSection(self::CONFIG_SECTION)
+            ->setWebsite(null)
+            ->setStore(null)
+            ->setGroups($value)
+            ->save();
+
+        Mage::dispatchEvent('admin_system_config_changed_section_currency_before_reinit',
+            array('website' => $this->_websiteId, 'store' => $this->_storeId)
+        );
+
+        // reinit configuration
+        Mage::getConfig()->reinit();
+        Mage::app()->reinitStores();
+
+        $this->clearCache();
+
+        Mage::dispatchEvent('admin_system_config_changed_section_currency',
+            array('website' => $this->_websiteId, 'store' => $this->_storeId)
+        );
+
+        return $this;
+    }
+
+    /**
+     * Returns custom currency symbol by currency code
+     *
+     * @param  $code
+     * @return bool|string
+     */
+    public function getCurrencySymbol($code)
+    {
+        $customSymbols = $this->_unserializeStoreConfig(self::XML_PATH_CUSTOM_CURRENCY_SYMBOL);
+        if (array_key_exists($code, $customSymbols)) {
+            return $customSymbols[$code];
+        }
+
+        return false;
+    }
+
+    /**
+     * Clear translate cache
+     *
+     * @return Saas_Translate_Helper_Data
+     */
+    public function clearCache()
+    {
+        // clear cache for frontend
+        foreach ($this->_cacheTypes as $cacheType) {
+            Mage::app()->getCacheInstance()->invalidateType($cacheType);
+        }
+        return $this;
+    }
+
+    /**
+     * Unserialize data from Store Config.
+     *
+     * @param string $configPath
+     * @param int $storeId
+     * @return array
+     */
+    protected function _unserializeStoreConfig($configPath, $storeId = null)
+    {
+        $result = array();
+        $configData = (string)Mage::getStoreConfig($configPath, $storeId);
+        if ($configData) {
+            $result = unserialize($configData);
+        }
+
+        return is_array($result) ? $result : array();
+    }
+}
diff --git a/app/code/core/Mage/CurrencySymbol/controllers/Adminhtml/System/CurrencysymbolController.php b/app/code/core/Mage/CurrencySymbol/controllers/Adminhtml/System/CurrencysymbolController.php
new file mode 100644
index 0000000000000000000000000000000000000000..637d3fc498e1ef5ac90c7a7eb2b80fcfb7352d56
--- /dev/null
+++ b/app/code/core/Mage/CurrencySymbol/controllers/Adminhtml/System/CurrencysymbolController.php
@@ -0,0 +1,100 @@
+<?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_CurrencySymbol
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Adminhtml Currency Symbols Controller
+ *
+ * @category    Mage
+ * @package     currencysymbol
+ * @author      Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_CurrencySymbol_Adminhtml_System_CurrencysymbolController extends Mage_Adminhtml_Controller_Action
+{
+    /**
+     * Show Currency Symbols Management dialog
+     */
+    public function indexAction()
+    {
+        // set active menu and breadcrumbs
+        $this->loadLayout()
+            ->_setActiveMenu('system/currency')
+            ->_addBreadcrumb(
+                Mage::helper('Mage_CurrencySymbol_Helper_Data')->__('System'),
+                Mage::helper('Mage_CurrencySymbol_Helper_Data')->__('System')
+            )
+            ->_addBreadcrumb(
+                Mage::helper('Mage_CurrencySymbol_Helper_Data')->__('Manage Currency Rates'),
+                Mage::helper('Mage_CurrencySymbol_Helper_Data')->__('Manage Currency Rates')
+            );
+
+        $this->_title($this->__('System'))
+            ->_title($this->__('Manage Currency Rates'));
+        $this->renderLayout();
+    }
+
+    /**
+     * Save custom Currency symbol
+     */
+    public function saveAction()
+    {
+        $symbolsDataArray = $this->getRequest()->getParam('custom_currency_symbol', null);
+        if (is_array($symbolsDataArray)) {
+            foreach ($symbolsDataArray as &$symbolsData) {
+                $symbolsData = Mage::helper('Mage_Adminhtml_Helper_Data')->stripTags($symbolsData);
+            }
+        }
+
+        try {
+            Mage::getModel('Mage_CurrencySymbol_Model_System_Currencysymbol')->setCurrencySymbolsData($symbolsDataArray);
+            Mage::getSingleton('Mage_Connect_Model_Session')->addSuccess(
+                Mage::helper('Mage_CurrencySymbol_Helper_Data')->__('Custom currency symbols were applied successfully.')
+            );
+        } catch (Exception $e) {
+            Mage::getSingleton('Mage_Adminhtml_Model_Session')->addError($e->getMessage());
+        }
+
+        $this->_redirectReferer();
+    }
+
+    /**
+     * Resets custom Currency symbol for all store views, websites and default value
+     */
+    public function resetAction()
+    {
+        Mage::getModel('Mage_CurrencySymbol_Model_System_Currencysymbol')->resetValues();
+        $this->_redirectReferer();
+    }
+
+    /**
+     * Check the permission to run it
+     *
+     * @return boolean
+     */
+    protected function _isAllowed()
+    {
+        return Mage::getSingleton('Mage_Admin_Model_Session')->isAllowed('system/currency/symbols');
+    }
+}
diff --git a/app/code/core/Mage/CurrencySymbol/etc/adminhtml.xml b/app/code/core/Mage/CurrencySymbol/etc/adminhtml.xml
new file mode 100644
index 0000000000000000000000000000000000000000..2c98705e055e72d7eacc4e283dd1c7effa97679b
--- /dev/null
+++ b/app/code/core/Mage/CurrencySymbol/etc/adminhtml.xml
@@ -0,0 +1,76 @@
+<?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    Mage
+ * @package     Mage_CurrencySymbol
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<config>
+    <menu>
+        <system>
+            <children>
+                <currency translate="title" module="Mage_CurrencySymbol">
+                    <title>Manage Currency</title>
+                    <children>
+                        <rates translate="title">
+                            <title>Rates</title>
+                            <action>adminhtml/system_currency</action>
+                            <sort_order>50</sort_order>
+                        </rates>
+                        <symbols translate="title">
+                            <title>Symbols</title>
+                            <action>adminhtml/system_currencysymbol</action>
+                            <sort_order>100</sort_order>
+                        </symbols>
+                    </children>
+                    <sort_order>50</sort_order>
+                </currency>
+            </children>
+        </system>
+    </menu>
+    <acl>
+        <resources>
+            <admin>
+                <children>
+                    <system>
+                        <children>
+                            <currency translate="title">
+                                <title>Manage Currency</title>
+                                <children>
+                                    <rates translate="title">
+                                        <title>Rates</title>
+                                        <sort_order>50</sort_order>
+                                    </rates>
+                                    <symbols translate="title">
+                                        <title>Symbols</title>
+                                        <sort_order>100</sort_order>
+                                    </symbols>
+                                </children>
+                            </currency>
+                        </children>
+                    </system>
+                </children>
+            </admin>
+        </resources>
+    </acl>
+</config>
diff --git a/app/code/core/Mage/CurrencySymbol/etc/config.xml b/app/code/core/Mage/CurrencySymbol/etc/config.xml
new file mode 100644
index 0000000000000000000000000000000000000000..3bfae8d03b0340a2a9ea3240fdaace4607090606
--- /dev/null
+++ b/app/code/core/Mage/CurrencySymbol/etc/config.xml
@@ -0,0 +1,78 @@
+<?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    Mage
+ * @package     Mage_CurrencySymbol
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<config>
+    <modules>
+        <Mage_CurrencySymbol>
+             <version>1.0.0.0.0</version>
+        </Mage_CurrencySymbol>
+    </modules>
+
+    <global>
+        <events>
+            <currency_display_options_forming>
+                <observers>
+                    <mage_currencysymbol_currency_display_options>
+                        <class>Mage_CurrencySymbol_Model_Observer</class>
+                        <method>currencyDisplayOptions</method>
+                    </mage_currencysymbol_currency_display_options>
+                </observers>
+            </currency_display_options_forming>
+        </events>
+    </global>
+
+    <admin>
+        <routers>
+            <adminhtml>
+                <args>
+                    <modules>
+                        <currencysymbol>Mage_CurrencySymbol_Adminhtml</currencysymbol>
+                    </modules>
+                </args>
+            </adminhtml>
+        </routers>
+    </admin>
+
+    <adminhtml>
+        <layout>
+            <updates>
+                <currencysymbol module="Mage_CurrencySymbol">
+                    <file>layout.xml</file>
+                </currencysymbol>
+            </updates>
+        </layout>
+        <translate>
+            <modules>
+                <Mage_CurrencySymbol>
+                     <files>
+                          <default>Mage_CurrencySymbol.csv</default>
+                     </files>
+                </Mage_CurrencySymbol>
+            </modules>
+        </translate>
+    </adminhtml>
+</config>
diff --git a/app/code/core/Mage/CurrencySymbol/view/adminhtml/grid.phtml b/app/code/core/Mage/CurrencySymbol/view/adminhtml/grid.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..7d2abf68843e5fb061da019f8529f64cfcc25041
--- /dev/null
+++ b/app/code/core/Mage/CurrencySymbol/view/adminhtml/grid.phtml
@@ -0,0 +1,100 @@
+<?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    Mage
+ * @package     Mage_CurrencySymbol
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<?php
+/**
+ * @var $this Mage_Currencysymbol_Block_Adminhtml_System_Currencysymbol
+ */
+?>
+<div class="content-header">
+    <table cellspacing="0">
+        <tr>
+            <td style="width:50%;"><h3 class="icon-head head-system-currency"><?php echo $this->getHeader() ?></h3></td>
+            <td class="form-buttons">
+                <?php
+                    echo $this->getSaveButtonHtml();
+                ?>
+            </td>
+        </tr>
+    </table>
+</div>
+
+<?php $this->getCurrencySymbolsData();?>
+
+<form id="currency_symbols_form" action="<?php echo $this->getFormActionUrl() ?>" method="post">
+    <input name="form_key" type="hidden" value="<?php echo $this->getFormKey() ?>" />
+
+    <div class="entry-edit">
+        <div class="fieldset fieldset-wide">
+            <div class="grid">
+                <div class="hor-scroll">
+                    <table cellspacing="0" class="data table-cat-img-sizes">
+                        <colgroup>
+                            <col width="15%"/>
+                            <col />
+                        </colgroup>
+                        <thead>
+                            <tr class="headings">
+                                <th><span class="nobr"><span class="not-sort"><?php echo $this->__('Currency'); ?></span></span></th>
+                                <th><span class="nobr"><span class="not-sort"><?php echo $this->__('Symbol'); ?><span class="required"><em>*</em></span></span></span></th>
+                            </tr>
+                        </thead>
+                        <tbody>
+                            <?php foreach($this->getCurrencySymbolsData() as $code => $data): ?>
+                            <tr>
+                                <td class="label">
+                                <label for="custom_currency_symbol<?php echo $code; ?>"><?php echo $code; ?> (<?php echo $data['displayName']; ?>)</label>
+                                </td>
+                                <td class="value">
+                                    <input id="custom_currency_symbol<?php echo $code; ?>" class=" required-entry input-text" type="text" value="<?php echo Mage::helper('Mage_Core_Helper_Data')->quoteEscape($data['displaySymbol']); ?>"<?php echo $data['inherited'] ? ' disabled="disabled"' : '';?> name="custom_currency_symbol[<?php echo $code; ?>]">
+                                    &nbsp; <input id="custom_currency_symbol_inherit<?php echo $code; ?>" class="checkbox config-inherit" type="checkbox" onclick="toggleUseDefault(<?php echo '\'' . $code . '\',\'' . Mage::helper('Mage_Core_Helper_Data')->quoteEscape($data['parentSymbol'], true) . '\''; ?>)"<?php echo $data['inherited'] ? ' checked="checked"' : ''; ?> value="1" name="inherit_custom_currency_symbol[<?php echo $code; ?>]">
+                                    <label class="inherit" title="" for="custom_currency_symbol_inherit<?php echo $code; ?>"><?php echo $this->getInheritText(); ?></label>
+                                </td>
+                            </tr>
+                            <? endforeach; ?>
+                        </tbody>
+                    </table>
+                </div>
+            </div>
+        </div>
+    </div>
+</form>
+<script type="text/javascript">
+    var currencySymbolsForm = new varienForm('currency_symbols_form');
+
+    function toggleUseDefault(code, value)
+    {
+        checkbox = $('custom_currency_symbol_inherit'+code);
+        input = $('custom_currency_symbol'+code);
+        if (checkbox.checked) {
+            input.value = value;
+            input.disabled = true;
+        } else {
+            input.disabled = false;
+        }
+    }
+</script>
+
diff --git a/app/code/core/Mage/CurrencySymbol/view/adminhtml/layout.xml b/app/code/core/Mage/CurrencySymbol/view/adminhtml/layout.xml
new file mode 100644
index 0000000000000000000000000000000000000000..df824185068bdb3d531d18c9e073a431f479c985
--- /dev/null
+++ b/app/code/core/Mage/CurrencySymbol/view/adminhtml/layout.xml
@@ -0,0 +1,34 @@
+<?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    Mage
+ * @package     Mage_CurrencySymbol
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<layout>
+    <adminhtml_system_currencysymbol_index>
+        <reference name="content">
+            <block type="Mage_CurrencySymbol_Block_Adminhtml_System_Currencysymbol" name="mage.system.currencysymbol" template="grid.phtml"/>
+        </reference>
+    </adminhtml_system_currencysymbol_index>
+</layout>
diff --git a/app/code/core/Mage/Customer/Block/Account/Link.php b/app/code/core/Mage/Customer/Block/Account/Link.php
new file mode 100644
index 0000000000000000000000000000000000000000..9610a57cdb410c336cb1f7036ba362aa3efbf771
--- /dev/null
+++ b/app/code/core/Mage/Customer/Block/Account/Link.php
@@ -0,0 +1,122 @@
+<?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_Customer
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Customer account link
+ *
+ * @category   Mage
+ * @package    Mage_Customer
+ * @author     Magento Core Team <core@magentocommerce.com>
+ */
+
+class Mage_Customer_Block_Account_Link extends Mage_Core_Block_Abstract
+{
+    /**
+     * Add link to customer account page to the target block
+     *
+     * @param string $target
+     * @param int $position
+     * @return Mage_Customer_Block_Account_Link
+     */
+    public function addAccountLink($target, $position)
+    {
+        $helper = Mage::helper('Mage_Customer_Helper_Data');
+        $this->_addLink(
+            $target, $this->__('My Account'), $helper->getAccountUrl(), $this->__('My Account'), $position, '', ''
+        );
+        return $this;
+    }
+
+    /**
+     * Add link to customer registration page to the target block
+     *
+     * @param string $target
+     * @param int $position
+     * @param string $textBefore
+     * @param string $textAfter
+     * @return Mage_Customer_Block_Account_Link
+     */
+    public function addRegisterLink($target, $position, $textBefore = '', $textAfter = '')
+    {
+
+        if (!Mage::getSingleton('Mage_Customer_Model_Session')->isLoggedIn()) {
+            $helper = Mage::helper('Mage_Customer_Helper_Data');
+            $this->_addLink(
+                $target,
+                $this->__('register'),
+                $helper->getRegisterUrl(),
+                $this->__('register'),
+                $position,
+                $textBefore,
+                $textAfter
+            );
+        }
+        return $this;
+    }
+
+    /**
+     * Add Log In/Out link to the target block
+     *
+     * @param string $target
+     * @param int $position
+     * @return Mage_Customer_Block_Account_Link
+     */
+    public function addAuthLink($target, $position)
+    {
+        $helper = Mage::helper('Mage_Customer_Helper_Data');
+        if (Mage::getSingleton('Mage_Customer_Model_Session')->isLoggedIn()) {
+            $this->_addLink(
+                $target, $this->__('Log Out'), $helper->getLogoutUrl(), $this->__('Log Out'), $position, '', ''
+            );
+        } else {
+            $this->_addLink(
+                $target, $this->__('Log In'), $helper->getLoginUrl(), $this->__('Log In'), $position, '', ''
+            );
+        }
+        return $this;
+    }
+
+    /**
+     * Add link to the block with $target name
+     *
+     * @param string $target
+     * @param string $text
+     * @param string $url
+     * @param string $title
+     * @param int $position
+     * @param string $textBefore
+     * @param string $textAfter
+     * @return Mage_Customer_Block_Account_Link
+     */
+    protected function _addLink($target, $text, $url, $title, $position, $textBefore='', $textAfter='')
+    {
+        $target = $this->getLayout()->getBlock($target);
+        if ($target && method_exists($target, 'addLink')) {
+            $target->addLink($text, $url, $title, false, array(), $position, null, null, $textBefore, $textAfter);
+        }
+        return $this;
+    }
+}
diff --git a/app/code/core/Mage/Customer/Block/Address/Edit.php b/app/code/core/Mage/Customer/Block/Address/Edit.php
index 66df2191424a96b860f8f3b42fd2a93773151245..1477f9c4eadf1801341e1a50a63164086142147a 100644
--- a/app/code/core/Mage/Customer/Block/Address/Edit.php
+++ b/app/code/core/Mage/Customer/Block/Address/Edit.php
@@ -61,8 +61,9 @@ class Mage_Customer_Block_Address_Edit extends Mage_Directory_Block_Data
         if ($headBlock = $this->getLayout()->getBlock('head')) {
             $headBlock->setTitle($this->getTitle());
         }
+
         if ($postedData = Mage::getSingleton('Mage_Customer_Model_Session')->getAddressFormData(true)) {
-            $this->_address->setData($postedData);
+            $this->_address->addData($postedData);
         }
     }
 
diff --git a/app/code/core/Mage/Customer/Block/Widget/Name.php b/app/code/core/Mage/Customer/Block/Widget/Name.php
index 74fb010cee2fe5175d3e1200df354f6a64ae6a31..1e74f1d98b37bc96108ae47b13bee6ece71adb1e 100644
--- a/app/code/core/Mage/Customer/Block/Widget/Name.php
+++ b/app/code/core/Mage/Customer/Block/Widget/Name.php
@@ -191,6 +191,22 @@ class Mage_Customer_Block_Widget_Name extends Mage_Customer_Block_Widget_Abstrac
         return $_attribute;
     }
 
+    /**
+     * Get string with frontend validation classes
+     *
+     * @param string $attributeCode
+     * @return string
+     */
+    public function getAttributeValidationClass($attributeCode)
+    {
+        $attribute = $this->_getAttribute($attributeCode);
+        if (!$attribute) {
+            return '';
+        }
+
+        return $attribute->getFrontend()->getClass();
+    }
+
     /**
      * Retrieve store attribute label
      *
diff --git a/app/code/core/Mage/Customer/Helper/Address.php b/app/code/core/Mage/Customer/Helper/Address.php
index 40be96a4c62e6c6c7490030a73a9dd755e87892d..f74617ad480700aaa26804277280f84c93331a50 100644
--- a/app/code/core/Mage/Customer/Helper/Address.php
+++ b/app/code/core/Mage/Customer/Helper/Address.php
@@ -169,6 +169,29 @@ class Mage_Customer_Helper_Address extends Mage_Core_Helper_Abstract
         return $this->_attributes;
     }
 
+    /**
+     * Get string with frontend validation classes for attribute
+     *
+     * @param string $attributeCode
+     * @return string
+     */
+    public function getAttributeValidationClass($attributeCode)
+    {
+        if (isset($this->_attributes[$attributeCode])) {
+            $attribute = $this->_attributes[$attributeCode];
+        }
+
+        if (!isset($attribute)) {
+            $attribute = Mage::getSingleton('Mage_Eav_Model_Config')->getAttribute('customer_address', $attributeCode);
+        }
+
+        if (!$attribute) {
+            return '';
+        }
+
+        return $attribute->getFrontend()->getClass();
+    }
+
     /**
      * Convert streets array to new street lines count
      * Examples of use:
diff --git a/app/code/core/Mage/Customer/Helper/Data.php b/app/code/core/Mage/Customer/Helper/Data.php
index 06a5e391e53f6763122779b17fa4c3a790522253..7cdef1e234591eef5e88b504384e909db46907b6 100644
--- a/app/code/core/Mage/Customer/Helper/Data.php
+++ b/app/code/core/Mage/Customer/Helper/Data.php
@@ -39,13 +39,18 @@ class Mage_Customer_Helper_Data extends Mage_Core_Helper_Abstract
      */
     const REFERER_QUERY_PARAM_NAME = 'referer';
 
+    /**
+     * Route for customer account login page
+     */
+    const ROUTE_ACCOUNT_LOGIN = 'customer/account/login';
+
     /**
      * Config name for Redirect Customer to Account Dashboard after Logging in setting
      */
     const XML_PATH_CUSTOMER_STARTUP_REDIRECT_TO_DASHBOARD = 'customer/startup/redirect_dashboard';
 
     /**
-     * Config pathes to VAT related customer groups
+     * Config paths to VAT related customer groups
      */
     const XML_PATH_CUSTOMER_VIV_INTRA_UNION_GROUP = 'customer/create_account/viv_intra_union_group';
     const XML_PATH_CUSTOMER_VIV_DOMESTIC_GROUP = 'customer/create_account/viv_domestic_group';
@@ -128,7 +133,7 @@ class Mage_Customer_Helper_Data extends Mage_Core_Helper_Abstract
     }
 
     /**
-     * Retrieve current (loggined) customer object
+     * Retrieve current (logged in) customer object
      *
      * @return Mage_Customer_Model_Customer
      */
@@ -167,22 +172,33 @@ class Mage_Customer_Helper_Data extends Mage_Core_Helper_Abstract
      * @return string
      */
     public function getLoginUrl()
+    {
+        return $this->_getUrl(self::ROUTE_ACCOUNT_LOGIN, $this->getLoginUrlParams());
+    }
+
+    /**
+     * Retrieve parameters of customer login url
+     *
+     * @return array
+     */
+    public function getLoginUrlParams()
     {
         $params = array();
 
         $referer = $this->_getRequest()->getParam(self::REFERER_QUERY_PARAM_NAME);
 
-        if (!$referer && !Mage::getStoreConfigFlag(self::XML_PATH_CUSTOMER_STARTUP_REDIRECT_TO_DASHBOARD)) {
-            if (!Mage::getSingleton('Mage_Customer_Model_Session')->getNoReferer()) {
-                $referer = Mage::getUrl('*/*/*', array('_current' => true, '_use_rewrite' => true));
-                $referer = Mage::helper('Mage_Core_Helper_Data')->urlEncode($referer);
-            }
+        if (!$referer && !Mage::getStoreConfigFlag(self::XML_PATH_CUSTOMER_STARTUP_REDIRECT_TO_DASHBOARD)
+            && !Mage::getSingleton('Mage_Customer_Model_Session')->getNoReferer()
+        ) {
+            $referer = Mage::getUrl('*/*/*', array('_current' => true, '_use_rewrite' => true));
+            $referer = Mage::helper('Mage_Core_Helper_Data')->urlEncode($referer);
         }
+
         if ($referer) {
             $params = array(self::REFERER_QUERY_PARAM_NAME => $referer);
         }
 
-        return $this->_getUrl('customer/account/login', $params);
+        return $params;
     }
 
     /**
@@ -453,9 +469,9 @@ class Mage_Customer_Helper_Data extends Mage_Core_Helper_Abstract
 
             $requestParams = array();
             $requestParams['countryCode'] = $countryCode;
-            $requestParams['vatNumber'] = $vatNumber;
+            $requestParams['vatNumber'] = str_replace(array(' ', '-'), array('', ''), $vatNumber);
             $requestParams['requesterCountryCode'] = $requesterCountryCode;
-            $requestParams['requesterVatNumber'] = $requesterVatNumber;
+            $requestParams['requesterVatNumber'] = str_replace(array(' ', '-'), array('', ''), $requesterVatNumber);
 
             // Send request to service
             $result = $soapClient->checkVatApprox($requestParams);
diff --git a/app/code/core/Mage/Customer/Model/Address/Abstract.php b/app/code/core/Mage/Customer/Model/Address/Abstract.php
index 4f821bf64de46a7d4b8c14458bf017b32d04bc0c..a9d94f9ed6f3867b7377a7132f4a9075d8020d9e 100644
--- a/app/code/core/Mage/Customer/Model/Address/Abstract.php
+++ b/app/code/core/Mage/Customer/Model/Address/Abstract.php
@@ -251,10 +251,8 @@ class Mage_Customer_Model_Address_Abstract extends Mage_Core_Model_Abstract
                 $this->setData('region_id', $region);
                 $this->unsRegion();
             } else {
-                $regionModel = Mage::getModel('Mage_Directory_Model_Region')->loadByCode(
-                    $this->getRegionCode(),
-                    $this->getCountryId()
-                );
+                $regionModel = Mage::getModel('Mage_Directory_Model_Region')
+                    ->loadByCode($this->getRegionCode(), $this->getCountryId());
                 $this->setData('region_id', $regionModel->getId());
             }
         }
@@ -264,7 +262,8 @@ class Mage_Customer_Model_Address_Abstract extends Mage_Core_Model_Abstract
     public function getCountry()
     {
         /*if ($this->getData('country_id') && !$this->getData('country')) {
-            $this->setData('country', Mage::getModel('Mage_Directory_Model_Country')->load($this->getData('country_id'))->getIso2Code());
+            $this->setData('country', Mage::getModel('Mage_Directory_Model_Country')
+                ->load($this->getData('country_id'))->getIso2Code());
         }
         return $this->getData('country');*/
         $country = $this->getCountryId();
@@ -279,9 +278,8 @@ class Mage_Customer_Model_Address_Abstract extends Mage_Core_Model_Abstract
     public function getCountryModel()
     {
         if(!isset(self::$_countryModels[$this->getCountryId()])) {
-            self::$_countryModels[$this->getCountryId()] = Mage::getModel('Mage_Directory_Model_Country')->load(
-                $this->getCountryId()
-            );
+            self::$_countryModels[$this->getCountryId()] = Mage::getModel('Mage_Directory_Model_Country')
+                ->load($this->getCountryId());
         }
 
         return self::$_countryModels[$this->getCountryId()];
@@ -373,7 +371,9 @@ class Mage_Customer_Model_Address_Abstract extends Mage_Core_Model_Abstract
         }
 
         if ($this->getCountryModel()->getRegionCollection()->getSize()
-               && !Zend_Validate::is($this->getRegionId(), 'NotEmpty')) {
+               && !Zend_Validate::is($this->getRegionId(), 'NotEmpty')
+               && Mage::helper('Mage_Directory_Helper_Data')->isRegionRequired($this->getCountryId())
+        ) {
             $errors[] = Mage::helper('Mage_Customer_Helper_Data')->__('Please enter the state/province.');
         }
 
diff --git a/app/code/core/Mage/Customer/Model/Observer.php b/app/code/core/Mage/Customer/Model/Observer.php
index 5e4badac60fa6d880f78115a364f8f856555e617..2ea762c7be9737d0af6481090a9e87b2b66e0849 100644
--- a/app/code/core/Mage/Customer/Model/Observer.php
+++ b/app/code/core/Mage/Customer/Model/Observer.php
@@ -88,19 +88,6 @@ class Mage_Customer_Model_Observer
         return $this->_isDefaultBilling($address);
     }
 
-    /**
-     * Before load layout event handler
-     *
-     * @param Varien_Event_Observer $observer
-     */
-    public function beforeLoadLayout($observer)
-    {
-        $loggedIn = Mage::getSingleton('Mage_Customer_Model_Session')->isLoggedIn();
-
-        $observer->getEvent()->getLayout()->getUpdate()
-           ->addHandle('customer_logged_' . ($loggedIn ? 'in' : 'out'));
-    }
-
     /**
      * Address before save event handler
      *
diff --git a/app/code/core/Mage/Customer/Model/Session.php b/app/code/core/Mage/Customer/Model/Session.php
index 4e588e43c5d4790eb71565f3036eee86833bd5dc..2fa47e1abb033f45924c720cada0441218638f1e 100644
--- a/app/code/core/Mage/Customer/Model/Session.php
+++ b/app/code/core/Mage/Customer/Model/Session.php
@@ -261,19 +261,25 @@ class Mage_Customer_Model_Session extends Mage_Core_Model_Session_Abstract
      * Authenticate controller action by login customer
      *
      * @param   Mage_Core_Controller_Varien_Action $action
+     * @param   bool $loginUrl
      * @return  bool
      */
     public function authenticate(Mage_Core_Controller_Varien_Action $action, $loginUrl = null)
     {
-        if (!$this->isLoggedIn()) {
-            $this->setBeforeAuthUrl(Mage::getUrl('*/*/*', array('_current'=>true)));
-            if (is_null($loginUrl)) {
-                $loginUrl = Mage::helper('Mage_Customer_Helper_Data')->getLoginUrl();
-            }
+        if ($this->isLoggedIn()) {
+            return true;
+        }
+
+        $this->setBeforeAuthUrl(Mage::getUrl('*/*/*', array('_current' => true)));
+        if (isset($loginUrl)) {
             $action->getResponse()->setRedirect($loginUrl);
-            return false;
+        } else {
+            $action->setRedirectWithCookieCheck(Mage_Customer_Helper_Data::ROUTE_ACCOUNT_LOGIN,
+                Mage::helper('Mage_Customer_Helper_Data')->getLoginUrlParams()
+            );
         }
-        return true;
+
+        return false;
     }
 
     /**
@@ -335,8 +341,7 @@ class Mage_Customer_Model_Session extends Mage_Core_Model_Session_Abstract
     public function renewSession()
     {
         parent::renewSession();
-        Mage::getSingleton('Mage_Core_Model_Session')->unsSessionHosts();
-
+        $this->_cleanHosts();
         return $this;
     }
 }
diff --git a/app/code/core/Mage/Customer/controllers/AccountController.php b/app/code/core/Mage/Customer/controllers/AccountController.php
index 33c386b07647174c6844b182851397247b41c511..abb837a8eba4591cd08306bf85f8483bd5c6005c 100644
--- a/app/code/core/Mage/Customer/controllers/AccountController.php
+++ b/app/code/core/Mage/Customer/controllers/AccountController.php
@@ -108,9 +108,7 @@ class Mage_Customer_AccountController extends Mage_Core_Controller_Front_Action
         $this->_initLayoutMessages('Mage_Customer_Model_Session');
         $this->_initLayoutMessages('Mage_Catalog_Model_Session');
 
-        $this->getLayout()->getBlock('content')->append(
-            $this->getLayout()->createBlock('Mage_Customer_Block_Account_Dashboard')
-        );
+        $this->getLayout()->addBlock('Mage_Customer_Block_Account_Dashboard', '', 'content');
         $this->getLayout()->getBlock('head')->setTitle($this->__('My Account'));
         $this->renderLayout();
     }
diff --git a/app/code/core/Mage/Customer/etc/config.xml b/app/code/core/Mage/Customer/etc/config.xml
index b1ac678539a05341159df4b77b68814e22cbf7cf..f46263829c2b4ed84352d47f4d02e6e1eae540c3 100644
--- a/app/code/core/Mage/Customer/etc/config.xml
+++ b/app/code/core/Mage/Customer/etc/config.xml
@@ -126,14 +126,6 @@
             <customer>/customer/</customer>
         </secure_url>
         <events>
-            <controller_action_layout_load_before>
-                <observers>
-                    <customer_is_logged_in_observer>
-                        <class>Mage_Customer_Model_Observer</class>
-                        <method>beforeLoadLayout</method>
-                    </customer_is_logged_in_observer>
-                </observers>
-            </controller_action_layout_load_before>
             <sales_model_service_quote_submit_after>
                 <observers>
                     <restore_customer_group_id>
diff --git a/app/code/core/Mage/Customer/etc/system.xml b/app/code/core/Mage/Customer/etc/system.xml
index bf28717454ac96d61eb4c29f2a5ffae587bb5874..dc8fbd3ad74b4ac63ca572083356a5430ede99c6 100644
--- a/app/code/core/Mage/Customer/etc/system.xml
+++ b/app/code/core/Mage/Customer/etc/system.xml
@@ -75,8 +75,8 @@
                             <frontend_type>text</frontend_type>
                             <sort_order>1</sort_order>
                             <show_in_default>1</show_in_default>
-                            <show_in_website>1</show_in_website>
-                            <show_in_store>1</show_in_store>
+                            <show_in_website>0</show_in_website>
+                            <show_in_store>0</show_in_store>
                             <comment>Leave empty for default (15 minutes).</comment>
                         </online_minutes_interval>
                     </fields>
@@ -98,7 +98,7 @@
                             <show_in_store>1</show_in_store>
                         </auto_group_assign>
                         <tax_calculation_address_type translate="label">
-                            <label>Tax Calculation Based on</label>
+                            <label>Tax Calculation Based On</label>
                             <frontend_type>select</frontend_type>
                             <source_model>Mage_Adminhtml_Model_System_Config_Source_Customer_Address_Type</source_model>
                             <sort_order>10</sort_order>
@@ -277,8 +277,9 @@
                         </forgot_email_identity>
                         <reset_link_expiration_period translate="label comment">
                             <label>Recovery Link Expiration Period (days)</label>
-                            <comment>This value must be greater than 0.</comment>
+                            <comment>Please enter a number 1 or greater in this field.</comment>
                             <frontend_type>text</frontend_type>
+                            <validate>required-entry validate-digits validate-digits-range digits-range-1-</validate>
                             <backend_model>Mage_Adminhtml_Model_System_Config_Backend_Customer_Password_Link_Expirationperiod</backend_model>
                             <sort_order>40</sort_order>
                             <show_in_default>1</show_in_default>
diff --git a/app/code/core/Mage/Customer/sql/customer_setup/upgrade-1.6.1.0-1.6.2.0.php b/app/code/core/Mage/Customer/sql/customer_setup/upgrade-1.6.1.0-1.6.2.0.php
index c2bd1385abe45dbd21baa528b3985a7dd2f15fe9..953b88649c04204ce0aa0642de010a49b5df4bac 100644
--- a/app/code/core/Mage/Customer/sql/customer_setup/upgrade-1.6.1.0-1.6.2.0.php
+++ b/app/code/core/Mage/Customer/sql/customer_setup/upgrade-1.6.1.0-1.6.2.0.php
@@ -31,7 +31,7 @@ $disableAGCAttributeCode = 'disable_auto_group_change';
 
 $installer->addAttribute('customer', $disableAGCAttributeCode, array(
     'type'      => 'static',
-    'label'     => 'Disable automatic group change',
+    'label'     => 'Disable automatic group change based on VAT ID',
     'input'     => 'boolean',
     'backend'   => 'Mage_Customer_Model_Attribute_Backend_Data_Boolean',
     'position'  => 28,
diff --git a/app/code/core/Mage/Customer/sql/customer_setup/upgrade-1.6.2.0-1.6.2.0.1.php b/app/code/core/Mage/Customer/sql/customer_setup/upgrade-1.6.2.0-1.6.2.0.1.php
index e767ca8d2aaab1d6344d01a7778af0b7fd3c2486..91a1f7d9fe959927f48355ed7bdae249ff9594cb 100644
--- a/app/code/core/Mage/Customer/sql/customer_setup/upgrade-1.6.2.0-1.6.2.0.1.php
+++ b/app/code/core/Mage/Customer/sql/customer_setup/upgrade-1.6.2.0-1.6.2.0.1.php
@@ -32,5 +32,5 @@ $installer->getConnection()->addColumn($installer->getTable('customer_entity'),
     'unsigned' => true,
     'nullable' => false,
     'default' => '0',
-    'comment' => 'Disable automatic group change'
+    'comment' => 'Disable automatic group change based on VAT ID'
 ));
diff --git a/app/code/core/Mage/Customer/view/email/account_new.html b/app/code/core/Mage/Customer/view/email/account_new.html
index dcded5947d9d7200c34df96ff40c9ccd92b525f1..97bb731ec103b45daa99a3cc7ed0ffe866561ed3 100644
--- a/app/code/core/Mage/Customer/view/email/account_new.html
+++ b/app/code/core/Mage/Customer/view/email/account_new.html
@@ -1,7 +1,7 @@
 <!--@subject Welcome, {{var customer.name}}! @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
 "escapehtml var=$customer.name":"Customer Name",
 "store url=\"customer/account/\"":"Customer Account Url",
 "var customer.email":"Customer Email",
@@ -21,7 +21,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
                 <table bgcolor="FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
                     <tr>
                         <td valign="top">
-                            <a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a></td>
+                            <a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a></td>
                     </tr>
                 <!-- [ middle starts here] -->
                     <tr>
diff --git a/app/code/core/Mage/Customer/view/email/account_new_confirmation.html b/app/code/core/Mage/Customer/view/email/account_new_confirmation.html
index 3d5cbcc14009eb71a162a070c6489dbd6d2e0f9f..b6f8ad41397f8a8bde708c9a675b641b6cebfbee 100644
--- a/app/code/core/Mage/Customer/view/email/account_new_confirmation.html
+++ b/app/code/core/Mage/Customer/view/email/account_new_confirmation.html
@@ -1,7 +1,8 @@
 <!--@subject Account confirmation for {{var customer.name}} @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "store url=\"customer/account/\"":"Customer Account Url",
 "escapehtml var=$customer.name":"Customer Name",
 "var customer.email":"Customer Email",
@@ -22,7 +23,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
                 <table bgcolor="FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
                     <tr>
                         <td valign="top">
-                            <a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a>
+                            <a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a>
                         </td>
                     </tr>
                     <!-- [ middle starts here] -->
diff --git a/app/code/core/Mage/Customer/view/email/account_new_confirmed.html b/app/code/core/Mage/Customer/view/email/account_new_confirmed.html
index 15850e9c077724b12bd2cb25d9e9f85ccffa1ab6..1d9a5930011c190ac0b2fd5a9be8f9df64c85703 100644
--- a/app/code/core/Mage/Customer/view/email/account_new_confirmed.html
+++ b/app/code/core/Mage/Customer/view/email/account_new_confirmed.html
@@ -1,7 +1,8 @@
 <!--@subject Welcome, {{var customer.name}}! @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "escapehtml var=$customer.name":"Customer Name",
 "store url=\"customer/account/\"":"Customer Account Url"}
 @-->
@@ -19,7 +20,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
                 <table bgcolor="FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
                     <tr>
                         <td valign="top">
-                            <a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a>
+                            <a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a>
                         </td>
                     </tr>
                     <!-- [ middle starts here] -->
diff --git a/app/code/core/Mage/Customer/view/email/password_new.html b/app/code/core/Mage/Customer/view/email/password_new.html
index 2171377a999224e228d5cb4fb8c991570b316d8f..d9cd06d2d0ce56779bfd2a5c9e84617b92e170c6 100644
--- a/app/code/core/Mage/Customer/view/email/password_new.html
+++ b/app/code/core/Mage/Customer/view/email/password_new.html
@@ -1,7 +1,8 @@
 <!--@subject New password for {{var customer.name}} @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "store url=\"customer/account/\"":"Customer Account Url",
 "escapehtml var=$customer.name":"Customer Name",
 "escapehtml var=$customer.password":"Customer New Password"}
@@ -19,7 +20,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
             <table bgcolor="FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
                 <tr>
                     <td valign="top">
-                        <a href="{{store url=""}}" style="color:#1E7EC8;"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}" border="0"/></a>
+                        <a href="{{store url=""}}" style="color:#1E7EC8;"><img src="{{var logo_url}}" alt="{{var logo_alt}}" border="0"/></a>
                     </td>
                 </tr>
                 <!-- [ middle starts here] -->
diff --git a/app/code/core/Mage/Customer/view/email/password_reset_confirmation.html b/app/code/core/Mage/Customer/view/email/password_reset_confirmation.html
index d29d5d835fb0e9fccc716e4f4cb845a9be91c4c9..1ad481e65c6970a8a7f2cc7b5a20360be7b7f5e8 100644
--- a/app/code/core/Mage/Customer/view/email/password_reset_confirmation.html
+++ b/app/code/core/Mage/Customer/view/email/password_reset_confirmation.html
@@ -1,7 +1,8 @@
 <!--@subject Password Reset Confirmation for {{var customer.name}} @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "escapehtml var=$customer.name":"Customer Name",
 "store url=\"customer/account/resetpassword/\" _query_id=$customer.id _query_token=$customer.rp_token":"Reset Password URL"}
 @-->
@@ -18,7 +19,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
                     <table bgcolor="FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
                         <tr>
                             <td valign="top">
-                                <a href="{{store url=""}}" style="color:#1E7EC8;"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}" border="0"/></a>
+                                <a href="{{store url=""}}" style="color:#1E7EC8;"><img src="{{var logo_url}}" alt="{{var logo_alt}}" border="0"/></a>
                             </td>
                         </tr>
                         <tr>
diff --git a/app/code/core/Mage/Customer/view/frontend/address/edit.phtml b/app/code/core/Mage/Customer/view/frontend/address/edit.phtml
index 9bb383d7048ebec1d0a956bfddac60125e622cc5..4af65a8c012fbd6a5284cdb941a1a4675639f64f 100644
--- a/app/code/core/Mage/Customer/view/frontend/address/edit.phtml
+++ b/app/code/core/Mage/Customer/view/frontend/address/edit.phtml
@@ -50,20 +50,20 @@
             <li class="wide">
                 <label for="company"><?php echo $this->__('Company') ?></label>
                 <div class="input-box">
-                    <input type="text" name="company" id="company" title="<?php echo $this->__('Company') ?>" value="<?php echo $this->escapeHtml($this->getAddress()->getCompany()) ?>" class="input-text" />
+                    <input type="text" name="company" id="company" title="<?php echo $this->__('Company') ?>" value="<?php echo $this->escapeHtml($this->getAddress()->getCompany()) ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('company') ?>" />
                 </div>
             </li>
             <li class="fields">
                 <div class="field">
                     <label for="telephone" class="required"><em>*</em><?php echo $this->__('Telephone') ?></label>
                     <div class="input-box">
-                        <input type="text" name="telephone" value="<?php echo $this->escapeHtml($this->getAddress()->getTelephone()) ?>" title="<?php echo $this->__('Telephone') ?>" class="input-text required-entry" id="telephone" />
+                        <input type="text" name="telephone" value="<?php echo $this->escapeHtml($this->getAddress()->getTelephone()) ?>" title="<?php echo $this->__('Telephone') ?>" class="input-text  <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('telephone') ?>" id="telephone" />
                     </div>
                 </div>
                 <div class="field">
                     <label for="fax"><?php echo $this->__('Fax') ?></label>
                     <div class="input-box">
-                        <input type="text" name="fax" id="fax" title="<?php echo $this->__('Fax') ?>" value="<?php echo $this->escapeHtml($this->getAddress()->getFax()) ?>" class="input-text" />
+                        <input type="text" name="fax" id="fax" title="<?php echo $this->__('Fax') ?>" value="<?php echo $this->escapeHtml($this->getAddress()->getFax()) ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('fax') ?>" />
                     </div>
                 </div>
             </li>
@@ -75,7 +75,7 @@
             <li class="wide">
                 <label for="street_1" class="required"><em>*</em><?php echo $this->__('Street Address') ?></label>
                 <div class="input-box">
-                    <input type="text" name="street[]" value="<?php echo $this->escapeHtml($this->getAddress()->getStreet(1)) ?>" title="<?php echo $this->__('Street Address') ?>" id="street_1" class="input-text required-entry" />
+                    <input type="text" name="street[]" value="<?php echo $this->escapeHtml($this->getAddress()->getStreet(1)) ?>" title="<?php echo $this->__('Street Address') ?>" id="street_1" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('street') ?>" />
                 </div>
             </li>
         <?php for ($_i=2, $_n=$this->helper('Mage_Customer_Helper_Address')->getStreetLines(); $_i<=$_n; $_i++): ?>
@@ -88,14 +88,14 @@
             <li class="wide">
                 <label for="vat_id"><?php echo $this->__('VAT Number') ?></label>
                 <div class="input-box">
-                    <input type="text" name="vat_id" value="<?php echo $this->escapeHtml($this->getAddress()->getVatId()) ?>" title="<?php echo $this->__('VAT Number') ?>" id="vat_id" class="input-text" />
+                    <input type="text" name="vat_id" value="<?php echo $this->escapeHtml($this->getAddress()->getVatId()) ?>" title="<?php echo $this->__('VAT Number') ?>" id="vat_id" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('vat_id') ?>" />
                 </div>
             </li>
             <li class="fields">
                 <div class="field">
                     <label for="city" class="required"><em>*</em><?php echo $this->__('City') ?></label>
                     <div class="input-box">
-                        <input type="text" name="city" value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>"  title="<?php echo $this->__('City') ?>" class="input-text required-entry" id="city" />
+                        <input type="text" name="city" value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>"  title="<?php echo $this->__('City') ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('city') ?>" id="city" />
                     </div>
                 </div>
                 <div class="field">
@@ -109,7 +109,7 @@
                             $('region_id').setAttribute('defaultValue',  "<?php echo $this->getAddress()->getRegionId() ?>");
                         //]]>
                         </script>
-                        <input type="text" id="region" name="region" value="<?php echo $this->escapeHtml($this->getAddress()->getRegion()) ?>"  title="<?php echo $this->__('State/Province') ?>" class="input-text" />
+                        <input type="text" id="region" name="region" value="<?php echo $this->escape($this->getAddress()->getRegion()) ?>"  title="<?php echo $this->__('State/Province') ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('region') ?>" />
                     </div>
                 </div>
             </li>
@@ -117,7 +117,7 @@
                 <div class="field">
                     <label for="zip" class="required"><em>*</em><?php echo $this->__('Zip/Postal Code') ?></label>
                     <div class="input-box">
-                        <input type="text" name="postcode" value="<?php echo $this->escapeHtml($this->getAddress()->getPostcode()) ?>" title="<?php echo $this->__('Zip/Postal Code') ?>" id="zip" class="input-text validate-zip-international required-entry" />
+                        <input type="text" name="postcode" value="<?php echo $this->escapeHtml($this->getAddress()->getPostcode()) ?>" title="<?php echo $this->__('Zip/Postal Code') ?>" id="zip" class="input-text validate-zip-international <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('postcode') ?>" />
                     </div>
                 </div>
                 <div class="field">
diff --git a/app/code/core/Mage/Customer/view/frontend/layout.xml b/app/code/core/Mage/Customer/view/frontend/layout.xml
index c0f902196748db30f14c46b6260f0b4c679ea29a..93722c1e3d391913a3bebf3783c12dc80483740a 100644
--- a/app/code/core/Mage/Customer/view/frontend/layout.xml
+++ b/app/code/core/Mage/Customer/view/frontend/layout.xml
@@ -47,41 +47,19 @@ Default layout, loads most of the pages
 -->
 
     <default>
-        <!-- Mage_Customer -->
         <reference name="top.links">
-            <action method="addLink" translate="label title" module="Mage_Customer"><label>My Account</label><url helper="Mage_Customer_Helper_Data::getAccountUrl"/><title>My Account</title><prepare/><urlParams/><position>10</position></action>
+            <block type="Mage_Customer_Block_Account_Link" name="account_links">
+                <action method="addAccountLink"><target>top.links</target><position>10</position></action>
+                <action method="addAuthLink"><target>top.links</target><position>100</position></action>
+            </block>
         </reference>
     </default>
 
-<!--
-Load this update on every page when customer is logged in
--->
-
-    <customer_logged_in>
-        <reference name="top.links">
-            <action method="addLink" translate="label title" module="Mage_Customer"><label>Log Out</label><url helper="Mage_Customer_Helper_Data::getLogoutUrl"/><title>Log Out</title><prepare/><urlParams/><position>100</position></action>
-        </reference>
-    </customer_logged_in>
-
-<!--
-Load this update on every page when customer is logged out
--->
-
-    <customer_logged_out>
-        <!---<reference name="right">
-            <block type="Mage_Customer_Block_Form_Login" name="customer_form_mini_login" before="-" template="customer/form/mini.login.phtml"/>
-        </reference>-->
-        <reference name="top.links">
-            <action method="addLink" translate="label title" module="Mage_Customer"><label>Log In</label><url helper="Mage_Customer_Helper_Data::getLoginUrl"/><title>Log In</title><prepare/><urlParams/><position>100</position></action>
-        </reference>
-        <remove name="reorder"></remove>
-    </customer_logged_out>
-
 <!--
 Layout for customer login page
 -->
 
-    <customer_account_login translate="label">
+    <customer_account_login translate="label" type="page" parent="customer_account">
         <label>Customer Account Login Form</label>
         <!-- Mage_Customer -->
         <remove name="right"/>
@@ -99,7 +77,7 @@ Layout for customer login page
 Layout for customer log out page
 -->
 
-    <customer_account_logoutsuccess translate="label">
+    <customer_account_logoutsuccess translate="label" type="page" parent="customer_account">
         <label>Customer Account Logout Success</label>
         <!-- Mage_Customer -->
         <remove name="right"/>
@@ -117,7 +95,7 @@ Layout for customer log out page
 New customer registration
 -->
 
-    <customer_account_create translate="label">
+    <customer_account_create translate="label" type="page" parent="customer_account">
         <label>Customer Account Registration Form</label>
         <!-- Mage_Customer -->
         <remove name="right"/>
@@ -128,14 +106,12 @@ New customer registration
         </reference>
         <reference name="content">
             <block type="Mage_Customer_Block_Form_Register" name="customer_form_register" template="form/register.phtml">
-                <block type="Mage_Page_Block_Html_Wrapper" name="customer.form.register.fields.before" as="form_fields_before" translate="label">
-                    <label>Form Fields Before</label>
-                </block>
+                <container name="customer.form.register.fields.before" as="form_fields_before" label="Form Fields Before" htmlTag="div"/>
             </block>
         </reference>
     </customer_account_create>
 
-    <customer_account_forgotpassword translate="label">
+    <customer_account_forgotpassword translate="label" type="page" parent="customer_account">
         <label>Customer Forgot Password Form</label>
         <remove name="right"/>
         <remove name="left"/>
@@ -152,7 +128,7 @@ New customer registration
         </reference>
     </customer_account_forgotpassword>
 
-    <customer_account_resetpassword translate="label">
+    <customer_account_resetpassword translate="label" type="page" parent="customer_account">
         <label>Reset a Password</label>
         <remove name="right"/>
         <remove name="left"/>
@@ -175,7 +151,8 @@ New customer registration
         </reference>
     </customer_account_resetpassword>
 
-    <customer_account_confirmation>
+    <customer_account_confirmation translate="label" type="page" parent="customer_account">
+        <label>Customer Account Confirmation</label>
         <remove name="right"/>
         <remove name="left"/>
 
@@ -188,7 +165,7 @@ New customer registration
         </reference>
     </customer_account_confirmation>
 
-    <customer_account_edit translate="label">
+    <customer_account_edit translate="label" type="page" parent="customer_account">
         <label>Customer Account Edit Form</label>
         <update handle="customer_account"/>
         <reference name="root">
@@ -207,7 +184,7 @@ New customer registration
 Customer account pages, rendered for all tabs in dashboard
 -->
 
-    <customer_account translate="label">
+    <customer_account translate="label" type="page" parent="default">
         <label>Customer My Account (All Pages)</label>
         <!--remove name="catalog.compare.sidebar"/>
         <remove name="sale.reorder.sidebar"/-->
@@ -217,10 +194,7 @@ Customer account pages, rendered for all tabs in dashboard
         </reference>
 
         <reference name="content">
-            <block type="Mage_Page_Block_Html_Wrapper" name="my.account.wrapper" translate="label">
-                <label>My Account Wrapper</label>
-                <action method="setElementClass"><value>my-account</value></action>
-            </block>
+            <container name="my.account.wrapper" label="My Account Wrapper" htmlTag="div" htmlClass="my-account"/>
         </reference>
 
         <reference name="left">
@@ -244,7 +218,7 @@ Customer account pages, rendered for all tabs in dashboard
 Customer account home dashboard layout
 -->
 
-    <customer_account_index translate="label">
+    <customer_account_index translate="label" type="page" parent="customer_account">
         <label>Customer My Account Dashboard</label>
         <update handle="customer_account"/>
         <!-- Mage_Customer -->
@@ -267,7 +241,7 @@ Customer account home dashboard layout
 Customer account address book
 -->
 
-    <customer_address_index translate="label">
+    <customer_address_index translate="label" type="page" parent="customer_account_index">
         <label>Customer My Account Address Book</label>
         <!-- Mage_Customer -->
         <update handle="customer_account"/>
@@ -280,7 +254,7 @@ Customer account address book
 Customer account address edit page
 -->
 
-    <customer_address_form translate="label">
+    <customer_address_form translate="label" type="page" parent="customer_address_index">
         <label>Customer My Account Address Edit Form</label>
         <!-- Mage_Customer -->
         <update handle="customer_account"/>
@@ -289,4 +263,4 @@ Customer account address edit page
         </reference>
     </customer_address_form>
 
-</layout>
\ No newline at end of file
+</layout>
diff --git a/app/code/core/Mage/Customer/view/frontend/widget/name.phtml b/app/code/core/Mage/Customer/view/frontend/widget/name.phtml
index 3f3ae6272f2b3c0ea7f4fddbd90aae9c1892e177..613c719bdf998442dc742eae2b7265966fc8d1f1 100644
--- a/app/code/core/Mage/Customer/view/frontend/widget/name.phtml
+++ b/app/code/core/Mage/Customer/view/frontend/widget/name.phtml
@@ -66,7 +66,7 @@ For checkout/onepage/shipping.phtml:
     <div class="field name-firstname">
         <label for="<?php echo $this->getFieldId('firstname')?>" class="required"><em>*</em><?php echo $this->getStoreLabel('firstname') ?></label>
         <div class="input-box">
-            <input type="text" id="<?php echo $this->getFieldId('firstname')?>" name="<?php echo $this->getFieldName('firstname')?>" value="<?php echo $this->escapeHtml($this->getObject()->getFirstname()) ?>" title="<?php echo $this->getStoreLabel('firstname') ?>" class="input-text required-entry" <?php echo $this->getFieldParams() ?> />
+            <input type="text" id="<?php echo $this->getFieldId('firstname')?>" name="<?php echo $this->getFieldName('firstname')?>" value="<?php echo $this->escapeHtml($this->getObject()->getFirstname()) ?>" title="<?php echo $this->getStoreLabel('firstname') ?>" maxlength="255" class="input-text <?php echo $this->getAttributeValidationClass('firstname') ?>" <?php echo $this->getFieldParams() ?> />
         </div>
     </div>
 <?php if ($this->showMiddlename()): ?>
@@ -74,14 +74,14 @@ For checkout/onepage/shipping.phtml:
     <div class="field name-middlename">
         <label for="<?php echo $this->getFieldId('middlename')?>"<?php echo $isMiddlenameRequired ? ' class="required"' : '' ?>><?php echo $isMiddlenameRequired ? '<em>*</em>' : '' ?><?php echo $this->getStoreLabel('middlename') ?></label>
         <div class="input-box">
-            <input type="text" id="<?php echo $this->getFieldId('middlename')?>" name="<?php echo $this->getFieldName('middlename')?>" value="<?php echo $this->escapeHtml($this->getObject()->getMiddlename()) ?>" title="<?php echo $this->getStoreLabel('middlename') ?>" class="input-text<?php echo $isMiddlenameRequired ? ' required-entry' : '' ?>" <?php echo $this->getFieldParams() ?> />
+            <input type="text" id="<?php echo $this->getFieldId('middlename')?>" name="<?php echo $this->getFieldName('middlename')?>" value="<?php echo $this->escapeHtml($this->getObject()->getMiddlename()) ?>" title="<?php echo $this->getStoreLabel('middlename') ?>" class="input-text <?php echo $this->getAttributeValidationClass('middlename') ?>" <?php echo $this->getFieldParams() ?> />
         </div>
     </div>
 <?php endif; ?>
     <div class="field name-lastname">
         <label for="<?php echo $this->getFieldId('lastname')?>" class="required"><em>*</em><?php echo $this->getStoreLabel('lastname') ?></label>
         <div class="input-box">
-            <input type="text" id="<?php echo $this->getFieldId('lastname')?>" name="<?php echo $this->getFieldName('lastname')?>" value="<?php echo $this->escapeHtml($this->getObject()->getLastname()) ?>" title="<?php echo $this->getStoreLabel('lastname') ?>" class="input-text required-entry" <?php echo $this->getFieldParams() ?> />
+            <input type="text" id="<?php echo $this->getFieldId('lastname')?>" name="<?php echo $this->getFieldName('lastname')?>" value="<?php echo $this->escapeHtml($this->getObject()->getLastname()) ?>" title="<?php echo $this->getStoreLabel('lastname') ?>" maxlength="255" class="input-text <?php echo $this->getAttributeValidationClass('lastname') ?>" <?php echo $this->getFieldParams() ?> />
         </div>
     </div>
 <?php if ($this->showSuffix()): ?>
diff --git a/app/code/core/Mage/DesignEditor/Block/Adminhtml/Launcher/Form.php b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Launcher/Form.php
new file mode 100644
index 0000000000000000000000000000000000000000..90feb8327a37b327c1f85da9ba052c1e7ab148eb
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Launcher/Form.php
@@ -0,0 +1,64 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Design editor launcher form
+ */
+class Mage_DesignEditor_Block_Adminhtml_Launcher_Form extends Mage_Adminhtml_Block_Widget_Form
+{
+    /**
+     * Create a form element with necessary controls
+     *
+     * @return Mage_Adminhtml_Block_Widget_Form
+     */
+    protected function _prepareForm()
+    {
+        $form = new Varien_Data_Form(array(
+            'id'        => 'edit_form',
+            'action'    => $this->getUrl('adminhtml/system_design_editor/launch'),
+            'target'    => '_blank'
+        ));
+
+        if (!Mage::app()->isSingleStoreMode()) {
+            $fieldset = $form->addFieldset(
+                'base_fieldset',
+                array('legend' => Mage::helper('Mage_DesignEditor_Helper_Data')->__('Context Information'))
+            );
+            $fieldset->addField('store_id', 'select', array(
+                'name'      => 'store_id',
+                'label'     => Mage::helper('Mage_DesignEditor_Helper_Data')->__('Store View'),
+                'title'     => Mage::helper('Mage_DesignEditor_Helper_Data')->__('Store View'),
+                'required'  => true,
+                'values'    => Mage::getSingleton('Mage_Adminhtml_Model_System_Store')->getStoreValuesForForm(),
+            ));
+        }
+
+        $this->setForm($form);
+        $form->setUseContainer(true);
+
+        return parent::_prepareForm();
+    }
+}
diff --git a/app/code/core/Mage/DesignEditor/Block/Adminhtml/Launcher/Form/Container.php b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Launcher/Form/Container.php
new file mode 100644
index 0000000000000000000000000000000000000000..970598eb316b8d37656bad7efb46eda7446e256f
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Block/Adminhtml/Launcher/Form/Container.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.
+ *
+ * @category    Mage
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Design editor launcher form container
+ */
+class Mage_DesignEditor_Block_Adminhtml_Launcher_Form_Container extends Mage_Adminhtml_Block_Widget_Form_Container
+{
+    /**
+     * Prevent dynamic form block creation, use the layout declaration instead
+     *
+     * @var string
+     */
+    protected $_mode = '';
+
+    /**
+     * Customize inherited buttons
+     */
+    public function __construct()
+    {
+        parent::__construct();
+        $this->_removeButton('back');
+        $this->_removeButton('reset');
+        $this->_removeButton('delete');
+        $this->_updateButton('save', 'label', Mage::helper('Mage_DesignEditor_Helper_Data')->__('Launch'));
+        $this->_updateButton('save', 'area', 'footer');
+    }
+
+    /**
+     * Retrieve appropriate text for the header element
+     *
+     * @return string
+     */
+    public function getHeaderText()
+    {
+        return Mage::helper('Mage_DesignEditor_Helper_Data')->__('Visual Design Editor');
+    }
+}
diff --git a/app/code/core/Mage/DesignEditor/Block/Toolbar.php b/app/code/core/Mage/DesignEditor/Block/Toolbar.php
new file mode 100644
index 0000000000000000000000000000000000000000..05ecf3e937c1c59dd6ff0267c1355728c122d405
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Block/Toolbar.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_DesignEditor
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Frontend toolbar panel for the design editor controls
+ */
+class Mage_DesignEditor_Block_Toolbar extends Mage_Core_Block_Template
+{
+    /**
+     * Prevent rendering if the design editor is inactive
+     *
+     * @return string
+     */
+    protected function _toHtml()
+    {
+        /** @var $session Mage_DesignEditor_Model_Session */
+        $session = Mage::getSingleton('Mage_DesignEditor_Model_Session');
+        if (!$session->isDesignEditorActive()) {
+            return '';
+        }
+        return parent::_toHtml();
+    }
+
+    /**
+     * Returns messages for Visual Design Editor, clears list of session messages
+     *
+     * @return array
+     */
+    public function getMessages()
+    {
+        return Mage::getSingleton('Mage_DesignEditor_Model_Session')
+            ->getMessages(true)
+            ->getItems();
+    }
+}
diff --git a/app/code/core/Mage/DesignEditor/Block/Toolbar/Breadcrumbs.php b/app/code/core/Mage/DesignEditor/Block/Toolbar/Breadcrumbs.php
new file mode 100644
index 0000000000000000000000000000000000000000..56b99eeec9a737802905e05d88987fefb95f2a30
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Block/Toolbar/Breadcrumbs.php
@@ -0,0 +1,76 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Breadcrumbs navigation for the current page
+ */
+class Mage_DesignEditor_Block_Toolbar_Breadcrumbs extends Mage_Core_Block_Template
+{
+    /**
+     * Retrieve breadcrumbs for the current page location
+     *
+     * Result format:
+     * array(
+     *     array(
+     *         'label' => 'Some Page Type',
+     *         'url'   => http://localhost/index.php/design/editor/page/page_type/some_page_type/',
+     *     ),
+     *     // ...
+     * )
+     *
+     * @return array
+     */
+    public function getBreadcrumbs()
+    {
+        $result = array();
+        $layoutUpdate = $this->getLayout()->getUpdate();
+        $pageTypes = $layoutUpdate->getPageHandles();
+        if (!$pageTypes) {
+            /** @var $controllerAction Mage_Core_Controller_Varien_Action */
+            $controllerAction = Mage::app()->getFrontController()->getAction();
+            if ($controllerAction) {
+                $pageTypes = $layoutUpdate->getPageLayoutHandles($controllerAction->getDefaultLayoutHandle());
+            }
+        }
+        foreach ($pageTypes as $pageTypeName) {
+            $result[] = array(
+                'label' => $this->escapeHtml($layoutUpdate->getPageTypeLabel($pageTypeName)),
+                'url'   => $this->getUrl('design/editor/page', array('page_type' => $pageTypeName))
+            );
+        }
+        /** @var $blockHead Mage_Page_Block_Html_Head */
+        $blockHead = $this->getLayout()->getBlock('head');
+        if ($blockHead && !$this->getOmitCurrentPage()) {
+            $result[] = array(
+                'label' => $blockHead->getTitle(),
+                'url'   => '',
+            );
+        } else if ($result) {
+            $result[count($result) - 1]['url'] = '';
+        }
+        return $result;
+    }
+}
diff --git a/app/code/core/Mage/DesignEditor/Block/Toolbar/Exit.php b/app/code/core/Mage/DesignEditor/Block/Toolbar/Exit.php
new file mode 100644
index 0000000000000000000000000000000000000000..0fcb95c41d81a535a7fcd81f2ad4457e8bc96374
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Block/Toolbar/Exit.php
@@ -0,0 +1,41 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Exit button control block
+ */
+class Mage_DesignEditor_Block_Toolbar_Exit extends Mage_Core_Block_Template
+{
+    /**
+     * Get exit editor URL
+     *
+     * @return string
+     */
+    public function getExitUrl()
+    {
+        return Mage::getSingleton('Mage_Adminhtml_Model_Url')->getUrl('adminhtml/system_design_editor/exit');
+    }
+}
diff --git a/app/code/core/Mage/DesignEditor/Block/Toolbar/PageType.php b/app/code/core/Mage/DesignEditor/Block/Toolbar/PageType.php
new file mode 100644
index 0000000000000000000000000000000000000000..039a161213df104e682868c3306e02fe8b19a778
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Block/Toolbar/PageType.php
@@ -0,0 +1,94 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Page types navigation control
+ */
+class Mage_DesignEditor_Block_Toolbar_PageType extends Mage_Core_Block_Template
+{
+    /**
+     * @var string|false
+     */
+    protected $_selectedPageType;
+
+    /**
+     * Recursively render each level of the page types hierarchy as an HTML list
+     *
+     * @param array $pageTypes
+     * @return string
+     */
+    protected function _renderPageTypes(array $pageTypes)
+    {
+        if (!$pageTypes) {
+            return '';
+        }
+        $result = '<ul>';
+        foreach ($pageTypes as $name => $info) {
+            $result .= '<li rel="' . $name . '">';
+            $result .= '<a href="' . $this->getUrl('design/editor/page', array('page_type' => $name)) . '">';
+            $result .= $this->escapeHtml($info['label']);
+            $result .= '</a>';
+            $result .= $this->_renderPageTypes($info['children']);
+            $result .= '</li>';
+        }
+        $result .= '</ul>';
+        return $result;
+    }
+
+    /**
+     * Render page types hierarchy as an HTML list
+     *
+     * @return string
+     */
+    public function renderPageTypes()
+    {
+        return $this->_renderPageTypes($this->getLayout()->getUpdate()->getPageTypesHierarchy());
+    }
+
+    /**
+     * Retrieve the name of the currently selected page type
+     *
+     * @return string|false
+     */
+    public function getSelectedPageType()
+    {
+        if ($this->_selectedPageType === null) {
+            $pageHandles = $this->getLayout()->getUpdate()->getPageHandles();
+            $this->_selectedPageType = end($pageHandles);
+        }
+        return $this->_selectedPageType;
+    }
+
+    /**
+     * Set the name of the currently selected page type
+     *
+     * @param string $name Page type name
+     */
+    public function setSelectedPageType($name)
+    {
+        $this->_selectedPageType = $name;
+    }
+}
diff --git a/app/code/core/Mage/DesignEditor/Block/Toolbar/Skin.php b/app/code/core/Mage/DesignEditor/Block/Toolbar/Skin.php
new file mode 100644
index 0000000000000000000000000000000000000000..806f699d51a98878efffa174e957cf49475281c4
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Block/Toolbar/Skin.php
@@ -0,0 +1,83 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * A skin selector for design editor frontend toolbar panel
+ */
+class Mage_DesignEditor_Block_Toolbar_Skin extends Mage_Core_Block_Template
+{
+    /**
+     * Returns list of skins in the system
+     *
+     * @return array
+     */
+    public function getOptions()
+    {
+        return Mage::getModel('Mage_Core_Model_Design_Source_Design')
+            ->getOptions();
+    }
+
+    /**
+     * Returns whether skin selected in current store design
+     *
+     * @param string $skin
+     * @return bool
+     */
+    public function isSkinSelected($skin)
+    {
+        $currentSkin = Mage::getDesign()->getDesignTheme();
+        return $currentSkin == $skin;
+    }
+
+    /**
+     * Returns string with JSON configuration for skin selector
+     *
+     * @return string
+     */
+    public function getJsonConfig()
+    {
+        $encodedUrl = Mage::helper('Mage_Core_Helper_Url')->getEncodedUrl();
+        $config = array(
+            'selectId' => $this->getSelectHtmlId(),
+            'changeSkinUrl' => $this->getUrl('design/editor/skin'),
+            'backParams' => array(
+                Mage_Core_Controller_Front_Action::PARAM_NAME_URL_ENCODED => $encodedUrl
+            )
+        );
+        return Mage::helper('Mage_Core_Helper_Data')
+            ->jsonEncode($config);
+    }
+
+    /**
+     * Returns html id of the skin select control
+     *
+     * @return string
+     */
+    public function getSelectHtmlId()
+    {
+        return 'visual_design_editor_skin';
+    }
+}
diff --git a/app/code/core/Mage/DesignEditor/Exception.php b/app/code/core/Mage/DesignEditor/Exception.php
new file mode 100644
index 0000000000000000000000000000000000000000..c8b3a735e5e3ebd1a9fa8beed60b80004ceb6cb7
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Exception.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    Mage
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Magento Design Editor Exception
+ *
+ * @category   Mage
+ * @package    Mage_DesignEditor
+ */
+class Mage_DesignEditor_Exception extends Mage_Core_Exception
+{
+}
diff --git a/app/code/core/Mage/DesignEditor/Helper/Data.php b/app/code/core/Mage/DesignEditor/Helper/Data.php
new file mode 100644
index 0000000000000000000000000000000000000000..fe83e3f697981e61cad112381d7493b31b1417ab
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Helper/Data.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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Design Editor main helper
+ */
+class Mage_DesignEditor_Helper_Data extends Mage_Core_Helper_Abstract
+{
+}
diff --git a/app/code/core/Mage/DesignEditor/Model/Layout.php b/app/code/core/Mage/DesignEditor/Model/Layout.php
new file mode 100644
index 0000000000000000000000000000000000000000..0e82426f01c6e401b69161eb05fb71ae35082eb9
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Model/Layout.php
@@ -0,0 +1,217 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Model for manipulating layout for purpose of design editor
+ */
+class Mage_DesignEditor_Model_Layout
+{
+    /**
+     * List of block types considered as "safe"
+     *
+     * "Safe" means that they will work with any template (if applicable)
+     *
+     * @var array
+     */
+    protected static $_blockWhiteList = array(
+        'Mage_Core_Block_Template',
+        'Mage_Page_Block_',
+        'Mage_DesignEditor_Block_',
+        'Mage_Checkout_Block_Onepage_',
+        'Mage_Paypal_Block_Express_Review_Details',
+    );
+
+    /**
+     * List of block types considered as "not safe"
+     *
+     * @var array
+     */
+    protected static $_blockBlackList = array(
+        'Mage_Page_Block_Html_Pager',
+    );
+
+    /**
+     * List of layout containers that potentially have "safe" blocks
+     *
+     * @var array
+     */
+    protected static $_containerWhiteList = array(
+        'root', 'head', 'after_body_start', 'header', 'footer', 'before_body_end',
+        'top.links', 'top.menu',
+    );
+
+    /**
+     * Replace all potentially dangerous blocks in layout into stubs
+     *
+     * It is important to sanitize the references first, because they refer to blocks to check whether they are safe.
+     * But if the blocks were sanitized before references, then they ALL will be considered safe.
+     *
+     * @param Varien_Simplexml_Element $node
+     */
+    public static function sanitizeLayout(Varien_Simplexml_Element $node)
+    {
+        self::_sanitizeLayout($node, 'reference'); // it is important to sanitize references first
+        self::_sanitizeLayout($node, 'block');
+    }
+
+    /**
+     * Sanitize nodes which names match the specified one
+     *
+     * Recursively goes through all underlying nodes
+     *
+     * @param Varien_Simplexml_Element $node
+     * @param string $nodeName
+     */
+    protected static function _sanitizeLayout(Varien_Simplexml_Element $node, $nodeName)
+    {
+        if ($node->getName() == $nodeName) {
+            switch ($nodeName) {
+                case 'block':
+                    self::_sanitizeBlock($node);
+                    break;
+                case 'reference':
+                    self::_sanitizeReference($node);
+                    break;
+            }
+        }
+        foreach ($node->children() as $child) {
+            self::_sanitizeLayout($child, $nodeName);
+        }
+    }
+
+    /**
+     * Replace "unsafe" types of blocks into Mage_Core_Block_Template and cut all their actions
+     *
+     * A "stub" template will be assigned for the blocks
+     *
+     * @param Varien_Simplexml_Element $node
+     */
+    protected static function _sanitizeBlock(Varien_Simplexml_Element $node)
+    {
+        $type = $node->getAttribute('type');
+        if (!$type) {
+            return; // we encountered a node with name "block", however it doesn't actually define any block...
+        }
+        if (self::_isParentSafe($node) || self::_isTypeSafe($type)) {
+            return;
+        }
+        self::_overrideAttribute($node, 'template', 'Mage_DesignEditor::stub.phtml');
+        self::_overrideAttribute($node, 'type', 'Mage_Core_Block_Template');
+        self::_deleteNodes($node, 'action');
+    }
+
+    /**
+     * Whether parent node of specified node can be considered a safe container
+     *
+     * @param Varien_Simplexml_Element $node
+     * @return bool
+     */
+    protected static function _isParentSafe(Varien_Simplexml_Element $node)
+    {
+        $parentAttributes = $node->getParent()->attributes();
+        if (isset($parentAttributes['name'])) {
+            if (!in_array($parentAttributes['name'], self::$_containerWhiteList)) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Check whether the specified type of block can be safely used in layout without required context
+     *
+     * @param string $type
+     * @return bool
+     */
+    protected static function _isTypeSafe($type)
+    {
+        if (in_array($type, self::$_blockBlackList)) {
+            return false;
+        }
+        foreach (self::$_blockWhiteList as $safeType) {
+            if ('_' !== substr($safeType, -1, 1)) {
+                if ($type === $safeType) {
+                    return true;
+                }
+            } elseif (0 === strpos($type, $safeType)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Add or update specified attribute of a node with specified value
+     *
+     * @param Varien_Simplexml_Element $node
+     * @param string $name
+     * @param string $value
+     */
+    protected static function _overrideAttribute(Varien_Simplexml_Element $node, $name, $value)
+    {
+        $attributes = $node->attributes();
+        if (isset($attributes[$name])) {
+            $attributes[$name] = $value;
+        } else {
+            $attributes->addAttribute($name, $value);
+        }
+    }
+
+    /**
+     * Delete child nodes by specified name
+     *
+     * @param Varien_Simplexml_Element $node
+     * @param string $name
+     */
+    protected static function _deleteNodes(Varien_Simplexml_Element $node, $name)
+    {
+        $count = count($node->{$name});
+        for ($i = $count; $i >= 0; $i--) {
+            unset($node->{$name}[$i]);
+        }
+    }
+
+    /**
+     * Cleanup reference node according to the block it refers to
+     *
+     * Look for the block by reference name and if the block is "unsafe", cleanup the reference node from actions
+     *
+     * @param Varien_Simplexml_Element $node
+     */
+    protected static function _sanitizeReference(Varien_Simplexml_Element $node)
+    {
+        $attributes = $node->attributes();
+        $name = $attributes['name'];
+        $result = $node->xpath("//block[@name='{$name}']") ?: array();
+        foreach ($result as $block) {
+            $isTypeSafe = self::_isTypeSafe($block->getAttribute('type'));
+            if (!$isTypeSafe || !self::_isParentSafe($block)) {
+                self::_deleteNodes($node, 'action');
+            }
+            break;
+        }
+    }
+}
diff --git a/app/code/core/Mage/DesignEditor/Model/Observer.php b/app/code/core/Mage/DesignEditor/Model/Observer.php
new file mode 100644
index 0000000000000000000000000000000000000000..eda45fdfb56a77acd8ef177102775ebb3b73fd4b
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Model/Observer.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.
+ *
+ * @category    Mage
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Observer for design editor module
+ */
+class Mage_DesignEditor_Model_Observer
+{
+    const PAGE_HANDLE = 'design_editor_page';
+    const TOOLBAR_HANDLE = 'design_editor_toolbar';
+
+    /**
+     * Renderer for wrapping html to be shown at frontend
+     *
+     * @var Mage_Core_Block_Template
+     */
+    protected $_wrappingRenderer = null;
+
+    /**
+     * Handler for 'controller_action_predispatch' event
+     */
+    public function preDispatch()
+    {
+        /* Deactivate the design editor, if the admin session has been already expired */
+        if (!$this->_getSession()->isLoggedIn()) {
+            $this->_getSession()->deactivateDesignEditor();
+        }
+        /* Apply custom design to the current page */
+        if ($this->_getSession()->isDesignEditorActive() && $this->_getSession()->getSkin()) {
+            Mage::getDesign()->setDesignTheme($this->_getSession()->getSkin());
+        }
+    }
+
+    /**
+     * Add the design editor toolbar to the current page
+     *
+     * @param Varien_Event_Observer $observer
+     */
+    public function addToolbar(Varien_Event_Observer $observer)
+    {
+        if (!$this->_getSession()->isDesignEditorActive()) {
+            return;
+        }
+        $layout = $observer->getEvent()->getLayout();
+        if (in_array('ajax_index', $layout->getUpdate()->getHandles())) {
+            $layout->getUpdate()->addHandle(self::PAGE_HANDLE);
+        }
+        $layout->getUpdate()->addHandle(self::TOOLBAR_HANDLE);
+    }
+
+    /**
+     * Disable blocks HTML output caching
+     */
+    public function disableBlocksOutputCaching()
+    {
+        if (!$this->_getSession()->isDesignEditorActive()) {
+            return;
+        }
+        Mage::app()->getCacheInstance()->banUse(Mage_Core_Block_Abstract::CACHE_GROUP);
+    }
+
+    /**
+     * Set design_editor_active flag, which allows to load DesignEditor's CSS or JS scripts
+     *
+     * @param Varien_Event_Observer $observer
+     */
+    public function setDesignEditorFlag(Varien_Event_Observer $observer)
+    {
+        if (!$this->_getSession()->isDesignEditorActive()) {
+            return;
+        }
+        /** @var $block Mage_Page_Block_Html_Head */
+        $block = $observer->getEvent()->getLayout()->getBlock('head');
+        if ($block) {
+            $block->setDesignEditorActive(true);
+        }
+    }
+
+    /**
+     * Retrieve session instance for the design editor
+     *
+     * @return Mage_DesignEditor_Model_Session
+     */
+    protected function _getSession()
+    {
+        return Mage::getSingleton('Mage_DesignEditor_Model_Session');
+    }
+
+    /**
+     * Wrap each element of a page that is being rendered, with a block-level HTML-element to hightligt it in VDE
+     *
+     * Subscriber to event 'core_layout_render_element'
+     *
+     * @param Varien_Event_Observer $observer
+     */
+    public function wrapPageElement(Varien_Event_Observer $observer)
+    {
+        if (!$this->_getSession()->isDesignEditorActive()) {
+            return;
+        }
+
+        if (!$this->_wrappingRenderer) {
+            $this->_wrappingRenderer = Mage::getModel('Mage_Core_Block_Template', array(
+                'template' => 'Mage_DesignEditor::wrapping.phtml'
+            ));
+        }
+
+        $event = $observer->getEvent();
+        /** @var $structure Mage_Core_Model_Layout_Structure */
+        $structure = $event->getData('structure');
+        /** @var $layout Mage_Core_Model_Layout */
+        $layout = $event->getData('layout');
+        $name = $event->getData('element_name');
+        /** @var $transport Varien_Object */
+        $transport = $event->getData('transport');
+
+        $block = $layout->getBlock($name);
+        $isVdeToolbar = ($block && 0 === strpos(get_class($block), 'Mage_DesignEditor_Block_'));
+
+        if ($structure->isManipulationAllowed($name) && !$isVdeToolbar) {
+            $this->_wrappingRenderer->setData(array(
+                'element_name' => $name, 'element_html' => $transport->getData('output')
+            ));
+            $transport->setData('output', $this->_wrappingRenderer->toHtml());
+        }
+    }
+
+    /**
+     * Deactivate the design editor
+     */
+    public function adminSessionUserLogout()
+    {
+        $this->_getSession()->deactivateDesignEditor();
+    }
+}
diff --git a/app/code/core/Mage/DesignEditor/Model/Session.php b/app/code/core/Mage/DesignEditor/Model/Session.php
new file mode 100644
index 0000000000000000000000000000000000000000..d9ca48d0a04181ce399063615027edf97f1d85f5
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/Model/Session.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.
+ *
+ * @category    Mage
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Design editor session model
+ */
+class Mage_DesignEditor_Model_Session extends Mage_Admin_Model_Session
+{
+    /**
+     * Session key that indicates whether the design editor is active
+     */
+    const SESSION_DESIGN_EDITOR_ACTIVE = 'DESIGN_EDITOR_ACTIVE';
+
+    /**
+     * Check whether the design editor is active for the current session or not
+     *
+     * @return bool
+     */
+    public function isDesignEditorActive()
+    {
+        return $this->getData(self::SESSION_DESIGN_EDITOR_ACTIVE) && $this->isLoggedIn();
+    }
+
+    /**
+     * Activate the design editor for the current session
+     */
+    public function activateDesignEditor()
+    {
+        if (!$this->getData(self::SESSION_DESIGN_EDITOR_ACTIVE) && $this->isLoggedIn()) {
+            $this->setData(self::SESSION_DESIGN_EDITOR_ACTIVE, 1);
+            Mage::dispatchEvent('design_editor_session_activate');
+        }
+    }
+
+    /**
+     * Deactivate the design editor for the current session
+     */
+    public function deactivateDesignEditor()
+    {
+        /*
+         * isLoggedIn() is intentionally not taken into account to be able to trigger event when admin session expires
+         */
+        if ($this->getData(self::SESSION_DESIGN_EDITOR_ACTIVE)) {
+            $this->unsetData(self::SESSION_DESIGN_EDITOR_ACTIVE);
+            Mage::dispatchEvent('design_editor_session_deactivate');
+        }
+    }
+
+    /**
+     * Sets skin to user session, so that next time everything will be rendered with this skin
+     *
+     * @param string $skin
+     * @return Mage_DesignEditor_Model_Session
+     */
+    public function setSkin($skin)
+    {
+        if ($skin && !$this->_isSkinApplicable($skin)) {
+            Mage::throwException(Mage::helper('Mage_DesignEditor_Helper_Data')->__("Skin doesn't exist"));
+        }
+        $this->setData('skin', $skin);
+        return $this;
+    }
+
+    /**
+     * Returns whether a skin is a valid one to set into user session
+     *
+     * @param string $skin
+     * @return bool
+     */
+    protected function _isSkinApplicable($skin)
+    {
+        if (!$skin) {
+            return false;
+        }
+        $options = Mage::getModel('Mage_Core_Model_Design_Source_Design')->getOptions();
+        foreach ($options as $optGroup) {
+            foreach ($optGroup['value'] as $option) {
+                if ($option['value'] == $skin) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+}
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
new file mode 100644
index 0000000000000000000000000000000000000000..efa52bc767f1b4276c1b530bab98e10309ba1a20
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/controllers/Adminhtml/System/Design/EditorController.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.
+ *
+ * @category    Mage
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2012 Magento 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_EditorController extends Mage_Adminhtml_Controller_Action
+{
+    /**
+     * Display the design editor launcher page
+     */
+    public function indexAction()
+    {
+        $this->_title($this->__('System'))->_title($this->__('Design'))->_title($this->__('Editor'));
+        $this->loadLayout();
+        $this->_setActiveMenu('system/design/editor');
+        $this->renderLayout();
+    }
+
+    /**
+     * Activate the design editor in the session and redirect to the frontend of the selected store
+     */
+    public function launchAction()
+    {
+        /** @var $session Mage_DesignEditor_Model_Session */
+        $session = Mage::getSingleton('Mage_DesignEditor_Model_Session');
+        $session->activateDesignEditor();
+        /* Redirect to the frontend */
+        $query = Mage_Core_Model_Session_Abstract::SESSION_ID_QUERY_PARAM . '=' . urlencode($session->getSessionId());
+        if (!Mage::app()->isSingleStoreMode()) {
+            $storeId = (int)$this->getRequest()->getParam('store_id');
+            $store = Mage::app()->getStore($storeId);
+            $baseUrl = $store->getBaseUrl();
+            $query .= '&___store=' . urlencode($store->getCode());
+        } else {
+            $baseUrl = Mage::app()->getStore(true)->getBaseUrl();
+        }
+        $this->_redirectUrl($baseUrl . '?' . $query);
+    }
+
+    /**
+     * Exit design editor
+     */
+    public function exitAction()
+    {
+        /** @var $session Mage_DesignEditor_Model_Session */
+        $session = Mage::getSingleton('Mage_DesignEditor_Model_Session');
+        $session->deactivateDesignEditor();
+        $this->loadLayout();
+        $this->renderLayout();
+    }
+
+    /**
+     * Whether the current user has enough permissions to execute an action
+     *
+     * @return bool
+     */
+    protected function _isAllowed()
+    {
+        return Mage::getSingleton('Mage_Admin_Model_Session')->isAllowed('system/design/editor');
+    }
+}
diff --git a/app/code/core/Mage/DesignEditor/controllers/EditorController.php b/app/code/core/Mage/DesignEditor/controllers/EditorController.php
new file mode 100644
index 0000000000000000000000000000000000000000..4b946649547f771142aefb29f94ba945c787ee24
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/controllers/EditorController.php
@@ -0,0 +1,133 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Controller that allows to display arbitrary page in design editor mode
+ */
+class Mage_DesignEditor_EditorController extends Mage_Core_Controller_Front_Action
+{
+    /**
+     * @var Mage_DesignEditor_Model_Session
+     */
+    protected $_session = null;
+
+    /**
+     * @var string
+     */
+    protected $_fullActionName = '';
+
+    /**
+     * Enforce admin session with the active design editor mode
+     *
+     * @return Mage_DesignEditor_EditorController
+     */
+    public function preDispatch()
+    {
+        parent::preDispatch();
+
+        $this->_session = Mage::getSingleton('Mage_DesignEditor_Model_Session');
+        if (!$this->_session->isDesignEditorActive()) {
+            Mage::getSingleton('Mage_Core_Model_Session')->addError(
+                $this->__('Design editor is not initialized by administrator.')
+            );
+            $this->norouteAction();
+            $this->setFlag('', self::FLAG_NO_DISPATCH, true);
+        }
+
+        return $this;
+    }
+
+    /**
+     * Display an arbitrary page by specified page type
+     */
+    public function pageAction()
+    {
+        try {
+            $pageType = $this->getRequest()->getParam('page_type');
+
+            // page type format
+            if (!$pageType || !preg_match('/^[a-z][a-z\d]*(_[a-z][a-z\d]*)*$/i', $pageType)) {
+                Mage::throwException($this->__('Invalid page type specified.'));
+            }
+
+            // whether such page type exists
+            if (!$this->getLayout()->getUpdate()->pageTypeExists($pageType)) {
+                Mage::throwException($this->__("Specified page type doesn't exist: '{$pageType}'."));
+            }
+
+            $this->_fullActionName = $pageType;
+            $this->addPageLayoutHandles();
+            $this->loadLayoutUpdates();
+            $this->generateLayoutXml();
+            Mage::getModel('Mage_DesignEditor_Model_Layout')->sanitizeLayout($this->getLayout()->getNode());
+            $this->generateLayoutBlocks();
+
+            $blockPageTypes = $this->getLayout()->getBlock('design_editor_toolbar_page_types');
+            if ($blockPageTypes) {
+                $blockPageTypes->setSelectedPageType($pageType);
+            }
+            $blockBreadcrumbs = $this->getLayout()->getBlock('design_editor_toolbar_breadcrumbs');
+            if ($blockBreadcrumbs) {
+                $blockBreadcrumbs->setOmitCurrentPage(true);
+            }
+
+            $this->renderLayout();
+        } catch (Mage_Core_Exception $e) {
+            $this->getResponse()->setBody($e->getMessage());
+            $this->getResponse()->setHeader('Content-Type', 'text/plain; charset=UTF-8')->setHttpResponseCode(503);
+        }
+    }
+
+    /**
+     * Hack the "full action name" in order to render emulated layout
+     *
+     * @param string $delimiter
+     * @return string
+     */
+    public function getFullActionName($delimiter = '_')
+    {
+        if ($this->_fullActionName) {
+            return $this->_fullActionName;
+        }
+        return parent::getFullActionName($delimiter);
+    }
+
+    /**
+     * Sets new skin for viewed store and returns customer back to the previous address
+     */
+    public function skinAction()
+    {
+        $skin = $this->getRequest()->get('skin');
+        $backUrl = $this->_getRefererUrl();
+
+        try {
+            $this->_session->setSkin($skin);
+        } catch (Mage_Core_Exception $e) {
+            $this->_session->addError($e->getMessage());
+        }
+        $this->getResponse()->setRedirect($backUrl);
+    }
+}
diff --git a/app/code/core/Mage/DesignEditor/etc/adminhtml.xml b/app/code/core/Mage/DesignEditor/etc/adminhtml.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e563d313fe0c5cb866297f550be063f3586e4e03
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/etc/adminhtml.xml
@@ -0,0 +1,64 @@
+<?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    Mage
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<config>
+    <menu>
+        <system>
+            <children>
+                <design>
+                    <children>
+                        <editor translate="title" module="Mage_DesignEditor">
+                            <title>Editor</title>
+                            <action>adminhtml/system_design_editor</action>
+                            <sort_order>20</sort_order>
+                        </editor>
+                    </children>
+                </design>
+            </children>
+        </system>
+    </menu>
+    <acl>
+        <resources>
+            <admin>
+                <children>
+                    <system>
+                        <children>
+                            <design>
+                                <children>
+                                    <editor translate="title" module="Mage_DesignEditor">
+                                        <title>Editor</title>
+                                        <sort_order>20</sort_order>
+                                    </editor>
+                                </children>
+                            </design>
+                        </children>
+                    </system>
+                </children>
+            </admin>
+        </resources>
+    </acl>
+</config>
diff --git a/app/code/core/Mage/DesignEditor/etc/config.xml b/app/code/core/Mage/DesignEditor/etc/config.xml
new file mode 100644
index 0000000000000000000000000000000000000000..8e0461354246f2ef2f851b30457cbdc8b3933d47
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/etc/config.xml
@@ -0,0 +1,117 @@
+<?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    Mage
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<config>
+    <modules>
+        <Mage_DesignEditor>
+            <version>1.0.0.0</version>
+        </Mage_DesignEditor>
+    </modules>
+    <frontend>
+        <layout>
+            <updates>
+                <designeditor module="Mage_DesignEditor">
+                    <file>layout.xml</file>
+                </designeditor>
+            </updates>
+        </layout>
+        <routers>
+            <designeditor>
+                <use>standard</use>
+                <args>
+                    <module>Mage_DesignEditor</module>
+                    <frontName>design</frontName>
+                </args>
+            </designeditor>
+        </routers>
+        <events>
+            <controller_action_predispatch>
+                <observers>
+                    <designeditor>
+                        <class>Mage_DesignEditor_Model_Observer</class>
+                        <method>preDispatch</method>
+                    </designeditor>
+                </observers>
+            </controller_action_predispatch>
+            <controller_action_layout_load_before>
+                <observers>
+                    <designeditor>
+                        <class>Mage_DesignEditor_Model_Observer</class>
+                        <method>addToolbar</method>
+                    </designeditor>
+                </observers>
+            </controller_action_layout_load_before>
+            <controller_action_layout_generate_blocks_after>
+                <observers>
+                    <designeditor>
+                        <class>Mage_DesignEditor_Model_Observer</class>
+                        <method>setDesignEditorFlag</method>
+                    </designeditor>
+                </observers>
+            </controller_action_layout_generate_blocks_after>
+            <core_layout_render_element>
+                <observers>
+                    <designeditor>
+                        <type>singleton</type>
+                        <class>Mage_DesignEditor_Model_Observer</class>
+                        <method>wrapPageElement</method>
+                    </designeditor>
+                </observers>
+            </core_layout_render_element>
+        </events>
+    </frontend>
+    <adminhtml>
+        <layout>
+            <updates>
+                <designeditor module="Mage_DesignEditor">
+                    <file>layout.xml</file>
+                </designeditor>
+            </updates>
+        </layout>
+        <events>
+            <admin_session_user_logout>
+                <observers>
+                    <designeditor>
+                        <class>Mage_DesignEditor_Model_Observer</class>
+                        <method>adminSessionUserLogout</method>
+                    </designeditor>
+                </observers>
+            </admin_session_user_logout>
+        </events>
+    </adminhtml>
+    <admin>
+        <routers>
+            <adminhtml>
+                <args>
+                    <modules>
+                        <mage_designeditor before="Mage_Adminhtml">Mage_DesignEditor_Adminhtml</mage_designeditor>
+                    </modules>
+                </args>
+            </adminhtml>
+        </routers>
+    </admin>
+</config>
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/exit.phtml b/app/code/core/Mage/DesignEditor/view/adminhtml/exit.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..f2694128259a38b4c2f7b1dc14b97fcd04642cfe
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/exit.phtml
@@ -0,0 +1,27 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<script type="text/javascript">window.close();</script>
diff --git a/app/code/core/Mage/DesignEditor/view/adminhtml/layout.xml b/app/code/core/Mage/DesignEditor/view/adminhtml/layout.xml
new file mode 100644
index 0000000000000000000000000000000000000000..f8ff2433dd990c7c45ea773c8f64426c2c1fa147
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/adminhtml/layout.xml
@@ -0,0 +1,42 @@
+<?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    design
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<layout>
+    <adminhtml_system_design_editor_index>
+        <reference name="content">
+            <block type="Mage_DesignEditor_Block_Adminhtml_Launcher_Form_Container" name="design_editor_launcher_form_container">
+                <block type="Mage_DesignEditor_Block_Adminhtml_Launcher_Form" name="design_editor_launcher_form" as="form"/>
+            </block>
+        </reference>
+    </adminhtml_system_design_editor_index>
+
+    <adminhtml_system_design_editor_exit>
+        <reference name="content">
+            <block type="Mage_Adminhtml_Block_Template" name="design_editor_exit" as="exit" template="Mage_DesignEditor::exit.phtml"/>
+        </reference>
+    </adminhtml_system_design_editor_exit>
+</layout>
diff --git a/app/code/core/Mage/DesignEditor/view/frontend/css/styles.css b/app/code/core/Mage/DesignEditor/view/frontend/css/styles.css
new file mode 100644
index 0000000000000000000000000000000000000000..9a9969e841dc9b2ca21ffd7ea97fd5ddc0d5ff5a
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/frontend/css/styles.css
@@ -0,0 +1,104 @@
+/**
+ * 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     pro_default
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+
+/* Visual Design Editor ================================================================== */
+#vde_toolbar {
+    z-index: 999;
+    font:11px/1.35 Arial, Helvetica, sans-serif;
+    color:#444;
+    background: white;
+    padding-top: 5px;
+    padding-bottom: 5px;
+}
+#vde_toolbar a.vde_button { border: 1px solid #777777; background: #ffffff; text-decoration: none; padding: 0 7px 1px 7px; text-align: center; }
+#vde_toolbar a.vde_button:hover { background: #eeeeee; }
+#vde_toolbar .item-msg {
+    border-style: solid;
+    border-width: 1px;
+    padding: 4px;
+}
+
+#vde_toolbar .error {
+    border-color: red;
+    color: red;
+}
+
+#vde_page_types_hierarchy {
+    position: absolute;
+    max-height: 300px; /* maximal allowed height */
+    overflow-y: auto; /* display vertical scrollbar when content exceeds the maximal allowed height */
+    overflow-x: hidden; /* don't display horizontal scrollbar */
+    padding-right: 20px; /* make sure vertical scrollbar doesn't overlap list items */
+    z-index: 1000;
+    text-align: left;
+    display: none;
+    border: 1px solid #aaa;
+    background-color: #fff;
+}
+
+.vde_marker {
+    display: none;
+}
+
+.vde_element_wrapper {
+    border: 1px solid green;
+    padding: 2px;
+}
+.vde_element_title {
+    background-color: green;
+    padding: 2px;
+    color: white;
+    font-size: 11px;
+    max-width: 150px;
+    height: 13px;
+    text-align: left;
+    line-height: 12px;
+}
+
+.vde_placeholder {
+    position: absolute;
+    background-color: #ff9;
+}
+
+.vde_toolbar_row {
+    margin-bottom: 5px;
+}
+
+.vde_toolbar_cell {
+    float: left;
+    padding-left: 10px;
+    padding-right: 10px;
+    border-left: 1px solid black;
+}
+
+.ui-draggable-dragging {
+    z-index: 201;
+}
+
+#vde_toolbar:after,
+.vde_toolbar_row:after {
+    display:block; content:"."; clear:both; font-size:0; line-height:0; height:0; overflow:hidden;
+}
+/* ======================================================================================= */
diff --git a/app/code/core/Mage/DesignEditor/view/frontend/js/design_editor.js b/app/code/core/Mage/DesignEditor/view/frontend/js/design_editor.js
new file mode 100644
index 0000000000000000000000000000000000000000..510094dd60a020c981989c73ea7eab9f1fbed05a
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/frontend/js/design_editor.js
@@ -0,0 +1,184 @@
+/**
+ * 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_DesignEditor
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+
+(function ($) {
+    /**
+     * Class for managing skin selector control
+     */
+    DesignEditorSkinSelector = function (config) {
+        this._init(config);
+        this._addListener();
+        return this;
+    }
+
+    DesignEditorSkinSelector.prototype._init = function (config) {
+        this._skinControlSelector = '#' + config.selectId;
+        this._backParams = config.backParams;
+        this.changeSkinUrl = config.changeSkinUrl;
+        return this;
+    }
+
+    DesignEditorSkinSelector.prototype._addListener = function () {
+        var thisObj = this;
+        $(this._skinControlSelector).change(
+            function () {thisObj.changeSkin()}
+        );
+        return this;
+    }
+
+    DesignEditorSkinSelector.prototype.changeSkin = function () {
+        var separator = /\?/.test(this.changeSkinUrl) ? '&' : '?';
+
+        var params = {skin: $(this._skinControlSelector).val()};
+        for (var i in this._backParams) {
+            params[i] = this._backParams[i];
+        }
+
+        var url = this.changeSkinUrl + separator + $.param(params);
+
+        window.location.href = url;
+        return this;
+    }
+
+    /**
+     * Class for design editor
+     */
+    DesignEditor = function () {
+        this._init();
+    }
+
+    DesignEditor.prototype._init = function () {
+        this._dragged = null;
+        this._placeholder = null;
+        this._templatePlaceholder = '<div class="vde_placeholder"></div>';
+
+        this._enableDragging();
+        return this;
+    }
+
+    DesignEditor.prototype._enableDragging = function () {
+        var thisObj = this;
+        $('.vde_element_wrapper').draggable({
+            helper: 'clone',
+            revert: true,
+            start: function (event, ui) {thisObj._onDragStarted(event, ui)},
+            stop: function (event, ui) {thisObj._onDragStopped(event, ui)}
+        });
+        return this;
+    }
+
+    DesignEditor.prototype._triggerStartedEvent = function () {
+        $(document).trigger('started.vde', this);
+        return this;
+    }
+
+    DesignEditor.prototype._onDragStarted = function (event, ui) {
+        if (this._dragged) {
+            return this;
+        }
+        var dragged = $(event.target);
+        this._hideDragged(dragged)
+            ._resizeHelperSameAsDragged(ui.helper, dragged)
+            ._putPlaceholder();
+    }
+
+    DesignEditor.prototype._onDragStopped = function (event, ui) {
+        if (!this._dragged) {
+            return this;
+        }
+        this._removePlaceholder()
+            ._showDragged();
+    }
+
+    DesignEditor.prototype._hideDragged = function (dragged) {
+        this._showDragged(); // Maybe some other dragged element was hidden before, just restore it
+        this._dragged = dragged;
+        this._dragged.css('visibility', 'hidden');
+        return this;
+    }
+
+    DesignEditor.prototype._showDragged = function () {
+        if (!this._dragged) {
+            return this;
+        }
+        this._dragged.css('visibility', 'visible');
+        this._dragged = null;
+        return this;
+    }
+
+    DesignEditor.prototype._resizeHelperSameAsDragged = function (helper, dragged) {
+        helper.height(dragged.height())
+            .width(dragged.width());
+        return this;
+    }
+
+    DesignEditor.prototype._putPlaceholder = function () {
+        if (!this._placeholder) {
+            this._placeholder = $(this._templatePlaceholder);
+        }
+        this._placeholder.css('height', this._dragged.outerHeight() + 'px')
+            .css('width', this._dragged.outerWidth() + 'px');
+        this._placeholder.insertBefore(this._dragged);
+        return this;
+    }
+
+    DesignEditor.prototype._removePlaceholder = function () {
+        if (!this._placeholder) {
+            return this;
+        }
+        this._placeholder.remove();
+        return this;
+    }
+
+    DesignEditor.prototype.highlight = function (isOn) {
+        if (isOn) {
+            this._turnHighlightingOn();
+        } else {
+            this._turnHighlightingOff();
+        }
+        return this;
+    }
+
+    DesignEditor.prototype._turnHighlightingOn = function () {
+        $('.vde_element_wrapper').each(function () {
+            var elem = $(this);
+            var children = elem.prop('vdeChildren');
+            elem.show().append(children).removeProp('vdeChildren');
+            elem.children('.vde_element_title').slideDown('fast');
+        });
+        return this;
+    }
+
+    DesignEditor.prototype._turnHighlightingOff = function () {
+        $('.vde_element_wrapper').each(function () {
+            var elem = $(this);
+            elem.children('.vde_element_title').slideUp('fast', function () {
+                var children = elem.children(':not(.vde_element_title)');
+                elem.after(children).hide().prop('vdeChildren', children);
+            });
+        });
+        return this;
+    }
+})(jQuery);
diff --git a/app/code/core/Mage/DesignEditor/view/frontend/layout.xml b/app/code/core/Mage/DesignEditor/view/frontend/layout.xml
new file mode 100644
index 0000000000000000000000000000000000000000..d711a78cd7ae2f0dfebf4bb3c6b55fee57c6b250
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/frontend/layout.xml
@@ -0,0 +1,62 @@
+<?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    design
+ * @package     Mage_DesignEditor
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<layout>
+    <design_editor_toolbar>
+        <label>Design Editor Toolbar</label>
+        <reference name="head">
+            <action method="addJs"><file>jquery/jquery-1.7.1.min.js</file></action>
+            <action method="addJs"><file>mage/jquery-no-conflict.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/jquery-ui-1.8.17.custom.min.js</file></action>
+            <action method="addCss"><file>Mage_DesignEditor::css/styles.css</file></action>
+        </reference>
+        <reference name="after_body_start">
+            <block type="Mage_DesignEditor_Block_Toolbar" name="design_editor_toolbar" template="toolbar.phtml" before="-">
+                <block type="Mage_Core_Block_Template" name="design_editor_toolbar_row1" template="Mage_DesignEditor::toolbar/row.phtml">
+                    <block type="Mage_DesignEditor_Block_Toolbar_Skin" name="design_editor_toolbar_skin" template="toolbar/skin.phtml"/>
+                    <block type="Mage_Core_Block_Template" name="design_editor_toolbar_highlighting" template="Mage_DesignEditor::toolbar/highlighting.phtml"/>
+                    <block type="Mage_DesignEditor_Block_Toolbar_Exit" name="design_editor_toolbar_exit" template="toolbar/exit.phtml"/>
+                </block>
+                <block type="Mage_Core_Block_Template" name="design_editor_toolbar_row2" template="Mage_DesignEditor::toolbar/row.phtml">
+                    <block type="Mage_DesignEditor_Block_Toolbar_Breadcrumbs" name="design_editor_toolbar_breadcrumbs" template="toolbar/breadcrumbs.phtml"/>
+                    <block type="Mage_DesignEditor_Block_Toolbar_PageType" name="design_editor_toolbar_page_types" template="toolbar/page_types.phtml"/>
+                </block>
+            </block>
+        </reference>
+    </design_editor_toolbar>
+
+    <design_editor_page>
+        <label>Design Editor Page Blocks Management Page</label>
+        <reference name="root">
+            <action method="setTemplate"><template>Mage_DesignEditor::page.phtml</template></action>
+            <block type="Mage_Page_Block_Html_Head" name="head" as="head"/>
+            <container name="after_body_start" as="after_body_start" label="Page Top"/>
+        </reference>
+    </design_editor_page>
+</layout>
diff --git a/app/code/core/Mage/DesignEditor/view/frontend/page.phtml b/app/code/core/Mage/DesignEditor/view/frontend/page.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..a14396f204f3605c392a4c283c352b3a3acb2be9
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/frontend/page.phtml
@@ -0,0 +1,40 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->getLang() ?>" lang="<?php echo $this->getLang() ?>">
+<head>
+    <?php echo $this->getChildHtml('head') ?>
+</head>
+<body>
+<?php echo $this->getChildHtml('after_body_start') ?>
+<?php foreach ($this->getChildNames() as $name): ?>
+    <?php if ($name != 'head' && $name != 'after_body_start'): ?>
+        <?php echo $this->getChildHtml($name) ?>
+    <?php endif; ?>
+<?php endforeach; ?>
+</body>
+</html>
diff --git a/app/code/core/Mage/DesignEditor/view/frontend/stub.phtml b/app/code/core/Mage/DesignEditor/view/frontend/stub.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..0d5ad4dc30e60c619d96611b9a4faaa11a2988af
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/frontend/stub.phtml
@@ -0,0 +1,32 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<div class="block-stub" style="padding:0 0 .5ex 0;margin:1px 1px 0 1ex;border:1px solid red;">
+<div style="line-height:1em;">
+    <span style="background-color:black;color:white;cursor:pointer;"><?php echo $this->getNameInLayout() ?></span>
+</div>
+<div style="padding-top:.5ex;"><?php echo $this->getChildHtml() ?></div>
+</div>
diff --git a/app/code/core/Mage/DesignEditor/view/frontend/toolbar.phtml b/app/code/core/Mage/DesignEditor/view/frontend/toolbar.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..da44ab2512fc71b7a46c2b3bc3d457d7805cbea0
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/frontend/toolbar.phtml
@@ -0,0 +1,40 @@
+<?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) 2012 Magento 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_Toolbar */ ?>
+<div id="vde_toolbar">
+    <?php $messages = $this->getMessages(); ?>
+    <?php foreach ($messages as $message): ?>
+        <p class="item-msg <?php echo $message->getType() ?>"><?php echo $this->escapeHtml($message->getCode()) ?></p>
+    <?php endforeach; ?>
+    <?php echo $this->getChildHtml(); ?>
+</div>
+
+<script type="text/javascript">
+jQuery(document).ready(function () {
+    designEditor = new DesignEditor();
+});
+</script>
diff --git a/app/code/core/Mage/DesignEditor/view/frontend/toolbar/breadcrumbs.phtml b/app/code/core/Mage/DesignEditor/view/frontend/toolbar/breadcrumbs.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..9cb21ede19de6847a8a69d42cc6df138b82f4b11
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/frontend/toolbar/breadcrumbs.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) 2012 Magento 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_Toolbar_Breadcrumbs */ ?>
+<div>
+    <span><?php echo $this->__('Current Location:'); ?></span>
+    <?php $isFirstItem = true; ?>
+    <?php foreach ($this->getBreadcrumbs() as $breadcrumb) : ?>
+        <?php if (!$isFirstItem) : ?>
+            <span>/</span>
+        <?php endif; ?>
+        <?php if ($breadcrumb['url']) : ?>
+            <a href="<?php echo $breadcrumb['url']; ?>"><?php echo $breadcrumb['label']; ?></a>
+        <?php else : ?>
+            <span><?php echo $breadcrumb['label']; ?></span>
+        <?php endif; ?>
+        <?php $isFirstItem = false; ?>
+    <?php endforeach; ?>
+</div>
diff --git a/app/code/core/Mage/DesignEditor/view/frontend/toolbar/exit.phtml b/app/code/core/Mage/DesignEditor/view/frontend/toolbar/exit.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..958e9fa8f972fb0c96dee0f5b56181bbd8ef6414
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/frontend/toolbar/exit.phtml
@@ -0,0 +1,31 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<div>
+    <a href="<?php echo $this->getExitUrl(); ?>" title="<?php echo $this->__('Exit'); ?>" class="vde_button">
+        <?php echo $this->__('Exit'); ?>
+    </a>
+</div>
diff --git a/app/code/core/Mage/DesignEditor/view/frontend/toolbar/highlighting.phtml b/app/code/core/Mage/DesignEditor/view/frontend/toolbar/highlighting.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..385e4a33c45ba86a2e8af3d90503dd6340e149dc
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/frontend/toolbar/highlighting.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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<div>
+    <input type="checkbox" checked="checked" id="vde_highlighting"/>
+    <label for="vde_highlighting"><?php echo $this->__('Highlight blocks'); ?></label>
+</div>
+
+<script type="text/javascript">
+    jQuery(document).ready(function () {
+        jQuery('#vde_highlighting').on('click', null, function (event) {
+            designEditor.highlight(jQuery(this).prop('checked'));
+        });
+    });
+</script>
diff --git a/app/code/core/Mage/DesignEditor/view/frontend/toolbar/page_types.phtml b/app/code/core/Mage/DesignEditor/view/frontend/toolbar/page_types.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..6447ce32241c98852ec547e3823a19a3df3097c4
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/frontend/toolbar/page_types.phtml
@@ -0,0 +1,67 @@
+<?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) 2012 Magento 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_Toolbar_PageType */ ?>
+<div id="vde_page_types_hierarchy">
+    <?php echo $this->renderPageTypes(); ?>
+</div>
+<div>
+    <?php echo $this->__('Page Type:'); ?>
+    <button id="vde_page_types_control"><?php echo $this->__('Select a Page Type'); ?></button>
+</div>
+<script type="text/javascript">
+(function ($) {
+    $(document).ready(function () {
+        $("#vde_page_types_hierarchy").jstree({
+            ui: {
+                select_limit: 1,
+                selected_parent_close: false
+            }
+        }).bind('select_node.jstree', function (e, data) {
+            var selectedListItem = data.rslt.obj;
+            $('#vde_page_types_control').text(selectedListItem.children('a').text());
+            if ($(this).is(':visible')) {
+                $(this).hide();
+                window.location = selectedListItem.children('a').attr('href');
+            }
+        });
+        $('#vde_page_types_control').bind('click', function (event) {
+            var controlPos = $(this).offset();
+            var controlHeight = $(this).outerHeight();
+            $("#vde_page_types_hierarchy").css({
+                left: controlPos.left,
+                top: controlPos.top + controlHeight
+            }).slideToggle();
+        });
+        <?php if ($this->getSelectedPageType()) : ?>
+        $("#vde_page_types_hierarchy").bind('loaded.jstree', function (e, data) {
+            var treeInstance = data.inst;
+            treeInstance.select_node($(this).find('li[rel="<?php echo $this->getSelectedPageType(); ?>"]'));
+        });
+        <?php endif; ?>
+    });
+})(jQuery);
+</script>
diff --git a/app/code/core/Mage/DesignEditor/view/frontend/toolbar/row.phtml b/app/code/core/Mage/DesignEditor/view/frontend/toolbar/row.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..51d479e0f16d744a268062e564557f4202a875fd
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/frontend/toolbar/row.phtml
@@ -0,0 +1,35 @@
+<?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) 2012 Magento 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_Template */ ?>
+<div class="vde_toolbar_row">
+    <?php $layout = $this->getLayout(); ?>
+    <?php foreach ($this->getChildNames() as $name): ?>
+    <div class="vde_toolbar_cell">
+        <?php echo $layout->renderElement($name) ?>
+    </div>
+    <?php endforeach; ?>
+</div>
diff --git a/app/code/core/Mage/DesignEditor/view/frontend/toolbar/skin.phtml b/app/code/core/Mage/DesignEditor/view/frontend/toolbar/skin.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..0492beb0f58f88103cf1a234c0e0d6a4dcb6a5a3
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/frontend/toolbar/skin.phtml
@@ -0,0 +1,48 @@
+<?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) 2012 Magento 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_Toolbar_Skin */ ?>
+<div class="skin-selector">
+    <?php echo Mage::helper('Mage_DesignEditor_Helper_Data')->__('Skin:'); ?>
+    <select id="<?php echo $this->getSelectHtmlId(); ?>">
+        <?php foreach ($this->getOptions() as $optGroup): ?>
+            <optgroup label="<?php echo $this->escapeHtml($optGroup['label']) ?>">
+                <?php foreach ($optGroup['value'] as $option): ?>
+                    <?php $selected = $this->isSkinSelected($option['value']) ? 'selected="selected"' : ''; ?>
+                    <option value="<?php echo $this->escapeHtml($option['value']); ?>" <?php echo $selected; ?>>
+                        <?php echo $this->escapeHtml($option['label']); ?>
+                    </option>
+                <?php endforeach; ?>
+            </optgroup>
+        <?php endforeach; ?>
+    </select>
+</div>
+
+<script type="text/javascript">
+jQuery(document).ready(function () {
+    new DesignEditorSkinSelector(<?php echo $this->getJsonConfig() ?>);
+});
+</script>
diff --git a/app/code/core/Mage/DesignEditor/view/frontend/wrapping.phtml b/app/code/core/Mage/DesignEditor/view/frontend/wrapping.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..0ddbb016a520e11b83fd4aa1a14f555df25d6d22
--- /dev/null
+++ b/app/code/core/Mage/DesignEditor/view/frontend/wrapping.phtml
@@ -0,0 +1,31 @@
+<?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) 2012 Magento 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_Template */ ?>
+<div class="vde_element_wrapper">
+    <div class="vde_element_title"><?php echo $this->getElementName() ?></div>
+    <?php echo $this->getElementHtml(); ?>
+</div>
diff --git a/app/code/core/Mage/Directory/Helper/Data.php b/app/code/core/Mage/Directory/Helper/Data.php
index bde0ab462c885ae1b9a1d50bb2693189d19d5999..9a35c6f16053ecf7a3b8241a88389ba1d7232a85 100644
--- a/app/code/core/Mage/Directory/Helper/Data.php
+++ b/app/code/core/Mage/Directory/Helper/Data.php
@@ -36,6 +36,16 @@ class Mage_Directory_Helper_Data extends Mage_Core_Helper_Abstract
      */
     const OPTIONAL_ZIP_COUNTRIES_CONFIG_PATH = 'general/country/optional_zip_countries';
 
+    /*
+     * Path to config value, which lists countries, for which state is required.
+     */
+    const XML_PATH_STATES_REQUIRED = 'general/region/state_required';
+
+    /*
+     * Path to config value, which detects whether or not display the state for the country, if it is not required
+     */
+    const XML_PATH_DISPLAY_ALL_STATES = 'general/region/display_all';
+
     /**
      * Country collection
      *
@@ -122,7 +132,12 @@ class Mage_Directory_Helper_Data extends Mage_Core_Helper_Abstract
                 $collection = Mage::getModel('Mage_Directory_Model_Region')->getResourceCollection()
                     ->addCountryFilter($countryIds)
                     ->load();
-                $regions = array();
+                $regions = array(
+                    'config' => array(
+                        'show_all_regions' => $this->getShowNonRequiredState(),
+                        'regions_required' => $this->getCountriesWithStatesRequired()
+                    )
+                );
                 foreach ($collection as $region) {
                     if (!$region->getRegionId()) {
                         continue;
@@ -194,4 +209,44 @@ class Mage_Directory_Helper_Data extends Mage_Core_Helper_Abstract
         $this->getCountriesWithOptionalZip();
         return in_array($countryCode, $this->_optionalZipCountries);
     }
+
+    /**
+     * Returns the list of countries, for which region is required
+     *
+     * @param boolean $asJson
+     * @return array
+     */
+    public function getCountriesWithStatesRequired($asJson = false)
+    {
+        $countryList = explode(',', Mage::getStoreConfig(self::XML_PATH_STATES_REQUIRED));
+        if ($asJson) {
+            return Mage::helper('Mage_Core_Helper_Data')->jsonEncode($countryList);
+        }
+        return $countryList;
+    }
+
+    /**
+     * Return flag, which indicates whether or not non required state should be shown
+     *
+     * @return bool
+     */
+    public function getShowNonRequiredState()
+    {
+        return (boolean)Mage::getStoreConfig(self::XML_PATH_DISPLAY_ALL_STATES);
+    }
+
+    /**
+     * Returns flag, which indicates whether region is required for specified country
+     *
+     * @param string $countryId
+     * @return bool
+     */
+    public function isRegionRequired($countryId)
+    {
+        $countyList = $this->getCountriesWithStatesRequired();
+        if(!is_array($countyList)) {
+            return false;
+        }
+        return in_array($countryId, $countyList);
+    }
 }
diff --git a/app/code/core/Mage/Directory/data/directory_setup/data-upgrade-1.6.0.0-1.6.0.1.php b/app/code/core/Mage/Directory/data/directory_setup/data-upgrade-1.6.0.0-1.6.0.1.php
new file mode 100644
index 0000000000000000000000000000000000000000..064683c64473eb478713c3321381a9e15b8fe4d8
--- /dev/null
+++ b/app/code/core/Mage/Directory/data/directory_setup/data-upgrade-1.6.0.0-1.6.0.1.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_Directory
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/*
+ * @var $installer Mage_Core_Model_Resource_Setup
+ */
+$installer = $this;
+$installer->getConnection()->insert(
+    $installer->getTable('core_config_data'), array(
+       'scope'    => 'default',
+       'scope_id' => 0,
+       'path'     => Mage_Directory_Helper_Data::XML_PATH_DISPLAY_ALL_STATES,
+       'value'    => 1
+    )
+);
+
+/**
+ * @var $countries array
+ */
+$countries = array();
+foreach(Mage::helper('Mage_Directory_Helper_Data')->getCountryCollection() as $country) {
+    if($country->getRegionCollection()->getSize() > 0) {
+        $countries[] = $country->getId();
+    }
+}
+
+$installer->getConnection()->insert(
+    $installer->getTable('core_config_data'), array(
+        'scope'    => 'default',
+        'scope_id' => 0,
+        'path'     => Mage_Directory_Helper_Data::XML_PATH_STATES_REQUIRED,
+        'value'    => implode(',', $countries)
+    )
+);
+
diff --git a/app/code/core/Mage/Directory/etc/config.xml b/app/code/core/Mage/Directory/etc/config.xml
index 475d636ce8163761991cea83d87557698af94a85..43f4f79349c23be3ffbc3e5f91d5d8ab769bb41e 100644
--- a/app/code/core/Mage/Directory/etc/config.xml
+++ b/app/code/core/Mage/Directory/etc/config.xml
@@ -28,7 +28,7 @@
 <config>
     <modules>
         <Mage_Directory>
-            <version>1.6.0.0</version>
+            <version>1.6.0.1</version>
         </Mage_Directory>
     </modules>
     <global>
diff --git a/app/code/core/Mage/Directory/etc/system.xml b/app/code/core/Mage/Directory/etc/system.xml
index 6052b9c2fbcf037936f74828008f9b8af57562fd..dafa757e10f4f8344ffe801599c5848753aef334 100644
--- a/app/code/core/Mage/Directory/etc/system.xml
+++ b/app/code/core/Mage/Directory/etc/system.xml
@@ -209,6 +209,34 @@
                         </optional_zip_countries>
                     </fields>
                 </country>
+                <region translate="label">
+                    <label>States Options</label>
+                    <frontend_type>text</frontend_type>
+                    <sort_order>4</sort_order>
+                    <show_in_default>1</show_in_default>
+                    <show_in_website>0</show_in_website>
+                    <show_in_store>0</show_in_store>
+                    <fields>
+                        <state_required translate="label">
+                            <label>State is required for</label>
+                            <frontend_type>multiselect</frontend_type>
+                            <source_model>Mage_Adminhtml_Model_System_Config_Source_Country</source_model>
+                            <sort_order>1</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>0</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </state_required>
+                        <display_all translate="label">
+                            <label>Display not required State</label>
+                            <frontend_type>select</frontend_type>
+                            <source_model>Mage_Adminhtml_Model_System_Config_Source_Yesno</source_model>
+                            <sort_order>8</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>0</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </display_all>
+                    </fields>
+                </region>
             </groups>
         </general>
     </sections>
diff --git a/app/code/core/Mage/Directory/view/frontend/layout.xml b/app/code/core/Mage/Directory/view/frontend/layout.xml
index 77bee91967bd2e5fe3cd33afa0bd383b7d104de1..cdda7c3cc6c595a8003e022f403c425a2cfc414a 100644
--- a/app/code/core/Mage/Directory/view/frontend/layout.xml
+++ b/app/code/core/Mage/Directory/view/frontend/layout.xml
@@ -37,21 +37,11 @@ Category default layout
         </reference>
     </default>
 
-    <catalog_category_default>
+    <catalog_category_view>
         <reference name="left">
             <block type="Mage_Directory_Block_Currency" name="currency" before="catalog.leftnav" template="currency.phtml"/>
         </reference>
-    </catalog_category_default>
-
-<!--
-Category layered navigation layout
--->
-
-    <catalog_category_layered>
-        <reference name="left">
-            <block type="Mage_Directory_Block_Currency" name="currency" before="catalog.leftnav" template="currency.phtml"/>
-        </reference>
-    </catalog_category_layered>
+    </catalog_category_view>
 
 <!--
 Catalog Search layout
diff --git a/app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Links.php b/app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Links.php
index d8e2a9c9edc7d95f7241dab1d8e2106844b123fc..8602be453a2b79561ad60c951ed3c8d9e75e4cee 100644
--- a/app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Links.php
+++ b/app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Links.php
@@ -264,7 +264,7 @@ class Mage_Downloadable_Block_Adminhtml_Catalog_Product_Edit_Tab_Downloadable_Li
      */
     public function getUploadButtonHtml()
     {
-        return $this->getChild('upload_button')->toHtml();
+        return $this->getChildBlock('upload_button')->toHtml();
     }
 
     /**
diff --git a/app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Samples.php b/app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Samples.php
index 4a0b9059fb0130aa196a29bc6a883025f3cdafd1..ed53cf717dd550ee8ade6de7ab62826b5ca3270a 100644
--- a/app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Samples.php
+++ b/app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Samples.php
@@ -167,7 +167,7 @@ class Mage_Downloadable_Block_Adminhtml_Catalog_Product_Edit_Tab_Downloadable_Sa
      */
     public function getUploadButtonHtml()
     {
-        return $this->getChild('upload_button')->toHtml();
+        return $this->getChildBlock('upload_button')->toHtml();
     }
 
     /**
diff --git a/app/code/core/Mage/Downloadable/Model/Observer.php b/app/code/core/Mage/Downloadable/Model/Observer.php
index c09e6f7f32e482f729e4ffcb5fe4d90d62eb6171..25cea949b6daa1d78018262414d2117cfd3bb412 100644
--- a/app/code/core/Mage/Downloadable/Model/Observer.php
+++ b/app/code/core/Mage/Downloadable/Model/Observer.php
@@ -280,4 +280,17 @@ class Mage_Downloadable_Model_Observer
 
         return $this;
     }
+
+    /**
+     * Initialize product options renderer with downloadable specific params
+     *
+     * @param Varien_Event_Observer $observer
+     * @return Mage_Downloadable_Model_Observer
+     */
+    public function initOptionRenderer(Varien_Event_Observer $observer)
+    {
+        $block = $observer->getBlock();
+        $block->addOptionsRenderCfg('downloadable', 'Mage_Downloadable_Helper_Catalog_Product_Configuration');
+        return $this;
+    }
 }
diff --git a/app/code/core/Mage/Downloadable/etc/adminhtml.xml b/app/code/core/Mage/Downloadable/etc/adminhtml.xml
index 1a316cc5436912a903aa5b3b90e83cb663b8f98e..3d0068bcfead336735330f8ab275835e05154358 100644
--- a/app/code/core/Mage/Downloadable/etc/adminhtml.xml
+++ b/app/code/core/Mage/Downloadable/etc/adminhtml.xml
@@ -35,7 +35,7 @@
                             <config>
                                 <children>
                                     <downloadable translate="title" module="Mage_Downloadable">
-                                        <title>Downloadable product Section</title>
+                                        <title>Downloadable Product Section</title>
                                     </downloadable>
                                 </children>
                             </config>
diff --git a/app/code/core/Mage/Downloadable/etc/config.xml b/app/code/core/Mage/Downloadable/etc/config.xml
index b5724a1e927432729df77685721d1be43e19f1ac..11eada301ca5af219662a81846695a10ee1d4a92 100644
--- a/app/code/core/Mage/Downloadable/etc/config.xml
+++ b/app/code/core/Mage/Downloadable/etc/config.xml
@@ -207,6 +207,14 @@
                     </checkout_allow_guest>
                 </observers>
             </checkout_allow_guest>
+            <product_option_renderer_init>
+                <observers>
+                    <downloadable_observer>
+                        <class>Mage_Downloadable_Model_Observer</class>
+                        <method>initOptionRenderer</method>
+                    </downloadable_observer>
+                </observers>
+            </product_option_renderer_init>
         </events>
     </frontend>
     <admin>
diff --git a/app/code/core/Mage/Downloadable/view/adminhtml/layout.xml b/app/code/core/Mage/Downloadable/view/adminhtml/layout.xml
index bb39cfaec0859d767ce41d22bcf57588454f6511..2874a40a4c709a882a64b1c06f10683b0cb500f9 100644
--- a/app/code/core/Mage/Downloadable/view/adminhtml/layout.xml
+++ b/app/code/core/Mage/Downloadable/view/adminhtml/layout.xml
@@ -89,9 +89,9 @@
         </reference>
     </adminhtml_customer_wishlist>
 
-    <PRODUCT_TYPE_downloadable>
+    <catalog_product_view_type_downloadable>
         <reference name="product.composite.fieldset">
             <block type="Mage_Downloadable_Block_Adminhtml_Catalog_Product_Composite_Fieldset_Downloadable" name="product.composite.fieldset.downloadable" before="product.composite.fieldset.options" template="product/composite/fieldset/downloadable.phtml" />
         </reference>
-    </PRODUCT_TYPE_downloadable>
+    </catalog_product_view_type_downloadable>
 </layout>
diff --git a/app/code/core/Mage/Downloadable/view/adminhtml/product/composite/fieldset/downloadable.phtml b/app/code/core/Mage/Downloadable/view/adminhtml/product/composite/fieldset/downloadable.phtml
index 8577ee3aa56153062677670c810f40f06f2ad9b2..1664fad30c9d77924f906781550ebd31c0685e96 100644
--- a/app/code/core/Mage/Downloadable/view/adminhtml/product/composite/fieldset/downloadable.phtml
+++ b/app/code/core/Mage/Downloadable/view/adminhtml/product/composite/fieldset/downloadable.phtml
@@ -26,7 +26,8 @@
 ?>
 <?php /* @var $this Mage_Downloadable_Block_Adminhtml_Catalog_Product_Composite_Fieldset_Downloadable */ ?>
 <?php $_linksPurchasedSeparately = $this->getLinksPurchasedSeparately(); ?>
-<?php if ($this->getProduct()->isSaleable() && $this->hasLinks()):?>
+<?php $_skipSaleableCheck = Mage::helper('Mage_Catalog_Helper_Product')->getSkipSaleableCheck(); ?>
+<?php if (($this->getProduct()->isSaleable() || $_skipSaleableCheck) && $this->hasLinks()):?>
 
 <div id="catalog_product_composite_configure_fields_downloadable" class="<?php echo $this->getIsLastFieldset() ? 'last-fieldset' : '' ?>">
     <h4><?php echo Mage::helper('Mage_Catalog_Helper_Data')->__('Downloadable Information') ?></h4>
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 054f55de883e60a9d1c9cc99cffc0557b48cce6b..fd0953037501ef45e170056a24f9922e5e66f5db 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
@@ -74,7 +74,7 @@
     </td>
     <?php if ($this->helper('Mage_Wishlist_Helper_Data')->isAllowInCart()) : ?>
     <td class="a-center">
-        <input type="checkbox" value="1" name="cart[<?php echo $_item->getId() ?>][wishlist]" title="<?php echo $this->__('Move to Wishlist') ?>" class="checkbox" />
+        <a href="<?php echo $this->helper('Mage_Wishlist_Helper_Data')->getMoveFromCartUrl($_item->getId()); ?>" class="link-wishlist"><?php echo $this->__('Move'); ?></a>
     </td>
     <?php endif ?>
 <?php if ($canApplyMsrp): ?>
@@ -180,7 +180,7 @@
     <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" />
     </td>
-    <?php if ($this->helper('Mage_Tax_Helper_Data')->displayCartPriceExclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()): ?>
+    <?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');">
@@ -225,7 +225,7 @@
         <?php endif; ?>
     </td>
     <?php endif; ?>
-    <?php if ($this->helper('Mage_Tax_Helper_Data')->displayCartPriceInclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()): ?>
+    <?php if (($this->helper('Mage_Tax_Helper_Data')->displayCartPriceInclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()) && !$_item->getNoSubtotal()): ?>
     <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()): ?>
diff --git a/app/code/core/Mage/Downloadable/view/frontend/layout.xml b/app/code/core/Mage/Downloadable/view/frontend/layout.xml
index b20276835639e194c179b341dd6f2378a3c86800..1c67dc13ba4dd046818aef9aabba05e0b76b0a57 100644
--- a/app/code/core/Mage/Downloadable/view/frontend/layout.xml
+++ b/app/code/core/Mage/Downloadable/view/frontend/layout.xml
@@ -34,7 +34,7 @@
         </reference>
     </customer_account>
 
-    <downloadable_customer_products translate="label">
+    <downloadable_customer_products translate="label" type="page" parent="customer_account">
         <label>Customer My Account Downloadable Items</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
@@ -52,7 +52,7 @@
     </checkout_cart_index>
 
     <checkout_onepage_review>
-        <reference name="root">
+        <reference name="order_review">
             <action method="addItemRender"><type>downloadable</type><block>Mage_Downloadable_Block_Checkout_Cart_Item_Renderer</block><template>checkout/onepage/review/item.phtml</template></action>
         </reference>
     </checkout_onepage_review>
@@ -104,7 +104,7 @@
         </reference>
     </paypaluk_express_review>
     <paypaluk_express_review_details>
-        <reference name="root">
+        <reference name="order_review">
             <action method="addItemRender"><type>downloadable</type><block>Mage_Downloadable_Block_Checkout_Cart_Item_Renderer</block><template>checkout/onepage/review/item.phtml</template></action>
         </reference>
     </paypaluk_express_review_details>
@@ -127,12 +127,6 @@
         </reference>
     </sales_order_creditmemo>
 
-    <wishlist_index_index>
-        <reference name="customer.wishlist">
-            <action method="addOptionsRenderCfg"><type>downloadable</type><helper>Mage_Downloadable_Helper_Catalog_Product_Configuration</helper></action>
-        </reference>
-    </wishlist_index_index>
-
 <!--
 Print pages
 -->
@@ -220,7 +214,7 @@ Emails
         </reference>
     </sales_email_order_creditmemo_items>
 
-    <PRODUCT_TYPE_downloadable translate="label" module="Mage_Downloadable">
+    <catalog_product_view_type_downloadable translate="label" module="Mage_Downloadable" type="page" parent="catalog_product_view">
         <label>Catalog Product View (Downloadable)</label>
         <reference name="product.info">
             <block type="Mage_Downloadable_Block_Catalog_Product_View_Type" name="product.info.downloadable" as="product_type_data" template="catalog/product/type.phtml">
@@ -232,6 +226,6 @@ Emails
             <block type="Mage_Downloadable_Block_Catalog_Product_Links" name="product.info.downloadable.options" as="type_downloadable_options" before="-" template="catalog/product/links.phtml"/>
             <action method="insert"><block>product.info.downloadable.options</block></action>
         </reference>
-    </PRODUCT_TYPE_downloadable>
+    </catalog_product_view_type_downloadable>
 
 </layout>
diff --git a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option/Collection.php b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option/Collection.php
index 22f5f3f6814cd2b3bb05ef4aa16c5d796edcfe93..f623f2dc16f93f525dfbc54cf6e0e3b17ea6cec4 100755
--- a/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option/Collection.php
+++ b/app/code/core/Mage/Eav/Model/Resource/Entity/Attribute/Option/Collection.php
@@ -101,7 +101,7 @@ class Mage_Eav_Model_Resource_Entity_Attribute_Option_Collection extends Mage_Co
                 ->where('tsv.store_id = ?', $storeId);
         }
 
-        $this->setOrder('tsv.value', self::SORT_ORDER_ASC);
+        $this->setOrder('value', self::SORT_ORDER_ASC);
 
         return $this;
     }
diff --git a/app/code/core/Mage/GoogleCheckout/Model/Api/Xml/Callback.php b/app/code/core/Mage/GoogleCheckout/Model/Api/Xml/Callback.php
index 403ade7355ccecb1bf89eee3f4d42cb0b5e675bf..309ad659a8dc2d1cdcd8f7181e79a52075d97c0e 100644
--- a/app/code/core/Mage/GoogleCheckout/Model/Api/Xml/Callback.php
+++ b/app/code/core/Mage/GoogleCheckout/Model/Api/Xml/Callback.php
@@ -789,8 +789,11 @@ class Mage_GoogleCheckout_Model_Api_Xml_Callback extends Mage_GoogleCheckout_Mod
         $order->addStatusToHistory($order->getStatus(), $msg);
 
         $order->setPaymentAuthorizationAmount($payment->getAmountAuthorized());
-        $order->setPaymentAuthExpiration(
-            Mage::getModel('Mage_Core_Model_Date')->gmtTimestamp($this->getData('root/authorization-expiration-date/VALUE'))
+        $timestamp = Mage::getModel('Mage_Core_Model_Date')->gmtTimestamp(
+            $this->getData('root/authorization-expiration-date/VALUE')
+        );
+        $order->setPaymentAuthorizationExpiration(
+            $timestamp ? $timestamp : Mage::getModel('Mage_Core_Model_Date')->gmtTimestamp()
         );
 
         $order->save();
diff --git a/app/code/core/Mage/GoogleCheckout/view/frontend/layout.xml b/app/code/core/Mage/GoogleCheckout/view/frontend/layout.xml
index d1a5e6dd6f6424b2dd86102e722d991f77e0ded7..9c212e2c7f74e04c3b336ed277bc16f1c74514fd 100644
--- a/app/code/core/Mage/GoogleCheckout/view/frontend/layout.xml
+++ b/app/code/core/Mage/GoogleCheckout/view/frontend/layout.xml
@@ -38,7 +38,8 @@
         </reference>
     </checkout_cart_index>
 
-    <googlecheckout_redirect_redirect>
+    <googlecheckout_redirect_redirect translate="label" type="page" parent="checkout_onepage_paymentmethod">
+        <label>GoogleCheckout Redirect</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-right.phtml</template></action>
         </reference>
diff --git a/app/code/core/Mage/GoogleOptimizer/view/adminhtml/layout.xml b/app/code/core/Mage/GoogleOptimizer/view/adminhtml/layout.xml
index 9cb3c1acbd3ee73710cdc8a2c8814cd538dd05fe..2459bff754ab2993224f9371e5654a27df4cabc5 100644
--- a/app/code/core/Mage/GoogleOptimizer/view/adminhtml/layout.xml
+++ b/app/code/core/Mage/GoogleOptimizer/view/adminhtml/layout.xml
@@ -74,7 +74,7 @@ Layout handle for cms page
                     </params>
                 </action>
                 <action method="ifGoogleOptimizerEnabledAppend">
-                    <container>js</container>
+                    <containerBlock>js</containerBlock>
                     <name>googleoptimizer_js</name>
                     <type>Mage_GoogleOptimizer_Block_Js</type>
                     <attributes>
diff --git a/app/code/core/Mage/GoogleOptimizer/view/frontend/layout.xml b/app/code/core/Mage/GoogleOptimizer/view/frontend/layout.xml
index 2bc1db6b5839aa159e92fa84f782ec5796cbc30e..b127253222cc0edffc755ae30a4438497b4619a9 100644
--- a/app/code/core/Mage/GoogleOptimizer/view/frontend/layout.xml
+++ b/app/code/core/Mage/GoogleOptimizer/view/frontend/layout.xml
@@ -44,7 +44,7 @@ Product view
         </reference>
     </catalog_product_view>
 
-    <catalog_category_default>
+    <catalog_category_view>
         <reference name="head">
             <block type="Mage_GoogleOptimizer_Block_Code_Category" before="-" name="googleoptimizer.control.script">
                 <action method="setScriptType"><scriptType>control_script</scriptType></action>
@@ -55,22 +55,9 @@ Product view
                 <action method="setScriptType"><scriptType>tracking_script</scriptType></action>
             </block>
         </reference>
-    </catalog_category_default>
+    </catalog_category_view>
 
-    <catalog_category_layered>
-        <reference name="head">
-            <block type="Mage_GoogleOptimizer_Block_Code_Category" before="-" name="googleoptimizer.control.script">
-                <action method="setScriptType"><scriptType>control_script</scriptType></action>
-            </block>
-        </reference>
-        <reference name="before_body_end">
-            <block type="Mage_GoogleOptimizer_Block_Code_Category" after="-" name="googleoptimizer.tracking.script">
-                <action method="setScriptType"><scriptType>tracking_script</scriptType></action>
-            </block>
-        </reference>
-    </catalog_category_layered>
-
-    <cms_page>
+    <cms_page_view>
         <reference name="head">
             <block type="Mage_GoogleOptimizer_Block_Code_Page" before="-" name="googleoptimizer.control.script">
                 <action method="setScriptType"><scriptType>control_script</scriptType></action>
@@ -81,7 +68,7 @@ Product view
                 <action method="setScriptType"><scriptType>tracking_script</scriptType></action>
             </block>
         </reference>
-    </cms_page>
+    </cms_page_view>
 
     <checkout_cart_index>
         <reference name="before_body_end">
diff --git a/app/code/core/Mage/GoogleShopping/Block/Adminhtml/Items/Product.php b/app/code/core/Mage/GoogleShopping/Block/Adminhtml/Items/Product.php
index 237a115bab666c602ff95b9011a830b1ebb234f6..d8a9084d448f46e4ea8d6a1de65c3580aed80845 100644
--- a/app/code/core/Mage/GoogleShopping/Block/Adminhtml/Items/Product.php
+++ b/app/code/core/Mage/GoogleShopping/Block/Adminhtml/Items/Product.php
@@ -49,8 +49,8 @@ class Mage_GoogleShopping_Block_Adminhtml_Items_Product extends Mage_Adminhtml_B
     protected function _beforeToHtml()
     {
         $this->setId($this->getId().'_'.$this->getIndex());
-        $this->getChild('reset_filter_button')->setData('onclick', $this->getJsObjectName().'.resetFilter()');
-        $this->getChild('search_button')->setData('onclick', $this->getJsObjectName().'.doFilter()');
+        $this->getChildBlock('reset_filter_button')->setData('onclick', $this->getJsObjectName().'.resetFilter()');
+        $this->getChildBlock('search_button')->setData('onclick', $this->getJsObjectName().'.doFilter()');
         return parent::_beforeToHtml();
     }
 
diff --git a/app/code/core/Mage/GoogleShopping/Block/Adminhtml/Types/Edit.php b/app/code/core/Mage/GoogleShopping/Block/Adminhtml/Types/Edit.php
index 44d8b933b8f52d1716cef100cc023a84bcb251ae..0d61e8ceb043eeff2239b174c62050661674b376 100644
--- a/app/code/core/Mage/GoogleShopping/Block/Adminhtml/Types/Edit.php
+++ b/app/code/core/Mage/GoogleShopping/Block/Adminhtml/Types/Edit.php
@@ -45,7 +45,7 @@ class Mage_GoogleShopping_Block_Adminhtml_Types_Edit extends Mage_Adminhtml_Bloc
         $this->_updateButton('save', 'label', $this->__('Save Mapping'));
         $this->_updateButton('save', 'id', 'save_button');
         $this->_updateButton('delete', 'label', $this->__('Delete Mapping'));
-        if(!$model->getId()) {
+        if ($model && !$model->getId()) {
             $this->_removeButton('delete');
         }
     }
diff --git a/app/code/core/Mage/GoogleShopping/etc/config.xml b/app/code/core/Mage/GoogleShopping/etc/config.xml
index c596e2de190a32e20b0eb0bac9a8c1c90c98090e..62b1a3038726599b9acd7f064e9dfec35ebf7565 100644
--- a/app/code/core/Mage/GoogleShopping/etc/config.xml
+++ b/app/code/core/Mage/GoogleShopping/etc/config.xml
@@ -92,7 +92,8 @@
             <googleshopping>
                 <target_country>US</target_country>
                 <account_type>HOSTED_OR_GOOGLE</account_type>
-                <!-- Availabled target countries. Each country must have
+
+                <!-- Available target countries. Each country must have
                      language code (ISO 639-1) and currency code (ISO 3166)
                      according to Google Content documentation. -->
                 <allowed_countries>
@@ -102,12 +103,25 @@
                         <currency>AUD</currency>
                         <currency_name>Australian Dollar</currency_name>
                     </AU>
+                    <BR translate="name currency_name">
+                        <name>Brazil</name>
+                        <language>pt</language>
+                        <locale>pt_BR</locale>
+                        <currency>BRL</currency>
+                        <currency_name>Brazilian Real</currency_name>
+                    </BR>
                     <CN translate="name currency_name">
                         <name>China</name>
                         <language>zh_CN</language>
                         <currency>CNY</currency>
                         <currency_name>Chinese Yuan Renminbi</currency_name>
                     </CN>
+                    <FR translate="name currency_name">
+                        <name>France</name>
+                        <language>fr</language>
+                        <currency>EUR</currency>
+                        <currency_name>Euro</currency_name>
+                    </FR>
                     <DE translate="name currency_name">
                         <name>Germany</name>
                         <language>de</language>
@@ -115,25 +129,6 @@
                         <currency>EUR</currency>
                         <currency_name>Euro</currency_name>
                     </DE>
-                    <ES translate="name currency_name">
-                        <name>Spain</name>
-                        <language>es</language>
-                        <currency>EUR</currency>
-                        <currency_name>Euro</currency_name>
-                    </ES>
-                    <FR translate="name currency_name">
-                        <name>France</name>
-                        <language>fr</language>
-                        <currency>EUR</currency>
-                        <currency_name>Euro</currency_name>
-                    </FR>
-                    <GB translate="name currency_name">
-                        <name>United Kingdom</name>
-                        <language>en</language>
-                        <locale>en_GB</locale>
-                        <currency>GBP</currency>
-                        <currency_name>British Pound Sterling</currency_name>
-                    </GB>
                     <IT translate="name currency_name">
                         <name>Italy</name>
                         <language>it</language>
@@ -152,6 +147,26 @@
                         <currency>EUR</currency>
                         <currency_name>Euro</currency_name>
                     </NL>
+                    <ES translate="name currency_name">
+                        <name>Spain</name>
+                        <language>es</language>
+                        <currency>EUR</currency>
+                        <currency_name>Euro</currency_name>
+                    </ES>
+                    <CH translate="name currency_name">
+                        <name>Switzerland</name>
+                        <language>de</language>
+                        <locale>de_CH</locale>
+                        <currency>CHF</currency>
+                        <currency_name>Swiss Franc</currency_name>
+                    </CH>
+                    <GB translate="name currency_name">
+                        <name>United Kingdom</name>
+                        <language>en</language>
+                        <locale>en_GB</locale>
+                        <currency>GBP</currency>
+                        <currency_name>British Pound Sterling</currency_name>
+                    </GB>
                     <US translate="name currency_name">
                         <name>United States</name>
                         <language>en</language>
diff --git a/app/code/core/Mage/GoogleShopping/view/adminhtml/items.phtml b/app/code/core/Mage/GoogleShopping/view/adminhtml/items.phtml
index 74ea839fe82e9e1a3ec28a04ba24c4edb70175f6..6c9235a67286350e5cd933c6a394d85669a02ce9 100644
--- a/app/code/core/Mage/GoogleShopping/view/adminhtml/items.phtml
+++ b/app/code/core/Mage/GoogleShopping/view/adminhtml/items.phtml
@@ -47,7 +47,7 @@
 
 <script type="text/javascript">
 //<![CDATA[
-var productsGridElement = $('<?php echo $this->getChild('product')->getId() ?>');
+var productsGridElement = $('<?php echo $this->getChildBlock('product')->getId() ?>');
 productsGridElement.hide();
 $('products_grid_button').observe('click', function (event) {
     var element = event.element();
diff --git a/app/code/core/Mage/ImportExport/Model/Export/Entity/Product.php b/app/code/core/Mage/ImportExport/Model/Export/Entity/Product.php
index a44b4b8d7896ff5f32ff21ccb602c1cc49851cde..cf6507d93796100dba6b27f0b8023474af0a8ca5 100644
--- a/app/code/core/Mage/ImportExport/Model/Export/Entity/Product.php
+++ b/app/code/core/Mage/ImportExport/Model/Export/Entity/Product.php
@@ -158,9 +158,9 @@ class Mage_ImportExport_Model_Export_Entity_Product extends Mage_ImportExport_Mo
         foreach ($collection as $category) {
             $structure = preg_split('#/+#', $category->getPath());
             $pathSize  = count($structure);
-            if ($pathSize > 2) {
+            if ($pathSize > 1) {
                 $path = array();
-                for ($i = 2; $i < $pathSize; $i++) {
+                for ($i = 1; $i < $pathSize; $i++) {
                     $path[] = $collection->getItemById($structure[$i])->getName();
                 }
                 $this->_categories[$category->getId()] = implode('/', $path);
diff --git a/app/code/core/Mage/ImportExport/Model/Import/Entity/Customer/Address.php b/app/code/core/Mage/ImportExport/Model/Import/Entity/Customer/Address.php
index b7bf80c1e07413f32b0699b13f6b5de81fe9b9c6..54bd858fd90ecd25ae6b434b845de786230cce83 100644
--- a/app/code/core/Mage/ImportExport/Model/Import/Entity/Customer/Address.php
+++ b/app/code/core/Mage/ImportExport/Model/Import/Entity/Customer/Address.php
@@ -165,14 +165,16 @@ class Mage_ImportExport_Model_Import_Entity_Customer_Address extends Mage_Import
         /** @var $resource Mage_Customer_Model_Address */
         $resource       = Mage::getModel('Mage_Customer_Model_Address');
         $strftimeFormat = Varien_Date::convertZendToStrftime(Varien_Date::DATETIME_INTERNAL_FORMAT, true, true);
-        $table = $resource->getResource()->getEntityTable();
+        $table          = $resource->getResource()->getEntityTable();
         $nextEntityId   = Mage::getResourceHelper('Mage_ImportExport')->getNextAutoincrement($table);
         $customerId     = null;
         $regionColName  = self::getColNameForAttrCode('region');
         $countryColName = self::getColNameForAttrCode('country_id');
+        /** @var $regionIdAttr Mage_Customer_Model_Attribute */
         $regionIdAttr   = Mage::getSingleton('Mage_Eav_Model_Config')->getAttribute($this->getEntityTypeCode(), 'region_id');
         $regionIdTable  = $regionIdAttr->getBackend()->getTable();
         $regionIdAttrId = $regionIdAttr->getId();
+        $isAppendMode   = Mage_ImportExport_Model_Import::BEHAVIOR_APPEND == $this->_customer->getBehavior();
 
         while ($bunch = $this->_dataSourceModel->getNextBunch()) {
             $entityRows = array();
@@ -191,6 +193,31 @@ class Mage_ImportExport_Model_Import_Entity_Customer_Address extends Mage_Import
                 if (!$customerId || !$this->_isRowWithAddress($rowData) || !$this->validateRow($rowData, $rowNum)) {
                     continue;
                 }
+
+                /** @var $addressCollection Mage_Customer_Model_Resource_Address_Collection */
+                $addressCollection = Mage::getResourceModel('Mage_Customer_Model_Resource_Address_Collection');
+                $addressCollection->addAttributeToFilter('parent_id', $customerId);
+
+                $addressAttributes = array();
+                foreach ($this->_attributes as $attrAlias => $attrParams) {
+                    if (isset($rowData[$attrAlias]) && strlen($rowData[$attrAlias])) {
+                        if ('select' == $attrParams['type']) {
+                            $value = $attrParams['options'][strtolower($rowData[$attrAlias])];
+                        } elseif ('datetime' == $attrParams['type']) {
+                            $value = gmstrftime($strftimeFormat, strtotime($rowData[$attrAlias]));
+                        } else {
+                            $value = $rowData[$attrAlias];
+                        }
+                        $addressAttributes[$attrParams['id']] = $value;
+                        $addressCollection->addAttributeToFilter($attrParams['code'], $value);
+                    }
+                }
+
+                // skip duplicate address
+                if ($isAppendMode && $addressCollection->getSize()) {
+                    continue;
+                }
+
                 $entityId = $nextEntityId++;
 
                 // entity table data
@@ -203,15 +230,9 @@ class Mage_ImportExport_Model_Import_Entity_Customer_Address extends Mage_Import
                 );
                 // attribute values
                 foreach ($this->_attributes as $attrAlias => $attrParams) {
-                    if (isset($rowData[$attrAlias]) && strlen($rowData[$attrAlias])) {
-                        if ('select' == $attrParams['type']) {
-                            $value = $attrParams['options'][strtolower($rowData[$attrAlias])];
-                        } elseif ('datetime' == $attrParams['type']) {
-                            $value = gmstrftime($strftimeFormat, strtotime($rowData[$attrAlias]));
-                        } else {
-                            $value = $rowData[$attrAlias];
-                        }
-                        $attributes[$attrParams['table']][$entityId][$attrParams['id']] = $value;
+                    if (isset($addressAttributes[$attrParams['id']])) {
+                        $attributes[$attrParams['table']][$entityId][$attrParams['id']]
+                            = $addressAttributes[$attrParams['id']];
                     }
                 }
                 // customer default addresses
@@ -237,8 +258,8 @@ class Mage_ImportExport_Model_Import_Entity_Customer_Address extends Mage_Import
                 }
             }
             $this->_saveAddressEntity($entityRows)
-                    ->_saveAddressAttributes($attributes)
-                    ->_saveCustomerDefaults($defaults);
+                ->_saveAddressAttributes($attributes)
+                ->_saveCustomerDefaults($defaults);
         }
         return true;
     }
@@ -251,8 +272,8 @@ class Mage_ImportExport_Model_Import_Entity_Customer_Address extends Mage_Import
     protected function _initAttributes()
     {
         $addrCollection = Mage::getResourceModel('Mage_Customer_Model_Resource_Address_Attribute_Collection')
-                            ->addSystemHiddenFilter()
-                            ->addExcludeHiddenFrontendFilter();
+            ->addSystemHiddenFilter()
+            ->addExcludeHiddenFrontendFilter();
 
         foreach ($addrCollection as $attribute) {
             $this->_attributes[self::getColNameForAttrCode($attribute->getAttributeCode())] = array(
diff --git a/app/code/core/Mage/ImportExport/Model/Import/Entity/Product.php b/app/code/core/Mage/ImportExport/Model/Import/Entity/Product.php
index 0487c6bf100e387a488eee75af80a9b1fc431cd8..f75c9ba0cdf34c800a7ee235c184ca06ae183c84 100644
--- a/app/code/core/Mage/ImportExport/Model/Import/Entity/Product.php
+++ b/app/code/core/Mage/ImportExport/Model/Import/Entity/Product.php
@@ -284,7 +284,6 @@ class Mage_ImportExport_Model_Import_Entity_Product extends Mage_ImportExport_Mo
     /**
      * Constructor.
      *
-     * @return void
      */
     public function __construct()
     {
@@ -377,9 +376,9 @@ class Mage_ImportExport_Model_Import_Entity_Product extends Mage_ImportExport_Mo
         foreach ($collection as $category) {
             $structure = explode('/', $category->getPath());
             $pathSize  = count($structure);
-            if ($pathSize > 2) {
+            if ($pathSize > 1) {
                 $path = array();
-                for ($i = 2; $i < $pathSize; $i++) {
+                for ($i = 1; $i < $pathSize; $i++) {
                     $path[] = $collection->getItemById($structure[$i])->getName();
                 }
                 $this->_categories[implode('/', $path)] = $category->getId();
@@ -640,20 +639,15 @@ class Mage_ImportExport_Model_Import_Entity_Product extends Mage_ImportExport_Mo
      */
     protected function _saveCustomOptions()
     {
-        $productTable   = Mage::getSingleton('Mage_Core_Model_Resource')
-                ->getTableName('catalog_product_entity');
-        $optionTable    = Mage::getSingleton('Mage_Core_Model_Resource')
-                ->getTableName('catalog_product_option');
-        $priceTable     = Mage::getSingleton('Mage_Core_Model_Resource')
-                ->getTableName('catalog_product_option_price');
-        $titleTable     = Mage::getSingleton('Mage_Core_Model_Resource')
-                ->getTableName('catalog_product_option_title');
-        $typePriceTable = Mage::getSingleton('Mage_Core_Model_Resource')
-                ->getTableName('catalog_product_option_type_price');
-        $typeTitleTable = Mage::getSingleton('Mage_Core_Model_Resource')
-                ->getTableName('catalog_product_option_type_title');
-        $typeValueTable = Mage::getSingleton('Mage_Core_Model_Resource')
-                ->getTableName('catalog_product_option_type_value');
+        /** @var $coreResource Mage_Core_Model_Resource */
+        $coreResource   = Mage::getSingleton('Mage_Core_Model_Resource');
+        $productTable   = $coreResource->getTableName('catalog_product_entity');
+        $optionTable    = $coreResource->getTableName('catalog_product_option');
+        $priceTable     = $coreResource->getTableName('catalog_product_option_price');
+        $titleTable     = $coreResource->getTableName('catalog_product_option_title');
+        $typePriceTable = $coreResource->getTableName('catalog_product_option_type_price');
+        $typeTitleTable = $coreResource->getTableName('catalog_product_option_type_title');
+        $typeValueTable = $coreResource->getTableName('catalog_product_option_type_value');
         $nextOptionId   = Mage::getResourceHelper('Mage_ImportExport')->getNextAutoincrement($optionTable);
         $nextValueId    = Mage::getResourceHelper('Mage_ImportExport')->getNextAutoincrement($typeValueTable);
         $priceIsGlobal  = Mage::helper('Mage_Catalog_Helper_Data')->isPriceGlobal();
@@ -818,10 +812,12 @@ class Mage_ImportExport_Model_Import_Entity_Product extends Mage_ImportExport_Mo
             // if complex options does not contain values - ignore them
             foreach ($customOptions[$optionTable] as $key => $optionData) {
                 if ($typeSpecific[$optionData['type']] === true
-                        && !isset($customOptions[$typeValueTable][$optionData['option_id']])) {
+                        && !isset($customOptions[$typeValueTable][$optionData['option_id']])
+                ) {
                     unset($customOptions[$optionTable][$key], $customOptions[$titleTable][$optionData['option_id']]);
                 }
             }
+
             if ($customOptions[$optionTable]) {
                 $this->_connection->insertMultiple($optionTable, $customOptions[$optionTable]);
             } else {
@@ -1540,27 +1536,28 @@ class Mage_ImportExport_Model_Import_Entity_Product extends Mage_ImportExport_Mo
     protected function _saveStockItem()
     {
         $defaultStockData = array(
-            'manage_stock'                       => 1,
-            'use_config_manage_stock'            => 1,
-            'qty'                                => 0,
-            'min_qty'                            => 0,
-            'use_config_min_qty'                 => 1,
-            'min_sale_qty'                       => 1,
-            'use_config_min_sale_qty'            => 1,
-            'max_sale_qty'                       => 10000,
-            'use_config_max_sale_qty'            => 1,
-            'is_qty_decimal'                     => 0,
-            'backorders'                         => 0,
-            'use_config_backorders'              => 1,
-            'notify_stock_qty'                   => 1,
-            'use_config_notify_stock_qty'        => 1,
-            'enable_qty_increments'              => 0,
-            'use_config_enable_qty_inc'          => 1,
-            'qty_increments'                     => 0,
-            'use_config_qty_increments'          => 1,
-            'is_in_stock'                        => 0,
-            'low_stock_date'                     => null,
-            'stock_status_changed_auto'          => 0
+            'manage_stock'                  => 1,
+            'use_config_manage_stock'       => 1,
+            'qty'                           => 0,
+            'min_qty'                       => 0,
+            'use_config_min_qty'            => 1,
+            'min_sale_qty'                  => 1,
+            'use_config_min_sale_qty'       => 1,
+            'max_sale_qty'                  => 10000,
+            'use_config_max_sale_qty'       => 1,
+            'is_qty_decimal'                => 0,
+            'backorders'                    => 0,
+            'use_config_backorders'         => 1,
+            'notify_stock_qty'              => 1,
+            'use_config_notify_stock_qty'   => 1,
+            'enable_qty_increments'         => 0,
+            'use_config_enable_qty_inc'     => 1,
+            'qty_increments'                => 0,
+            'use_config_qty_increments'     => 1,
+            'is_in_stock'                   => 0,
+            'low_stock_date'                => null,
+            'stock_status_changed_auto'     => 0,
+            'is_decimal_divided'            => 0
         );
 
         $entityTable = Mage::getResourceModel('Mage_CatalogInventory_Model_Resource_Stock_Item')->getMainTable();
diff --git a/app/code/core/Mage/ImportExport/controllers/Adminhtml/ImportController.php b/app/code/core/Mage/ImportExport/controllers/Adminhtml/ImportController.php
index 527c87705ea420fc150cfadabff4ee8b7428e5a8..aeb1dda0a20f7b58775ca240b0fd4824181ec621 100644
--- a/app/code/core/Mage/ImportExport/controllers/Adminhtml/ImportController.php
+++ b/app/code/core/Mage/ImportExport/controllers/Adminhtml/ImportController.php
@@ -99,7 +99,7 @@ class Mage_ImportExport_Adminhtml_ImportController extends Mage_Adminhtml_Contro
 
             /** @var $resultBlock Mage_ImportExport_Block_Adminhtml_Import_Frame_Result */
             $resultBlock = $this->getLayout()->getBlock('import.frame.result');
-
+            /** @var $importModel Mage_ImportExport_Model_Import */
             $importModel = Mage::getModel('Mage_ImportExport_Model_Import');
 
             try {
diff --git a/app/code/core/Mage/ImportExport/view/adminhtml/layout.xml b/app/code/core/Mage/ImportExport/view/adminhtml/layout.xml
index ce1e3f50ba699a6fe1e4823ab9da89e8e2248c35..c5b3cf4e3e174c712e6ef322238c633046ed23e2 100644
--- a/app/code/core/Mage/ImportExport/view/adminhtml/layout.xml
+++ b/app/code/core/Mage/ImportExport/view/adminhtml/layout.xml
@@ -34,10 +34,10 @@
         </reference>
     </adminhtml_import_index>
     <adminhtml_import_validate>
-        <block type="Mage_ImportExport_Block_Adminhtml_Import_Frame_Result" template="import/frame/result.phtml" name="import.frame.result" alias="import_frame_result" output="toHtml"/>
+        <block type="Mage_ImportExport_Block_Adminhtml_Import_Frame_Result" template="import/frame/result.phtml" name="import.frame.result" alias="import_frame_result" output="1"/>
     </adminhtml_import_validate>
     <adminhtml_import_start>
-        <block type="Mage_ImportExport_Block_Adminhtml_Import_Frame_Result" template="import/frame/result.phtml" name="import.frame.result" alias="import_frame_result" output="toHtml"/>
+        <block type="Mage_ImportExport_Block_Adminhtml_Import_Frame_Result" template="import/frame/result.phtml" name="import.frame.result" alias="import_frame_result" output="1"/>
     </adminhtml_import_start>
     <adminhtml_import_busy>
         <reference name="content">
@@ -52,8 +52,8 @@
         </reference>
     </adminhtml_export_index>
     <adminhtml_export_getfilter>
-        <block type="Mage_Core_Block_Text_List" name="root">
+        <container name="root" label="Root">
             <block type="Mage_ImportExport_Block_Adminhtml_Export_Filter" name="export.filter"/>
-        </block>
+        </container>
     </adminhtml_export_getfilter>
 </layout>
diff --git a/app/code/core/Mage/Index/Model/Process.php b/app/code/core/Mage/Index/Model/Process.php
index d806783d7001cc4273348e9be7289afa694b4b67..e5a531bd22f4a02530a1d50b035646134f977d2b 100644
--- a/app/code/core/Mage/Index/Model/Process.php
+++ b/app/code/core/Mage/Index/Model/Process.php
@@ -107,7 +107,8 @@ class Mage_Index_Model_Process extends Mage_Core_Model_Abstract
     /**
      * Remove indexer namespace from event
      *
-     * @return  Mage_Index_Model_Process
+     * @param Mage_Index_Model_Event $event
+     * @return Mage_Index_Model_Process
      */
     protected function _resetEventNamespace($event)
     {
@@ -120,6 +121,7 @@ class Mage_Index_Model_Process extends Mage_Core_Model_Abstract
      * Register data required by process in event object
      *
      * @param Mage_Index_Model_Event $event
+     * @return Mage_Index_Model_Process
      */
     public function register(Mage_Index_Model_Event $event)
     {
diff --git a/app/code/core/Mage/Install/Controller/Action.php b/app/code/core/Mage/Install/Controller/Action.php
index 641c5f776b17bffdf895eaeefdc365b1adaf9166..8617a7237c4f9af3b1a1f1f4fdec029cc887cc75 100644
--- a/app/code/core/Mage/Install/Controller/Action.php
+++ b/app/code/core/Mage/Install/Controller/Action.php
@@ -27,10 +27,16 @@
 
 class Mage_Install_Controller_Action extends Mage_Core_Controller_Varien_Action
 {
+    /**
+     * Currently used area
+     *
+     * @var string
+     */
+    protected $_currentArea = 'install';
+
     protected function _construct()
     {
         parent::_construct();
-        $this->getLayout()->setArea('install');
         $this->_areaDesign = (string)Mage::getConfig()->getNode(
             'install/' . Mage_Core_Model_Design_Package::XML_PATH_THEME
         ) ?: 'default/default/default';
diff --git a/app/code/core/Mage/Install/controllers/WizardController.php b/app/code/core/Mage/Install/controllers/WizardController.php
index 60adb2d8a00cc67862ddfdd6bd59959877a0c7b1..a0f3af54982fa5306ad0e8984a3b7cd93210515d 100644
--- a/app/code/core/Mage/Install/controllers/WizardController.php
+++ b/app/code/core/Mage/Install/controllers/WizardController.php
@@ -73,8 +73,7 @@ class Mage_Install_WizardController extends Mage_Install_Controller_Action
             $step->setActive(true);
         }
 
-        $leftBlock = $this->getLayout()->createBlock('Mage_Install_Block_State', 'install.state');
-        $this->getLayout()->getBlock('left')->append($leftBlock);
+        $this->getLayout()->addBlock('Mage_Install_Block_State', 'install.state', 'left');
         return $this;
     }
 
@@ -113,9 +112,7 @@ class Mage_Install_WizardController extends Mage_Install_Controller_Action
         $this->_prepareLayout();
         $this->_initLayoutMessages('Mage_Install_Model_Session');
 
-        $this->getLayout()->getBlock('content')->append(
-            $this->getLayout()->createBlock('Mage_Install_Block_Begin', 'install.begin')
-        );
+        $this->getLayout()->addBlock('Mage_Install_Block_Begin', 'install.begin', 'content');
 
         $this->renderLayout();
     }
@@ -147,9 +144,7 @@ class Mage_Install_WizardController extends Mage_Install_Controller_Action
 
         $this->_prepareLayout();
         $this->_initLayoutMessages('Mage_Install_Model_Session');
-        $this->getLayout()->getBlock('content')->append(
-            $this->getLayout()->createBlock('Mage_Install_Block_Locale', 'install.locale')
-        );
+        $this->getLayout()->addBlock('Mage_Install_Block_Locale', 'install.locale', 'content');
 
         $this->renderLayout();
     }
@@ -196,9 +191,7 @@ class Mage_Install_WizardController extends Mage_Install_Controller_Action
 
         $this->_prepareLayout();
         $this->_initLayoutMessages('Mage_Install_Model_Session');
-        $this->getLayout()->getBlock('content')->append(
-            $this->getLayout()->createBlock('Mage_Install_Block_Download', 'install.download')
-        );
+        $this->getLayout()->addBlock('Mage_Install_Block_Download', 'install.download', 'content');
 
         $this->renderLayout();
     }
@@ -294,9 +287,7 @@ class Mage_Install_WizardController extends Mage_Install_Controller_Action
 
         $this->_prepareLayout();
         $this->_initLayoutMessages('Mage_Install_Model_Session');
-        $this->getLayout()->getBlock('content')->append(
-            $this->getLayout()->createBlock('Mage_Install_Block_Config', 'install.config')
-        );
+        $this->getLayout()->addBlock('Mage_Install_Block_Config', 'install.config', 'content');
 
         $this->renderLayout();
     }
@@ -367,9 +358,7 @@ class Mage_Install_WizardController extends Mage_Install_Controller_Action
         $this->_prepareLayout();
         $this->_initLayoutMessages('Mage_Install_Model_Session');
 
-        $this->getLayout()->getBlock('content')->append(
-            $this->getLayout()->createBlock('Mage_Install_Block_Admin', 'install.administrator')
-        );
+        $this->getLayout()->addBlock('Mage_Install_Block_Admin', 'install.administrator', 'content');
         $this->renderLayout();
     }
 
@@ -437,9 +426,7 @@ class Mage_Install_WizardController extends Mage_Install_Controller_Action
         $this->_prepareLayout();
         $this->_initLayoutMessages('Mage_Install_Model_Session');
 
-        $this->getLayout()->getBlock('content')->append(
-            $this->getLayout()->createBlock('Mage_Install_Block_End', 'install.end')
-        );
+        $this->getLayout()->addBlock('Mage_Install_Block_End', 'install.end', 'content');
         $this->renderLayout();
         Mage::getSingleton('Mage_Install_Model_Session')->clear();
     }
diff --git a/app/code/core/Mage/Install/view/install/layout.xml b/app/code/core/Mage/Install/view/install/layout.xml
index c3ca1bc4c44c5d559a21c743aa3ad48c4d0e5ee7..55438a0a1cccb69fc36a0a596dd6f1c43f3ab028 100644
--- a/app/code/core/Mage/Install/view/install/layout.xml
+++ b/app/code/core/Mage/Install/view/install/layout.xml
@@ -29,10 +29,10 @@
 <layout>
     <install_wizard>
         <!-- Mage_Install -->
-        <block type="Mage_Core_Block_Template" name="root" output="toHtml">
+        <block type="Mage_Core_Block_Template" name="root" output="1">
             <action method="setTemplate"><template>Mage_Install::page.phtml</template></action>
-            <block type="Mage_Core_Block_Text_List" name="left" as="left"/>
-            <block type="Mage_Core_Block_Text_List" name="content" as="content" />
+            <container name="left" as="left" label="Left Column"/>
+            <container name="content" as="content" label="Content"/>
         </block>
         <block type="Mage_Install_Block_Db_Main" name="database" as="database"/>
     </install_wizard>
diff --git a/app/code/core/Mage/Log/Model/Visitor.php b/app/code/core/Mage/Log/Model/Visitor.php
index 896a5d64fb829006a42696f49385b7db8f887c38..d81fe019fd0aa8e233176e6fb91f4ddeb7b4e783 100644
--- a/app/code/core/Mage/Log/Model/Visitor.php
+++ b/app/code/core/Mage/Log/Model/Visitor.php
@@ -165,6 +165,7 @@ class Mage_Log_Model_Visitor extends Mage_Core_Model_Abstract
             $this->setFirstVisitAt(now());
             $this->setIsNewVisitor(true);
             $this->save();
+            Mage::dispatchEvent('visitor_init', array('visitor' => $this));
         }
         return $this;
     }
diff --git a/app/code/core/Mage/Newsletter/Model/Subscriber.php b/app/code/core/Mage/Newsletter/Model/Subscriber.php
index e03dae5ea323c3283a7a47dd0be82d7c5785dfec..f09ce7ef20dd7277f281ff795f6e9c6da59934f1 100644
--- a/app/code/core/Mage/Newsletter/Model/Subscriber.php
+++ b/app/code/core/Mage/Newsletter/Model/Subscriber.php
@@ -440,7 +440,8 @@ class Mage_Newsletter_Model_Subscriber extends Mage_Core_Model_Abstract
                 ->setCustomerId($customer->getId())
                 ->setEmail($customer->getEmail());
         } else {
-            $this->setEmail($customer->getEmail());
+            $this->setStoreId($customer->getStoreId())
+                ->setEmail($customer->getEmail());
         }
 
         $this->save();
diff --git a/app/code/core/Mage/Newsletter/view/email/subscr_confirm.html b/app/code/core/Mage/Newsletter/view/email/subscr_confirm.html
index a7281c8b8f727bcba248077ce67aa96966ebd6a8..a81577afd43b0f69dc3b8a704abade974dd8c838 100644
--- a/app/code/core/Mage/Newsletter/view/email/subscr_confirm.html
+++ b/app/code/core/Mage/Newsletter/view/email/subscr_confirm.html
@@ -1,7 +1,8 @@
 <!--@subject Newsletter subscription confirmation @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "escapehtml var=$customer.name":"Customer Name",
 "var subscriber.getConfirmationLink()":"Subscriber Confirmation Url"}
 @-->
@@ -18,7 +19,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
             <table bgcolor="FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
                 <tr>
                     <td valign="top">
-                        <a href="{{store url=""}}" style="color:#1E7EC8;"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}" border="0"/></a>
+                        <a href="{{store url=""}}" style="color:#1E7EC8;"><img src="{{var logo_url}}" alt="{{var logo_alt}}" border="0"/></a>
                     </td>
                 </tr>
                 <!-- [ middle starts here] -->
diff --git a/app/code/core/Mage/Newsletter/view/frontend/layout.xml b/app/code/core/Mage/Newsletter/view/frontend/layout.xml
index 54347b1d54c4bb631381af8ef252e2fca086644b..d3c79ff528eaf827b5432bfd29633c488db818b3 100644
--- a/app/code/core/Mage/Newsletter/view/frontend/layout.xml
+++ b/app/code/core/Mage/Newsletter/view/frontend/layout.xml
@@ -53,15 +53,12 @@ Customer account pages, rendered for all tabs in dashboard
         <remove name="left.newsletter"/>
     </customer_account>
 
-    <newsletter_manage_index translate="label">
+    <newsletter_manage_index translate="label" type="page" parent="customer_account_index">
         <label>Customer My Account Newsletter Subscriptions</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
             <block type="Mage_Customer_Block_Newsletter" name="customer_newsletter">
-                <block type="Mage_Page_Block_Html_Wrapper" name="customer.newsletter.form.before" as="form_before" translate="label">
-                    <label>Newsletter Subscription Form Before</label>
-                    <action method="setMayBeInvisible"><value>1</value></action>
-                </block>
+                <container name="customer.newsletter.form.before" as="form_before" label="Newsletter Subscription Form Before" htmlTag="div"/>
             </block>
         </reference>
     </newsletter_manage_index>
diff --git a/app/code/core/Mage/Ogone/view/frontend/layout.xml b/app/code/core/Mage/Ogone/view/frontend/layout.xml
index a986cb1d4d1b93cbacef67fff08eb98924a31039..0bcaf9546cba501821b518e0cd7c84c597fbe06f 100644
--- a/app/code/core/Mage/Ogone/view/frontend/layout.xml
+++ b/app/code/core/Mage/Ogone/view/frontend/layout.xml
@@ -26,7 +26,8 @@
  */
 -->
 <layout version="0.1.0">
-    <ogone_api_paypage>
+    <ogone_api_paypage translate="label" type="page" parent="checkout_onepage_paymentmethod">
+        <label>Ogone Paygate Payment</label>
         <remove name="right"/>
         <remove name="left"/>
         <remove name="catalog.topnav"/>
@@ -49,7 +50,8 @@
         </reference>
     </ogone_api_paypage>
 
-    <ogone_api_placeform>
+    <ogone_api_placeform translate="label" type="page" parent="ogone_api_paypage">
+        <label>Ogone Paygate Payment Place</label>
         <remove name="right"/>
         <remove name="left"/>
         <reference name="content">
diff --git a/app/code/core/Mage/Page/Block/Html/Footer.php b/app/code/core/Mage/Page/Block/Html/Footer.php
index 5019ee7a0b80f7b788fd16dc23b2a1545bf05c4c..0afaf512c600d29df8dc2e9adb085cc869d355f3 100644
--- a/app/code/core/Mage/Page/Block/Html/Footer.php
+++ b/app/code/core/Mage/Page/Block/Html/Footer.php
@@ -75,17 +75,4 @@ class Mage_Page_Block_Html_Footer extends Mage_Core_Block_Template
 
         return $this->_copyright;
     }
-
-    /**
-     * Retrieve child block HTML, sorted by default
-     *
-     * @param   string $name
-     * @param   boolean $useCache
-     * @return  string
-     */
-    public function getChildHtml($name='', $useCache=true, $sorted=true)
-    {
-        return parent::getChildHtml($name, $useCache, $sorted);
-    }
-
 }
diff --git a/app/code/core/Mage/Page/Block/Html/Notices.php b/app/code/core/Mage/Page/Block/Html/Notices.php
index 264164938f6c1655169bb08ff2cf4efab7045c64..a66cf8845564fe40abe0d131756a112a9478aefe 100644
--- a/app/code/core/Mage/Page/Block/Html/Notices.php
+++ b/app/code/core/Mage/Page/Block/Html/Notices.php
@@ -33,6 +33,10 @@
  */
 class Mage_Page_Block_Html_Notices extends Mage_Core_Block_Template
 {
+    /**
+     * Path to configuration, check is enable cookie restriction mode
+     */
+    const XML_PATH_COOKIE_RESTRICTION  = 'web/cookie/cookie_restriction';
 
     /**
      * Check if noscript notice should be displayed
@@ -54,4 +58,49 @@ class Mage_Page_Block_Html_Notices extends Mage_Core_Block_Template
         return Mage::getStoreConfig('design/head/demonotice');
     }
 
+    /**
+     * Check if cookie restriction notice should be displayed
+     *
+     * @return bool
+     */
+    public function displayCookieRestrictionNotice()
+    {
+        $acceptedSaveCookiesWebsites = $this->_getAcceptedSaveCookiesWebsites();
+        return Mage::getStoreConfig(self::XML_PATH_COOKIE_RESTRICTION) &&
+            empty($acceptedSaveCookiesWebsites[Mage::app()->getWebsite()->getId()]);
+    }
+
+    /**
+     * Get Link to cookie restriction privacy policy page
+     *
+     * @return string
+     */
+    public function getPrivacyPolicyLink()
+    {
+        return Mage::getUrl('privacy-policy-cookie-restriction-mode');
+    }
+
+    /**
+     * Return serialzed list of accepted save cookie website
+     *
+     * @return string
+     */
+    public function getAcceptedSaveCookiesWebsiteIds()
+    {
+        $acceptedSaveCookiesWebsites = $this->_getAcceptedSaveCookiesWebsites();
+        $acceptedSaveCookiesWebsites[Mage::app()->getWebsite()->getId()] = 1;
+        return serialize($acceptedSaveCookiesWebsites);
+    }
+
+    /**
+     * Get accepted save cookies websites
+     *
+     * @return array
+     */
+    protected function _getAcceptedSaveCookiesWebsites()
+    {
+        $serializedList = Mage::getSingleton('Mage_Core_Model_Cookie')->get(Mage_Page_Helper_Data::IS_USER_ALLOWED_SAVE_COOKIE);
+        $unSerializedList = unserialize($serializedList);
+        return is_array($unSerializedList) ? $unSerializedList : array();
+    }
 }
diff --git a/app/code/core/Mage/Page/Block/Html/Topmenu.php b/app/code/core/Mage/Page/Block/Html/Topmenu.php
new file mode 100644
index 0000000000000000000000000000000000000000..2b7b162bbc90cf1328dba2b4ab9394ff2a1c7c3a
--- /dev/null
+++ b/app/code/core/Mage/Page/Block/Html/Topmenu.php
@@ -0,0 +1,206 @@
+<?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_Page
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Top menu block
+ *
+ * @category    Mage
+ * @package     Mage_Page
+ * @author      Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_Page_Block_Html_Topmenu extends Mage_Core_Block_Template
+{
+    /**
+     * Top menu data tree
+     *
+     * @var Varien_Data_Tree_Node
+     */
+    protected $_menu;
+
+    /**
+     * Init top menu tree structure
+     */
+    public function _construct()
+    {
+        $this->_menu = new Varien_Data_Tree_Node(array(), 'root', new Varien_Data_Tree());
+    }
+
+    /**
+     * Get top menu html
+     *
+     * @param string $outermostClass
+     * @param string $childrenWrapClass
+     * @return string
+     */
+    public function getHtml($outermostClass = '', $childrenWrapClass = '')
+    {
+        Mage::dispatchEvent('page_block_html_topmenu_gethtml_before', array(
+            'menu' => $this->_menu
+        ));
+
+        $this->_menu->setOutermostClass($outermostClass);
+        $this->_menu->setChildrenWrapClass($childrenWrapClass);
+
+        $html = $this->_getHtml($this->_menu, $childrenWrapClass);
+
+        Mage::dispatchEvent('page_block_html_topmenu_gethtml_after', array(
+            'menu' => $this->_menu,
+            'html' => $html
+        ));
+
+        return $html;
+    }
+
+    /**
+     * Recursively generates top menu html from data that is specified in $menuTree
+     *
+     * @param Varien_Data_Tree_Node $menuTree
+     * @param string $childrenWrapClass
+     * @return string
+     */
+    protected function _getHtml(Varien_Data_Tree_Node $menuTree, $childrenWrapClass)
+    {
+        $html = '';
+
+        $children = $menuTree->getChildren();
+        $parentLevel = $menuTree->getLevel();
+        $childLevel = is_null($parentLevel) ? 0 : $parentLevel + 1;
+
+        $counter = 1;
+        $childrenCount = $children->count();
+
+        $parentPositionClass = $menuTree->getPositionClass();
+        $itemPositionClassPrefix = $parentPositionClass ? $parentPositionClass . '-' : 'nav-';
+
+        foreach ($children as $child) {
+
+            $child->setLevel($childLevel);
+            $child->setIsFirst($counter == 1);
+            $child->setIsLast($counter == $childrenCount);
+            $child->setPositionClass($itemPositionClassPrefix . $counter);
+
+            $outermostClassCode = '';
+            $outermostClass = $menuTree->getOutermostClass();
+
+            if ($childLevel == 0 && $outermostClass) {
+                $outermostClassCode = ' class="' . $outermostClass . '" ';
+                $child->setClass($outermostClass);
+            }
+
+            $html .= '<li ' . $this->_getRenderedMenuItemAttributes($child) . '>';
+            $html .= '<a href="' . $child->getUrl() . '" ' . $outermostClassCode . '><span>'
+                . $this->escapeHtml($child->getName()) . '</span></a>';
+
+            if ($child->hasChildren()) {
+                if (!empty($childrenWrapClass)) {
+                    $html .= '<div class="' . $childrenWrapClass . '">';
+                }
+                $html .= '<ul class="level' . $childLevel . '">';
+                $html .= $this->_getHtml($child, $childrenWrapClass);
+                $html .= '</ul>';
+
+                if (!empty($childrenWrapClass)) {
+                    $html .= '</div>';
+                }
+            }
+            $html .= '</li>';
+
+            $counter++;
+        }
+
+        return $html;
+    }
+
+    /**
+     * Generates string with all attributes that should be present in menu item element
+     *
+     * @param Varien_Data_Tree_Node $item
+     * @return string
+     */
+    protected function _getRenderedMenuItemAttributes(Varien_Data_Tree_Node $item)
+    {
+        $html = '';
+        $attributes = $this->_getMenuItemAttributes($item);
+
+        foreach ($attributes as $attributeName => $attributeValue) {
+            $html .= ' ' . $attributeName . '="' . str_replace('"', '\"', $attributeValue) . '"';
+        }
+
+        return $html;
+    }
+
+    /**
+     * Returns array of menu item's attributes
+     *
+     * @param Varien_Data_Tree_Node $item
+     * @return array
+     */
+    protected function _getMenuItemAttributes(Varien_Data_Tree_Node $item)
+    {
+        $menuItemClasses = $this->_getMenuItemClasses($item);
+        $attributes = array(
+            'class' => implode(' ', $menuItemClasses)
+        );
+
+        return $attributes;
+    }
+
+    /**
+     * Returns array of menu item's classes
+     *
+     * @param Varien_Data_Tree_Node $item
+     * @return array
+     */
+    protected function _getMenuItemClasses(Varien_Data_Tree_Node $item)
+    {
+        $classes = array();
+
+        $classes[] = 'level' . $item->getLevel();
+        $classes[] = $item->getPositionClass();
+
+        if ($item->getIsFirst()) {
+            $classes[] = 'first';
+        }
+
+        if ($item->getIsActive()) {
+            $classes[] = 'active';
+        }
+
+        if ($item->getIsLast()) {
+            $classes[] = 'last';
+        }
+
+        if ($item->getClass()) {
+            $classes[] = $item->getClass();
+        }
+
+        if ($item->hasChildren()) {
+            $classes[] = 'parent';
+        }
+
+        return $classes;
+    }
+}
diff --git a/app/code/core/Mage/Page/Block/Html/Wrapper.php b/app/code/core/Mage/Page/Block/Html/Wrapper.php
deleted file mode 100644
index a0ce0fa440048aac5fbe21eebbfe518884bcf13f..0000000000000000000000000000000000000000
--- a/app/code/core/Mage/Page/Block/Html/Wrapper.php
+++ /dev/null
@@ -1,104 +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    Mage
- * @package     Mage_Page
- * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
- * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
- */
-
-/**
- * A generic wrapper block that renders its children and supports a few parameters of the wrapper HTML-element
- */
-class Mage_Page_Block_Html_Wrapper extends Mage_Core_Block_Abstract
-{
-    /**
-     * Whether block should render its content if there are no children (no)
-     * @var bool
-     */
-    protected $_dependsOnChildren = true;
-
-    /**
-     * Render the wrapper element html
-     * Supports different optional parameters, set in data by keys:
-     * - element_tag_name (div by default)
-     * - element_id
-     * - element_class
-     * - element_other_attributes
-     *
-     * Renders all children inside the element.
-     *
-     * @return string
-     */
-    protected function _toHtml()
-    {
-        $html = empty($this->_children) ? '' : trim($this->getChildHtml('', true, true));
-        if ($this->_dependsOnChildren && empty($html)) {
-            return '';
-        }
-        if ($this->_isInvisible()) {
-            return $html;
-        }
-        $id          = $this->hasElementId() ? sprintf(' id="%s"', $this->getElementId()) : '';
-        $class       = $this->hasElementClass() ? sprintf(' class="%s"', $this->getElementClass()) : '';
-        $otherParams = $this->hasOtherParams() ? ' ' . $this->getOtherParams() : '';
-        return sprintf('<%1$s%2$s%3$s%4$s>%5$s</%1$s>', $this->getElementTagName(), $id, $class, $otherParams, $html);
-    }
-
-    /**
-     * Wrapper element tag name getter
-     * @return string
-     */
-    public function getElementTagName()
-    {
-        $tagName = $this->_getData('html_tag_name');
-        return $tagName ? $tagName : 'div';
-    }
-
-    /**
-     * Setter whether this block depends on children
-     * @param $depends
-     * @return Mage_Page_Block_Html_Wrapper
-     */
-    public function dependsOnChildren($depends = '0')
-    {
-        $this->_dependsOnChildren = (bool)(int)$depends;
-        return $this;
-    }
-
-    /**
-     * Whether the wrapper element should be eventually rendered
-     * If it becomes "invisible", the behaviour will be somewhat similar to core/text_list
-     *
-     * @return bool
-     */
-    protected function _isInvisible()
-    {
-        if (!$this->hasMayBeInvisible()) {
-            return false;
-        }
-        foreach ($this->_children as $child) {
-            if ($child->hasWrapperMustBeVisible()) {
-                return false;
-            }
-        }
-        return true;
-    }
-}
diff --git a/app/code/core/Mage/Page/Block/Template/Links.php b/app/code/core/Mage/Page/Block/Template/Links.php
index 06a7dce20fdb0bcf1ed518beb2ad9d0f3a307864..71dc35c9711fc8ad29248ce603a76f4ed686e3e6 100644
--- a/app/code/core/Mage/Page/Block/Template/Links.php
+++ b/app/code/core/Mage/Page/Block/Template/Links.php
@@ -34,7 +34,6 @@
  */
 class Mage_Page_Block_Template_Links extends Mage_Core_Block_Template
 {
-
     /**
      * All links
      *
@@ -117,6 +116,23 @@ class Mage_Page_Block_Template_Links extends Mage_Core_Block_Template
     {
         $block = $this->getLayout()->getBlock($blockName);
         $this->_links[$this->_getNewPosition((int)$block->getPosition())] = $block;
+        ksort($this->_links);
+        return $this;
+    }
+
+    /**
+     * Remove Link block by blockName
+     *
+     * @param string $blockName
+     * @return Mage_Page_Block_Template_Links
+     */
+    public function removeLinkBlock($blockName)
+    {
+        foreach ($this->_links as $key => $link) {
+            if ($link instanceof Mage_Core_Block_Abstract && $link->getNameInLayout() == $blockName) {
+                unset($this->_links[$key]);
+            }
+        }
         return $this;
     }
 
diff --git a/app/code/core/Mage/Page/Helper/Data.php b/app/code/core/Mage/Page/Helper/Data.php
index 94b44a116464df9a0d86598f24636c91b94e424f..9dd649ccaaf5eb009a1795869a4aa397be653bd8 100644
--- a/app/code/core/Mage/Page/Helper/Data.php
+++ b/app/code/core/Mage/Page/Helper/Data.php
@@ -29,4 +29,8 @@
  */
 class Mage_Page_Helper_Data extends Mage_Core_Helper_Abstract
 {
+    /**
+     * Cookie name for users who allowed cookie save
+     */
+    const IS_USER_ALLOWED_SAVE_COOKIE  = 'user_allowed_save_cookie';
 }
diff --git a/app/code/core/Mage/Page/etc/system.xml b/app/code/core/Mage/Page/etc/system.xml
index 7340a949dd390ddf64f81588c9f94d35830913ce..3848e2522934f8eb70d7ac00effab19fa7957f57 100644
--- a/app/code/core/Mage/Page/etc/system.xml
+++ b/app/code/core/Mage/Page/etc/system.xml
@@ -39,7 +39,7 @@
                     <fields>
                         <shortcut_icon translate="label comment">
                             <label>Favicon Icon</label>
-                            <comment>Allowed file types: ICO, PNG, GIF, JPEG, APNG, SVG. Not all browsers support all these formats!</comment>
+                            <comment>Allowed file types: ICO, PNG, GIF, JPG, JPEG, APNG, SVG. Not all browsers support all these formats!</comment>
                             <frontend_type>image</frontend_type>
                             <backend_model>Mage_Adminhtml_Model_System_Config_Backend_Image_Favicon</backend_model>
                             <base_url type="media" scope_info="1">favicon</base_url>
diff --git a/app/code/core/Mage/Page/view/frontend/html/notices.phtml b/app/code/core/Mage/Page/view/frontend/html/notices.phtml
index e84cab4896396f725a8df441228b2a4833badb19..44d474669e65e3dba72ff214035a80e2c944dc36 100644
--- a/app/code/core/Mage/Page/view/frontend/html/notices.phtml
+++ b/app/code/core/Mage/Page/view/frontend/html/notices.phtml
@@ -31,14 +31,31 @@
 ?>
 <?php if ($this->displayNoscriptNotice()): ?>
     <noscript>
-        <div class="noscript">
-            <div class="noscript-inner">
-                <p><strong><?php echo $this->__('JavaScript seems to be disabled in your browser.'); ?></strong></p>
-                <p><?php echo $this->__('You must have JavaScript enabled in your browser to utilize the functionality of this website.'); ?></p>
+        <div class="global-site-notice noscript">
+            <div class="notice-inner">
+                <p>
+                    <strong><?php echo $this->__('JavaScript seems to be disabled in your browser.'); ?></strong><br />
+                    <?php echo $this->__('You must have JavaScript enabled in your browser to utilize the functionality of this website.'); ?>
+                </p>
             </div>
         </div>
     </noscript>
 <?php endif; ?>
 <?php if ($this->displayDemoNotice()): ?>
-    <p class="demo-notice"><?php echo $this->__('This is a demo store. Any orders placed through this store will not be honored or fulfilled.') ?></p>
+    <div class="global-site-notice demo-notice">
+        <div class="notice-inner"><p><?php echo $this->__('This is a demo store. Any orders placed through this store will not be honored or fulfilled.') ?></p></div>
+    </div>
+<?php endif; ?>
+<?php if ($this->displayCookieRestrictionNotice()): ?>
+    <div class="global-site-notice notice-cookie" id="notice-cookie-block" style="display: none">
+        <div class="notice-inner">
+            <p><?php echo $this->__('This website requires cookies provide all of its features.  For more information on what data is contained in the cookies, please see our <a href="%s">privacy policy page</a> To accept cookies from this site, please click accept below.', $this->getPrivacyPolicyLink()) ?></p>
+            <div class="actions"><button class="button" onclick="Mage.Cookies.set('<?php echo Mage_Page_Helper_Data::IS_USER_ALLOWED_SAVE_COOKIE; ?>', '<?php echo $this->getAcceptedSaveCookiesWebsiteIds()?>'); window.location.reload()"><span><span><?php echo $this->__('Allow');?></span></span></button></div>
+        </div>
+    </div>
+    <script type="text/javascript">
+    /* <![CDATA[ */
+    $('notice-cookie-block').show();
+    /* ]]> */
+    </script>
 <?php endif; ?>
diff --git a/app/code/core/Mage/Page/view/frontend/html/topmenu.phtml b/app/code/core/Mage/Page/view/frontend/html/topmenu.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..634e6b9710659a74cc7caf0fe43439ba0ec18cbb
--- /dev/null
+++ b/app/code/core/Mage/Page/view/frontend/html/topmenu.phtml
@@ -0,0 +1,41 @@
+<?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    Mage
+ * @package     Mage_Page
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<?php
+/**
+ * Top menu for store
+ *
+ * @see Mage_Page_Block_Html_Topmenu
+ */
+?>
+<?php $_menu = $this->getHtml('level-top') ?>
+<?php if($_menu): ?>
+<div class="nav-container">
+    <ul id="nav">
+        <?php echo $_menu ?>
+    </ul>
+</div>
+<?php endif ?>
diff --git a/app/code/core/Mage/Page/view/frontend/layout.xml b/app/code/core/Mage/Page/view/frontend/layout.xml
index caac86bd29791f0c7be88028047cafee99e72d96..6ce3d417176b67fe677113f4045c32245237ab19 100644
--- a/app/code/core/Mage/Page/view/frontend/layout.xml
+++ b/app/code/core/Mage/Page/view/frontend/layout.xml
@@ -30,9 +30,9 @@
 Default layout, loads most of the pages
 -->
 
-    <default translate="label" module="Mage_Page">
+    <default translate="label" module="Mage_Page" type="page">
         <label>All Pages</label>
-        <block type="Mage_Page_Block_Html" name="root" output="toHtml" template="3columns.phtml">
+        <block type="Mage_Page_Block_Html" name="root" output="1" template="3columns.phtml">
 
             <block type="Mage_Page_Block_Html_Head" name="head" as="head">
                 <action method="addJs"><file>prototype/prototype.js</file></action>
@@ -52,60 +52,49 @@ Default layout, loads most of the pages
                 <block type="Mage_Page_Block_Js_Cookie" name="js_cookies" template="js/cookie.phtml"/>
             </block>
 
-            <block type="Mage_Core_Block_Text_List" name="after_body_start" as="after_body_start" translate="label">
-                <label>Page Top</label>
-            </block>
+            <container name="after_body_start" as="after_body_start" label="Page Top"/>
 
             <block type="Mage_Page_Block_Html_Notices" name="global_notices" as="global_notices" template="html/notices.phtml" />
 
             <block type="Mage_Page_Block_Html_Header" name="header" as="header">
                 <block type="Mage_Page_Block_Template_Links" name="top.links" as="topLinks"/>
                 <block type="Mage_Page_Block_Switch" name="store_language" as="store_language" template="switch/languages.phtml"/>
-                <block type="Mage_Core_Block_Text_List" name="top.menu" as="topMenu" translate="label">
-                    <label>Navigation Bar</label>
-                </block>
-                <block type="Mage_Page_Block_Html_Wrapper" name="top.container" as="topContainer" translate="label">
-                    <label>Page Header</label>
-                    <action method="setElementClass"><value>top-container</value></action>
-                </block>
+                <container name="top.menu" as="topMenu" label="Navigation Bar">
+                    <block type="Mage_Page_Block_Html_Topmenu" name="catalog.topnav" template="html/topmenu.phtml"/>
+                </container>
+                <container name="top.container" as="topContainer" label="Page Header" htmlTag="div" htmlClass="top-container"/>
             </block>
 
             <block type="Mage_Page_Block_Html_Breadcrumbs" name="breadcrumbs" as="breadcrumbs"/>
 
-            <block type="Mage_Core_Block_Text_List" name="left" as="left" translate="label">
-                <label>Left Column</label>
-            </block>
+            <container name="left" as="left" label="Left Column"/>
 
             <block type="Mage_Core_Block_Messages" name="global_messages" as="global_messages"/>
             <block type="Mage_Core_Block_Messages" name="messages" as="messages"/>
 
-            <block type="Mage_Core_Block_Text_List" name="content" as="content" translate="label">
-                <label>Main Content Area</label>
-            </block>
+            <container name="content" as="content" label="Main Content Area"/>
 
-            <block type="Mage_Core_Block_Text_List" name="right" as="right" translate="label">
-                <label>Right Column</label>
-            </block>
+            <container name="right" as="right" label="Right Column"/>
 
             <block type="Mage_Page_Block_Html_Footer" name="footer" as="footer" template="html/footer.phtml">
-                <block type="Mage_Page_Block_Html_Wrapper" name="bottom.container" as="bottomContainer" translate="label">
-                    <label>Page Footer</label>
-                    <action method="setElementClass"><value>bottom-container</value></action>
-                </block>
+                <container name="bottom.container" as="bottomContainer" label="Page Footer" htmlTag="div" htmlClass="bottom-container"/>
                 <block type="Mage_Page_Block_Switch" name="store_switcher" as="store_switcher" template="switch/stores.phtml"/>
                 <block type="Mage_Page_Block_Template_Links" name="footer_links" as="footer_links" template="template/links.phtml"/>
             </block>
 
-            <block type="Mage_Core_Block_Text_List" name="before_body_end" as="before_body_end" translate="label">
-                <label>Page Bottom</label>
-            </block>
+            <container name="before_body_end" as="before_body_end" label="Page Bottom"/>
         </block>
     </default>
 
-    <print translate="label" module="Mage_Page">
+    <ajax_index translate="label" type="page">
+        <label>Dynamic Page Blocks (Updated by Ajax Request)</label>
+        <block type="Mage_Page_Block_Html" name="root" output="1" template="page_part.phtml"/>
+    </ajax_index>
+
+    <print translate="label" module="Mage_Page" type="page">
         <label>All Pages (Print Version)</label>
         <!-- Mage_Page -->
-        <block type="Mage_Page_Block_Html" name="root" output="toHtml" template="print.phtml">
+        <block type="Mage_Page_Block_Html" name="root" output="1" template="print.phtml">
 
             <block type="Mage_Page_Block_Html_Head" name="head" as="head">
                 <action method="addJs"><file>prototype/prototype.js</file></action>
@@ -115,15 +104,15 @@ Default layout, loads most of the pages
                 <action method="addJs"><file>varien/js.js</file></action>
             </block>
 
-            <block type="Mage_Core_Block_Text_List" name="content" as="content" translate="label">
-                <label>Main Content Area</label>
-            </block>
+            <container name="after_body_start" as="after_body_start" label="Page Top"/>
+
+            <container name="content" as="content" label="Main Content Area"/>
 
         </block>
     </print>
 
      <!-- Custom page layout handles -->
-    <page_empty translate="label">
+    <page_empty translate="label" type="page" parent="default">
         <label>All Empty Layout Pages</label>
         <reference name="root">
             <action method="setTemplate"><template>empty.phtml</template></action>
@@ -132,7 +121,7 @@ Default layout, loads most of the pages
         </reference>
     </page_empty>
 
-    <page_one_column translate="label">
+    <page_one_column translate="label" type="page" parent="default">
         <label>All One-Column Layout Pages</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -141,7 +130,7 @@ Default layout, loads most of the pages
         </reference>
     </page_one_column>
 
-    <page_two_columns_left translate="label">
+    <page_two_columns_left translate="label" type="page" parent="default">
         <label>All Two-Column Layout Pages (Left Column)</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-left.phtml</template></action>
@@ -150,7 +139,7 @@ Default layout, loads most of the pages
         </reference>
     </page_two_columns_left>
 
-    <page_two_columns_right translate="label">
+    <page_two_columns_right translate="label" type="page" parent="default">
         <label>All Two-Column Layout Pages (Right Column)</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-right.phtml</template></action>
@@ -159,7 +148,7 @@ Default layout, loads most of the pages
         </reference>
     </page_two_columns_right>
 
-    <page_three_columns translate="label">
+    <page_three_columns translate="label" type="page" parent="default">
         <label>All Three-Column Layout Pages</label>
         <reference name="root">
             <action method="setTemplate"><template>3columns.phtml</template></action>
diff --git a/app/code/core/Mage/Page/view/frontend/page_part.phtml b/app/code/core/Mage/Page/view/frontend/page_part.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..195c627baeef2cb175cdde0d34acf479a2b29797
--- /dev/null
+++ b/app/code/core/Mage/Page/view/frontend/page_part.phtml
@@ -0,0 +1,27 @@
+<?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_Core
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<?php echo $this->getChildHtml() ?>
\ No newline at end of file
diff --git a/app/code/core/Mage/Page/view/frontend/print.phtml b/app/code/core/Mage/Page/view/frontend/print.phtml
index b14d04ab12e40240f4c5620e13880b6240ec8fc1..ffe0c9bd2442cf70407cc2c901913be0d1418141 100644
--- a/app/code/core/Mage/Page/view/frontend/print.phtml
+++ b/app/code/core/Mage/Page/view/frontend/print.phtml
@@ -35,6 +35,7 @@
 <?php echo $this->getChildHtml('head') ?>
 </head>
 <body class="page-print<?php echo $this->getBodyClass()?$this->getBodyClass():'' ?>">
+<?php echo $this->getChildHtml('after_body_start') ?>
 <div>
     <div class="print-head">
         <img src="<?php echo $this->getPrintLogoUrl() ? $this->getPrintLogoUrl() : $this->getSkinUrl('images/logo_print.gif') ?>" class="logo" alt="" />
diff --git a/app/code/core/Mage/PageCache/Helper/Data.php b/app/code/core/Mage/PageCache/Helper/Data.php
index 218a44b575bc2712ea7a11eb4dcf96a2c5994d02..21b7cfb9c977d15f9dfcbd6d93c38bde47c45318 100644
--- a/app/code/core/Mage/PageCache/Helper/Data.php
+++ b/app/code/core/Mage/PageCache/Helper/Data.php
@@ -34,7 +34,7 @@
 class Mage_PageCache_Helper_Data extends Mage_Core_Helper_Abstract
 {
     /**
-     * Pathes to external cache config options
+     * Paths to external cache config options
      */
     const XML_PATH_EXTERNAL_CACHE_ENABLED  = 'system/external_page_cache/enabled';
     const XML_PATH_EXTERNAL_CACHE_LIFETIME = 'system/external_page_cache/cookie_lifetime';
@@ -47,11 +47,37 @@ class Mage_PageCache_Helper_Data extends Mage_Core_Helper_Abstract
 
     /**
      * Cookie name for disabling external caching
-     *
-     * @var string
      */
     const NO_CACHE_COOKIE = 'external_no_cache';
 
+    /**
+     * Cookie name for locking the NO_CACHE_COOKIE for modification
+     */
+    const NO_CACHE_LOCK_COOKIE = 'external_no_cache_cookie_locked';
+
+    /**
+     * @var bool
+     */
+    protected $_isNoCacheCookieLocked = false;
+
+    /**
+     * Initialize 'no cache' cookie locking
+     */
+    function __construct()
+    {
+        $this->_isNoCacheCookieLocked = (bool)$this->_getCookie()->get(self::NO_CACHE_LOCK_COOKIE);
+    }
+
+    /**
+     * Retrieve the cookie model instance
+     *
+     * @return Mage_Core_Model_Cookie
+     */
+    protected function _getCookie()
+    {
+        return Mage::getSingleton('Mage_Core_Model_Cookie');
+    }
+
     /**
      * Check whether external cache is enabled
      *
@@ -93,21 +119,60 @@ class Mage_PageCache_Helper_Data extends Mage_Core_Helper_Abstract
     }
 
     /**
-     * Disable caching on external storage side by setting special cookie
+     * Disable caching on external storage side by setting special cookie, if the cookie has not been locked
      *
-     * @return void
+     * @param int|null $lifetime
+     * @return Mage_PageCache_Helper_Data
      */
-    public function setNoCacheCookie()
+    public function setNoCacheCookie($lifetime = null)
     {
-        $cookie   = Mage::getSingleton('Mage_Core_Model_Cookie');
-        $lifetime = Mage::getStoreConfig(self::XML_PATH_EXTERNAL_CACHE_LIFETIME);
-        $noCache  = $cookie->get(self::NO_CACHE_COOKIE);
-
-        if ($noCache) {
-            $cookie->renew(self::NO_CACHE_COOKIE, $lifetime);
+        if ($this->_isNoCacheCookieLocked) {
+            return $this;
+        }
+        $lifetime = $lifetime !== null ? $lifetime : Mage::getStoreConfig(self::XML_PATH_EXTERNAL_CACHE_LIFETIME);
+        if ($this->_getCookie()->get(self::NO_CACHE_COOKIE)) {
+            $this->_getCookie()->renew(self::NO_CACHE_COOKIE, $lifetime);
         } else {
-            $cookie->set(self::NO_CACHE_COOKIE, 1, $lifetime);
+            $this->_getCookie()->set(self::NO_CACHE_COOKIE, '1', $lifetime);
         }
+        return $this;
+    }
+
+    /**
+     * Remove the 'no cache' cookie, if it has not been locked
+     *
+     * @return Mage_PageCache_Helper_Data
+     */
+    public function removeNoCacheCookie()
+    {
+        if (!$this->_isNoCacheCookieLocked) {
+            $this->_getCookie()->delete(self::NO_CACHE_COOKIE);
+        }
+        return $this;
+    }
+
+    /**
+     * Disable modification of the 'no cache' cookie
+     *
+     * @return Mage_PageCache_Helper_Data
+     */
+    public function lockNoCacheCookie()
+    {
+        $this->_getCookie()->set(self::NO_CACHE_LOCK_COOKIE, '1', 0);
+        $this->_isNoCacheCookieLocked = true;
+        return $this;
+    }
+
+    /**
+     * Enable modification of the 'no cache' cookie
+     *
+     * @return Mage_PageCache_Helper_Data
+     */
+    public function unlockNoCacheCookie()
+    {
+        $this->_getCookie()->delete(self::NO_CACHE_LOCK_COOKIE);
+        $this->_isNoCacheCookieLocked = false;
+        return $this;
     }
 
     /**
diff --git a/app/code/core/Mage/PageCache/Model/Observer.php b/app/code/core/Mage/PageCache/Model/Observer.php
index 22e40c545374891f898478fe1621ab555da69ecd..4ab6141d9bf6852ac42d6be5483a405e44886710 100644
--- a/app/code/core/Mage/PageCache/Model/Observer.php
+++ b/app/code/core/Mage/PageCache/Model/Observer.php
@@ -35,6 +35,16 @@ class Mage_PageCache_Model_Observer
 {
     const XML_NODE_ALLOWED_CACHE = 'frontend/cache/allowed_requests';
 
+    /**
+     * Retrieve the helper instance
+     *
+     * @return Mage_PageCache_Helper_Data
+     */
+    protected function _getHelper()
+    {
+        return Mage::helper('Mage_PageCache_Helper_Data');
+    }
+
     /**
      * Check if full page cache is enabled
      *
@@ -42,7 +52,7 @@ class Mage_PageCache_Model_Observer
      */
     public function isCacheEnabled()
     {
-        return Mage::helper('Mage_PageCache_Helper_Data')->isEnabled();
+        return $this->_getHelper()->isEnabled();
     }
 
     /**
@@ -88,9 +98,39 @@ class Mage_PageCache_Model_Observer
         }
 
         if (!$needCaching) {
-            Mage::helper('Mage_PageCache_Helper_Data')->setNoCacheCookie();
+            $this->_getHelper()->setNoCacheCookie();
+        }
+
+        return $this;
+    }
+
+    /**
+     * Temporary disabling full page caching if Design Editor was launched.
+     *
+     * @param Varien_Event_Observer $observer
+     * @return Mage_PageCache_Model_Observer
+     */
+    public function designEditorSessionActivate(Varien_Event_Observer $observer)
+    {
+        if (!$this->isCacheEnabled()) {
+            return $this;
         }
+        $this->_getHelper()->setNoCacheCookie(0)->lockNoCacheCookie();
+        return $this;
+    }
 
+    /**
+     * Activating full page cache after Design Editor was deactivated
+     *
+     * @param Varien_Event_Observer $observer
+     * @return Mage_PageCache_Model_Observer
+     */
+    public function designEditorSessionDeactivate(Varien_Event_Observer $observer)
+    {
+        if (!$this->isCacheEnabled()) {
+            return $this;
+        }
+        $this->_getHelper()->unlockNoCacheCookie()->removeNoCacheCookie();
         return $this;
     }
 }
diff --git a/app/code/core/Mage/PageCache/etc/config.xml b/app/code/core/Mage/PageCache/etc/config.xml
index 5ae7aee961ef11fdc4de7b86038b1fd22086b746..6c9c8a496f16d9d87ce61e7df3566ceab8b85dc9 100644
--- a/app/code/core/Mage/PageCache/etc/config.xml
+++ b/app/code/core/Mage/PageCache/etc/config.xml
@@ -40,6 +40,24 @@
                 </zend_page_cache>
             </controls>
         </external_cache>
+        <events>
+            <design_editor_session_activate>
+                <observers>
+                    <mage_pagecache>
+                        <class>Mage_PageCache_Model_Observer</class>
+                        <method>designEditorSessionActivate</method>
+                    </mage_pagecache>
+                </observers>
+            </design_editor_session_activate>
+            <design_editor_session_deactivate>
+                <observers>
+                    <mage_pagecache>
+                        <class>Mage_PageCache_Model_Observer</class>
+                        <method>designEditorSessionDeactivate</method>
+                    </mage_pagecache>
+                </observers>
+            </design_editor_session_deactivate>
+        </events>
     </global>
     <adminhtml>
         <layout>
diff --git a/app/code/core/Mage/Payment/Block/Form/Banktransfer.php b/app/code/core/Mage/Payment/Block/Form/Banktransfer.php
new file mode 100644
index 0000000000000000000000000000000000000000..23792c7be6eb26ddaf038d096ec04152b9ee769f
--- /dev/null
+++ b/app/code/core/Mage/Payment/Block/Form/Banktransfer.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_Payment
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Block for Bank Transfer payment method form
+ */
+class Mage_Payment_Block_Form_Banktransfer extends Mage_Payment_Block_Form
+{
+
+    /**
+     * Instructions text
+     *
+     * @var string
+     */
+    protected $_instructions;
+
+    /**
+     * Block construction. Set block template.
+     */
+    protected function _construct()
+    {
+        parent::_construct();
+        $this->setTemplate('form/banktransfer.phtml');
+    }
+
+    /**
+     * Get instructions text from config
+     *
+     * @return string
+     */
+    public function getInstructions()
+    {
+        if (is_null($this->_instructions)) {
+            $this->_instructions = $this->getMethod()->getInstructions();
+        }
+        return $this->_instructions;
+    }
+
+}
diff --git a/app/code/core/Mage/Payment/Block/Form/Cashondelivery.php b/app/code/core/Mage/Payment/Block/Form/Cashondelivery.php
new file mode 100644
index 0000000000000000000000000000000000000000..76e532515ddfdb35db1a50d4faa2c06edb0bea43
--- /dev/null
+++ b/app/code/core/Mage/Payment/Block/Form/Cashondelivery.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_Payment
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Block for Cash On Delivery payment method form
+ */
+class Mage_Payment_Block_Form_Cashondelivery extends Mage_Payment_Block_Form
+{
+
+    /**
+     * Instructions text
+     *
+     * @var string
+     */
+    protected $_instructions;
+
+    /**
+     * Block construction. Set block template.
+     */
+    protected function _construct()
+    {
+        parent::_construct();
+        $this->setTemplate('form/cashondelivery.phtml');
+    }
+
+    /**
+     * Get instructions text from config
+     *
+     * @return string
+     */
+    public function getInstructions()
+    {
+        if (is_null($this->_instructions)) {
+            $this->_instructions = $this->getMethod()->getInstructions();
+        }
+        return $this->_instructions;
+    }
+
+}
diff --git a/app/code/core/Mage/Payment/Block/Form/Container.php b/app/code/core/Mage/Payment/Block/Form/Container.php
index c23bf915b89d3610140298896679e83a5b1cc1c1..e43c4b1413055d89166695cd405235b6ee59669f 100644
--- a/app/code/core/Mage/Payment/Block/Form/Container.php
+++ b/app/code/core/Mage/Payment/Block/Form/Container.php
@@ -97,7 +97,7 @@ class Mage_Payment_Block_Form_Container extends Mage_Core_Block_Template
     public function setMethodFormTemplate($method='', $template='')
     {
         if (!empty($method) && !empty($template)) {
-            if ($block = $this->getChild('payment.method.'.$method)) {
+            if ($block = $this->getChildBlock('payment.method.'.$method)) {
                 $block->setTemplate($template);
             }
         }
diff --git a/app/code/core/Mage/Payment/Block/Info.php b/app/code/core/Mage/Payment/Block/Info.php
index 0e2798dd291ce574c17b0fcae40107a3a2c95233..9b286819ca54a0f65daf73c2c732cbca00cf048e 100644
--- a/app/code/core/Mage/Payment/Block/Info.php
+++ b/app/code/core/Mage/Payment/Block/Info.php
@@ -87,7 +87,7 @@ class Mage_Payment_Block_Info extends Mage_Core_Block_Template
     public function getChildPdfAsArray()
     {
         $result = array();
-        foreach ($this->getChild() as $child) {
+        foreach ($this->getLayout()->getChildBlocks($this->getNameInLayout()) as $child) {
             if (is_callable(array($child, 'toPdf'))) {
                 $result[] = $child->toPdf();
             }
diff --git a/app/code/core/Mage/Payment/Block/Info/Banktransfer.php b/app/code/core/Mage/Payment/Block/Info/Banktransfer.php
new file mode 100644
index 0000000000000000000000000000000000000000..70736476c188c8629953e28c22dfd72c5324310b
--- /dev/null
+++ b/app/code/core/Mage/Payment/Block/Info/Banktransfer.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.
+ *
+ * @category    Mage
+ * @package     Mage_Payment
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Block for Bank Transfer payment generic info
+ */
+class Mage_Payment_Block_Info_Banktransfer extends Mage_Payment_Block_Info
+{
+    /**
+     * Instructions text
+     *
+     * @var string
+     */
+    protected $_instructions;
+
+    protected function _construct()
+    {
+        parent::_construct();
+        $this->setTemplate('info/banktransfer.phtml');
+    }
+
+    /**
+     * Get instructions text from order payment
+     * (or from config, if instructions are missed in payment)
+     *
+     * @return string
+     */
+    public function getInstructions()
+    {
+        if (is_null($this->_instructions)) {
+            $this->_instructions = $this->getInfo()->getAdditionalInformation('instructions');
+            if(empty($this->_instructions)) {
+                $this->_instructions = $this->getMethod()->getInstructions();
+            }
+        }
+        return $this->_instructions;
+    }
+}
diff --git a/app/code/core/Mage/Payment/Block/Info/Container.php b/app/code/core/Mage/Payment/Block/Info/Container.php
index fecebf76a7f0a0fbdec6140d4c059fd286e1bede..118d0d9fd2a6a7851761b74a7e8d97d742ef0d59 100644
--- a/app/code/core/Mage/Payment/Block/Info/Container.php
+++ b/app/code/core/Mage/Payment/Block/Info/Container.php
@@ -83,7 +83,7 @@ class Mage_Payment_Block_Info_Container extends Mage_Core_Block_Template
     {
         if ($info = $this->getPaymentInfo()) {
             if ($info->getMethodInstance()->getCode() == $method) {
-                $this->getChild($this->_getInfoBlockName())->setTemplate($template);
+                $this->getChildBlock($this->_getInfoBlockName())->setTemplate($template);
             }
         }
         return $this;
diff --git a/app/code/core/Mage/Payment/Model/Method/Abstract.php b/app/code/core/Mage/Payment/Model/Method/Abstract.php
index e99303ba86be601aa1e737d56d314c8ce63cc166..4bc63b79d794fabc9d0ac71053a512e7b8171d9f 100644
--- a/app/code/core/Mage/Payment/Model/Method/Abstract.php
+++ b/app/code/core/Mage/Payment/Model/Method/Abstract.php
@@ -615,7 +615,7 @@ abstract class Mage_Payment_Model_Method_Abstract extends Varien_Object
      *
      * TODO: payment method instance is not supposed to know about quote
      *
-     * @param Mage_Sales_Model_Quote $quote
+     * @param Mage_Sales_Model_Quote|null $quote
      *
      * @return bool
      */
diff --git a/app/code/core/Mage/Payment/Model/Method/Banktransfer.php b/app/code/core/Mage/Payment/Model/Method/Banktransfer.php
new file mode 100644
index 0000000000000000000000000000000000000000..aa6aa629781460c9e8d79b41057340a2c446c2b6
--- /dev/null
+++ b/app/code/core/Mage/Payment/Model/Method/Banktransfer.php
@@ -0,0 +1,59 @@
+<?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_Payment
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Bank Transfer payment method model
+ */
+class Mage_Payment_Model_Method_Banktransfer extends Mage_Payment_Model_Method_Abstract
+{
+    const PAYMENT_METHOD_BANKTRANSFER_CODE = 'banktransfer';
+
+    /**
+     * Payment method code
+     *
+     * @var string
+     */
+    protected $_code = self::PAYMENT_METHOD_BANKTRANSFER_CODE;
+
+    /**
+     * Bank Transfer payment block paths
+     *
+     * @var string
+     */
+    protected $_formBlockType = 'Mage_Payment_Block_Form_Banktransfer';
+    protected $_infoBlockType = 'Mage_Payment_Block_Info_Banktransfer';
+
+    /**
+     * Get instructions text from config
+     *
+     * @return string
+     */
+    public function getInstructions()
+    {
+        return trim($this->getConfigData('instructions'));
+    }
+
+}
diff --git a/app/code/core/Mage/Payment/Model/Method/Cashondelivery.php b/app/code/core/Mage/Payment/Model/Method/Cashondelivery.php
new file mode 100644
index 0000000000000000000000000000000000000000..f6b4a4e1ff3581e67aa8dcd29ddd8977ebec0894
--- /dev/null
+++ b/app/code/core/Mage/Payment/Model/Method/Cashondelivery.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_Payment
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Cash on delivery payment method model
+ */
+class Mage_Payment_Model_Method_Cashondelivery extends Mage_Payment_Model_Method_Abstract
+{
+
+    /**
+     * Payment method code
+     *
+     * @var string
+     */
+    protected $_code  = 'cashondelivery';
+
+    /**
+     * Cash On Delivery payment block paths
+     *
+     * @var string
+     */
+    protected $_formBlockType = 'Mage_Payment_Block_Form_Cashondelivery';
+    protected $_infoBlockType = 'Mage_Payment_Block_Info';
+
+    /**
+     * Get instructions text from config
+     *
+     * @return string
+     */
+    public function getInstructions()
+    {
+        return trim($this->getConfigData('instructions'));
+    }
+
+}
diff --git a/app/code/core/Mage/Payment/Model/Method/Cc.php b/app/code/core/Mage/Payment/Model/Method/Cc.php
index e7f68a3fadf24e9570e2827a48ca013175f5160f..1e7d095b7a3dd58921a76a3c3850ec13a6b9fa83 100644
--- a/app/code/core/Mage/Payment/Model/Method/Cc.php
+++ b/app/code/core/Mage/Payment/Model/Method/Cc.php
@@ -271,6 +271,7 @@ class Mage_Payment_Model_Method_Cc extends Mage_Payment_Model_Method_Abstract
     /**
      * Check whether there are CC types set in configuration
      *
+     * @param Mage_Sales_Model_Quote|null $quote
      * @return bool
      */
     public function isAvailable($quote = null)
diff --git a/app/code/core/Mage/Payment/Model/Observer.php b/app/code/core/Mage/Payment/Model/Observer.php
index 196f43b25743f6527234cff56602a074d08880d4..f7d76dc2ae9eb73b0fb302a4680cd26e21a7071a 100644
--- a/app/code/core/Mage/Payment/Model/Observer.php
+++ b/app/code/core/Mage/Payment/Model/Observer.php
@@ -51,8 +51,7 @@ class Mage_Payment_Model_Observer
             return $this;
         }
 
-        if ($order->isCanceled() ||
-            $order->getState() === Mage_Sales_Model_Order::STATE_CLOSED ) {
+        if ($order->isCanceled() || $order->getState() === Mage_Sales_Model_Order::STATE_CLOSED) {
             return $this;
         }
         /**
@@ -108,4 +107,20 @@ class Mage_Payment_Model_Observer
         }
         $product->addCustomOption('additional_options', serialize($infoOptions));
     }
+
+    /**
+     * Sets current instructions for bank transfer account
+     *
+     * @param Varien_Event_Observer $observer
+     * @return void
+     */
+    public function beforeOrderPaymentSave(Varien_Event_Observer $observer)
+    {
+        /** @var Mage_Sales_Model_Order_Payment $payment */
+        $payment = $observer->getEvent()->getPayment();
+        if($payment->getMethod() === Mage_Payment_Model_Method_Banktransfer::PAYMENT_METHOD_BANKTRANSFER_CODE) {
+            $payment->setAdditionalInformation('instructions',
+                $payment->getMethodInstance()->getInstructions());
+        }
+    }
 }
diff --git a/app/code/core/Mage/Payment/etc/config.xml b/app/code/core/Mage/Payment/etc/config.xml
index d551c11c7e0228b55c13487d3bcdaa046f732d9e..f0571b9310f76bb355f10084a9d514d40986f843 100644
--- a/app/code/core/Mage/Payment/etc/config.xml
+++ b/app/code/core/Mage/Payment/etc/config.xml
@@ -96,6 +96,14 @@
                     </payment_sales_order_save_before>
                 </observers>
             </sales_order_save_before>
+            <sales_order_payment_save_before>
+                <observers>
+                    <payment_before_save>
+                        <class>Mage_Payment_Model_Observer</class>
+                        <method>beforeOrderPaymentSave</method>
+                    </payment_before_save>
+                </observers>
+            </sales_order_payment_save_before>
         </events>
     </global>
     <frontend>
@@ -172,6 +180,22 @@
                 <allowspecific>0</allowspecific>
                 <group>offline</group>
             </purchaseorder>
+            <banktransfer>
+                <active>0</active>
+                <model>Mage_Payment_Model_Method_Banktransfer</model>
+                <order_status>pending</order_status>
+                <title>Bank Transfer Payment</title>
+                <allowspecific>0</allowspecific>
+                <group>offline</group>
+            </banktransfer>
+            <cashondelivery>
+                <active>0</active>
+                <model>Mage_Payment_Model_Method_Cashondelivery</model>
+                <order_status>pending</order_status>
+                <title>Cash On Delivery</title>
+                <allowspecific>0</allowspecific>
+                <group>offline</group>
+            </cashondelivery>
         </payment>
     </default>
 </config>
diff --git a/app/code/core/Mage/Payment/etc/system.xml b/app/code/core/Mage/Payment/etc/system.xml
index 0684816261d59c6d20d508c61d036a0c720c03f6..a27f7555ceb900b4b1c78cd78b884a34d944515c 100644
--- a/app/code/core/Mage/Payment/etc/system.xml
+++ b/app/code/core/Mage/Payment/etc/system.xml
@@ -445,6 +445,180 @@
                         </model>
                     </fields>
                 </purchaseorder>
+                <banktransfer translate="label">
+                    <label>Bank Transfer Payment</label>
+                    <frontend_type>text</frontend_type>
+                    <sort_order>5</sort_order>
+                    <show_in_default>1</show_in_default>
+                    <show_in_website>1</show_in_website>
+                    <show_in_store>1</show_in_store>
+                    <fields>
+                        <active translate="label">
+                            <label>Enabled</label>
+                            <frontend_type>select</frontend_type>
+                            <source_model>Mage_Adminhtml_Model_System_Config_Source_Yesno</source_model>
+                            <sort_order>1</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </active>
+                        <title translate="label">
+                            <label>Title</label>
+                            <frontend_type>text</frontend_type>
+                            <sort_order>10</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>1</show_in_store>
+                        </title>
+                        <order_status translate="label">
+                            <label>New Order Status</label>
+                            <frontend_type>select</frontend_type>
+                            <source_model>Mage_Adminhtml_Model_System_Config_Source_Order_Status_New</source_model>
+                            <sort_order>20</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </order_status>
+                        <allowspecific translate="label">
+                            <label>Payment from Applicable Countries</label>
+                            <frontend_type>allowspecific</frontend_type>
+                            <sort_order>50</sort_order>
+                            <source_model>Mage_Adminhtml_Model_System_Config_Source_Payment_Allspecificcountries</source_model>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </allowspecific>
+                        <specificcountry translate="label">
+                            <label>Payment from Specific Countries</label>
+                            <frontend_type>multiselect</frontend_type>
+                            <sort_order>51</sort_order>
+                            <source_model>Mage_Adminhtml_Model_System_Config_Source_Country</source_model>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                            <can_be_empty>1</can_be_empty>
+                        </specificcountry>
+                        <instructions translate="label">
+                            <label>Instructions</label>
+                            <frontend_type>textarea</frontend_type>
+                            <sort_order>62</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>1</show_in_store>
+                        </instructions>
+                        <min_order_total translate="label">
+                            <label>Minimum Order Total</label>
+                            <frontend_type>text</frontend_type>
+                            <sort_order>98</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </min_order_total>
+                        <max_order_total translate="label">
+                            <label>Maximum Order Total</label>
+                            <frontend_type>text</frontend_type>
+                            <sort_order>99</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </max_order_total>
+                        <sort_order translate="label">
+                            <label>Sort Order</label>
+                            <frontend_type>text</frontend_type>
+                            <sort_order>100</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </sort_order>
+                    </fields>
+                </banktransfer>
+                <cashondelivery translate="label">
+                    <label>Cash On Delivery Payment</label>
+                    <frontend_type>text</frontend_type>
+                    <sort_order>5</sort_order>
+                    <show_in_default>1</show_in_default>
+                    <show_in_website>1</show_in_website>
+                    <show_in_store>1</show_in_store>
+                    <fields>
+                        <active translate="label">
+                            <label>Enabled</label>
+                            <frontend_type>select</frontend_type>
+                            <source_model>Mage_Adminhtml_Model_System_Config_Source_Yesno</source_model>
+                            <sort_order>1</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </active>
+                        <title translate="label">
+                            <label>Title</label>
+                            <frontend_type>text</frontend_type>
+                            <sort_order>10</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>1</show_in_store>
+                        </title>
+                        <order_status translate="label">
+                            <label>New Order Status</label>
+                            <frontend_type>select</frontend_type>
+                            <source_model>Mage_Adminhtml_Model_System_Config_Source_Order_Status_New</source_model>
+                            <sort_order>20</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </order_status>
+                        <allowspecific translate="label">
+                            <label>Payment from Applicable Countries</label>
+                            <frontend_type>allowspecific</frontend_type>
+                            <sort_order>50</sort_order>
+                            <source_model>Mage_Adminhtml_Model_System_Config_Source_Payment_Allspecificcountries</source_model>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </allowspecific>
+                        <specificcountry translate="label">
+                            <label>Payment from Specific Countries</label>
+                            <frontend_type>multiselect</frontend_type>
+                            <sort_order>51</sort_order>
+                            <source_model>Mage_Adminhtml_Model_System_Config_Source_Country</source_model>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                            <can_be_empty>1</can_be_empty>
+                        </specificcountry>
+                        <instructions translate="label">
+                            <label>Instructions</label>
+                            <frontend_type>textarea</frontend_type>
+                            <sort_order>62</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>1</show_in_store>
+                        </instructions>
+                        <min_order_total translate="label">
+                            <label>Minimum Order Total</label>
+                            <frontend_type>text</frontend_type>
+                            <sort_order>98</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </min_order_total>
+                        <max_order_total translate="label">
+                            <label>Maximum Order Total</label>
+                            <frontend_type>text</frontend_type>
+                            <sort_order>99</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </max_order_total>
+                        <sort_order translate="label">
+                            <label>Sort Order</label>
+                            <frontend_type>text</frontend_type>
+                            <sort_order>100</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </sort_order>
+                    </fields>
+                </cashondelivery>
             </groups>
         </payment>
     </sections>
diff --git a/app/code/core/Mage/Payment/view/adminhtml/form/banktransfer.phtml b/app/code/core/Mage/Payment/view/adminhtml/form/banktransfer.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..a85ceaffd27661079cd747a5aea08d9ce2cc73a2
--- /dev/null
+++ b/app/code/core/Mage/Payment/view/adminhtml/form/banktransfer.phtml
@@ -0,0 +1,35 @@
+<?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    Mage
+ * @package     Mage_Payment
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<?php if ($instructions = $this->getInstructions()): ?>
+    <ul class="form-list checkout-agreements" id="payment_form_<?php echo $this->getMethodCode() ?>" style="display:none;">
+        <li>
+            <div class="<?php echo $this->getMethodCode() ?>-instructions-content agreement-content">
+                <?php echo nl2br($instructions) ?>
+            </div>
+        </li>
+    </ul>
+<?php endif; ?>
diff --git a/app/code/core/Mage/Payment/view/adminhtml/form/cashondelivery.phtml b/app/code/core/Mage/Payment/view/adminhtml/form/cashondelivery.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..8382f10ac7b839a93cb2ac742af1e8b18121dd67
--- /dev/null
+++ b/app/code/core/Mage/Payment/view/adminhtml/form/cashondelivery.phtml
@@ -0,0 +1,39 @@
+<?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    Mage
+ * @package     Mage_Payment
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+
+/**
+ * @see Saas_Payment_Block_Form_Cashondelivery
+ */
+?>
+<?php if ($this->getInstructions()): ?>
+    <ul class="form-list checkout-agreements" id="payment_form_<?php echo $this->getMethodCode() ?>" style="display:none;">
+        <li>
+            <div class="<?php echo $this->getMethodCode() ?>-instructions-content agreement-content">
+                <?php echo nl2br($this->getInstructions()) ?>
+            </div>
+        </li>
+    </ul>
+<?php endif; ?>
diff --git a/app/code/core/Mage/Payment/view/adminhtml/info/banktransfer.phtml b/app/code/core/Mage/Payment/view/adminhtml/info/banktransfer.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..a4b1f6dd7dc808df8f18a3065d44c6d0162bbeaf
--- /dev/null
+++ b/app/code/core/Mage/Payment/view/adminhtml/info/banktransfer.phtml
@@ -0,0 +1,41 @@
+<?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    Mage
+ * @package     Mage_Payment
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<?php
+/**
+ * @see Mage_Payment_Block_Info
+ */
+?>
+<p><?php echo $this->escapeHtml($this->getMethod()->getTitle()) ?></p>
+<?php if ($this->getInstructions()): ?>
+<table>
+    <tbody>
+        <tr>
+            <td><?php echo nl2br($this->getInstructions()) ?></td>
+        </tr>
+    </tbody>
+</table>
+<?php endif; ?>
diff --git a/app/code/core/Mage/Payment/view/frontend/form/banktransfer.phtml b/app/code/core/Mage/Payment/view/frontend/form/banktransfer.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..a85ceaffd27661079cd747a5aea08d9ce2cc73a2
--- /dev/null
+++ b/app/code/core/Mage/Payment/view/frontend/form/banktransfer.phtml
@@ -0,0 +1,35 @@
+<?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    Mage
+ * @package     Mage_Payment
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<?php if ($instructions = $this->getInstructions()): ?>
+    <ul class="form-list checkout-agreements" id="payment_form_<?php echo $this->getMethodCode() ?>" style="display:none;">
+        <li>
+            <div class="<?php echo $this->getMethodCode() ?>-instructions-content agreement-content">
+                <?php echo nl2br($instructions) ?>
+            </div>
+        </li>
+    </ul>
+<?php endif; ?>
diff --git a/app/code/core/Mage/Payment/view/frontend/form/cashondelivery.phtml b/app/code/core/Mage/Payment/view/frontend/form/cashondelivery.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..8382f10ac7b839a93cb2ac742af1e8b18121dd67
--- /dev/null
+++ b/app/code/core/Mage/Payment/view/frontend/form/cashondelivery.phtml
@@ -0,0 +1,39 @@
+<?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    Mage
+ * @package     Mage_Payment
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+
+/**
+ * @see Saas_Payment_Block_Form_Cashondelivery
+ */
+?>
+<?php if ($this->getInstructions()): ?>
+    <ul class="form-list checkout-agreements" id="payment_form_<?php echo $this->getMethodCode() ?>" style="display:none;">
+        <li>
+            <div class="<?php echo $this->getMethodCode() ?>-instructions-content agreement-content">
+                <?php echo nl2br($this->getInstructions()) ?>
+            </div>
+        </li>
+    </ul>
+<?php endif; ?>
diff --git a/app/code/core/Mage/Payment/view/frontend/info/banktransfer.phtml b/app/code/core/Mage/Payment/view/frontend/info/banktransfer.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..a4b1f6dd7dc808df8f18a3065d44c6d0162bbeaf
--- /dev/null
+++ b/app/code/core/Mage/Payment/view/frontend/info/banktransfer.phtml
@@ -0,0 +1,41 @@
+<?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    Mage
+ * @package     Mage_Payment
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<?php
+/**
+ * @see Mage_Payment_Block_Info
+ */
+?>
+<p><?php echo $this->escapeHtml($this->getMethod()->getTitle()) ?></p>
+<?php if ($this->getInstructions()): ?>
+<table>
+    <tbody>
+        <tr>
+            <td><?php echo nl2br($this->getInstructions()) ?></td>
+        </tr>
+    </tbody>
+</table>
+<?php endif; ?>
diff --git a/app/code/core/Mage/Paypal/Block/Express/Review.php b/app/code/core/Mage/Paypal/Block/Express/Review.php
index 6b34e898c3bc165464a2a0662fe1e42cd642efe7..c45e5000e4c55c1f852dd58a195b95cb673b3d28 100644
--- a/app/code/core/Mage/Paypal/Block/Express/Review.php
+++ b/app/code/core/Mage/Paypal/Block/Express/Review.php
@@ -140,10 +140,9 @@ class Mage_Paypal_Block_Express_Review extends Mage_Core_Block_Template
         if ($rate->getErrorMessage()) {
             $price = $rate->getErrorMessage();
         } else {
-            $price = $this->_getShippingPrice(
-                $rate->getPrice(),
-                $this->helper('Mage_Tax_Helper_Data')->displayShippingPriceIncludingTax()
-            );
+            $price = $this->_getShippingPrice($rate->getPrice(),
+                $this->helper('Mage_Tax_Helper_Data')->displayShippingPriceIncludingTax());
+
             $incl = $this->_getShippingPrice($rate->getPrice(), true);
             if (($incl != $price) && $this->helper('Mage_Tax_Helper_Data')->displayShippingBothPrices()) {
                 $renderedInclTax = sprintf(
@@ -213,6 +212,8 @@ class Mage_Paypal_Block_Express_Review extends Mage_Core_Block_Template
     {
         $methodInstance = $this->_quote->getPayment()->getMethodInstance();
         $this->setPaymentMethodTitle($methodInstance->getTitle());
+        $this->setUpdateOrderSubmitUrl($this->getUrl("{$this->_paypalActionPrefix}/express/updateOrder"));
+        $this->setUpdateShippingMethodsUrl($this->getUrl("{$this->_paypalActionPrefix}/express/updateShippingMethods"));
 
         $this->setShippingRateRequired(true);
         if ($this->_quote->getIsVirtual()) {
diff --git a/app/code/core/Mage/Paypal/Block/Express/Review/Billing.php b/app/code/core/Mage/Paypal/Block/Express/Review/Billing.php
new file mode 100644
index 0000000000000000000000000000000000000000..0143db2be15f80b400e81de1aaf41ab4755c53f7
--- /dev/null
+++ b/app/code/core/Mage/Paypal/Block/Express/Review/Billing.php
@@ -0,0 +1,59 @@
+<?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_Paypal
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Paypal Express Onepage checkout block for Billing Address
+ *
+ * @category   Mage
+ * @package    Mage_Paypal
+ * @author     Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_Paypal_Block_Express_Review_Billing extends Mage_Checkout_Block_Onepage_Billing
+{
+    /**
+     * Return Sales Quote Address model
+     *
+     * @return Mage_Sales_Model_Quote_Address
+     */
+    public function getAddress()
+    {
+        if (is_null($this->_address)) {
+            if ($this->isCustomerLoggedIn() || $this->getQuote()->getBillingAddress()) {
+                $this->_address = $this->getQuote()->getBillingAddress();
+                if (!$this->_address->getFirstname()) {
+                    $this->_address->setFirstname($this->getQuote()->getCustomer()->getFirstname());
+                }
+                if (!$this->_address->getLastname()) {
+                    $this->_address->setLastname($this->getQuote()->getCustomer()->getLastname());
+                }
+            } else {
+                $this->_address = Mage::getModel('Mage_Sales_Model_Quote_Address');
+            }
+        }
+
+        return $this->_address;
+    }
+}
diff --git a/app/code/core/Mage/Paypal/Block/Express/Review/Shipping.php b/app/code/core/Mage/Paypal/Block/Express/Review/Shipping.php
new file mode 100644
index 0000000000000000000000000000000000000000..82a7bf2207d2f029adffd3518bf2fd7f148809eb
--- /dev/null
+++ b/app/code/core/Mage/Paypal/Block/Express/Review/Shipping.php
@@ -0,0 +1,53 @@
+<?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_Paypal
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Paypal Express Onepage checkout block for Shipping Address
+ *
+ * @category   Mage
+ * @package    Mage_Paypal
+ * @author     Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_Paypal_Block_Express_Review_Shipping extends Mage_Checkout_Block_Onepage_Shipping
+{
+    /**
+     * Return Sales Quote Address model (shipping address)
+     *
+     * @return Mage_Sales_Model_Quote_Address
+     */
+    public function getAddress()
+    {
+        if (is_null($this->_address)) {
+            if ($this->isCustomerLoggedIn() || $this->getQuote()->getShippingAddress()) {
+                $this->_address = $this->getQuote()->getShippingAddress();
+            } else {
+                $this->_address = Mage::getModel('Mage_Sales_Model_Quote_Address');
+            }
+        }
+
+        return $this->_address;
+    }
+}
diff --git a/app/code/core/Mage/Paypal/Block/Express/Shortcut.php b/app/code/core/Mage/Paypal/Block/Express/Shortcut.php
index 1126e6584c8e6e2424f1925e47ec39d7ee61206f..1954effdfe7111a7e0bbd26c091c04a89454af7b 100644
--- a/app/code/core/Mage/Paypal/Block/Express/Shortcut.php
+++ b/app/code/core/Mage/Paypal/Block/Express/Shortcut.php
@@ -61,7 +61,7 @@ class Mage_Paypal_Block_Express_Shortcut extends Mage_Core_Block_Template
      *
      * @var string
      */
-    protected $_checkoutType = 'paypal/express_checkout';
+    protected $_checkoutType = 'Mage_Paypal_Model_Express_Checkout';
 
     protected function _beforeToHtml()
     {
diff --git a/app/code/core/Mage/Paypal/Block/Iframe.php b/app/code/core/Mage/Paypal/Block/Iframe.php
index 59fef66f1db052d1a7bdb9c26778285a26418e71..930c0e7716253537e243f287044214c3382187f0 100644
--- a/app/code/core/Mage/Paypal/Block/Iframe.php
+++ b/app/code/core/Mage/Paypal/Block/Iframe.php
@@ -75,8 +75,13 @@ class Mage_Paypal_Block_Iframe extends Mage_Payment_Block_Form
             ->getMethod();
         if (in_array($paymentCode, $this->helper('Mage_Paypal_Helper_Hss')->getHssMethods())) {
             $this->_paymentMethodCode = $paymentCode;
-            $template_path = str_replace('_', '', $paymentCode);
-            $this->setTemplate("{$template_path}/iframe.phtml");
+            $templatePath = str_replace('_', '', $paymentCode);
+            $templateFile = "{$templatePath}/iframe.phtml";
+            if (file_exists(Mage::getDesign()->getTemplateFilename($templateFile))) {
+                $this->setTemplate($templateFile);
+            } else {
+                $this->setTemplate('hss/iframe.phtml');
+            }
         }
     }
 
diff --git a/app/code/core/Mage/Paypal/Block/Standard/Redirect.php b/app/code/core/Mage/Paypal/Block/Standard/Redirect.php
index a4b90608e13f6084115a3d9ee6fc758035f29d1f..e4859c2e139967e13df2619853f6b060e7068ca4 100644
--- a/app/code/core/Mage/Paypal/Block/Standard/Redirect.php
+++ b/app/code/core/Mage/Paypal/Block/Standard/Redirect.php
@@ -38,6 +38,13 @@ class Mage_Paypal_Block_Standard_Redirect extends Mage_Core_Block_Abstract
         foreach ($standard->getStandardCheckoutFormFields() as $field=>$value) {
             $form->addField($field, 'hidden', array('name'=>$field, 'value'=>$value));
         }
+        $idSuffix = Mage::helper('Mage_Core_Helper_Data')->uniqHash();
+        $submitButton = new Varien_Data_Form_Element_Submit(array(
+            'value'    => $this->__('Click here if you are not redirected within 10 seconds...'),
+        ));
+        $id = "submit_to_paypal_button_{$idSuffix}";
+        $submitButton->setId($id);
+        $form->addElement($submitButton);
         $html = '<html><body>';
         $html.= $this->__('You will be redirected to the PayPal website in a few seconds.');
         $html.= $form->toHtml();
diff --git a/app/code/core/Mage/Paypal/Controller/Express/Abstract.php b/app/code/core/Mage/Paypal/Controller/Express/Abstract.php
index b457722dad007a66bdc418ae75dbd84d0ee44be2..59a8160ca83b52ea2a4000ebcfbb8e965c97ebe7 100644
--- a/app/code/core/Mage/Paypal/Controller/Express/Abstract.php
+++ b/app/code/core/Mage/Paypal/Controller/Express/Abstract.php
@@ -183,10 +183,12 @@ abstract class Mage_Paypal_Controller_Express_Abstract extends Mage_Core_Control
             $this->_checkout->prepareOrderReview($this->_initToken());
             $this->loadLayout();
             $this->_initLayoutMessages('Mage_Paypal_Model_Session');
-            $this->getLayout()->getBlock('paypal.express.review')
-                ->setQuote($this->_getQuote())
-                ->getChild('details')->setQuote($this->_getQuote())
-            ;
+            $reviewBlock = $this->getLayout()->getBlock('paypal.express.review');
+            $reviewBlock->setQuote($this->_getQuote());
+            $reviewBlock->getChildBlock('details')->setQuote($this->_getQuote());
+            if ($reviewBlock->getChildBlock('shipping_method')) {
+                $reviewBlock->getChildBlock('shipping_method')->setQuote($this->_getQuote());
+            }
             $this->renderLayout();
             return;
         }
@@ -232,12 +234,64 @@ abstract class Mage_Paypal_Controller_Express_Abstract extends Mage_Core_Control
                     ->toHtml());
                 return;
             }
+        } catch (Mage_Core_Exception $e) {
+            $this->_getSession()->addError($e->getMessage());
+        } catch (Exception $e) {
+            $this->_getSession()->addError($this->__('Unable to update shipping method.'));
+            Mage::logException($e);
         }
-        catch (Mage_Core_Exception $e) {
+        if ($isAjax) {
+            $this->getResponse()->setBody('<script type="text/javascript">window.location.href = '
+                . Mage::getUrl('*/*/review') . ';</script>');
+        } else {
+            $this->_redirect('*/*/review');
+        }
+    }
+
+    /**
+     * Update Order (combined action for ajax and regular request)
+     */
+    public function updateShippingMethodsAction()
+    {
+        try {
+            $this->_initCheckout();
+            $this->_checkout->prepareOrderReview($this->_initToken());
+            $this->loadLayout('paypal_express_review');
+
+            $this->getResponse()->setBody($this->getLayout()->getBlock('express.review.shipping.method')
+                ->setQuote($this->_getQuote())
+                ->toHtml());
+            return;
+        } catch (Mage_Core_Exception $e) {
             $this->_getSession()->addError($e->getMessage());
+        } catch (Exception $e) {
+            $this->_getSession()->addError($this->__('Unable to update Order data.'));
+            Mage::logException($e);
         }
-        catch (Exception $e) {
-            $this->_getSession()->addError($this->__('Unable to update shipping method.'));
+        $this->getResponse()->setBody('<script type="text/javascript">window.location.href = '
+            . Mage::getUrl('*/*/review') . ';</script>');
+    }
+
+    /**
+     * Update Order (combined action for ajax and regular request)
+     */
+    public function updateOrderAction()
+    {
+        try {
+            $isAjax = $this->getRequest()->getParam('isAjax');
+            $this->_initCheckout();
+            $this->_checkout->updateOrder($this->getRequest()->getParams());
+            if ($isAjax) {
+                $this->loadLayout('paypal_express_review_details');
+                $this->getResponse()->setBody($this->getLayout()->getBlock('root')
+                    ->setQuote($this->_getQuote())
+                    ->toHtml());
+                return;
+            }
+        } catch (Mage_Core_Exception $e) {
+            $this->_getSession()->addError($e->getMessage());
+        } catch (Exception $e) {
+            $this->_getSession()->addError($this->__('Unable to update Order data.'));
             Mage::logException($e);
         }
         if ($isAjax) {
diff --git a/app/code/core/Mage/Paypal/Model/Api/Nvp.php b/app/code/core/Mage/Paypal/Model/Api/Nvp.php
index 6fb28c1ca81a17afaee46597b398bd5b8eeace6c..645e46732f5e400abd756f6199d05232c11a6884 100644
--- a/app/code/core/Mage/Paypal/Model/Api/Nvp.php
+++ b/app/code/core/Mage/Paypal/Model/Api/Nvp.php
@@ -90,6 +90,7 @@ class Mage_Paypal_Model_Api_Nvp extends Mage_Paypal_Model_Api_Abstract
         'ACTION'            => 'action',
         'REDIRECTREQUIRED'  => 'redirect_required',
         'SUCCESSPAGEREDIRECTREQUESTED'  => 'redirect_requested',
+        'REQBILLINGADDRESS' => 'require_billing_address',
         // style settings
         'PAGESTYLE'      => 'page_style',
         'HDRIMG'         => 'hdrimg',
@@ -227,7 +228,7 @@ class Mage_Paypal_Model_Api_Nvp extends Mage_Paypal_Model_Api_Abstract
         'PAYMENTACTION', 'AMT', 'CURRENCYCODE', 'RETURNURL', 'CANCELURL', 'INVNUM', 'SOLUTIONTYPE', 'NOSHIPPING',
         'GIROPAYCANCELURL', 'GIROPAYSUCCESSURL', 'BANKTXNPENDINGURL',
         'PAGESTYLE', 'HDRIMG', 'HDRBORDERCOLOR', 'HDRBACKCOLOR', 'PAYFLOWCOLOR', 'LOCALECODE',
-        'BILLINGTYPE', 'SUBJECT', 'ITEMAMT', 'SHIPPINGAMT', 'TAXAMT',
+        'BILLINGTYPE', 'SUBJECT', 'ITEMAMT', 'SHIPPINGAMT', 'TAXAMT', 'REQBILLINGADDRESS',
     );
     protected $_setExpressCheckoutResponse = array('TOKEN');
 
@@ -630,6 +631,11 @@ class Mage_Paypal_Model_Api_Nvp extends Mage_Paypal_Model_Api_Abstract
         $request = $this->_exportToRequest($this->_doExpressCheckoutPaymentRequest);
         $this->_exportLineItems($request);
 
+        if ($this->getAddress()) {
+            $request = $this->_importAddresses($request);
+            $request['ADDROVERRIDE'] = 1;
+        }
+
         $response = $this->call(self::DO_EXPRESS_CHECKOUT_PAYMENT, $request);
         $this->_importFromResponse($this->_paymentInformationResponse, $response);
         $this->_importFromResponse($this->_doExpressCheckoutPaymentResponse, $response);
@@ -1136,11 +1142,17 @@ class Mage_Paypal_Model_Api_Nvp extends Mage_Paypal_Model_Api_Abstract
             Varien_Object_Mapper::accumulateByMap($data, $shippingAddress, $this->_shippingAddressMap);
             $this->_applyStreetAndRegionWorkarounds($shippingAddress);
             // PayPal doesn't provide detailed shipping name fields, so the name will be overwritten
+            $firstName = $data['SHIPTONAME'];
+            $lastName = null;
+            if (isset($data['FIRSTNAME']) && $data['LASTNAME']) {
+                $firstName = $data['FIRSTNAME'];
+                $lastName = $data['LASTNAME'];
+            }
             $shippingAddress->addData(array(
                 'prefix'     => null,
-                'firstname'  => $data['SHIPTONAME'],
+                'firstname'  => $firstName,
                 'middlename' => null,
-                'lastname'   => null,
+                'lastname'   => $lastName,
                 'suffix'     => null,
             ));
             $this->setExportedShippingAddress($shippingAddress);
diff --git a/app/code/core/Mage/Paypal/Model/Config.php b/app/code/core/Mage/Paypal/Model/Config.php
index c39453906cb87cc07ef76267c3a959e50819c53a..c8aa6e326d999441659b116a853218f4c00a2200 100644
--- a/app/code/core/Mage/Paypal/Model/Config.php
+++ b/app/code/core/Mage/Paypal/Model/Config.php
@@ -106,6 +106,14 @@ class Mage_Paypal_Model_Config
     const AUTHORIZATION_AMOUNT_ONE = 1;
     const AUTHORIZATION_AMOUNT_FULL = 2;
 
+    /**
+     * Require Billing Address
+     * @var int
+     */
+    const REQUIRE_BILLING_ADDRESS_NO = 0;
+    const REQUIRE_BILLING_ADDRESS_ALL = 1;
+    const REQUIRE_BILLING_ADDRESS_VIRTUAL = 2;
+
     /**
      * Fraud management actions
      * @var string
@@ -855,6 +863,20 @@ class Mage_Paypal_Model_Config
         return $paymentActions;
     }
 
+    /**
+     * Require Billing Address source getter
+     *
+     * @return array
+     */
+    public function getRequireBillingAddressOptions()
+    {
+        return array(
+            self::REQUIRE_BILLING_ADDRESS_ALL       => Mage::helper('Mage_Paypal_Helper_Data')->__('Yes'),
+            self::REQUIRE_BILLING_ADDRESS_NO        => Mage::helper('Mage_Paypal_Helper_Data')->__('No'),
+            self::REQUIRE_BILLING_ADDRESS_VIRTUAL   => Mage::helper('Mage_Paypal_Helper_Data')->__('For Virtual Quotes Only'),
+        );
+    }
+
     /**
      * Mapper from PayPal-specific payment actions to Magento payment actions
      *
@@ -1189,6 +1211,7 @@ class Mage_Paypal_Model_Config
             case 'solution_type':
             case 'visible_on_cart':
             case 'visible_on_product':
+            case 'require_billing_address':
             case 'authorization_honor_period':
             case 'order_valid_period':
             case 'child_authorization_number':
diff --git a/app/code/core/Mage/Paypal/Model/Express.php b/app/code/core/Mage/Paypal/Model/Express.php
index aeb16f459acaddce539c87bbf956438af0abb00f..14f4c865d291cd92a9209f28a6ec59ca3b5a94af 100644
--- a/app/code/core/Mage/Paypal/Model/Express.php
+++ b/app/code/core/Mage/Paypal/Model/Express.php
@@ -106,6 +106,21 @@ class Mage_Paypal_Model_Express extends Mage_Payment_Model_Method_Abstract
         return $this;
     }
 
+   /**
+    * Can be used in regular checkout
+    *
+    * @return bool
+    */
+   public function canUseCheckout()
+   {
+       if (Mage::getStoreConfigFlag('payment/hosted_pro/active')
+           && !Mage::getStoreConfigFlag('payment/hosted_pro/display_ec')
+       ) {
+           return false;
+       }
+       return parent::canUseCheckout();
+   }
+
     /**
      * Whether method is available for specified currency
      *
@@ -535,6 +550,12 @@ class Mage_Paypal_Model_Express extends Mage_Payment_Model_Method_Abstract
             ->setPaypalCart(Mage::getModel('Mage_Paypal_Model_Cart', array($order)))
             ->setIsLineItemsEnabled($this->_pro->getConfig()->lineItemsEnabled)
         ;
+        if ($order->getIsVirtual()) {
+            $api->setAddress($order->getBillingAddress())->setSuppressShipping(true);
+        } else {
+            $api->setAddress($order->getShippingAddress());
+            $api->setBillingAddress($order->getBillingAddress());
+        }
 
         // call api and get details from it
         $api->callDoExpressCheckoutPayment();
diff --git a/app/code/core/Mage/Paypal/Model/Express/Checkout.php b/app/code/core/Mage/Paypal/Model/Express/Checkout.php
index 6f4c68f93477fee5d778c37c60d6dcd1b4c5f7f1..04d5b4f4d6a60833688ade31ca9fe3f291e37812 100644
--- a/app/code/core/Mage/Paypal/Model/Express/Checkout.php
+++ b/app/code/core/Mage/Paypal/Model/Express/Checkout.php
@@ -194,6 +194,7 @@ class Mage_Paypal_Model_Express_Checkout
      * @param string $successUrl - payment success result
      * @param string $cancelUrl  - payment cancellation result
      * @param string $pendingUrl - pending payment result
+     * @return Mage_Paypal_Model_Express_Checkout
      */
     public function prepareGiropayUrls($successUrl, $cancelUrl, $pendingUrl)
     {
@@ -243,7 +244,10 @@ class Mage_Paypal_Model_Express_Checkout
 
     /**
      * Reserve order ID for specified quote and start checkout on PayPal
-     * @return string
+     *
+     * @param string $returnUrl
+     * @param string $cancelUrl
+     * @return mixed
      */
     public function start($returnUrl, $cancelUrl)
     {
@@ -275,8 +279,15 @@ class Mage_Paypal_Model_Express_Checkout
 
         $this->_setBillingAgreementRequest();
 
+        if ($this->_config->requireBillingAddress == Mage_Paypal_Model_Config::REQUIRE_BILLING_ADDRESS_ALL) {
+            $this->_api->setRequireBillingAddress(1);
+        }
+
         // supress or export shipping address
         if ($this->_quote->getIsVirtual()) {
+            if ($this->_config->requireBillingAddress == Mage_Paypal_Model_Config::REQUIRE_BILLING_ADDRESS_VIRTUAL) {
+                $this->_api->setRequireBillingAddress(1);
+            }
             $this->_api->setSuppressShipping(true);
         } else {
             $address = $this->_quote->getShippingAddress();
@@ -357,7 +368,18 @@ class Mage_Paypal_Model_Express_Checkout
         $quote->setCustomerSuffix($billingAddress->getSuffix());
         $quote->setCustomerNote($exportedBillingAddress->getData('note'));
         foreach ($exportedBillingAddress->getExportedKeys() as $key) {
-            if (!$billingAddress->getDataUsingMethod($key)) {
+            $oldData = $billingAddress->getDataUsingMethod($key);
+            $isEmpty = null;
+            if (is_array($oldData)) {
+                foreach($oldData as $val) {
+                    if(!empty($val)) {
+                        $isEmpty = false;
+                        break;
+                    }
+                    $isEmpty = true;
+                }
+            }
+            if (empty($oldData) || $isEmpty === true) {
                 $billingAddress->setDataUsingMethod($key, $exportedBillingAddress->getData($key));
             }
         }
@@ -472,11 +494,42 @@ class Mage_Paypal_Model_Express_Checkout
             if ($methodCode != $shippingAddress->getShippingMethod()) {
                 $this->_ignoreAddressValidation();
                 $shippingAddress->setShippingMethod($methodCode)->setCollectShippingRates(true);
-                $this->_quote->collectTotals()->save();
+                $this->_quote->collectTotals();
             }
         }
     }
 
+    /**
+     * Update order data
+     *
+     * @param array $data
+     */
+    public function updateOrder($data)
+    {
+        /** @var $checkout Mage_Checkout_Model_Type_Onepage */
+        $checkout = Mage::getModel('Mage_Checkout_Model_Type_Onepage');
+
+        $this->_quote->setTotalsCollectedFlag(true);
+        $checkout->setQuote($this->_quote);
+        if (isset($data['billing'])) {
+            if (isset($data['customer-email'])) {
+                $data['billing']['email'] = $data['customer-email'];
+            }
+            $checkout->saveBilling($data['billing'], 0);
+        }
+        if (!$this->_quote->getIsVirtual() && isset($data['shipping'])) {
+            $checkout->saveShipping($data['shipping'], 0);
+        }
+
+        if (isset($data['shipping_method'])) {
+            $this->updateShippingMethod($data['shipping_method']);
+        }
+        $this->_quote->setTotalsCollectedFlag(false);
+        $this->_quote->collectTotals();
+        $this->_quote->setDataChanges(true);
+        $this->_quote->save();
+    }
+
     /**
      * Place the order and recurring payment profiles when customer returned from paypal
      * Until this moment all quote data must be valid
@@ -491,7 +544,7 @@ class Mage_Paypal_Model_Express_Checkout
         }
 
         $isNewCustomer = false;
-        switch ($this->_quote->getCheckoutMethod()) {
+        switch ($this->getCheckoutMethod()) {
             case Mage_Checkout_Model_Type_Onepage::METHOD_GUEST:
                 $this->_prepareGuestQuote();
                 break;
@@ -557,13 +610,15 @@ class Mage_Paypal_Model_Express_Checkout
         $this->_quote->getBillingAddress()->setShouldIgnoreValidation(true);
         if (!$this->_quote->getIsVirtual()) {
             $this->_quote->getShippingAddress()->setShouldIgnoreValidation(true);
+            if (!$this->_config->requireBillingAddress && !$this->getCustomerSession()->isLoggedIn()) {
+                $this->_quote->getBillingAddress()->setSameAsShipping(1);
+            }
         }
     }
 
     /**
      * Determine whether redirect somewhere specifically is required
      *
-     * @param string $action
      * @return string
      */
     public function getRedirectUrl()
@@ -601,6 +656,26 @@ class Mage_Paypal_Model_Express_Checkout
         return $this->_order;
     }
 
+    /**
+     * Get checkout method
+     *
+     * @return string
+     */
+    public function getCheckoutMethod()
+    {
+        if ($this->getCustomerSession()->isLoggedIn()) {
+            return Mage_Checkout_Model_Type_Onepage::METHOD_CUSTOMER;
+        }
+        if (!$this->_quote->getCheckoutMethod()) {
+            if (Mage::helper('Mage_Checkout_Helper_Data')->isAllowedGuestCheckout($this->_quote)) {
+                $this->_quote->setCheckoutMethod(Mage_Checkout_Model_Type_Onepage::METHOD_GUEST);
+            } else {
+                $this->_quote->setCheckoutMethod(Mage_Checkout_Model_Type_Onepage::METHOD_REGISTER);
+            }
+        }
+        return $this->_quote->getCheckoutMethod();
+    }
+
     /**
      * Set create billing agreement flag to api call
      *
@@ -822,8 +897,8 @@ class Mage_Paypal_Model_Express_Checkout
         $customer->setSuffix($quote->getCustomerSuffix());
         $customer->setPassword($customer->decryptPassword($quote->getPasswordHash()));
         $customer->setPasswordHash($customer->hashPassword($customer->getPassword()));
-        $quote->setCustomer($customer)
-            ->setCustomerId(true);
+        $customer->save();
+        $quote->setCustomer($customer);
 
         return $this;
     }
diff --git a/app/code/core/Mage/Paypal/Model/System/Config/Source/RequireBillingAddress.php b/app/code/core/Mage/Paypal/Model/System/Config/Source/RequireBillingAddress.php
new file mode 100644
index 0000000000000000000000000000000000000000..4e723a95354536b9ed0bf4ab1fb806e37ea6e1f3
--- /dev/null
+++ b/app/code/core/Mage/Paypal/Model/System/Config/Source/RequireBillingAddress.php
@@ -0,0 +1,43 @@
+<?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_Paypal
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Source model for Require Billing Address
+ */
+class Mage_Paypal_Model_System_Config_Source_RequireBillingAddress
+{
+    /**
+     * Options getter
+     *
+     * @return array
+     */
+    public function toOptionArray()
+    {
+        /** @var $configModel Mage_Paypal_Model_Config */
+        $configModel = Mage::getModel('Mage_Paypal_Model_Config');
+        return $configModel->getRequireBillingAddressOptions();
+    }
+}
diff --git a/app/code/core/Mage/Paypal/controllers/ExpressController.php b/app/code/core/Mage/Paypal/controllers/ExpressController.php
index 0f940ddb5f3a386b3d30202bfc41c9b2129b20cb..5452b2a76759fd7e33f8919780923f53f0e9bb1d 100644
--- a/app/code/core/Mage/Paypal/controllers/ExpressController.php
+++ b/app/code/core/Mage/Paypal/controllers/ExpressController.php
@@ -48,7 +48,7 @@ class Mage_Paypal_ExpressController extends Mage_Paypal_Controller_Express_Abstr
      *
      * @var string
      */
-    protected $_checkoutType = 'paypal/express_checkout';
+    protected $_checkoutType = 'Mage_Paypal_Model_Express_Checkout';
 
     /**
      * Redirect to login page
diff --git a/app/code/core/Mage/Paypal/controllers/HostedproController.php b/app/code/core/Mage/Paypal/controllers/HostedproController.php
index d9f366c57fcb74daae064a1ba619de1d9a78ca0f..59d5646eecf21eecd69cb1f76c8c7007ea98f86d 100644
--- a/app/code/core/Mage/Paypal/controllers/HostedproController.php
+++ b/app/code/core/Mage/Paypal/controllers/HostedproController.php
@@ -50,12 +50,12 @@ class Mage_Paypal_HostedproController extends Mage_Core_Controller_Front_Action
      */
     public function cancelAction()
     {
+        $this->loadLayout(false);
         $gotoSection = $this->_cancelPayment();
-        $redirectBlock = $this->_getIframeBlock()
-            ->setGotoSection($gotoSection)
-            ->setTemplate('hss/redirect.phtml');
+        $redirectBlock = $this->getLayout()->getBlock('hosted.pro.iframe');
+        $redirectBlock->setGotoSection($gotoSection);
         //TODO: clarify return logic whether customer will be returned in iframe or in parent window
-        $this->getResponse()->setBody($redirectBlock->toHtml());
+        $this->renderLayout();
     }
 
     /**
@@ -103,16 +103,4 @@ class Mage_Paypal_HostedproController extends Mage_Core_Controller_Front_Action
     {
         return Mage::getSingleton('Mage_Checkout_Model_Session');
     }
-
-    /**
-     * Get iframe block
-     *
-     * @return Mage_Paypal_Block_Hosted_Pro_Iframe
-     */
-    protected function _getIframeBlock()
-    {
-        $this->loadLayout('paypal_hosted_pro_iframe');
-        return $this->getLayout()
-            ->getBlock('hosted.pro.iframe');
-    }
 }
diff --git a/app/code/core/Mage/Paypal/controllers/PayflowController.php b/app/code/core/Mage/Paypal/controllers/PayflowController.php
index 4083f236dab6423c6411cca00c01fcb8a95f6ce1..55dfb4c188ba5d3eb8c89b5b7a82ad37e01fbe92 100644
--- a/app/code/core/Mage/Paypal/controllers/PayflowController.php
+++ b/app/code/core/Mage/Paypal/controllers/PayflowController.php
@@ -38,11 +38,11 @@ class Mage_Paypal_PayflowController extends Mage_Core_Controller_Front_Action
      */
     public function cancelPaymentAction()
     {
+        $this->loadLayout(false);
         $gotoSection = $this->_cancelPayment();
-        $redirectBlock = $this->_getIframeBlock()
-            ->setGotoSection($gotoSection)
-            ->setTemplate('payflowlink/redirect.phtml');
-        $this->getResponse()->setBody($redirectBlock->toHtml());
+        $redirectBlock = $this->getLayout()->getBlock('payflow.link.iframe');
+        $redirectBlock->setGotoSection($gotoSection);
+        $this->renderLayout();
     }
 
     /**
@@ -50,8 +50,8 @@ class Mage_Paypal_PayflowController extends Mage_Core_Controller_Front_Action
      */
     public function returnUrlAction()
     {
-        $redirectBlock = $this->_getIframeBlock()
-            ->setTemplate('paypal/payflowlink/redirect.phtml');
+        $this->loadLayout(false);
+        $redirectBlock = $this->getLayout()->getBlock('payflow.link.iframe');
 
         $session = $this->_getCheckout();
         if ($session->getLastRealOrderId()) {
@@ -73,7 +73,7 @@ class Mage_Paypal_PayflowController extends Mage_Core_Controller_Front_Action
             }
         }
 
-        $this->getResponse()->setBody($redirectBlock->toHtml());
+        $this->renderLayout();
     }
 
     /**
@@ -81,8 +81,7 @@ class Mage_Paypal_PayflowController extends Mage_Core_Controller_Front_Action
      */
     public function formAction()
     {
-        $this->getResponse()
-            ->setBody($this->_getIframeBlock()->toHtml());
+        $this->loadLayout(false)->renderLayout();
     }
 
     /**
@@ -147,16 +146,4 @@ class Mage_Paypal_PayflowController extends Mage_Core_Controller_Front_Action
     {
         return Mage::getSingleton('Mage_Checkout_Model_Session');
     }
-
-    /**
-     * Get iframe block
-     *
-     * @return Mage_Paypal_Block_Payflow_Link_Iframe
-     */
-    protected function _getIframeBlock()
-    {
-        $this->loadLayout('paypal_payflow_link_iframe');
-        return $this->getLayout()
-            ->getBlock('payflow.link.iframe');
-    }
 }
diff --git a/app/code/core/Mage/Paypal/controllers/PayflowadvancedController.php b/app/code/core/Mage/Paypal/controllers/PayflowadvancedController.php
index 9b129006d6264b0254707d09ef6f79fbecafbd79..277ecd38705c10afcbfc1deddcc69bb60cf830ee 100644
--- a/app/code/core/Mage/Paypal/controllers/PayflowadvancedController.php
+++ b/app/code/core/Mage/Paypal/controllers/PayflowadvancedController.php
@@ -33,6 +33,27 @@
  */
 class Mage_Paypal_PayflowadvancedController extends Mage_Paypal_Controller_Express_Abstract
 {
+    /**
+     * Config mode type
+     *
+     * @var string
+     */
+    protected $_configType = 'Mage_Paypal_Model_Config';
+
+    /**
+     * Config method type
+     *
+     * @var string
+     */
+    protected $_configMethod = Mage_Paypal_Model_Config::METHOD_PAYFLOWADVANCED;
+
+    /**
+     * Checkout mode type
+     *
+     * @var string
+     */
+    protected $_checkoutType = 'Mage_Paypal_Model_Payflowadvanced';
+
     /**
      * When a customer cancel payment from payflow gateway.
      *
@@ -40,11 +61,11 @@ class Mage_Paypal_PayflowadvancedController extends Mage_Paypal_Controller_Expre
      */
     public function cancelPaymentAction()
     {
+        $this->loadLayout(false);
         $gotoSection = $this->_cancelPayment();
-        $redirectBlock = $this->_getIframeBlock()
-            ->setGotoSection($gotoSection)
-            ->setTemplate('payflowadvanced/redirect.phtml');
-        $this->getResponse()->setBody($redirectBlock->toHtml());
+        $redirectBlock = $this->getLayout()->getBlock('payflow.advanced.iframe');
+        $redirectBlock->setGotoSection($gotoSection);
+        $this->renderLayout();
     }
 
     /**
@@ -54,8 +75,8 @@ class Mage_Paypal_PayflowadvancedController extends Mage_Paypal_Controller_Expre
      */
     public function returnUrlAction()
     {
-        $redirectBlock = $this->_getIframeBlock()
-            ->setTemplate('paypal/payflowadvanced/redirect.phtml');
+        $this->loadLayout(false);
+        $redirectBlock = $this->getLayout()->getBlock('payflow.advanced.iframe');;
 
         $session = $this->_getCheckout();
         if ($session->getLastRealOrderId()) {
@@ -77,7 +98,7 @@ class Mage_Paypal_PayflowadvancedController extends Mage_Paypal_Controller_Expre
             }
         }
 
-        $this->getResponse()->setBody($redirectBlock->toHtml());
+        $this->renderLayout();
     }
 
     /**
@@ -87,8 +108,7 @@ class Mage_Paypal_PayflowadvancedController extends Mage_Paypal_Controller_Expre
      */
     public function formAction()
     {
-        $this->getResponse()
-            ->setBody($this->_getIframeBlock()->toHtml());
+        $this->loadLayout(false)->renderLayout();
     }
 
     /**
@@ -155,16 +175,4 @@ class Mage_Paypal_PayflowadvancedController extends Mage_Paypal_Controller_Expre
     {
         return Mage::getSingleton('Mage_Checkout_Model_Session');
     }
-
-    /**
-     * Get iframe block
-     *
-     * @return Mage_Paypal_Block_Payflow_Advanced_Iframe
-     */
-    protected function _getIframeBlock()
-    {
-        $this->loadLayout('paypal_payflow_advanced_iframe');
-        return $this->getLayout()
-            ->getBlock('payflow.advanced.iframe');
-    }
 }
diff --git a/app/code/core/Mage/Paypal/controllers/StandardController.php b/app/code/core/Mage/Paypal/controllers/StandardController.php
index 2a3d13e21df900a6cc223e95ca5d677f11c521ed..fcc69bc86536ce06e834b6dfd13a042352f6f750 100644
--- a/app/code/core/Mage/Paypal/controllers/StandardController.php
+++ b/app/code/core/Mage/Paypal/controllers/StandardController.php
@@ -81,7 +81,7 @@ class Mage_Paypal_StandardController extends Mage_Core_Controller_Front_Action
     {
         $session = Mage::getSingleton('Mage_Checkout_Model_Session');
         $session->setPaypalStandardQuoteId($session->getQuoteId());
-        $this->getResponse()->setBody($this->getLayout()->createBlock('Mage_Paypal_Block_Standard_Redirect')->toHtml());
+        $this->loadLayout(false)->renderLayout();
         $session->unsQuoteId();
         $session->unsRedirectUrl();
     }
diff --git a/app/code/core/Mage/Paypal/etc/config.xml b/app/code/core/Mage/Paypal/etc/config.xml
index 92c4afa0530a8f3c876de685d1785fd7e58b76f8..2ce93e7003c6ffddba1086c15bcbdc7db5ace3eb 100644
--- a/app/code/core/Mage/Paypal/etc/config.xml
+++ b/app/code/core/Mage/Paypal/etc/config.xml
@@ -251,6 +251,7 @@
                 <title>Payment by cards or by PayPal account</title>
                 <payment_action>Authorization</payment_action>
                 <group>paypal</group>
+                <display_ec>0</display_ec>
             </hosted_pro>
         </payment>
     </default>
diff --git a/app/code/core/Mage/Paypal/etc/system.xml b/app/code/core/Mage/Paypal/etc/system.xml
index 00b1abf1693f9d65ed44da9649cebb052a330c80..c84156be42f237af5ede1cbb849cbc89981dedba 100644
--- a/app/code/core/Mage/Paypal/etc/system.xml
+++ b/app/code/core/Mage/Paypal/etc/system.xml
@@ -483,6 +483,16 @@
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
                         </solution_type>
+                        <require_billing_address translate="label comment">
+                            <label>Require Customer's Billing Address</label>
+                            <comment>This feature needs be enabled first for the merchant account through PayPal technical support.</comment>
+                            <config_path>payment/paypal_express/require_billing_address</config_path>
+                            <frontend_type>select</frontend_type>
+                            <source_model>Mage_Paypal_Model_System_Config_Source_RequireBillingAddress</source_model>
+                            <sort_order>65</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                        </require_billing_address>
                         <allow_ba_signup translate="label comment tooltip">
                             <label>Billing Agreement Signup </label>
                             <comment>Whether to create a billing agreement, if there are no active billing agreements available.</comment>
@@ -1932,6 +1942,15 @@
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
                         </debug>
+                        <display_ec translate="label">
+                            <label>Display Express Checkout in the Payment Information step</label>
+                            <config_path>payment/hosted_pro/display_ec</config_path>
+                            <frontend_type>select</frontend_type>
+                            <source_model>Mage_Adminhtml_Model_System_Config_Source_Yesno</source_model>
+                            <sort_order>45</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                        </display_ec>
                     </fields>
                 </hosted_pro>
             </groups>
diff --git a/app/code/core/Mage/Paypal/view/frontend/express/review.phtml b/app/code/core/Mage/Paypal/view/frontend/express/review.phtml
index 2c5493471147c2532ad0332ae4f5383a8b93e52b..851e08528d048ee3eb0dd4c624abf245695726dd 100644
--- a/app/code/core/Mage/Paypal/view/frontend/express/review.phtml
+++ b/app/code/core/Mage/Paypal/view/frontend/express/review.phtml
@@ -23,112 +23,87 @@
  * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
+/** @var $this Mage_Paypal_Block_Express_Review */
+
+$billingBlock = $this->getChildBlock('billing')->setFieldNamePrefix('billing')->setHideEmailAddress(true);
+$shippingAddress = $this->getShippingAddress();
 ?>
 <div class="page-title">
     <h1><?php echo $this->__('Review Order') ?></h1>
 </div>
-<?php echo $this->getMessagesBlock()->getGroupedHtml() ?>
-
-<?php if ($this->getShippingAddress()): ?>
-<div class="info-set col2-set">
-    <h2 class="legend"><?php echo $this->__('Shipping Information') ?></h2>
-    <div class="col-1">
-        <div class="box">
-            <div class="box-title">
-                <h3><?php echo $this->__('Shipping Address') ?><span class="separator"><?php if ($this->getCanEditShippingAddress()):?> | </span><a href="<?php echo $this->getEditUrl() ?>"><?php echo $this->__('Change Shipping Address') ?></a><?php endif;?></h3>
-            </div>
-            <div class="box-content">
-                <address><?php echo $this->renderAddress($this->getShippingAddress())?></address>
-            </div>
+<?php echo $this->getMessagesBlock()->toHtml() ?>
+<script type="text/javascript">
+//<![CDATA[
+    var countryRegions = <?php echo $this->helper('Mage_Directory_Helper_Data')->getRegionJson() ?>
+//]]>
+</script>
+<h2 class="sub-title">
+    Please confirm your addresses
+</h2>
+<div class="paypal-review-order">
+    <form method="post" id="order_review_form" action="<?php echo $this->getPlaceOrderUrl() ?>">
+    <?php if(!$billingBlock->isCustomerLoggedIn()): ?>
+        <div class="info-set col2-set">
+            <h2 class="legend"><?php echo $this->__('Customer Information') ?></h2>
+            <ul class="form-list form-list-narrow">
+                <li id="customer-info-form" class="address-form">
+                    <div class="field">
+                        <label for="customer:email" class="required"><em>*</em><?php echo $this->__('Email Address') ?></label>
+                        <div class="input-box">
+                            <input type="text" name="customer-email" id="customer:email" value="<?php echo $this->escapeHtml($billingBlock->getAddress()->getEmail()) ?>" title="<?php echo $this->__('Email Address') ?>" class="input-text validate-email required-entry" />
+                        </div>
+                    </div>
+                </li>
+            </ul>
         </div>
-    </div>
-    <div class="col-2">
-        <div class="box">
-            <div class="box-title">
-                <h3><?php echo $this->__('Shipping Method') ?></h3>
-            </div>
-            <div class="box-content">
-            <?php if ($this->getCanEditShippingMethod() || !$this->getCurrentShippingRate()):?>
-                <?php if ($groups = $this->getShippingRateGroups()):?>
-                    <?php $currentRate = $this->getCurrentShippingRate(); ?>
-                    <form method="post" id="shipping_method_form" action="<?php echo $this->escapeHtml($this->getShippingMethodSubmitUrl()) ?>">
-                        <fieldset>
-                            <select name="shipping_method" id="shipping_method" style="width:250px;" class="required-entry">
-                            <?php if (!$currentRate):?>
-                                <option value=""><?php echo $this->__('Please select a shipping method...') ?></option>
-                            <?php endif;?>
-                            <?php foreach ($groups as $code => $rates):?>
-                                <optgroup label="<?php echo $this->getCarrierName($code) ?>" style="font-style:normal;">
-                                <?php foreach ($rates as $rate):?>
-                                    <option value="<?php echo $this->renderShippingRateValue($rate)?>"<?php echo ($currentRate === $rate) ? ' selected="selected"' : '' ;?>>
-                                        <?php echo $this->renderShippingRateOption($rate)?>
-                                    </option>
-                                <?php endforeach;?>
-                                </optgroup>
-                            <?php endforeach;?>
-                            </select>
-                        </fieldset>
-                        <p class="actions">
-                            <button id="update_shipping_method_submit" type="submit" class="button"><span><span><?php echo $this->__('Update Shipping Method') ?></span></span></button>
-                        </p>
-                    </form>
-                <?php else: ?>
-                    <p><strong><?php echo $this->__('Sorry, no quotes are available for this order at this time.') ?></strong></p>
-                <?php endif;?>
+    <?php endif ?>
+    <div class="info-set col2-set">
+        <div class="col-1" id="billing-address">
+            <h2 class="legend"><?php echo $this->__('Billing Address') ?></h2>
+            <?php if ($shippingAddress): ?>
+                <?php echo $billingBlock->setShowAsShippingCheckbox(true)->toHtml(); ?>
             <?php else: ?>
-                <p><strong><?php echo $this->renderShippingRateOption($this->getCurrentShippingRate())?></strong></p>
+                <?php echo $billingBlock->toHtml(); ?>
             <?php endif; ?>
-            </div>
         </div>
-    </div>
-</div>
-<?php endif; ?>
-
-<div class="info-set col2-set">
-    <h2 class="legend"><?php echo $this->__('Billing Information') ?></h2>
-    <div class="col-1">
-        <div class="box">
-            <div class="box-title">
-                <h3><?php echo $this->__('Payment Method') ?> <span class="separator">|</span>
-                    <?php if($this->getEditUrl()):?><a href="<?php echo $this->getEditUrl() ?>"><?php echo $this->__('Change Payment Method') ?></a> <?php endif ?>
-                </h3>
-            </div>
-            <div class="box-content">
-                <?php echo $this->escapeHtml($this->getPaymentMethodTitle()) ?>
-            </div>
+    <?php if ($shippingAddress): ?>
+        <div class="col-2" id="shipping-address">
+            <h2 class="legend"><?php echo $this->__('Shipping Address') ?></h2>
+            <?php echo $this->getChildBlock('shipping')->setFieldNamePrefix('shipping')->setHideEmailAddress(true)->toHtml(); ?>
         </div>
     </div>
-    <div class="col-2">
-        <div class="box">
-            <div class="box-title">
-                <h3><?php echo $this->__('Billing Address') ?></h3>
-            </div>
-            <div class="box-content">
-                <address>
-                    <?php echo $this->renderAddress($this->getBillingAddress()) ?><br />
-                    <?php echo $this->__('Payer Email: %s', $this->getBillingAddress()->getEmail()) ?>
-                </address>
+
+    <div class="info-set col2-set">
+        <div class="col-2">
+            <div class="box paypal-shipping-method">
+                <div class="box-title">
+                    <h3><?php echo $this->__('Shipping Method') ?></h3>
+                </div>
+                <div class="box-content">
+                    <?php echo $this->getChildBlock('shipping_method')->toHtml(); ?>
+                </div>
             </div>
         </div>
+    <?php endif; ?>
     </div>
-</div>
 
-<div class="info-set">
-    <h2 class="legend"><?php echo $this->__('Items in Your Shopping Cart') ?><span class="separator"> | </span><a href="<?php echo $this->getUrl('checkout/cart') ?>"><?php echo $this->__('Edit Shopping Cart') ?></a></h2>
-    <div id="details-reload">
-        <?php echo $this->getChildHtml('details') ?>
+    <div class="info-set">
+        <h2 class="legend"><?php echo $this->__('Items in Your Shopping Cart') ?><span class="separator"> | </span><a href="<?php echo $this->getUrl('checkout/cart') ?>"><?php echo $this->__('Edit Shopping Cart') ?></a></h2>
+        <div id="details-reload">
+            <?php echo $this->getChildHtml('details') ?>
+        </div>
     </div>
+        <?php echo $this->getChildHtml('agreements'); ?>
+        <div class="buttons-set buttons-set-order" id="review-buttons-container">
+            <button type="button" id="review_button" value="<?php echo $this->__('Place Order') ?>" class="button btn-checkout"><span><span><?php echo $this->__('Place Order') ?></span></span></button>
+            <button type="button" id="review_submit" value="<?php echo $this->__('Place Order') ?>" class="button btn-checkout"><span><span><?php echo $this->__('Place Order') ?></span></span></button>
+            <button type="button" id="update_order" class="button btn-checkout"><span><span><?php echo $this->__('Update Order Data') ?></span></span></button>
+            <span class="please-wait" id="review-please-wait" style="display:none;">
+                <img src="<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif') ?>" alt="<?php echo $this->__('Submitting order information...') ?>" title="<?php echo $this->__('Submitting order information...') ?>" class="v-middle" /> <?php echo $this->__('Submitting order information...') ?>
+            </span>
+        </div>
+    </form>
 </div>
-<form method="post" id="order_review_form" action="<?php echo $this->getPlaceOrderUrl() ?>">
-    <?php echo $this->getChildHtml('agreements'); ?>
-    <div class="buttons-set buttons-set-order" id="review-buttons-container">
-        <button type="button" id="review_button" value="<?php echo $this->__('Place Order') ?>" class="button btn-checkout"><span><span><?php echo $this->__('Place Order') ?></span></span></button>
-        <button type="button" id="review_submit" value="<?php echo $this->__('Place Order') ?>" class="button btn-checkout"><span><span><?php echo $this->__('Place Order') ?></span></span></button>
-        <span class="please-wait" id="review-please-wait" style="display:none;">
-            <img src="<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif') ?>" alt="<?php echo $this->__('Submitting order information...') ?>" title="<?php echo $this->__('Submitting order information...') ?>" class="v-middle" /> <?php echo $this->__('Submitting order information...') ?>
-        </span>
-    </div>
-</form>
 <script type="text/javascript">
 //<![CDATA[
 // submit buttons are not needed when submitting with ajax
@@ -181,10 +156,15 @@ if ($('update_shipping_method_submit')) {
         }
     }
 <?php endif ?>
-
 PayPalExpressAjax = new OrderReviewController($('order_review_form'), $('review_button'),
-    $('shipping_method'), $('shipping_method_form'), 'details-reload'
+    'shipping_method', null, 'details-reload'
 );
 PayPalExpressAjax.addPleaseWait($('review-please-wait'));
+PayPalExpressAjax.setShippingAddressContainer($('shipping-address'));
+PayPalExpressAjax.shippingMethodsUpdateUrl = '<?php echo $this->escapeHtml($this->getUpdateShippingMethodsUrl()) ?>';
+PayPalExpressAjax.setUpdateButton($('update_order'),'<?php echo $this->escapeHtml($this->getUpdateOrderSubmitUrl()) ?>','details-reload');
+if ($('billing:as_shipping')) {
+    PayPalExpressAjax.setCopyElement($('billing:as_shipping'));
+}
 //]]>
 </script>
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
new file mode 100644
index 0000000000000000000000000000000000000000..ac3bd148e1412cd2ec72720f79c07b0970eff3cc
--- /dev/null
+++ b/app/code/core/Mage/Paypal/view/frontend/express/review/address.phtml
@@ -0,0 +1,141 @@
+<?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    Mage
+ * @package     Mage_Paypal
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<?php $prefix = $this->getFieldNamePrefix();?>
+<fieldset>
+    <ul class="form-list form-list-narrow">
+    <li id="<?php echo $prefix ?>-address-form" class="address-form">
+        <fieldset>
+            <input type="hidden" name="<?php echo $prefix ?>[address_id]" value="<?php echo $this->getAddress()->getId() ?>" id="<?php echo $prefix ?>:address_id" />
+            <ul>
+                <li class="fields"><?php echo $this->getLayout()->createBlock('Mage_Customer_Block_Widget_Name')->setObject($this->getAddress()->getFirstname() ? $this->getAddress() : $this->getQuote()->getCustomer())->setForceUseCustomerRequiredAttributes(!$this->isCustomerLoggedIn())->setFieldIdFormat($prefix . ':%s')->setFieldNameFormat($prefix . '[%s]')->toHtml() ?></li>
+                <li class="fields">
+                    <div class="field">
+                        <label for="<?php echo $prefix ?>:company"><?php echo $this->__('Company') ?></label>
+                        <div class="input-box">
+                            <input type="text" id="<?php echo $prefix ?>:company" name="<?php echo $prefix ?>[company]" value="<?php echo $this->escapeHtml($this->getAddress()->getCompany()) ?>" title="<?php echo $this->__('Company') ?>" class="input-text" />
+                        </div>
+                    </div>
+        <?php if(!$this->isCustomerLoggedIn() && !$this->getHideEmailAddress()): ?>
+                    <div class="field">
+                        <label for="<?php echo $prefix ?>:email" class="required"><em>*</em><?php echo $this->__('Email Address') ?></label>
+                        <div class="input-box">
+                            <input type="text" name="<?php echo $prefix ?>[email]" id="<?php echo $prefix ?>:email" value="<?php echo $this->escapeHtml($this->getAddress()->getEmail()) ?>" title="<?php echo $this->__('Email Address') ?>" class="input-text validate-email required-entry" />
+                        </div>
+                    </div>
+        <?php endif ?>
+                </li>
+                <li class="wide">
+                    <label for="<?php echo $prefix ?>:street1" class="required"><em>*</em><?php echo $this->__('Address') ?></label>
+                    <div class="input-box">
+                        <input type="text" title="<?php echo $this->__('Street Address') ?>" name="<?php echo $prefix ?>[street][]" id="<?php echo $prefix ?>:street1" value="<?php echo $this->escapeHtml($this->getAddress()->getStreet(1)) ?>" class="input-text required-entry" />
+                    </div>
+                </li>
+        <?php for ($_i=2, $_n=$this->helper('Mage_Customer_Helper_Address')->getStreetLines(); $_i<=$_n; $_i++): ?>
+                <li class="add-field">
+                    <div class="input-box">
+                        <input type="text" title="<?php echo $this->__('Street Address %s', $_i) ?>" name="<?php echo $prefix ?>[street][]" id="<?php echo $prefix ?>:street<?php echo $_i?>" value="<?php echo $this->escapeHtml($this->getAddress()->getStreet($_i)) ?>" class="input-text" />
+                    </div>
+                </li>
+        <?php endfor ?>
+                <li class="wide">
+                    <label for="<?php echo $prefix ?>:vat_id"><?php echo $this->__('VAT Number') ?></label>
+                    <div class="input-box">
+                        <input type="text" id="<?php echo $prefix ?>:vat_id" name="<?php echo $prefix ?>[vat_id]" value="<?php echo $this->escapeHtml($this->getAddress()->getVatId()) ?>" title="<?php echo $this->__('VAT Number') ?>" class="input-text" />
+                    </div>
+                </li>
+                <li class="fields">
+                    <div class="field">
+                        <label for="<?php echo $prefix ?>:city" class="required"><em>*</em><?php echo $this->__('City') ?></label>
+                        <div class="input-box">
+                            <input type="text" title="<?php echo $this->__('City') ?>" name="<?php echo $prefix ?>[city]" value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>" class="input-text required-entry" id="<?php echo $prefix ?>:city" />
+                        </div>
+                    </div>
+                    <div class="field">
+                        <label for="<?php echo $prefix ?>:region_id" class="required"><em>*</em><?php echo $this->__('State/Province') ?></label>
+                        <div class="input-box">
+                            <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" style="display:none;" />
+                        </div>
+                    </div>
+                </li>
+                <li class="fields">
+                    <div class="field">
+                        <label for="<?php echo $prefix ?>:postcode" class="required"><em>*</em><?php echo $this->__('Zip/Postal Code') ?></label>
+                        <div class="input-box">
+                            <input type="text" title="<?php echo $this->__('Zip/Postal Code') ?>" name="<?php echo $prefix ?>[postcode]" id="<?php echo $prefix ?>:postcode" value="<?php echo $this->escapeHtml($this->getAddress()->getPostcode()) ?>" class="input-text validate-zip-international required-entry" />
+                        </div>
+                    </div>
+                    <div class="field">
+                        <label for="<?php echo $prefix ?>:country_id" class="required"><em>*</em><?php echo $this->__('Country') ?></label>
+                        <div class="input-box">
+                            <?php echo $this->getCountryHtmlSelect($prefix) ?>
+                        </div>
+                    </div>
+                </li>
+                <li class="fields">
+                    <div class="field">
+                        <label for="<?php echo $prefix ?>:telephone" class="required"><em>*</em><?php echo $this->__('Telephone') ?></label>
+                        <div class="input-box">
+                            <input type="text" name="<?php echo $prefix ?>[telephone]" value="<?php echo $this->escapeHtml($this->getAddress()->getTelephone()) ?>" title="<?php echo $this->__('Telephone') ?>" class="input-text required-entry" id="<?php echo $prefix ?>:telephone" />
+                        </div>
+                    </div>
+                    <div class="field">
+                        <label for="<?php echo $prefix ?>:fax"><?php echo $this->__('Fax') ?></label>
+                        <div class="input-box">
+                            <input type="text" name="<?php echo $prefix ?>[fax]" value="<?php echo $this->escapeHtml($this->getAddress()->getFax()) ?>" title="<?php echo $this->__('Fax') ?>" class="input-text" id="<?php echo $prefix ?>:fax" />
+                        </div>
+                    </div>
+                </li>
+                <?php echo $this->getChildHtml('form.additional.info'); ?>
+                <?php if ($this->getShowAsShippingCheckbox()): ?>
+                    <li class="control">
+                        <div class="field">
+                            <div class="input-box">
+                                <input type="checkbox" name="<?php echo $prefix ?>[as_shipping]" class="checkbox" value="1" title="<?php echo $this->__('Same as shipping') ?>" id="<?php echo $prefix ?>:as_shipping" <?php if ($this->getAddress()->getSameAsShipping()):?>checked="checked"<?php endif;?>/>
+                            </div>
+                            <label for="<?php echo $prefix ?>:as_shipping"><?php echo $this->__('Same as shipping') ?></label>
+                        </div>
+                    </li>
+                <?php endif; ?>
+            </ul>
+        </fieldset>
+     </li>
+    </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', countryRegions, undefined, '<?php echo $prefix ?>:postcode');
+    <?php echo $prefix ?>RegionUpdater.update();
+//]]>
+</script>
diff --git a/app/code/core/Mage/Paypal/view/frontend/express/review/shipping/method.phtml b/app/code/core/Mage/Paypal/view/frontend/express/review/shipping/method.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..90ccee339165a498cb416b502fc16485e2ed3ea5
--- /dev/null
+++ b/app/code/core/Mage/Paypal/view/frontend/express/review/shipping/method.phtml
@@ -0,0 +1,53 @@
+<?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     base_default
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+/** @var $this Mage_Paypal_Block_Express_Review */
+?>
+<?php if ($this->getCanEditShippingMethod() || !$this->getCurrentShippingRate()):?>
+    <?php if ($groups = $this->getShippingRateGroups()):?>
+        <?php $currentRate = $this->getCurrentShippingRate(); ?>
+            <fieldset>
+                <select name="shipping_method" id="shipping_method" style="width:250px;" class="required-entry">
+                <?php if (!$currentRate):?>
+                    <option value=""><?php echo $this->__('Please select a shipping method...') ?></option>
+                <?php endif;?>
+                <?php foreach ($groups as $code => $rates):?>
+                    <optgroup label="<?php echo $this->getCarrierName($code) ?>" style="font-style:normal;">
+                    <?php foreach ($rates as $rate):?>
+                        <option value="<?php echo $this->renderShippingRateValue($rate)?>"<?php echo ($currentRate === $rate) ? ' selected="selected"' : '' ;?>>
+                            <?php echo $this->renderShippingRateOption($rate)?>
+                        </option>
+                    <?php endforeach;?>
+                    </optgroup>
+                <?php endforeach;?>
+                </select>
+                <div style="display:none" id="shipping_method_update"><p><?php echo $this->__('Please update order data to get shipping methods and rates') ?></p></div>
+            </fieldset>
+    <?php else: ?>
+        <p><strong><?php echo $this->__('Sorry, no quotes are available for this order at this time.') ?></strong></p>
+    <?php endif;?>
+<?php else: ?>
+    <p><strong><?php echo $this->renderShippingRateOption($this->getCurrentShippingRate())?></strong></p>
+<?php endif; ?>
diff --git a/app/code/core/Mage/Paypal/view/frontend/layout.xml b/app/code/core/Mage/Paypal/view/frontend/layout.xml
index 73f8165498f3014f4f573011b31ec2f2bb462cf0..937c35ba69ab782973c132d0143391b1cf2e7f17 100644
--- a/app/code/core/Mage/Paypal/view/frontend/layout.xml
+++ b/app/code/core/Mage/Paypal/view/frontend/layout.xml
@@ -43,7 +43,7 @@
         <update handle="SHORTCUT_popup" />
     </checkout_cart_index>
 
-    <paypal_express_review translate="label">
+    <paypal_express_review translate="label" type="page" parent="default">
         <label>PayPal Express Order Review Form</label>
         <remove name="right"/>
         <remove name="left"/>
@@ -53,6 +53,9 @@
         </reference>
         <reference name="content">
             <block type="Mage_Paypal_Block_Express_Review" name="paypal.express.review" template="express/review.phtml">
+                <block type="Mage_Paypal_Block_Express_Review_Billing" name="express.review.billing" as="billing" template="express/review/address.phtml"/>
+                <block type="Mage_Paypal_Block_Express_Review_Shipping" name="express.review.shipping" as="shipping" template="express/review/address.phtml"/>
+                <block type="Mage_Paypal_Block_Express_Review" name="express.review.shipping.method" as="shipping_method" template="express/review/shipping/method.phtml"/>
                 <block type="Mage_Paypal_Block_Express_Review_Details" name="paypal.express.review.details" as="details" template="express/review/details.phtml">
                     <action method="addItemRender"><type>default</type><block>Mage_Checkout_Block_Cart_Item_Renderer</block><template>onepage/review/item.phtml</template></action>
                     <action method="addItemRender"><type>grouped</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Grouped</block><template>onepage/review/item.phtml</template></action>
@@ -65,11 +68,12 @@
         <reference name="head">
             <action method="addJs"><file>Mage_Paypal::review.js</file></action>
         </reference>
-        <block type="Mage_Core_Block_Text_List" name="additional.product.info" />
+        <container name="additional.product.info" label="Additional Product Info"/>
     </paypal_express_review>
 
-    <paypal_express_review_details>
-        <block type="Mage_Paypal_Block_Express_Review_Details" name="root" output="toHtml" template="express/review/details.phtml">
+    <paypal_express_review_details translate="label" type="page" parent="checkout_onepage_review">
+        <label>Paypal Express Review Details</label>
+        <block type="Mage_Paypal_Block_Express_Review_Details" name="root" output="1" template="express/review/details.phtml">
             <action method="addItemRender"><type>default</type><block>Mage_Checkout_Block_Cart_Item_Renderer</block><template>onepage/review/item.phtml</template></action>
             <action method="addItemRender"><type>grouped</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Grouped</block><template>onepage/review/item.phtml</template></action>
             <action method="addItemRender"><type>configurable</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Configurable</block><template>onepage/review/item.phtml</template></action>
@@ -90,12 +94,11 @@ Available logo types can be assigned with action="setLogoType":
 -->
     <catalog_product_view>
         <reference name="product.info.addtocart">
-            <block type="Mage_Page_Block_Html_Wrapper" name="product.info.addtocart.paypal.wrapper" translate="label">
-                <label>PayPal Express Checkout Shortcut Wrapper</label>
+            <container name="product.info.addtocart.paypal.wrapper" label="PayPal Express Checkout Shortcut Wrapper" htmlTag="div">
                 <block type="Mage_Paypal_Block_Express_Shortcut" name="product.info.addtocart.paypal" template="express/shortcut.phtml">
                     <action method="setIsInCatalogProduct"><value>1</value></action>
                 </block>
-            </block>
+            </container>
         </reference>
         <update handle="SHORTCUT_popup" />
         <reference name="right">
@@ -105,19 +108,12 @@ Available logo types can be assigned with action="setLogoType":
         </reference>
     </catalog_product_view>
 
-    <catalog_category_default>
+    <catalog_category_view>
         <update handle="SHORTCUT_popup" />
         <reference name="right">
             <block type="Mage_Paypal_Block_Logo" name="paypal.partner.right.logo" template="partner/logo.phtml"/>
         </reference>
-    </catalog_category_default>
-
-    <catalog_category_layered>
-        <update handle="SHORTCUT_popup" />
-        <reference name="right">
-            <block type="Mage_Paypal_Block_Logo" name="paypal.partner.right.logo" template="partner/logo.phtml"/>
-        </reference>
-    </catalog_category_layered>
+    </catalog_category_view>
 
     <catalog_product_compare_index>
         <update handle="SHORTCUT_popup" />
@@ -176,26 +172,55 @@ Available logo types can be assigned with action="setLogoType":
         </reference>
     </checkout_onepage_review>
 
-    <paypal_payflow_link_iframe>
-        <block type="Mage_Paypal_Block_Payflow_Link_Iframe" name="payflow.link.iframe" template="payflowlink/form.phtml" />
-    </paypal_payflow_link_iframe>
-
-    <paypal_payflow_advanced_iframe>
-        <block type="Mage_Paypal_Block_Payflow_Advanced_Iframe" name="payflow.advanced.iframe" template="payflowadvanced/form.phtml" />
-    </paypal_payflow_advanced_iframe>
-
-    <paypal_hosted_pro_iframe>
-        <block type="Mage_Paypal_Block_Hosted_Pro_Iframe" name="hosted.pro.iframe" template="hss/form.phtml"/>
-    </paypal_hosted_pro_iframe>
-
-    <SHORTCUT_popup>
+    <paypal_payflowadvanced_cancelpayment translate="label" type="page" parent="paypal_payflowadvanced_form">
+        <label>Paypal Payflow Advanced Cancel Payment</label>
+        <block type="Mage_Paypal_Block_Payflow_Advanced_Iframe" name="payflow.advanced.iframe" template="payflowadvanced/redirect.phtml" output="1"/>
+    </paypal_payflowadvanced_cancelpayment>
+
+    <paypal_payflowadvanced_returnurl translate="label" type="page" parent="paypal_payflowadvanced_form">
+        <label>Paypal Payflow Advanced Return URL</label>
+        <block type="Mage_Paypal_Block_Payflow_Advanced_Iframe" name="payflow.advanced.iframe" template="payflowadvanced/redirect.phtml" output="1"/>
+    </paypal_payflowadvanced_returnurl>
+
+    <paypal_payflowadvanced_form translate="label" type="page" parent="paypal_payflow_form">
+        <label>Paypal Payflow Advanced Form</label>
+        <block type="Mage_Paypal_Block_Payflow_Advanced_Iframe" name="payflow.advanced.iframe" template="payflowadvanced/form.phtml" output="1"/>
+    </paypal_payflowadvanced_form>
+
+    <paypal_hostedpro_cancel translate="label" type="page" parent="checkout_onepage_paymentmethod">
+        <label>Paypal Hosted Pro Frame</label>
+        <block type="Mage_Paypal_Block_Hosted_Pro_Iframe" name="hosted.pro.iframe" template="hss/redirect.phtml" output="1"/>
+    </paypal_hostedpro_cancel>
+
+    <paypal_standard_redirect translate="label" type="page" parent="checkout_onepage_paymentmethod">
+        <label>Paypal Standard Redirect</label>
+        <block type="Mage_Paypal_Block_Standard_Redirect" name="standard.redirect" output="1"/>
+    </paypal_standard_redirect>
+
+    <SHORTCUT_popup translate="label">
+        <label>Paypal Shortcut Popup</label>
         <reference name="product.tooltip">
-            <block type="Mage_Page_Block_Html_Wrapper" name="product.info.addtocart.paypal.wrapper" translate="label">
+            <container name="product.info.addtocart.paypal.wrapper" label="PayPal Express Checkout Shortcut Wrapper" htmlTag="div">
                 <block type="Mage_Paypal_Block_Express_Shortcut" name="product.info.addtocart.paypal" template="express/shortcut.phtml">
                     <action method="setIsInCatalogProduct"><value>1</value></action>
                     <action method="setShowOrPosition"><value>after</value></action>
                 </block>
-            </block>
+            </container>
         </reference>
     </SHORTCUT_popup>
+
+    <paypal_payflow_form translate="label" type="page" parent="checkout_onepage_paymentmethod">
+        <label>Paypal Payflow Form</label>
+        <block type="Mage_Paypal_Block_Payflow_Link_Iframe" output="1" name="payflow.link.iframe" template="payflowlink/form.phtml" />
+    </paypal_payflow_form>
+
+    <paypal_payflow_cancelpayment translate="label" type="page" parent="paypal_payflow_form">
+        <label>Paypal Payflow Cancel Payment</label>
+        <block type="Mage_Paypal_Block_Payflow_Link_Iframe" output="1" name="payflow.link.iframe" template="payflowlink/redirect.phtml" />
+    </paypal_payflow_cancelpayment>
+
+    <paypal_payflow_returnurl translate="label" type="page" parent="paypal_payflow_form">
+        <label>Paypal Payflow Return URL</label>
+        <block type="Mage_Paypal_Block_Payflow_Link_Iframe" output="1" name="payflow.link.iframe" template="payflowlink/redirect.phtml" />
+    </paypal_payflow_returnurl>
 </layout>
diff --git a/app/code/core/Mage/Paypal/view/frontend/review.js b/app/code/core/Mage/Paypal/view/frontend/review.js
index 2fdf46c3a719a3a770e52fad04b8fda0f3bcf5bb..47168c8b7b4db4f65887623ba9100b1981bdbd1a 100644
--- a/app/code/core/Mage/Paypal/view/frontend/review.js
+++ b/app/code/core/Mage/Paypal/view/frontend/review.js
@@ -31,7 +31,15 @@ OrderReviewController.prototype = {
     _canSubmitOrder : false,
     _pleaseWait : false,
     shippingSelect : false,
+    reloadByShippingSelect : false,
+    _copyElement : false,
     onSubmitShippingSuccess : false,
+    shippingMethodsUpdateUrl : false,
+    _updateShippingMethods: false,
+    _ubpdateOrderButton : false,
+    shippingMethodsContainer: false,
+    _submitUpdateOrderUrl : false,
+    _itemsGrid : false,
 
     /**
      * Add listeners to provided objects, if any
@@ -52,12 +60,27 @@ OrderReviewController.prototype = {
             Event.observe(orderFormSubmit, 'click', this._submitOrder.bind(this));
         }
 
-        if (shippingSubmitForm && shippingSelect) {
-            this.shippingSelect = shippingSelect;
-            Event.observe(shippingSelect, 'change', this._submitShipping.bindAsEventListener(this, shippingSubmitForm.action, shippingResultId));
-            this._updateOrderSubmit(false);
+        if (shippingSubmitForm) {
+            this.reloadByShippingSelect = true;
+            if (shippingSubmitForm && shippingSelect) {
+                this.shippingSelect = shippingSelect;
+                Event.observe(
+                    shippingSelect,
+                    'change',
+                    this._submitShipping.bindAsEventListener(this, shippingSubmitForm.action, shippingResultId)
+                );
+                this._updateOrderSubmit(false);
+            } else {
+                this._canSubmitOrder = true;
+            }
         } else {
-            this._canSubmitOrder = true;
+            Form.getElements(this.form).each(this._bindElementChange, this);
+
+            if (shippingSelect && $(shippingSelect)) {
+                this.shippingSelect = $(shippingSelect).id;
+                this.shippingMethodsContainer = $(this.shippingSelect).up(1);
+            }
+            this._updateOrderSubmit(false);
         }
     },
 
@@ -100,18 +123,257 @@ OrderReviewController.prototype = {
         }
     },
 
+    /**
+     * Set event observer to Update Order button
+     * @param element
+     * @param url - url to submit on Update button
+     * @param resultId - id of element to be updated
+     */
+    setUpdateButton : function(element, url, resultId)
+    {
+        if (element) {
+            this._ubpdateOrderButton = element;
+            this._submitUpdateOrderUrl = url;
+            this._itemsGrid = resultId;
+            Event.observe(element, 'click', this._submitUpdateOrder.bindAsEventListener(this, url, resultId));
+            if(this.shippingSelect) {
+                this._updateShipping();
+            }
+            if (!this._validateForm()) {
+                this._updateOrderSubmit(true);
+            }
+            this.formValidator.reset();
+            this._clearValidation('');
+        }
+    },
+
+    /**
+     * Set event observer to copy data from shipping address to billing
+     * @param element
+     */
+    setCopyElement : function(element)
+    {
+        if (element) {
+            this._copyElement = element;
+            Event.observe(element, 'click', this._copyShippingToBilling.bind(this));
+            this._copyShippingToBilling();
+        }
+    },
+
+    /**
+     * Set observers to Shipping Address elements
+     * @param element Container of Shipping Address elements
+     */
+    setShippingAddressContainer: function(element)
+    {
+        if (element) {
+            Form.getElements(element).each(function(input) {
+                if (input.type.toLowerCase() == 'radio' || input.type.toLowerCase() == 'checkbox') {
+                    Event.observe(input, 'click', this._onShippingChange.bindAsEventListener(this));
+                } else {
+                    Event.observe(input, 'change', this._onShippingChange.bindAsEventListener(this));
+                }
+            }, this);
+        }
+    },
+
+    /**
+     * Copy data from shipping address to billing
+     */
+    _copyShippingToBilling : function ()
+    {
+        if (!this._copyElement) {
+            return;
+        }
+        if (this._copyElement.checked) {
+            $$('[id^="shipping:"]').each(function(el){
+                var newId = el.id.replace('shipping:','billing:');
+                if (newId && $(newId) && $(newId).type != 'hidden') {
+                    $(newId).value = el.value;
+                    $(newId).setAttribute('readonly', 'readonly');
+                    $(newId).addClassName('local-validation');
+                    $(newId).setStyle({opacity:.5});
+                    $(newId).disable();
+                }
+            });
+            this._clearValidation('billing');
+        } else {
+            $$('[id^="billing:"]').invoke('enable');
+            $$('[id^="billing:"]').invoke('removeAttribute', 'readonly');
+            $$('[id^="billing:"]').invoke('removeClassName', 'local-validation');
+            $$('[id^="billing:"]').invoke('setStyle', {opacity:1});
+        }
+        this._updateOrderSubmit(true);
+    },
+
+    /**
+     * Dispatch an ajax request of Update Order submission
+     * @param url - url where to submit shipping method
+     * @param resultId - id of element to be updated
+     */
+    _submitUpdateOrder : function(event, url, resultId)
+    {
+        this._copyShippingToBilling();
+        if (url && resultId && this._validateForm()) {
+            if (this._copyElement && this._copyElement.checked) {
+                this._clearValidation('billing');
+            }
+            this._updateOrderSubmit(true);
+            if (this._pleaseWait) {
+                this._pleaseWait.show();
+            }
+
+            arr = $$('[id^="billing:"]').invoke('enable');
+            var formData = this.form.serialize(true);
+            if (this._copyElement.checked) {
+                $$('[id^="billing:"]').invoke('disable');
+                this._copyElement.enable();
+            }
+            formData.isAjax = true;
+            new Ajax.Updater(resultId, url, {
+                parameters: formData,
+                onComplete: function() {
+                    if (this._pleaseWait && !this._updateShippingMethods) {
+                        this._pleaseWait.hide();
+                    }
+                }.bind(this),
+                onSuccess: this._updateShippingMethodsElement.bind(this),
+                evalScripts: true
+            });
+        } else {
+            if (this._copyElement && this._copyElement.checked) {
+                this._clearValidation('billing');
+            }
+        }
+    },
+
+    /**
+     * Update Shipping Methods Element from server
+     */
+    _updateShippingMethodsElement : function (){
+        if (this._updateShippingMethods) {
+            new Ajax.Updater(this.shippingMethodsContainer, this.shippingMethodsUpdateUrl, {
+                onComplete: this._updateShipping.bind(this),
+                onSuccess: this._onSubmitShippingSuccess.bind(this),
+                evalScripts: false
+            });
+        } else {
+            this._onSubmitShippingSuccess();
+        }
+    },
+
+    /**
+     * Update Shipping Method select element and bind events
+     */
+    _updateShipping : function () {
+        if ($(this.shippingSelect)) {
+            $(this.shippingSelect).enable();
+            Event.stopObserving($(this.shippingSelect), 'change');
+
+            this._bindElementChange($(this.shippingSelect));
+            Event.observe(
+                $(this.shippingSelect),
+                'change',
+                this._submitUpdateOrder.bindAsEventListener(this, this._submitUpdateOrderUrl, this._itemsGrid)
+            );
+
+            $(this.shippingSelect + '_update').hide();
+            $(this.shippingSelect).show();
+        }
+        this._updateShippingMethods = false;
+        if (this._pleaseWait) {
+            this._pleaseWait.hide();
+        }
+    },
+
+    /**
+     * Validate Order form
+     */
+    _validateForm : function()
+    {
+        if (!this.form) {
+            return false;
+        }
+        if (!this.formValidator) {
+            this.formValidator = new Validation(this.form);
+        }
+
+        return this.formValidator.validate();
+    },
+
+    /**
+     * Actions on change Shipping Address data
+     * @param event
+     */
+    _onShippingChange : function(event){
+        var element = Event.element(event);
+        if (element != $(this.shippingSelect) && !$(this.shippingSelect).disabled) {
+            $(this.shippingSelect).disable();
+            $(this.shippingSelect).hide();
+            if ($('advice-required-entry-' + this.shippingSelect)) {
+                $('advice-required-entry-' + this.shippingSelect).hide();
+            }
+            $(this.shippingSelect + '_update').show();
+            this._updateShippingMethods = true;
+        }
+    },
+
+    /**
+     * Bind onChange event listener to elements for update Submit Order button state
+     * @param input
+     */
+    _bindElementChange : function(input){
+        Event.observe(input, 'change', this._onElementChange.bindAsEventListener(this))
+    },
+
+    /**
+     * Disable Submit Order button
+     */
+    _onElementChange : function(){
+        this._updateOrderSubmit(true);
+    },
+
+    /**
+     * Clear validation result for all form elements or for elements with id prefix
+     * @param idprefix
+     */
+    _clearValidation : function(idprefix)
+    {
+        var prefix = '';
+        if (idprefix) {
+            prefix = '[id*="' + idprefix + ':"]';
+            $$(prefix).each(function(el){
+                el.up().removeClassName('validation-failed')
+                    .removeClassName('validation-passed')
+                    .removeClassName('validation-error');
+            });
+        } else {
+            this.formValidator.reset();
+        }
+        $$('.validation-advice' + prefix).invoke('remove');
+        $$('.validation-failed' + prefix).invoke('removeClassName', 'validation-failed');
+        $$('.validation-passed' + prefix).invoke('removeClassName', 'validation-passed');
+        $$('.validation-error' + prefix).invoke('removeClassName', 'validation-error');
+    },
+
     /**
      * Attempt to submit order
      */
     _submitOrder : function()
     {
-        if (this._canSubmitOrder) {
+        if (this._canSubmitOrder && (this.reloadByShippingSelect || this._validateForm())) {
             this.form.submit();
             this._updateOrderSubmit(true);
+            if (this._ubpdateOrderButton) {
+                this._ubpdateOrderButton.addClassName('no-checkout');
+                this._ubpdateOrderButton.setStyle({opacity:.5});
+            }
             if (this._pleaseWait) {
                 this._pleaseWait.show();
             }
+            return;
         }
+        this._updateOrderSubmit(true);
     },
 
     /**
@@ -132,7 +394,9 @@ OrderReviewController.prototype = {
      */
     _updateOrderSubmit : function(shouldDisable)
     {
-        var isDisabled = shouldDisable || !this.shippingSelect || '' == this.shippingSelect.value;
+        var isDisabled = shouldDisable || (
+            this.reloadByShippingSelect && (!this.shippingSelect || '' == this.shippingSelect.value)
+        );
         this._canSubmitOrder = !isDisabled;
         if (this.formSubmit) {
             this.formSubmit.disabled = isDisabled;
diff --git a/app/code/core/Mage/PaypalUk/Block/Express/Shortcut.php b/app/code/core/Mage/PaypalUk/Block/Express/Shortcut.php
index fef56af7d571f008b81b160378e220bf67497b33..f56021c2810980ea4485fec2e017347eb588f447 100644
--- a/app/code/core/Mage/PaypalUk/Block/Express/Shortcut.php
+++ b/app/code/core/Mage/PaypalUk/Block/Express/Shortcut.php
@@ -48,5 +48,5 @@ class Mage_PaypalUk_Block_Express_Shortcut extends Mage_Paypal_Block_Express_Sho
      *
      * @var string
      */
-    protected $_checkoutType = 'paypaluk/express_checkout';
+    protected $_checkoutType = 'Mage_PaypalUk_Model_Express_Checkout';
 }
diff --git a/app/code/core/Mage/PaypalUk/Model/Express/Checkout.php b/app/code/core/Mage/PaypalUk/Model/Express/Checkout.php
index e06cdca4523a378814d0e4cbc94945496e4eb32d..795160ffa52493a72708fe1be7009dca1b150d82 100644
--- a/app/code/core/Mage/PaypalUk/Model/Express/Checkout.php
+++ b/app/code/core/Mage/PaypalUk/Model/Express/Checkout.php
@@ -35,7 +35,7 @@ class Mage_PaypalUk_Model_Express_Checkout extends Mage_Paypal_Model_Express_Che
      *
      * @var string
      */
-    protected $_apiType = 'paypaluk/api_nvp';
+    protected $_apiType = 'Mage_PaypalUk_Model_Api_Nvp';
 
     /**
      * Payment method tpye
@@ -43,4 +43,13 @@ class Mage_PaypalUk_Model_Express_Checkout extends Mage_Paypal_Model_Express_Che
      */
     protected $_methodType = Mage_Paypal_Model_Config::METHOD_WPP_PE_EXPRESS;
 
+    /**
+     * Set shipping method to quote, if needed
+     * @param string $methodCode
+     */
+    public function updateShippingMethod($methodCode)
+    {
+        parent::updateShippingMethod($methodCode);
+        $this->_quote->save();
+    }
 }
diff --git a/app/code/core/Mage/PaypalUk/Model/Pro.php b/app/code/core/Mage/PaypalUk/Model/Pro.php
index bfd680eec04a4c6a41870cdefc24e20d5ce3b036..9a12bfe891abac1bde0763a58dcf76e23d65cb54 100644
--- a/app/code/core/Mage/PaypalUk/Model/Pro.php
+++ b/app/code/core/Mage/PaypalUk/Model/Pro.php
@@ -36,7 +36,7 @@ class Mage_PaypalUk_Model_Pro extends Mage_Paypal_Model_Pro
      *
      * @var string
      */
-    protected $_apiType = 'paypaluk/api_nvp';
+    protected $_apiType = 'Mage_PaypalUk_Model_Api_Nvp';
 
     /**
      * Config model type
diff --git a/app/code/core/Mage/PaypalUk/controllers/ExpressController.php b/app/code/core/Mage/PaypalUk/controllers/ExpressController.php
index 5bd8dc644ecccd00afdad590bf4b86b79c691b84..976d45418869e919d3d5b67f1e13620947e670e0 100644
--- a/app/code/core/Mage/PaypalUk/controllers/ExpressController.php
+++ b/app/code/core/Mage/PaypalUk/controllers/ExpressController.php
@@ -49,5 +49,5 @@ class Mage_PaypalUk_ExpressController extends Mage_Paypal_Controller_Express_Abs
      *
      * @var string
      */
-    protected $_checkoutType = 'paypaluk/express_checkout';
+    protected $_checkoutType = 'Mage_PaypalUk_Model_Express_Checkout';
 }
diff --git a/app/code/core/Mage/PaypalUk/view/frontend/express/review.phtml b/app/code/core/Mage/PaypalUk/view/frontend/express/review.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..4013b8984d7f95553a2d434c78d646105715648e
--- /dev/null
+++ b/app/code/core/Mage/PaypalUk/view/frontend/express/review.phtml
@@ -0,0 +1,191 @@
+<?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     base_default
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+/** @var $this Mage_Paypal_Block_Express_Review */
+?>
+<div class="page-title">
+    <h1><?php echo $this->__('Review Order') ?></h1>
+</div>
+<?php echo $this->getMessagesBlock()->toHtml() ?>
+
+<?php if ($this->getShippingAddress()): ?>
+<div class="info-set col2-set">
+    <h2 class="legend"><?php echo $this->__('Shipping Information') ?></h2>
+    <div class="col-1">
+        <div class="box">
+            <div class="box-title">
+                <h3><?php echo $this->__('Shipping Address') ?><span class="separator"><?php if ($this->getCanEditShippingAddress()):?> | </span><a href="<?php echo $this->getEditUrl() ?>"><?php echo $this->__('Change Shipping Address') ?></a><?php endif;?></h3>
+            </div>
+            <div class="box-content">
+                <address><?php echo $this->renderAddress($this->getShippingAddress())?></address>
+            </div>
+        </div>
+    </div>
+    <div class="col-2">
+        <div class="box">
+            <div class="box-title">
+                <h3><?php echo $this->__('Shipping Method') ?></h3>
+            </div>
+            <div class="box-content">
+                <form method="post" id="shipping_method_form" action="<?php echo $this->escapeHtml($this->getShippingMethodSubmitUrl()) ?>">
+                <?php if ($this->getCanEditShippingMethod() || !$this->getCurrentShippingRate()):?>
+                    <?php if ($groups = $this->getShippingRateGroups()):?>
+                        <?php $currentRate = $this->getCurrentShippingRate(); ?>
+                            <fieldset>
+                                <select name="shipping_method" id="shipping_method" style="width:250px;" class="required-entry">
+                                <?php if (!$currentRate):?>
+                                    <option value=""><?php echo $this->__('Please select a shipping method...') ?></option>
+                                <?php endif;?>
+                                <?php foreach ($groups as $code => $rates):?>
+                                    <optgroup label="<?php echo $this->getCarrierName($code) ?>" style="font-style:normal;">
+                                    <?php foreach ($rates as $rate):?>
+                                        <option value="<?php echo $this->renderShippingRateValue($rate)?>"<?php echo ($currentRate === $rate) ? ' selected="selected"' : '' ;?>>
+                                            <?php echo $this->renderShippingRateOption($rate)?>
+                                        </option>
+                                    <?php endforeach;?>
+                                    </optgroup>
+                                <?php endforeach;?>
+                                </select>
+                            </fieldset>
+                            <p class="actions">
+                                <button id="update_shipping_method_submit" type="submit" class="button"><span><span><?php echo $this->__('Update Shipping Method') ?></span></span></button>
+                            </p>
+                    <?php else: ?>
+                        <p><strong><?php echo $this->__('Sorry, no quotes are available for this order at this time.') ?></strong></p>
+                    <?php endif;?>
+                <?php else: ?>
+                    <p><strong><?php echo $this->renderShippingRateOption($this->getCurrentShippingRate())?></strong></p>
+                <?php endif; ?>
+                </form>
+            </div>
+        </div>
+    </div>
+</div>
+<?php endif; ?>
+
+<div class="info-set col2-set">
+    <h2 class="legend"><?php echo $this->__('Billing Information') ?></h2>
+    <div class="col-1">
+        <div class="box">
+            <div class="box-title">
+                <h3><?php echo $this->__('Payment Method') ?> <span class="separator">|</span>
+                    <?php if($this->getEditUrl()):?><a href="<?php echo $this->getEditUrl() ?>"><?php echo $this->__('Change Payment Method') ?></a> <?php endif ?>
+                </h3>
+            </div>
+            <div class="box-content">
+                <?php echo $this->escapeHtml($this->getPaymentMethodTitle()) ?>
+            </div>
+        </div>
+    </div>
+    <div class="col-2">
+        <div class="box">
+            <div class="box-title">
+                <h3><?php echo $this->__('Billing Address') ?></h3>
+            </div>
+            <div class="box-content">
+                <address>
+                    <?php echo $this->renderAddress($this->getBillingAddress()) ?><br />
+                    <?php echo $this->__('Payer Email: %s', $this->getBillingAddress()->getEmail()) ?>
+                </address>
+            </div>
+        </div>
+    </div>
+</div>
+
+<div class="info-set">
+    <h2 class="legend"><?php echo $this->__('Items in Your Shopping Cart') ?><span class="separator"> | </span><a href="<?php echo $this->getUrl('checkout/cart') ?>"><?php echo $this->__('Edit Shopping Cart') ?></a></h2>
+    <div id="details-reload">
+        <?php echo $this->getChildHtml('details') ?>
+    </div>
+</div>
+<form method="post" id="order_review_form" action="<?php echo $this->getPlaceOrderUrl() ?>">
+    <?php echo $this->getChildHtml('agreements'); ?>
+    <div class="buttons-set buttons-set-order" id="review-buttons-container">
+        <button type="button" id="review_button" value="<?php echo $this->__('Place Order') ?>" class="button btn-checkout"><span><span><?php echo $this->__('Place Order') ?></span></span></button>
+        <button type="button" id="review_submit" value="<?php echo $this->__('Place Order') ?>" class="button btn-checkout"><span><span><?php echo $this->__('Place Order') ?></span></span></button>
+        <span class="please-wait" id="review-please-wait" style="display:none;">
+            <img src="<?php echo $this->getSkinUrl('images/opc-ajax-loader.gif') ?>" alt="<?php echo $this->__('Submitting order information...') ?>" title="<?php echo $this->__('Submitting order information...') ?>" class="v-middle" /> <?php echo $this->__('Submitting order information...') ?>
+        </span>
+    </div>
+</form>
+<script type="text/javascript">
+//<![CDATA[
+// submit buttons are not needed when submitting with ajax
+$('review_submit').hide();
+if ($('update_shipping_method_submit')) {
+    $('update_shipping_method_submit').hide();
+}
+
+<?php if ($this->getUseAjax()):?>
+    OrderReviewController.prototype._submitOrder = function() {
+        if (this._canSubmitOrder) {
+            if (this._pleaseWait) {
+                this._pleaseWait.show();
+            }
+            new Ajax.Request(this.form.action, {
+                parameters: {isAjax: 1, method: 'POST'},
+                onSuccess: function(transport) {
+                    try{
+                        response = eval('(' + transport.responseText + ')');
+                    } catch (e) {
+                        response = {};
+                    }
+                    if (response.redirect) {
+                        setLocation(response.redirect);
+                        return;
+                    }
+                    if (response.success) {
+                        setLocation('<?php echo $this->getSuccessUrl()?>');
+                        return;
+                    } else {
+                        var msg = response.error_messages;
+                        if (typeof(msg)=='object') {
+                            msg = msg.join("\n");
+                        }
+                        if (msg) {
+                            $('review-please-wait').hide();
+                            alert(msg);
+                            return;
+                        }
+                    }
+                    $('review-please-wait').hide();
+                    alert('<?php echo $this->jsQuoteEscape($this->__('Unknown Error. Please try again later.')); ?>');
+                    return;
+                },
+                onFailure: function(){
+                    alert('<?php echo $this->jsQuoteEscape($this->__('Server Error. Please try again.')) ?>');
+                    $('review-please-wait').hide();
+                }
+            });
+        }
+    }
+<?php endif ?>
+
+PayPalExpressAjax = new OrderReviewController($('order_review_form'), $('review_button'),
+    $('shipping_method'), $('shipping_method_form'), 'details-reload'
+);
+PayPalExpressAjax.addPleaseWait($('review-please-wait'));
+//]]>
+</script>
diff --git a/app/code/core/Mage/PaypalUk/view/frontend/layout.xml b/app/code/core/Mage/PaypalUk/view/frontend/layout.xml
index 8fa647dc79e828b2d0a8c4088acdf02e97db83a8..c7f7a96cd18684f811f44ee800ca0b979b2eb96c 100644
--- a/app/code/core/Mage/PaypalUk/view/frontend/layout.xml
+++ b/app/code/core/Mage/PaypalUk/view/frontend/layout.xml
@@ -42,7 +42,7 @@
         <update handle="SHORTCUT_uk_popup" />
     </checkout_cart_index>
 
-    <paypaluk_express_review translate="label" module="Mage_PaypalUk">
+    <paypaluk_express_review translate="label" module="Mage_PaypalUk" type="page" parent="default">
         <label>PayPal Express Order Review Form</label>
         <remove name="right"/>
         <remove name="left"/>
@@ -51,7 +51,7 @@
             <action method="setTemplate"><template>1column.phtml</template></action>
         </reference>
         <reference name="content">
-            <block type="Mage_Paypal_Block_Express_Review" name="paypal.express.review" template="express/review.phtml">
+            <block type="Mage_Paypal_Block_Express_Review" name="paypal.express.review" template="Mage_PaypalUk::express/review.phtml">
                 <action method="setPaypalActionPrefix"><prefix>paypaluk</prefix></action>
                 <block type="Mage_Paypal_Block_Express_Review_Details" name="paypal.express.review.details" as="details" template="express/review/details.phtml">
                     <action method="addItemRender"><type>default</type><block>Mage_Checkout_Block_Cart_Item_Renderer</block><template>onepage/review/item.phtml</template></action>
@@ -68,7 +68,7 @@
     </paypaluk_express_review>
 
     <paypal_express_review_details>
-        <block type="Mage_Paypal_Block_Express_Review_Details" name="root" output="toHtml" template="express/review/details.phtml">
+        <block type="Mage_Paypal_Block_Express_Review_Details" name="root" output="1" template="express/review/details.phtml">
             <action method="addItemRender"><type>default</type><block>Mage_Checkout_Block_Cart_Item_Renderer</block><template>onepage/review/item.phtml</template></action>
             <action method="addItemRender"><type>grouped</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Grouped</block><template>onepage/review/item.phtml</template></action>
             <action method="addItemRender"><type>configurable</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Configurable</block><template>onepage/review/item.phtml</template></action>
@@ -78,14 +78,11 @@
 
     <catalog_product_view>
         <reference name="product.info.addtocart">
-            <block type="Mage_Page_Block_Html_Wrapper" name="product.info.addtocart.paypaluk.wrapper" translate="label">
-                <label>PayPal Express Checkout (Payflow Edition) Shortcut Wrapper</label>
-                <action method="setHtmlTagName"><tag>p</tag></action>
-                <action method="setElementClass"><class>paypal-logo</class></action>
+            <container name="product.info.addtocart.paypaluk.wrapper" label="PayPal Express Checkout (Payflow Edition) Shortcut Wrapper" htmlTag="p" htmlClass="paypal-logo">
                 <block type="Mage_PaypalUk_Block_Express_Shortcut" name="product.info.addtocart.paypaluk" template="Mage_Paypal::express/shortcut.phtml">
                     <action method="setIsInCatalogProduct"><value>1</value></action>
                 </block>
-            </block>
+            </container>
         </reference>
         <update handle="SHORTCUT_uk_popup" />
     </catalog_product_view>
@@ -99,13 +96,9 @@
         </reference>
     </default>
 
-    <catalog_category_default>
-        <update handle="SHORTCUT_uk_popup" />
-    </catalog_category_default>
-
-    <catalog_category_layered>
+    <catalog_category_view>
         <update handle="SHORTCUT_uk_popup" />
-    </catalog_category_layered>
+    </catalog_category_view>
 
     <catalog_product_compare_index>
         <update handle="SHORTCUT_uk_popup" />
@@ -141,14 +134,19 @@
         <update handle="SHORTCUT_uk_popup" />
     </checkout_onepage_failure>
 
-    <SHORTCUT_uk_popup>
+    <SHORTCUT_uk_popup translate="label">
+        <label>PaypalUk Shortcut Popup</label>
         <reference name="product.tooltip">
-            <block type="Mage_Page_Block_Html_Wrapper" name="product.info.addtocart.paypaluk.wrapper" translate="label">
+            <container name="product.info.addtocart.paypaluk.wrapper" label="PayPal Express Checkout (Payflow Edition) Shortcut Wrapper" htmlTag="div">
                 <block type="Mage_PaypalUk_Block_Express_Shortcut" name="product.info.addtocart.paypaluk" template="Mage_Paypal::express/shortcut.phtml">
                     <action method="setIsInCatalogProduct"><value>1</value></action>
                     <action method="setShowOrPosition"><value>after</value></action>
                 </block>
-            </block>
+            </container>
         </reference>
     </SHORTCUT_uk_popup>
+
+    <paypaluk_express_review_details translate="label" type="page" parent="checkout_onepage_review">
+        <label>Paypal UK Express Review Details</label>
+    </paypaluk_express_review_details>
 </layout>
diff --git a/app/code/core/Mage/Persistent/Helper/Data.php b/app/code/core/Mage/Persistent/Helper/Data.php
index 2ddb5e92feac88583ec746e1fe45667e969ad938..8296e5662eca9152a6ae822f595e6bfdba76ff3a 100644
--- a/app/code/core/Mage/Persistent/Helper/Data.php
+++ b/app/code/core/Mage/Persistent/Helper/Data.php
@@ -41,9 +41,6 @@ class Mage_Persistent_Helper_Data extends Mage_Core_Helper_Data
     const XML_PATH_REMEMBER_ME_DEFAULT = 'persistent/options/remember_default';
     const XML_PATH_PERSIST_SHOPPING_CART = 'persistent/options/shopping_cart';
 
-    const LOGGED_IN_LAYOUT_HANDLE = 'customer_logged_in_psc_handle';
-    const LOGGED_OUT_LAYOUT_HANDLE = 'customer_logged_out_psc_handle';
-
     /**
      * Name of config file
      *
diff --git a/app/code/core/Mage/Persistent/Model/Observer.php b/app/code/core/Mage/Persistent/Model/Observer.php
index 75d7ff2068deca717d396351d0f2b12699797ae4..ee7d5452061fd95d592dd257246e31aa4171a4fd 100644
--- a/app/code/core/Mage/Persistent/Model/Observer.php
+++ b/app/code/core/Mage/Persistent/Model/Observer.php
@@ -111,11 +111,10 @@ class Mage_Persistent_Model_Observer
             null
         );
 
-        $block->setWelcome(Mage::helper('Mage_Persistent_Helper_Data')->__('Welcome, %s!', $escapedName));
-
         $this->_applyAccountLinksPersistentData();
-        $block->setAdditionalHtml(Mage::app()->getLayout()->getBlock('header.additional')->toHtml());
-
+        $welcomeMessage = Mage::helper('Mage_Persistent_Helper_Data')->__('Welcome, %s!', $escapedName)
+            . ' ' . Mage::app()->getLayout()->getBlock('header.additional')->toHtml();
+        $block->setWelcome($welcomeMessage);
         return $this;
     }
 
@@ -129,29 +128,6 @@ class Mage_Persistent_Model_Observer
         }
     }
 
-    /**
-     * Emulate 'account links' block with persistent data
-     *
-     * @param Mage_Core_Block_Abstract $block
-     */
-    public function emulateAccountLinks($block)
-    {
-        $this->_applyAccountLinksPersistentData();
-        $block->getCacheKeyInfo();
-        $helper = Mage::helper('Mage_Persistent_Helper_Data');
-        $block->addLink(
-            $helper->getPersistentName(),
-            $helper->getUnsetCookieUrl(),
-            $helper->getPersistentName(),
-            false,
-            array(),
-            110
-        );
-        $customerHelper = Mage::helper('Mage_Customer_Helper_Data');
-        $block->removeLinkByUrl($customerHelper->getRegisterUrl());
-        $block->removeLinkByUrl($customerHelper->getLoginUrl());
-    }
-
     /**
      * Emulate 'top links' block with persistent data
      *
@@ -546,27 +522,6 @@ class Mage_Persistent_Model_Observer
         return $this;
     }
 
-    /**
-     * Create handle for persistent session if persistent cookie and customer not logged in
-     *
-     * @param Varien_Event_Observer $observer
-     */
-    public function createPersistentHandleLayout(Varien_Event_Observer $observer)
-    {
-        /** @var $layout Mage_Core_Model_Layout */
-        $layout = $observer->getEvent()->getLayout();
-        $helper = Mage::helper('Mage_Persistent_Helper_Data');
-        if ($helper->canProcess($observer)
-            && $layout && $helper->isEnabled()
-            && Mage::helper('Mage_Persistent_Helper_Session')->isPersistent()
-        ) {
-            $handle = (Mage::getSingleton('Mage_Customer_Model_Session')->isLoggedIn())
-                ? Mage_Persistent_Helper_Data::LOGGED_IN_LAYOUT_HANDLE
-                : Mage_Persistent_Helper_Data::LOGGED_OUT_LAYOUT_HANDLE;
-            $layout->getUpdate()->addHandle($handle);
-        }
-    }
-
     /**
      * Update customer id and customer group id if user is in persistent session
      *
diff --git a/app/code/core/Mage/Persistent/Model/Resource/Session.php b/app/code/core/Mage/Persistent/Model/Resource/Session.php
index d308fb83f4437b3013df953406ca2120604e036f..afe9e3c1caa21eeaf9512721e71c0f1dfb760d1e 100644
--- a/app/code/core/Mage/Persistent/Model/Resource/Session.php
+++ b/app/code/core/Mage/Persistent/Model/Resource/Session.php
@@ -61,10 +61,10 @@ class Mage_Persistent_Model_Resource_Session extends Mage_Core_Model_Resource_Db
     {
         $select = parent::_getLoadSelect($field, $value, $object);
         if (!$object->getLoadExpired()) {
-            $select->join(
-                array('customer' => $this->getTable('customer_entity')),
-                'customer.entity_id = persistent_session.customer_id'
-            )->where('persistent_session.updated_at >= ?', $object->getExpiredBefore());
+            $tableName = $this->getMainTable();
+            $select->join(array('customer' => $this->getTable('customer_entity')),
+                'customer.entity_id = ' . $tableName . '.customer_id'
+            )->where($tableName . '.updated_at >= ?', $object->getExpiredBefore());
         }
 
         return $select;
diff --git a/app/code/core/Mage/Persistent/etc/config.xml b/app/code/core/Mage/Persistent/etc/config.xml
index 99392349cf7a047797299f24f045efe9080a89a4..535ab2fbac89ac8cd1ff65a58403851be90d6a14 100644
--- a/app/code/core/Mage/Persistent/etc/config.xml
+++ b/app/code/core/Mage/Persistent/etc/config.xml
@@ -85,14 +85,6 @@
                     </persistent>
                 </observers>
             </controller_front_send_response_after>
-            <controller_action_layout_load_before>
-                <observers>
-                    <persistent>
-                        <class>Mage_Persistent_Model_Observer</class>
-                        <method>createPersistentHandleLayout</method>
-                    </persistent>
-                </observers>
-            </controller_action_layout_load_before>
             <controller_action_predispatch_customer_account_loginPost>
                 <observers>
                     <persistent>
diff --git a/app/code/core/Mage/Persistent/etc/persistent.xml b/app/code/core/Mage/Persistent/etc/persistent.xml
index 60846b683fe23ce34c35694f6d807b28f1c1b446..d94fdc245c30a5dc5bd931f14be69e5c4b2e863b 100644
--- a/app/code/core/Mage/Persistent/etc/persistent.xml
+++ b/app/code/core/Mage/Persistent/etc/persistent.xml
@@ -34,12 +34,6 @@
                 <method>emulateWelcomeBlock</method>
                 <block_type>Mage_Page_Block_Html_Header</block_type>
             </welcome>
-            <account_links>
-                <name_in_layout>account.links</name_in_layout>
-                <class>Mage_Persistent_Model_Observer</class>
-                <method>emulateAccountLinks</method>
-                <block_type>Mage_Page_Block_Template_Links</block_type>
-            </account_links>
             <top_links>
                 <name_in_layout>top.links</name_in_layout>
                 <class>Mage_Persistent_Model_Observer</class>
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 7094709660cb28066e6aa1433b1989c69414d723..f2f2e655144bec8a4ac5de638a1f5eef53c79c14 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
@@ -60,7 +60,7 @@
                 <li class="wide">
                     <label for="billing:street1" class="required"><em>*</em><?php echo $this->__('Address') ?></label>
                     <div class="input-box">
-                        <input type="text" title="<?php echo $this->__('Street Address') ?>" name="billing[street][]" id="billing:street1" value="<?php echo $this->escapeHtml($this->getAddress()->getStreet(1)) ?>" class="input-text required-entry" />
+                        <input type="text" title="<?php echo $this->__('Street Address') ?>" name="billing[street][]" id="billing:street1" value="<?php echo $this->escapeHtml($this->getAddress()->getStreet(1)) ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('street') ?>" />
                     </div>
                 </li>
         <?php for ($_i=2, $_n=$this->helper('Mage_Customer_Helper_Address')->getStreetLines(); $_i<=$_n; $_i++): ?>
@@ -73,14 +73,14 @@
                 <li class="wide">
                     <label for="billing:vat_id"><?php echo $this->__('VAT Number') ?></label>
                     <div class="input-box">
-                        <input type="text" id="billing:vat_id" name="billing[vat_id]" value="<?php echo $this->escapeHtml($this->getAddress()->getVatId()) ?>" title="<?php echo $this->__('VAT Number') ?>" class="input-text" />
+                        <input type="text" id="billing:vat_id" name="billing[vat_id]" value="<?php echo $this->escapeHtml($this->getAddress()->getVatId()) ?>" title="<?php echo $this->__('VAT Number') ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('vat_id') ?>" />
                     </div>
                 </li>
                 <li class="fields">
                     <div class="field">
                         <label for="billing:city" class="required"><em>*</em><?php echo $this->__('City') ?></label>
                         <div class="input-box">
-                            <input type="text" title="<?php echo $this->__('City') ?>" name="billing[city]" value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>" class="input-text required-entry" id="billing:city" />
+                            <input type="text" title="<?php echo $this->__('City') ?>" name="billing[city]" value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('city') ?>" id="billing:city" />
                         </div>
                     </div>
                     <div class="field">
@@ -94,7 +94,7 @@
                                 $('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" style="display:none;" />
+                            <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>
                 </li>
@@ -102,7 +102,7 @@
                     <div class="field">
                         <label for="billing:postcode" class="required"><em>*</em><?php echo $this->__('Zip/Postal Code') ?></label>
                         <div class="input-box">
-                            <input type="text" title="<?php echo $this->__('Zip/Postal Code') ?>" name="billing[postcode]" id="billing:postcode" value="<?php echo $this->escapeHtml($this->getAddress()->getPostcode()) ?>" class="input-text validate-zip-international required-entry" />
+                            <input type="text" title="<?php echo $this->__('Zip/Postal Code') ?>" name="billing[postcode]" id="billing:postcode" value="<?php echo $this->escapeHtml($this->getAddress()->getPostcode()) ?>" class="input-text validate-zip-international <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('postcode') ?>" />
                         </div>
                     </div>
                     <div class="field">
@@ -116,13 +116,13 @@
                     <div class="field">
                         <label for="billing:telephone" class="required"><em>*</em><?php echo $this->__('Telephone') ?></label>
                         <div class="input-box">
-                            <input type="text" name="billing[telephone]" value="<?php echo $this->escapeHtml($this->getAddress()->getTelephone()) ?>" title="<?php echo $this->__('Telephone') ?>" class="input-text required-entry" id="billing:telephone" />
+                            <input type="text" name="billing[telephone]" value="<?php echo $this->escapeHtml($this->getAddress()->getTelephone()) ?>" title="<?php echo $this->__('Telephone') ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('telephone') ?>" id="billing:telephone" />
                         </div>
                     </div>
                     <div class="field">
                         <label for="billing:fax"><?php echo $this->__('Fax') ?></label>
                         <div class="input-box">
-                            <input type="text" name="billing[fax]" value="<?php echo $this->escapeHtml($this->getAddress()->getFax()) ?>" title="<?php echo $this->__('Fax') ?>" class="input-text" id="billing:fax" />
+                            <input type="text" name="billing[fax]" value="<?php echo $this->escapeHtml($this->getAddress()->getFax()) ?>" title="<?php echo $this->__('Fax') ?>" class="input-text <?php echo $this->helper('Mage_Customer_Helper_Address')->getAttributeValidationClass('fax') ?>" id="billing:fax" />
                         </div>
                     </div>
                 </li>
diff --git a/app/code/core/Mage/Persistent/view/frontend/layout.xml b/app/code/core/Mage/Persistent/view/frontend/layout.xml
index c326592c90c49692f6cec4358f98a031f3c8abac..35aaafba99cd5aa93f133bd685e2194c1b141e29 100644
--- a/app/code/core/Mage/Persistent/view/frontend/layout.xml
+++ b/app/code/core/Mage/Persistent/view/frontend/layout.xml
@@ -27,6 +27,7 @@
 
 -->
 <layout version="0.1.0">
+
     <customer_account_login>
         <reference name="customer_form_login">
             <action method="setTemplate"><template>Mage_Persistent::customer/form/login.phtml</template></action>
@@ -54,9 +55,4 @@
             <block type="Mage_Core_Block_Template" name="persistent.remember.me.tooltip" template="Mage_Persistent::remember_me_tooltip.phtml" />
         </reference>
     </checkout_onepage_index>
-    <customer_logged_out>
-        <reference name="right">
-            <block type="Mage_Sales_Block_Reorder_Sidebar" name="sale.reorder.sidebar" as="reorder" template="reorder/sidebar.phtml"/>
-        </reference>
-    </customer_logged_out>
 </layout>
diff --git a/app/code/core/Mage/Persistent/view/frontend/remember_me.phtml b/app/code/core/Mage/Persistent/view/frontend/remember_me.phtml
index 9b821229c55f9c61c38bb32211749ad6db94548f..eb260574f61ac11a9c0225de4e8848751acda71c 100644
--- a/app/code/core/Mage/Persistent/view/frontend/remember_me.phtml
+++ b/app/code/core/Mage/Persistent/view/frontend/remember_me.phtml
@@ -31,11 +31,11 @@
  */
 /** @var $this Mage_Persistent_Block_Form_Remember */
 ?>
-<li>
-    <div id="remember-me-box" class="input-box remember-me">
-        <?php $rememberMeId = 'remember_me' . Mage::helper('Mage_Core_Helper_Data')->getRandomString(10); ?>
-        <input type="checkbox" name="persistent_remember_me" class="input-checkbox" id="<?php echo $rememberMeId; ?>"<?php if ($this->isRememberMeChecked()): ?> checked="checked"<?php endif; ?> title="<?php echo $this->__('Remember Me') ?>" />
-        <label for="<?php echo $rememberMeId; ?>"><?php echo $this->__('Remember Me') ?></label>
-        <a href="#"><?php echo $this->__('What\'s this?') ?></a>
+<li id="remember-me-box" class="control">
+    <?php $rememberMeId = 'remember_me' . Mage::helper('Mage_Core_Helper_Data')->getRandomString(10); ?>
+    <div class="input-box">
+        <input type="checkbox" name="persistent_remember_me" class="checkbox" id="<?php echo $rememberMeId; ?>"<?php if ($this->isRememberMeChecked()): ?> checked="checked"<?php endif; ?> title="<?php echo $this->__('Remember Me') ?>" />
     </div>
+    <label for="<?php echo $rememberMeId; ?>"><?php echo $this->__('Remember Me') ?></label>
+    <a class="link-tip" href="#"><?php echo $this->__('What\'s this?') ?></a>
 </li>
diff --git a/app/code/core/Mage/Poll/Block/ActivePoll.php b/app/code/core/Mage/Poll/Block/ActivePoll.php
index 40937c32ecd3b6a3df74db46411fb4fe31473551..b23f571043a32488c3fa396f47f030ba5961a887 100755
--- a/app/code/core/Mage/Poll/Block/ActivePoll.php
+++ b/app/code/core/Mage/Poll/Block/ActivePoll.php
@@ -204,13 +204,20 @@ class Mage_Poll_Block_ActivePoll extends Mage_Core_Block_Template
      */
     protected function _toHtml()
     {
+        /** @var $coreSessionModel Mage_Core_Model_Session */
+        $coreSessionModel = Mage::getSingleton('Mage_Core_Model_Session');
+        $justVotedPollId = $coreSessionModel->getJustVotedPoll();
+        if ($justVotedPollId && !$this->_pollModel->isVoted($justVotedPollId)) {
+            $this->_pollModel->setVoted($justVotedPollId);
+        }
+
         $pollId = $this->getPollToShow();
         $data = $this->getPollData($pollId);
         $this->assign($data);
 
-        Mage::getSingleton('Mage_Core_Model_Session')->setJustVotedPoll(false);
+        $coreSessionModel->setJustVotedPoll(false);
 
-        if ($this->_pollModel->isVoted($pollId) === true) {
+        if ($this->_pollModel->isVoted($pollId) === true || $justVotedPollId) {
             $this->setTemplate($this->_templates['results']);
         } else {
             $this->setTemplate($this->_templates['poll']);
diff --git a/app/code/core/Mage/Poll/Model/Poll.php b/app/code/core/Mage/Poll/Model/Poll.php
index c7d3409bf4668c8f335c4e5604d7568cd762c8c3..c2b166eee7d6c2382bc366e7315c414a82a581da 100644
--- a/app/code/core/Mage/Poll/Model/Poll.php
+++ b/app/code/core/Mage/Poll/Model/Poll.php
@@ -81,16 +81,28 @@ class Mage_Poll_Model_Poll extends Mage_Core_Model_Abstract
      */
     public function getCookieName($pollId = null)
     {
-        return $this->_pollCookieDefaultName . $this->getPoolId($pollId);
+        return $this->_pollCookieDefaultName . $this->getPollId($pollId);
     }
 
     /**
      * Retrieve defined or current Id
      *
+     * @deprecated since 1.7.0.0
      * @param int $pollId
      * @return int
      */
     public function getPoolId($pollId = null)
+    {
+        return $this->getPollId($pollId);
+    }
+
+    /**
+     * Retrieve defined or current Id
+     *
+     * @param int|null $pollId
+     * @return int
+     */
+    public function getPollId($pollId = null)
     {
         if (is_null($pollId)) {
             $pollId = $this->getId();
@@ -116,7 +128,7 @@ class Mage_Poll_Model_Poll extends Mage_Core_Model_Abstract
      */
     public function setVoted($pollId=null)
     {
-        $this->getCookie()->set($this->getCookieName($pollId), $this->getPoolId($pollId));
+        $this->getCookie()->set($this->getCookieName($pollId), $this->getPollId($pollId));
 
         return $this;
     }
@@ -129,7 +141,7 @@ class Mage_Poll_Model_Poll extends Mage_Core_Model_Abstract
      */
     public function isVoted($pollId = null)
     {
-        $pollId = $this->getPoolId($pollId);
+        $pollId = $this->getPollId($pollId);
 
         // check if it is in cookie
         $cookie = $this->getCookie()->get($this->getCookieName($pollId));
diff --git a/app/code/core/Mage/ProductAlert/Block/Product/View.php b/app/code/core/Mage/ProductAlert/Block/Product/View.php
index fabe2868c7717b11f3d5e9bab2391017930d0713..b8d252bbb61e6ed105558befeb3700c7e119f48a 100644
--- a/app/code/core/Mage/ProductAlert/Block/Product/View.php
+++ b/app/code/core/Mage/ProductAlert/Block/Product/View.php
@@ -32,36 +32,45 @@ class Mage_ProductAlert_Block_Product_View extends Mage_Core_Block_Template
     /**
      * Current product instance
      *
-     * @var Mage_Catalog_Model_Product
+     * @var null|Mage_Catalog_Model_Product
      */
     protected $_product = null;
 
+    /**
+     * Helper instance
+     *
+     * @var null|Mage_ProductAlert_Helper_Data
+     */
+    protected $_helper = null;
+
     /**
      * Check whether the stock alert data can be shown and prepare related data
+     *
+     * @return void
      */
     public function prepareStockAlertData()
     {
-        if (!Mage::getStoreConfigFlag(Mage_ProductAlert_Model_Observer::XML_PATH_STOCK_ALLOW)
-            || !$this->_product || $this->_product->isAvailable()
-        ) {
+        if (!$this->_getHelper()->isStockAlertAllowed() || !$this->_product || $this->_product->isAvailable()) {
             $this->setTemplate('');
             return;
         }
-        $this->setSignupUrl(Mage::helper('Mage_ProductAlert_Helper_Data')->getSaveUrl('stock'));
+        $this->setSignupUrl($this->_getHelper()->getSaveUrl('stock'));
     }
 
     /**
      * Check whether the price alert data can be shown and prepare related data
+     *
+     * @return void
      */
     public function preparePriceAlertData()
     {
-        if (!Mage::getStoreConfigFlag(Mage_ProductAlert_Model_Observer::XML_PATH_PRICE_ALLOW)
+        if (!$this->_getHelper()->isPriceAlertAllowed()
             || !$this->_product || false === $this->_product->getCanShowPrice()
         ) {
             $this->setTemplate('');
             return;
         }
-        $this->setSignupUrl(Mage::helper('Mage_ProductAlert_Helper_Data')->getSaveUrl('price'));
+        $this->setSignupUrl($this->_getHelper()->getSaveUrl('price'));
     }
 
     /**
@@ -78,4 +87,17 @@ class Mage_ProductAlert_Block_Product_View extends Mage_Core_Block_Template
 
         return parent::_prepareLayout();
     }
+
+    /**
+     * Retrieve helper instance
+     *
+     * @return Mage_ProductAlert_Helper_Data|null
+     */
+    protected function _getHelper()
+    {
+        if (is_null($this->_helper)) {
+            $this->_helper = Mage::helper('Mage_ProductAlert_Helper_Data');
+        }
+        return $this->_helper;
+    }
 }
diff --git a/app/code/core/Mage/ProductAlert/Helper/Data.php b/app/code/core/Mage/ProductAlert/Helper/Data.php
index 690fca27d0c546583354b4ceac704518f197e8fd..fd9fb7bfc78fda6e0ebdd03236dd6ad4b7551a05 100644
--- a/app/code/core/Mage/ProductAlert/Helper/Data.php
+++ b/app/code/core/Mage/ProductAlert/Helper/Data.php
@@ -97,4 +97,24 @@ class Mage_ProductAlert_Helper_Data extends Mage_Core_Helper_Url
         }
         return $block;
     }
+
+    /**
+     * Check whether stock alert is allowed
+     *
+     * @return bool
+     */
+    public function isStockAlertAllowed()
+    {
+        return Mage::getStoreConfigFlag(Mage_ProductAlert_Model_Observer::XML_PATH_STOCK_ALLOW);
+    }
+
+    /**
+     * Check whether price alert is allowed
+     *
+     * @return bool
+     */
+    public function isPriceAlertAllowed()
+    {
+        return Mage::getStoreConfigFlag(Mage_ProductAlert_Model_Observer::XML_PATH_PRICE_ALLOW);
+    }
 }
diff --git a/app/code/core/Mage/Rating/Model/Resource/Rating.php b/app/code/core/Mage/Rating/Model/Resource/Rating.php
index b2f164c1fe1e3542f0b3a1a9b2906056b237c6f7..71bea5f3ff628a18672f2eceda8d6ec5caaa3694 100755
--- a/app/code/core/Mage/Rating/Model/Resource/Rating.php
+++ b/app/code/core/Mage/Rating/Model/Resource/Rating.php
@@ -109,15 +109,25 @@ class Mage_Rating_Model_Resource_Rating extends Mage_Core_Model_Resource_Db_Abst
         }
 
         // load rating available in stores
-        $select  = $adapter->select()
-            ->from($this->getTable('rating_store'), 'store_id')
-            ->where('rating_id=:rating_id');
-        $result  = $adapter->fetchCol($select, $bind);
-        $object->setStores($result);
+        $object->setStores($this->getStores((int)$object->getId()));
 
         return $this;
     }
 
+    /**
+     * Retrieve store IDs related to given rating
+     *
+     * @param  int $ratingId
+     * @return array
+     */
+    public function getStores($ratingId)
+    {
+        $select = $this->_getReadAdapter()->select()
+            ->from($this->getTable('rating_store'), 'store_id')
+            ->where('rating_id = ?', $ratingId);
+        return $this->_getReadAdapter()->fetchCol($select);
+    }
+
     /**
      * Actions after save
      *
@@ -139,19 +149,21 @@ class Mage_Rating_Model_Resource_Rating extends Mage_Core_Model_Resource_Db_Abst
                     ->from($ratingTitleTable, array('store_id', 'value'))
                     ->where('rating_id = :rating_id');
                 $old    = $adapter->fetchPairs($select, array(':rating_id' => $ratingId));
-                $new    = $object->getRatingCodes();
+                $new    = array_filter(array_map('trim', $object->getRatingCodes()));
 
                 $insert = array_diff_assoc($new, $old);
                 $delete = array_diff_assoc($old, $new);
+                if (!empty($delete)) {
+                    $where = array(
+                        'rating_id = ?' => $ratingId,
+                        'store_id IN(?)' => array_keys($delete)
+                    );
+                    $adapter->delete($ratingTitleTable, $where);
+                }
 
                 if ($insert) {
                     $data = array();
                     foreach ($insert as $storeId => $title) {
-                        //remove record if title is empty
-                        if (empty($title)) {
-                            $delete[$storeId] = $title;
-                            continue;
-                        }
                         $data[] = array(
                             'rating_id' => $ratingId,
                             'store_id'  => (int)$storeId,
@@ -162,13 +174,6 @@ class Mage_Rating_Model_Resource_Rating extends Mage_Core_Model_Resource_Db_Abst
                         $adapter->insertMultiple($ratingTitleTable, $data);
                     }
                 }
-                if ($old && $delete) {
-                    $where = array(
-                        'rating_id = ?' => $ratingId,
-                        'store_id IN(?)' => array_keys($delete)
-                    );
-                    $adapter->delete($ratingTitleTable, $where);
-                }
                 $adapter->commit();
             } catch (Exception $e) {
                 Mage::logException($e);
diff --git a/app/code/core/Mage/Reports/Model/Resource/Review/Product/Collection.php b/app/code/core/Mage/Reports/Model/Resource/Review/Product/Collection.php
index a1cb50c04dc5f5c11472e10afb7fe03bf98ab4d5..14b1f1acbb41b082b76a8f3575d9094cea3d51b8 100755
--- a/app/code/core/Mage/Reports/Model/Resource/Review/Product/Collection.php
+++ b/app/code/core/Mage/Reports/Model/Resource/Review/Product/Collection.php
@@ -86,7 +86,7 @@ class Mage_Reports_Model_Resource_Review_Product_Collection extends Mage_Catalog
                     'avg_rating'          => sprintf('%s/%s', $sumPercentField, $countRatingId),
                     'avg_rating_approved' => sprintf('%s/%s', $sumPercentApproved, $countRatingId),
             ));
-//ECHO $this->getSelect();dd();
+
         return $this;
     }
 
@@ -106,4 +106,30 @@ class Mage_Reports_Model_Resource_Review_Product_Collection extends Mage_Catalog
 
         return parent::addAttributeToSort($attribute, $dir);
     }
+
+    /**
+     * Get select count sql
+     *
+     * @return Varien_Db_Select
+     */
+    public function getSelectCountSql()
+    {
+        $this->_renderFilters();
+
+        /* @var Varien_Db_Select $select */
+        $select = clone $this->getSelect();
+        $select->reset(Zend_Db_Select::ORDER);
+        $select->reset(Zend_Db_Select::LIMIT_COUNT);
+        $select->reset(Zend_Db_Select::LIMIT_OFFSET);
+        $select->reset(Zend_Db_Select::COLUMNS);
+        $select->resetJoinLeft();
+        $select->columns(new Zend_Db_Expr('1'));
+
+        /* @var Varien_Db_Select $countSelect */
+        $countSelect = clone $select;
+        $countSelect->reset();
+        $countSelect->from($select, "COUNT(*)");
+
+        return $countSelect;
+    }
 }
diff --git a/app/code/core/Mage/Reports/etc/adminhtml.xml b/app/code/core/Mage/Reports/etc/adminhtml.xml
index 3c36e1df78412f3946b550575b8e2fad1c2bb357..b7a4327a98226c55ae79e3f9e3e72dd1319ac17d 100644
--- a/app/code/core/Mage/Reports/etc/adminhtml.xml
+++ b/app/code/core/Mage/Reports/etc/adminhtml.xml
@@ -124,11 +124,11 @@
                     <sort_order>60</sort_order>
                     <action>adminhtml/report/search</action>
                 </search>
-                <refresh_statistics translate="title" module="Mage_Reports">
+                <statistics translate="title" module="Mage_Reports">
                     <sort_order>65535</sort_order>
                     <title>Refresh Statistics</title>
                     <action>adminhtml/report_statistics</action>
-                </refresh_statistics>
+                </statistics>
             </children>
         </report>
     </menu>
diff --git a/app/code/core/Mage/Reports/etc/widget.xml b/app/code/core/Mage/Reports/etc/widget.xml
index 994c5b1ff3b8344ecba025f02eec58bf39ec7d71..36e2372df47ab2c83f064a91c197905419134ace 100644
--- a/app/code/core/Mage/Reports/etc/widget.xml
+++ b/app/code/core/Mage/Reports/etc/widget.xml
@@ -68,9 +68,9 @@
                 </values>
             </template>
         </parameters>
-        <supported_blocks>
+        <supported_containers>
             <left_column>
-                <block_name>left</block_name>
+                <container_name>left</container_name>
                 <template>
                     <default>list_default</default>
                     <names_only>list_names</names_only>
@@ -78,21 +78,21 @@
                 </template>
             </left_column>
             <main_content>
-                <block_name>content</block_name>
+                <container_name>content</container_name>
                 <template>
                     <grid>default</grid>
                     <list>list</list>
                 </template>
             </main_content>
             <right_column>
-                <block_name>right</block_name>
+                <container_name>right</container_name>
                 <template>
                     <default>list_default</default>
                     <names_only>list_names</names_only>
                     <images_only>list_images</images_only>
                 </template>
             </right_column>
-        </supported_blocks>
+        </supported_containers>
     </recently_viewed>
     <recently_compared type="Mage_Reports_Block_Product_Widget_Compared" translate="name description" module="Mage_Reports">
         <name>Recently Compared Products</name>
@@ -136,9 +136,9 @@
                 </values>
             </template>
         </parameters>
-        <supported_blocks>
+        <supported_containers>
             <left_column>
-                <block_name>left</block_name>
+                <container_name>left</container_name>
                 <template>
                     <default>list_default</default>
                     <names_only>list_names</names_only>
@@ -146,20 +146,20 @@
                 </template>
             </left_column>
             <main_content>
-                <block_name>content</block_name>
+                <container_name>content</container_name>
                 <template>
                     <grid>default</grid>
                     <list>list</list>
                 </template>
             </main_content>
             <right_column>
-                <block_name>right</block_name>
+                <container_name>right</container_name>
                 <template>
                     <default>list_default</default>
                     <names_only>list_names</names_only>
                     <images_only>list_images</images_only>
                 </template>
             </right_column>
-        </supported_blocks>
+        </supported_containers>
     </recently_compared>
 </widgets>
diff --git a/app/code/core/Mage/Reports/view/frontend/layout.xml b/app/code/core/Mage/Reports/view/frontend/layout.xml
index e40939379c62855da50b5b9a32d565e50969bb3a..fe6cc734864886712d90ae0b03a39cdce7fd7367 100644
--- a/app/code/core/Mage/Reports/view/frontend/layout.xml
+++ b/app/code/core/Mage/Reports/view/frontend/layout.xml
@@ -44,11 +44,16 @@
         </reference>
     </print>
 
-    <catalog_category_layered_nochildren translate="label">
-        <label>Catalog Category (Without Subcategories)</label>
+    <catalog_category_view_type_layered_without_children>
         <remove name="right.reports.product.viewed" />
         <reference name="right">
             <block type="Mage_Reports_Block_Product_Viewed" before="right.permanent.callout" name="left.reports.product.viewed" template="product_viewed.phtml" />
         </reference>
-    </catalog_category_layered_nochildren>
+    </catalog_category_view_type_layered_without_children>
+    <catalog_category_view_type_default_without_children>
+        <remove name="right.reports.product.viewed" />
+        <reference name="right">
+            <block type="Mage_Reports_Block_Product_Viewed" before="right.permanent.callout" name="left.reports.product.viewed" template="product_viewed.phtml" />
+        </reference>
+    </catalog_category_view_type_default_without_children>
 </layout>
diff --git a/app/code/core/Mage/Review/controllers/ProductController.php b/app/code/core/Mage/Review/controllers/ProductController.php
index 726ebd3d57317ecb8c8d4413fe406571e58dad9c..2c83a274270d16c6b956bf75317fa317f408b5b4 100644
--- a/app/code/core/Mage/Review/controllers/ProductController.php
+++ b/app/code/core/Mage/Review/controllers/ProductController.php
@@ -281,19 +281,16 @@ class Mage_Review_ProductController extends Mage_Core_Controller_Front_Action
     protected function _initProductLayout($product)
     {
         $update = $this->getLayout()->getUpdate();
-
-        $update->addHandle('default');
-        $this->addActionLayoutHandles();
-
-
-        $update->addHandle('PRODUCT_TYPE_'.$product->getTypeId());
+        $this->addPageLayoutHandles(
+            array('id' => $product->getId(), 'sku' => $product->getSku(), 'type' => $product->getTypeId())
+        );
 
         if ($product->getPageLayout()) {
             $this->getLayout()->helper('Mage_Page_Helper_Layout')
                 ->applyHandle($product->getPageLayout());
         }
-
         $this->loadLayoutUpdates();
+
         if ($product->getPageLayout()) {
             $this->getLayout()->helper('Mage_Page_Helper_Layout')
                 ->applyTemplate($product->getPageLayout());
diff --git a/app/code/core/Mage/Review/view/frontend/layout.xml b/app/code/core/Mage/Review/view/frontend/layout.xml
index d40063a043612de47d52ac8d37cfaf907c2985eb..4a7859d6a54e5a68801a8fca03c9592bb2feb5f8 100644
--- a/app/code/core/Mage/Review/view/frontend/layout.xml
+++ b/app/code/core/Mage/Review/view/frontend/layout.xml
@@ -54,7 +54,8 @@ Customer account home dashboard layout
 Product reviews page (?)
 -->
 
-    <reviews>
+    <reviews translate="label">
+        <label>Review</label>
         <!-- Mage_Review -->
         <reference name="root">
             <action method="setTemplate"><template>2columns-left.phtml</template></action>
@@ -65,7 +66,7 @@ Product reviews page (?)
 Product reviews page
 -->
 
-    <review_product_list translate="label">
+    <review_product_list translate="label" type="page" parent="default">
         <label>Catalog Product Reviews List</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-right.phtml</template></action>
@@ -82,12 +83,11 @@ Product reviews page
                 <block type="Mage_Catalog_Block_Product_View" name="product.info.addto" as="addto" template="product/view/addto.phtml"/>
                 <block type="Mage_Catalog_Block_Product_View" name="product.info.addtocart" as="addtocart" template="product/view/addtocart.phtml">
                     <!-- workaround: a better place for this code is in paypal.xml -->
-                    <block type="Mage_Page_Block_Html_Wrapper" name="review.product.info.addtocart.paypal.wrapper" translate="label" module="Mage_Paypal">
-                        <label>PayPal Express Checkout Shortcut Wrapper</label>
+                    <container name="review.product.info.addtocart.paypal.wrapper" label="PayPal Express Checkout Shortcut Wrapper" module="Mage_Paypal" htmlTag="div">
                         <block type="Mage_Paypal_Block_Express_Shortcut" name="review.product.info.addtocart.paypal" template="express/shortcut.phtml">
                             <action method="setIsInCatalogProduct"><value>1</value></action>
                         </block>
-                    </block>
+                    </container>
                 </block>
                 <block type="Mage_Catalog_Block_Product_View" name="product.tierprices" as="tierprices" template="product/view/tierprices.phtml"/>
                 <block type="Mage_Core_Block_Template" name="product.info.other" as="other" template="Mage_Review::product/view/other.phtml"/>
@@ -95,17 +95,14 @@ Product reviews page
                 <block type="Mage_Core_Block_Template" name="product_review_list.count" template="Mage_Review::product/view/count.phtml" />
                 <block type="Mage_Review_Block_Product_View_List" name="product.info.product_additional_data" as="product_additional_data" template="product/view/list.phtml">
                     <block type="Mage_Review_Block_Form" name="product.review.form" as="review_form">
-                        <block type="Mage_Page_Block_Html_Wrapper" name="product.review.form.fields.before" as="form_fields_before" translate="label">
-                            <label>Review Form Fields Before</label>
-                            <action method="setMayBeInvisible"><value>1</value></action>
-                        </block>
+                        <container name="product.review.form.fields.before" as="form_fields_before" label="Review Form Fields Before" htmlTag="div"/>
                     </block>
                 </block>
             </block>
         </reference>
     </review_product_list>
 
-    <review_product_view translate="label">
+    <review_product_view translate="label" type="page" parent="review_product_list">
         <label>Catalog Product Review View</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-right.phtml</template></action>
@@ -115,7 +112,7 @@ Product reviews page
         </reference>
     </review_product_view>
 
-    <review_customer_index translate="label">
+    <review_customer_index translate="label" type="page" parent="customer_account_index">
         <label>Customer My Account Product Reviews</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
@@ -123,7 +120,7 @@ Product reviews page
         </reference>
     </review_customer_index>
 
-    <review_customer_view translate="label">
+    <review_customer_view translate="label" type="page" parent="review_customer_index">
         <label>Customer My Account Review Details</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
diff --git a/app/code/core/Mage/Rss/Block/Catalog/NotifyStock.php b/app/code/core/Mage/Rss/Block/Catalog/NotifyStock.php
index 4c0a72170136731bcb2c12509411646c7ce67ef5..3a4c3fff0e8dbbc0589eda1a8c03563d917962b2 100644
--- a/app/code/core/Mage/Rss/Block/Catalog/NotifyStock.php
+++ b/app/code/core/Mage/Rss/Block/Catalog/NotifyStock.php
@@ -86,10 +86,12 @@ class Mage_Rss_Block_Catalog_NotifyStock extends Mage_Rss_Block_Abstract
         $collection = $product->getCollection();
         $stockItemTable = $collection->getTable('cataloginventory_stock_item');
 
+        $adapter = $collection->getConnection();
         $stockItemWhere = '({{table}}.low_stock_date is not null) '
             . " AND ( ({{table}}.use_config_manage_stock=1 AND {$configManageStock}=1)"
             . " AND {{table}}.qty < "
-            . "IF({$stockItemTable}.`use_config_notify_stock_qty`, {$globalNotifyStockQty}, {{table}}.notify_stock_qty)"
+            . $adapter->getCheckSql("{$stockItemTable}.use_config_notify_stock_qty = 1", $globalNotifyStockQty,
+                '{{table}}.notify_stock_qty')
             . ' OR ({{table}}.use_config_manage_stock=0 AND {{table}}.manage_stock=1) )';
 
         $collection
diff --git a/app/code/core/Mage/Rss/Block/Wishlist.php b/app/code/core/Mage/Rss/Block/Wishlist.php
index 4c0a8936962155f70654e5c662560dfee422d444..375641f519612e290a16b2bfd34d8f1d23de2f57 100644
--- a/app/code/core/Mage/Rss/Block/Wishlist.php
+++ b/app/code/core/Mage/Rss/Block/Wishlist.php
@@ -56,8 +56,16 @@ class Mage_Rss_Block_Wishlist extends Mage_Wishlist_Block_Abstract
     {
         if (is_null($this->_wishlist)) {
             $this->_wishlist = Mage::getModel('Mage_Wishlist_Model_Wishlist');
-            if ($this->_getCustomer()->getId()) {
-                $this->_wishlist->loadByCustomer($this->_getCustomer());
+            $wishlistId = $this->getRequest()->getParam('wishlist_id');
+            if ($wishlistId) {
+                $this->_wishlist->load($wishlistId);
+                if ($this->_wishlist->getCustomerId() != $this->_getCustomer()->getId()) {
+                    $this->_wishlist->unsetData();
+                }
+            } else {
+                if($this->_getCustomer()->getId()) {
+                    $this->_wishlist->loadByCustomer($this->_getCustomer());
+                }
             }
         }
         return $this->_wishlist;
@@ -84,6 +92,16 @@ class Mage_Rss_Block_Wishlist extends Mage_Wishlist_Block_Abstract
         return $this->_customer;
     }
 
+    /**
+     * Build wishlist rss feed title
+     *
+     * @return string
+     */
+    protected function _getTitle()
+    {
+        return Mage::helper('Mage_Rss_Helper_Data')->__('%s\'s Wishlist', $this->_getCustomer()->getName());
+    }
+
     /**
      * Render block HTML
      *
@@ -99,7 +117,7 @@ class Mage_Rss_Block_Wishlist extends Mage_Wishlist_Block_Abstract
                 'code'  => $this->_getWishlist()->getSharingCode()
             ));
 
-            $title  = Mage::helper('Mage_Rss_Helper_Data')->__('%s\'s Wishlist', $this->_getCustomer()->getName());
+            $title  = $this->_getTitle();
             $lang   = Mage::getStoreConfig('general/locale/code');
 
             $rssObj->_addHeader(array(
diff --git a/app/code/core/Mage/Adminhtml/controllers/Rss/CatalogController.php b/app/code/core/Mage/Rss/Controller/AdminhtmlAbstract.php
similarity index 54%
rename from app/code/core/Mage/Adminhtml/controllers/Rss/CatalogController.php
rename to app/code/core/Mage/Rss/Controller/AdminhtmlAbstract.php
index b51fe96cba787c578632c85ce298636658f1bfce..cf7a793e4930145a19f0ad018298ba6dc7beb4e6 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Rss/CatalogController.php
+++ b/app/code/core/Mage/Rss/Controller/AdminhtmlAbstract.php
@@ -19,45 +19,41 @@
  * needs please refer to http://www.magentocommerce.com for more information.
  *
  * @category    Mage
- * @package     Mage_Adminhtml
+ * @package     Mage_Rss
  * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
 /**
- * Adminhtml Rss Controller
+ * Base class for Rss controllers, where admin login required for some actions
  *
  * @category   Mage
  * @package    Mage_Rss
  * @author     Magento Core Team <core@magentocommerce.com>
  */
-
-class Mage_Adminhtml_Rss_CatalogController extends Mage_Adminhtml_Controller_Action
+abstract class Mage_Rss_Controller_AdminhtmlAbstract extends Mage_Core_Controller_Front_Action
 {
+    /**
+     * Returns map of action to acl paths, needed to check user's access to a specific action
+     *
+     * @return array
+     */
+    abstract protected function _getAdminAclMap();
+
+    /**
+     * Controller predispatch method to change area for a specific action
+     *
+     * @return Mage_Rss_Controller_AdminhtmlAbstract
+     */
     public function preDispatch()
     {
-        $path = '';
-        if ($this->getRequest()->getActionName() == 'review') {
-            $path = 'catalog/reviews_ratings';
-        } elseif ($this->getRequest()->getActionName() == 'notifystock') {
-            $path = 'catalog/products';
+        $action = $this->getRequest()->getActionName();
+        $map = $this->_getAdminAclMap();
+        if (isset($map[$action])) {
+            $this->_currentArea = 'adminhtml';
+            $path = $map[$action];
+            Mage::helper('Mage_Rss_Helper_Data')->authAdmin($path);
         }
-        Mage::helper('Mage_Adminhtml_Helper_Rss')->authAdmin($path);
-        parent::preDispatch();
-        return $this;
-    }
-
-    public function notifystockAction()
-    {
-        $this->getResponse()->setHeader('Content-type', 'text/xml; charset=UTF-8');
-        $this->loadLayout(false);
-        $this->renderLayout();
-    }
-
-    public function reviewAction()
-    {
-        $this->getResponse()->setHeader('Content-type', 'text/xml; charset=UTF-8');
-        $this->loadLayout(false);
-        $this->renderLayout();
+        return parent::preDispatch();
     }
 }
diff --git a/app/code/core/Mage/Rss/Helper/Data.php b/app/code/core/Mage/Rss/Helper/Data.php
index 8f517dd8200bdedaef341a97e63856ea09f0a730..51ff52cfbe5ed7e6035f4da448178d943b6956bd 100644
--- a/app/code/core/Mage/Rss/Helper/Data.php
+++ b/app/code/core/Mage/Rss/Helper/Data.php
@@ -54,25 +54,29 @@ class Mage_Rss_Helper_Data extends Mage_Core_Helper_Abstract
     }
 
     /**
-     * Authenticate admin and check ACL
+     * Authenticates admin user and checks ACL. Returns user model upon successful authentication.
+     * If user authentication fails, then shows error and exits php instantly.
      *
      * @param string $path
+     * @return Mage_Admin_Model_User
      */
     public function authAdmin($path)
     {
         $session = Mage::getSingleton('Mage_Rss_Model_Session');
         if ($session->isAdminLoggedIn()) {
-            return;
+            return $session->getAdmin();
         }
+
         list($username, $password) = $this->authValidate();
         Mage::getSingleton('Mage_Adminhtml_Model_Url')->setNoSecret(true);
         $adminSession = Mage::getSingleton('Mage_Admin_Model_Session');
         $user = $adminSession->login($username, $password);
-        //$user = Mage::getModel('Mage_Admin_Model_User')->login($username, $password);
-        if($user && $user->getId() && $user->getIsActive() == '1' && $adminSession->isAllowed($path)){
+        if ($user && $user->getIsActive() == '1' && $adminSession->isAllowed($path)){
             $session->setAdmin($user);
+            return $user;
         } else {
-            $this->authFailed();
+            // Error is shown and exit() is called
+            Mage::helper('Mage_Core_Helper_Http')->authFailed();
         }
     }
 
diff --git a/app/code/core/Mage/Rss/controllers/CatalogController.php b/app/code/core/Mage/Rss/controllers/CatalogController.php
index 59cc01ea9af35d0a6e399a0dd8103f7621e27be7..0fa5e51356b50bdc7366accd373e94a028d28908 100644
--- a/app/code/core/Mage/Rss/controllers/CatalogController.php
+++ b/app/code/core/Mage/Rss/controllers/CatalogController.php
@@ -32,8 +32,21 @@
  * @author      Magento Core Team <core@magentocommerce.com>
  */
 
-class Mage_Rss_CatalogController extends Mage_Core_Controller_Front_Action
+class Mage_Rss_CatalogController extends Mage_Rss_Controller_AdminhtmlAbstract
 {
+    /**
+     * Returns map of action to acl paths, needed to check user's access to a specific action
+     *
+     * @return array
+     */
+    protected function _getAdminAclMap()
+    {
+        return array(
+            'notifystock' => 'catalog/products',
+            'review' => 'catalog/reviews_ratings'
+        );
+    }
+
     protected function isFeedEnable($code)
     {
         return Mage::getStoreConfig('rss/catalog/'.$code);
@@ -110,22 +123,4 @@ class Mage_Rss_CatalogController extends Mage_Core_Controller_Front_Action
             $this->renderLayout();
         }
     }
-
-    /**
-     * Controller predispatch method to change area for some specific action.
-     *
-     * @return Mage_Rss_CatalogController
-     */
-    public function preDispatch()
-    {
-        if ($this->getRequest()->getActionName() == 'notifystock') {
-            $this->_currentArea = 'adminhtml';
-            Mage::helper('Mage_Rss_Helper_Data')->authAdmin('catalog/products');
-        }
-        if ($this->getRequest()->getActionName() == 'review') {
-            $this->_currentArea = 'adminhtml';
-            Mage::helper('Mage_Rss_Helper_Data')->authAdmin('catalog/reviews_ratings');
-        }
-        return parent::preDispatch();
-    }
 }
diff --git a/app/code/core/Mage/Rss/controllers/IndexController.php b/app/code/core/Mage/Rss/controllers/IndexController.php
index bb89b7d8cba0846976dbfc0941001cb76efb9448..d340435f68bc4785ea6fe8479b00a8ce551e64e7 100644
--- a/app/code/core/Mage/Rss/controllers/IndexController.php
+++ b/app/code/core/Mage/Rss/controllers/IndexController.php
@@ -33,6 +33,23 @@
 
 class Mage_Rss_IndexController extends Mage_Core_Controller_Front_Action
 {
+    /**
+     * Current wishlist
+     *
+     * @var Mage_Wishlist_Model_Wishlist
+     */
+    protected $_wishlist;
+
+    /**
+     * Current customer
+     *
+     * @var Mage_Customer_Model_Customer
+     */
+    protected $_customer;
+
+    /**
+     * Index action
+     */
     public function indexAction()
     {
         if (Mage::getStoreConfig('rss/config/active')) {
@@ -45,27 +62,99 @@ class Mage_Rss_IndexController extends Mage_Core_Controller_Front_Action
         }
     }
 
+    /**
+     * Display feed not found message
+     */
     public function nofeedAction()
     {
         $this->getResponse()->setHeader('HTTP/1.1','404 Not Found');
         $this->getResponse()->setHeader('Status','404 File not found');
         $this->loadLayout(false);
-           $this->renderLayout();
+        $this->renderLayout();
     }
 
+    /**
+     * Wishlist rss feed action
+     * Show all public wishlists and private wishlists that belong to current user
+     *
+     * @return mixed
+     */
     public function wishlistAction()
     {
-        if ( Mage::getSingleton('Mage_Customer_Model_Session')->authenticate($this) ) {
-            if (Mage::getStoreConfig('rss/wishlist/active')) {
-                $this->getResponse()->setHeader('Content-type', 'text/xml; charset=UTF-8');
-                $this->loadLayout(false);
-                $this->renderLayout();
+        if (!Mage::getStoreConfig('rss/wishlist/active')) {
+            $this->getResponse()->setHeader('HTTP/1.1','404 Not Found');
+            $this->getResponse()->setHeader('Status','404 File not found');
+            $this->_forward('nofeed','index','rss');
+            return;
+        }
+
+        $wishlist = $this->_getWishlist();
+        if (!$wishlist) {
+            $this->_forward('nofeed','index','rss');
+            return;
+        }
+
+        if ($wishlist->getVisibility()) {
+            $this->_showWishlistRss();
+            return ;
+        } else if (Mage::getSingleton('Mage_Customer_Model_Session')->authenticate($this)
+            && $wishlist->getCustomerId() == $this->_getCustomer()->getId()
+        ) {
+            $this->_showWishlistRss();
+        } else {
+            $this->_forward('nofeed','index','rss');
+        }
+    }
+
+    /**
+     * Show wishlist rss
+     */
+    protected function _showWishlistRss()
+    {
+        $this->getResponse()->setHeader('Content-type', 'text/xml; charset=UTF-8');
+        $this->loadLayout(false);
+        $this->renderLayout();
+    }
+
+    /**
+     * Retrieve Wishlist model
+     *
+     * @return Mage_Wishlist_Model_Wishlist
+     */
+    protected function _getWishlist()
+    {
+        if (is_null($this->_wishlist)) {
+            $this->_wishlist = Mage::getModel('Mage_Wishlist_Model_Wishlist');
+            $wishlistId = $this->getRequest()->getParam('wishlist_id');
+            if ($wishlistId) {
+                $this->_wishlist->load($wishlistId);
             } else {
-                $this->getResponse()->setHeader('HTTP/1.1','404 Not Found');
-                $this->getResponse()->setHeader('Status','404 File not found');
-                $this->_forward('nofeed','index','rss');
-                return;
+                if($this->_getCustomer()->getId()) {
+                    $this->_wishlist->loadByCustomer($this->_getCustomer());
+                }
+            }
+        }
+        return $this->_wishlist;
+    }
+
+    /**
+     * Retrieve Customer instance
+     *
+     * @return Mage_Customer_Model_Customer
+     */
+    protected function _getCustomer()
+    {
+        if (is_null($this->_customer)) {
+            $this->_customer = Mage::getModel('Mage_Customer_Model_Customer');
+
+            $params = Mage::helper('Mage_Core_Helper_Data')->urlDecode($this->getRequest()->getParam('data'));
+            $data   = explode(',', $params);
+            $customerId    = abs(intval($data[0]));
+            if ($customerId && ($customerId == Mage::getSingleton('Mage_Customer_Model_Session')->getCustomerId()) ) {
+                $this->_customer->load($customerId);
             }
         }
+
+        return $this->_customer;
     }
 }
diff --git a/app/code/core/Mage/Rss/controllers/OrderController.php b/app/code/core/Mage/Rss/controllers/OrderController.php
index ad6b3d942043cc8c219262f4f6ada4340fb8d5f0..c94318afad512188ced213f903e5b30a644ca016 100644
--- a/app/code/core/Mage/Rss/controllers/OrderController.php
+++ b/app/code/core/Mage/Rss/controllers/OrderController.php
@@ -32,8 +32,20 @@
  * @author      Magento Core Team <core@magentocommerce.com>
  */
 
-class Mage_Rss_OrderController extends Mage_Core_Controller_Front_Action
+class Mage_Rss_OrderController extends Mage_Rss_Controller_AdminhtmlAbstract
 {
+    /**
+     * Returns map of action to acl paths, needed to check user's access to a specific action
+     *
+     * @return array
+     */
+    protected function _getAdminAclMap()
+    {
+        return array(
+            'new' => 'sales/order'
+        );
+    }
+
     public function newAction()
     {
         $this->getResponse()->setHeader('Content-type', 'text/xml; charset=UTF-8');
@@ -69,18 +81,4 @@ class Mage_Rss_OrderController extends Mage_Core_Controller_Front_Action
         }
         $this->_forward('nofeed', 'index', 'rss');
     }
-
-    /**
-     * Controller predispatch method to change area for some specific action.
-     *
-     * @return Mage_Rss_OrderController
-     */
-    public function preDispatch()
-    {
-        if ($this->getRequest()->getActionName() == 'new') {
-            $this->_currentArea = 'adminhtml';
-            Mage::helper('Mage_Rss_Helper_Data')->authAdmin('sales/order');
-        }
-        return parent::preDispatch();
-    }
 }
diff --git a/app/code/core/Mage/Rss/etc/adminhtml.xml b/app/code/core/Mage/Rss/etc/adminhtml.xml
index 9dbafb9e366e597160fe82b40689e75c6d8b8bdd..c5b0b918e1567e2f1369a0d2cd0dbf7e4a58ccfb 100644
--- a/app/code/core/Mage/Rss/etc/adminhtml.xml
+++ b/app/code/core/Mage/Rss/etc/adminhtml.xml
@@ -35,7 +35,7 @@
                             <config>
                                 <children>
                                     <rss translate="title">
-                                        <title>Rss Feeds Section</title>
+                                        <title>RSS Feeds Section</title>
                                         <sort_order>135</sort_order>
                                     </rss>
                                 </children>
diff --git a/app/code/core/Mage/Rss/view/adminhtml/layout.xml b/app/code/core/Mage/Rss/view/adminhtml/layout.xml
index c4c7f21619c25ffbc8f13a80f81eb6b94a6eaf00..4a14a6607ac2b0067233a3b218c45556d64197c9 100644
--- a/app/code/core/Mage/Rss/view/adminhtml/layout.xml
+++ b/app/code/core/Mage/Rss/view/adminhtml/layout.xml
@@ -27,19 +27,15 @@
 -->
 
 <layout>
+    <rss_catalog_review>
+        <block type="Mage_Rss_Block_Catalog_Review" output="1" name="rss.catalog.review" />
+    </rss_catalog_review>
 
-<!--
-
--->
-    <adminhtml_rss_catalog_review>
-        <block type="Mage_Rss_Block_Catalog_Review" output="toHtml" name="rss.catalog.review" />
-    </adminhtml_rss_catalog_review>
-
-    <adminhtml_rss_catalog_notifystock>
-        <block type="Mage_Rss_Block_Catalog_NotifyStock" output="toHtml" name="rss.catalog.notifystock" />
-    </adminhtml_rss_catalog_notifystock>
+    <rss_catalog_notifystock>
+        <block type="Mage_Rss_Block_Catalog_NotifyStock" output="1" name="rss.catalog.notifystock" />
+    </rss_catalog_notifystock>
 
-    <adminhtml_rss_order_new>
-        <block type="Mage_Rss_Block_Order_New" output="toHtml" name="rss.order.new"/>
-    </adminhtml_rss_order_new>
+    <rss_order_new>
+        <block type="Mage_Rss_Block_Order_New" output="1" name="rss.order.new"/>
+    </rss_order_new>
 </layout>
diff --git a/app/code/core/Mage/Rss/view/frontend/layout.xml b/app/code/core/Mage/Rss/view/frontend/layout.xml
index 4ea01610c94c72a86157292b637a312c5bd00759..67f0a135e76931b65af4722b4d89a6016169725b 100644
--- a/app/code/core/Mage/Rss/view/frontend/layout.xml
+++ b/app/code/core/Mage/Rss/view/frontend/layout.xml
@@ -36,7 +36,7 @@
         <block type="Mage_Rss_Block_List" name="head_rss" ifconfig="rss/config/active" />
     </default>
 
-    <rss_index_index translate="label">
+    <rss_index_index translate="label" type="page" parent="default">
         <label>RSS Feeds List</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-right.phtml</template></action>
@@ -46,58 +46,55 @@
         </reference>
     </rss_index_index>
 
-    <rss_index_nofeed>
-        <block type="Mage_Core_Block_Template" name="root" output="toHtml" template="Mage_Rss::nofeed.phtml"/>
+    <rss_index_nofeed translate="label" type="page" parent="rss_index_index">
+        <label>RSS No Feed</label>
+        <block type="Mage_Core_Block_Template" name="root" output="1" template="Mage_Rss::nofeed.phtml"/>
     </rss_index_nofeed>
 
-    <rss_index_wishlist>
-        <block type="Mage_Rss_Block_Wishlist" name="rss.wishlist" output="toHtml">
+    <rss_index_wishlist translate="label" type="page" parent="rss_index_index">
+        <label>RSS Wishlist</label>
+        <block type="Mage_Rss_Block_Wishlist" name="rss.wishlist" output="1">
             <action method="addPriceBlockType"><type>msrp_rss</type><block>Mage_Catalog_Block_Product_Price</block><template>Mage_Wishlist::render/item/price_msrp_rss.phtml</template></action>
         </block>
     </rss_index_wishlist>
 <!--
 Catalog layout
 -->
-    <rss_catalog_new>
-        <block type="Mage_Rss_Block_Catalog_New" output="toHtml" name="rss.catalog.new">
+    <rss_catalog_new translate="label" type="page" parent="rss_index_index">
+        <label>RSS New</label>
+        <block type="Mage_Rss_Block_Catalog_New" output="1" name="rss.catalog.new">
             <action method="addPriceBlockType"><type>msrp_rss</type><block>Mage_Catalog_Block_Product_Price</block><template>product/price_msrp_rss.phtml</template></action>
         </block>
     </rss_catalog_new>
 
-    <rss_catalog_special>
-        <block type="Mage_Rss_Block_Catalog_Special" output="toHtml" name="rss.catalog.special" />
+    <rss_catalog_special translate="label" type="page" parent="rss_catalog_new">
+        <label>RSS Special</label>
+        <block type="Mage_Rss_Block_Catalog_Special" output="1" name="rss.catalog.special" />
     </rss_catalog_special>
 
-    <rss_catalog_salesrule>
-        <block type="Mage_Rss_Block_Catalog_Salesrule" output="toHtml" name="rss.catalog.salesrule" />
+    <rss_catalog_salesrule translate="label" type="page" parent="rss_catalog_new">
+        <label>RSS Sales Rule</label>
+        <block type="Mage_Rss_Block_Catalog_Salesrule" output="1" name="rss.catalog.salesrule" />
     </rss_catalog_salesrule>
 
-    <rss_catalog_tag>
-        <block type="Mage_Rss_Block_Catalog_Tag" output="toHtml" name="rss.catalog.tag">
+    <rss_catalog_tag translate="label" type="page" parent="rss_catalog_new">
+        <label>RSS Tag</label>
+        <block type="Mage_Rss_Block_Catalog_Tag" output="1" name="rss.catalog.tag">
             <action method="addPriceBlockType"><type>msrp_rss</type><block>Mage_Catalog_Block_Product_Price</block><template>product/price_msrp_rss.phtml</template></action>
         </block>
     </rss_catalog_tag>
 
-    <rss_catalog_notifystock>
-        <block type="Mage_Rss_Block_Catalog_NotifyStock" output="toHtml" name="rss.catalog.notifystock" />
-    </rss_catalog_notifystock>
-
-    <rss_catalog_review>
-        <block type="Mage_Rss_Block_Catalog_Review" output="toHtml" name="rss.catalog.review" />
-    </rss_catalog_review>
-
-    <rss_catalog_category>
-        <block type="Mage_Rss_Block_Catalog_Category" output="toHtml" name="rss.catalog.category">
+    <rss_catalog_category translate="label" type="page" parent="rss_catalog_new">
+        <label>RSS Catalog Category</label>
+        <block type="Mage_Rss_Block_Catalog_Category" output="1" name="rss.catalog.category">
             <action method="addPriceBlockType"><type>msrp_rss</type><block>Mage_Catalog_Block_Product_Price</block><template>product/price_msrp_rss.phtml</template></action>
         </block>
     </rss_catalog_category>
 <!--
 Order layout
 -->
-    <rss_order_new>
-        <block type="Mage_Rss_Block_Order_New" output="toHtml" name="rss.order.new"/>
-    </rss_order_new>
-    <rss_order_status>
-        <block type="Mage_Rss_Block_Order_Status" output="toHtml" name="rss.order.status"/>
+    <rss_order_status translate="label" type="page" parent="rss_index_index">
+        <label>RSS Order Status</label>
+        <block type="Mage_Rss_Block_Order_Status" output="1" name="rss.order.status"/>
     </rss_order_status>
 </layout>
diff --git a/app/code/core/Mage/Rule/Model/Abstract.php b/app/code/core/Mage/Rule/Model/Abstract.php
index 6dbc467331d641ff34b54406a1ae469704af7a43..6eb99d155be40594b82d19d262a4c2070168cca4 100644
--- a/app/code/core/Mage/Rule/Model/Abstract.php
+++ b/app/code/core/Mage/Rule/Model/Abstract.php
@@ -82,40 +82,6 @@ abstract class Mage_Rule_Model_Abstract extends Mage_Core_Model_Abstract
      */
     abstract public function getActionsInstance();
 
-    /**
-     * Prepare rule conditions and actions
-     *
-     * @return Mage_Rule_Model_Abstract
-     */
-    protected function _afterLoad()
-    {
-        parent::_afterLoad();
-
-        // Load rule conditions if it is applicable
-        if ($this->hasConditionsSerialized()) {
-            $conditions = $this->getConditionsSerialized();
-            if (!empty($conditions)) {
-                $conditions = unserialize($conditions);
-                if (is_array($conditions) && !empty($conditions)) {
-                    $this->getConditions()->loadArray($conditions);
-                }
-            }
-        }
-
-        // Load rule actions if it is applicable
-        if ($this->hasActionsSerialized()) {
-            $actions = $this->getActionsSerialized();
-            if (!empty($actions)) {
-                $actions = unserialize($actions);
-                if (is_array($actions) && !empty($actions)) {
-                    $this->getActions()->loadArray($actions);
-                }
-            }
-        }
-
-        return $this;
-    }
-
     /**
      * Prepare data before saving
      *
@@ -191,6 +157,19 @@ abstract class Mage_Rule_Model_Abstract extends Mage_Core_Model_Abstract
         if (empty($this->_conditions)) {
             $this->_resetConditions();
         }
+
+        // Load rule conditions if it is applicable
+        if ($this->hasConditionsSerialized()) {
+            $conditions = $this->getConditionsSerialized();
+            if (!empty($conditions)) {
+                $conditions = unserialize($conditions);
+                if (is_array($conditions) && !empty($conditions)) {
+                    $this->_conditions->loadArray($conditions);
+                }
+            }
+            $this->unsConditionsSerialized();
+        }
+
         return $this->_conditions;
     }
 
@@ -217,6 +196,19 @@ abstract class Mage_Rule_Model_Abstract extends Mage_Core_Model_Abstract
         if (!$this->_actions) {
             $this->_resetActions();
         }
+
+        // Load rule actions if it is applicable
+        if ($this->hasActionsSerialized()) {
+            $actions = $this->getActionsSerialized();
+            if (!empty($actions)) {
+                $actions = unserialize($actions);
+                if (is_array($actions) && !empty($actions)) {
+                    $this->_actions->loadArray($actions);
+                }
+            }
+            $this->unsActionsSerialized();
+        }
+
         return $this->_actions;
     }
 
diff --git a/app/code/core/Mage/Rule/Model/Condition/Product/Abstract.php b/app/code/core/Mage/Rule/Model/Condition/Product/Abstract.php
index 43a460c06eb90924021a5606a6b3e01c667e1168..3cf645acd5c73378acfe2fdfff270beaa36f6478 100644
--- a/app/code/core/Mage/Rule/Model/Condition/Product/Abstract.php
+++ b/app/code/core/Mage/Rule/Model/Condition/Product/Abstract.php
@@ -445,6 +445,9 @@ abstract class Mage_Rule_Model_Condition_Product_Abstract extends Mage_Rule_Mode
         if ('category_ids' == $attrCode) {
             return $this->validateAttribute($object->getAvailableInCategories());
         } elseif (! isset($this->_entityAttributeValues[$object->getId()])) {
+            if (!$object->getResource()) {
+                return false;
+            }
             $attr = $object->getResource()->getAttribute($attrCode);
 
             if ($attr && $attr->getBackendType() == 'datetime' && !is_int($this->getValue())) {
diff --git a/app/code/core/Mage/Rule/Model/Resource/Rule/Collection/Abstract.php b/app/code/core/Mage/Rule/Model/Resource/Rule/Collection/Abstract.php
index 3f75cf4f3d72c483c92b3c7d6abc909af5055b30..36d56b73227d903a9df6f06fab296872eb4509f2 100644
--- a/app/code/core/Mage/Rule/Model/Resource/Rule/Collection/Abstract.php
+++ b/app/code/core/Mage/Rule/Model/Resource/Rule/Collection/Abstract.php
@@ -31,7 +31,8 @@
  * @package Mage_Rule
  * @author Magento Core Team <core@magentocommerce.com>
  */
-abstract class Mage_Rule_Model_Resource_Rule_Collection_Abstract extends Mage_Core_Model_Resource_Db_Collection_Abstract
+abstract class Mage_Rule_Model_Resource_Rule_Collection_Abstract
+    extends Mage_Core_Model_Resource_Db_Collection_Abstract
 {
     /**
      * Store associated with rule entities information map
@@ -108,18 +109,18 @@ abstract class Mage_Rule_Model_Resource_Rule_Collection_Abstract extends Mage_Co
         $entityInfo = $this->_getAssociatedEntityInfo('website');
         if (!$this->getFlag('is_website_table_joined')) {
             $this->setFlag('is_website_table_joined', true);
-            $this->getSelect()->joinInner(
-                array('website' => $this->getTable($entityInfo['associations_table'])),
-                'main_table.' . $entityInfo['rule_id_field'] . ' = website.' . $entityInfo['rule_id_field'],
-                array()
-            );
-        }
+            if ($websiteId instanceof Mage_Core_Model_Website) {
+                $websiteId = $websiteId->getId();
+            }
 
-        if ($websiteId instanceof Mage_Core_Model_Website) {
-            $websiteId = $websiteId->getId();
+            $subSelect = $this->getConnection()->select()
+                ->from(array('website' => $this->getTable($entityInfo['associations_table'])), '')
+                ->where('website.' . $entityInfo['entity_id_field'] . ' IN (?)', $websiteId);
+            $this->getSelect()->exists(
+                $subSelect,
+                'main_table.' . $entityInfo['rule_id_field'] . ' = website.' . $entityInfo['rule_id_field']
+            );
         }
-        $this->getSelect()->where('website.' . $entityInfo['entity_id_field'] . ' IN (?)', $websiteId);
-
         return $this;
     }
 
diff --git a/app/code/core/Mage/Sales/Block/Order/Creditmemo/Items.php b/app/code/core/Mage/Sales/Block/Order/Creditmemo/Items.php
index f7d59ff4e82d9ebbde42d21479aca553fc2fb2ef..738823bbe212e092fbde4b0ab13ec7e4e9648ad0 100644
--- a/app/code/core/Mage/Sales/Block/Order/Creditmemo/Items.php
+++ b/app/code/core/Mage/Sales/Block/Order/Creditmemo/Items.php
@@ -61,7 +61,7 @@ class Mage_Sales_Block_Order_Creditmemo_Items extends Mage_Sales_Block_Items_Abs
      */
     public function getTotalsHtml($creditmemo)
     {
-        $totals = $this->getChild('creditmemo_totals');
+        $totals = $this->getChildBlock('creditmemo_totals');
         $html = '';
         if ($totals) {
             $totals->setCreditmemo($creditmemo);
@@ -79,7 +79,7 @@ class Mage_Sales_Block_Order_Creditmemo_Items extends Mage_Sales_Block_Items_Abs
     public function getCommentsHtml($creditmemo)
     {
         $html = '';
-        $comments = $this->getChild('creditmemo_comments');
+        $comments = $this->getChildBlock('creditmemo_comments');
         if ($comments) {
             $comments->setEntity($creditmemo)
                 ->setTitle(Mage::helper('Mage_Sales_Helper_Data')->__('About Your Refund'));
diff --git a/app/code/core/Mage/Sales/Block/Order/Invoice/Items.php b/app/code/core/Mage/Sales/Block/Order/Invoice/Items.php
index e1b6e9c0bd6dd4f6aacc073676b6ff603dde1239..eb8d6ee04fb3c5243c4079a124d70bc9ecbd759c 100644
--- a/app/code/core/Mage/Sales/Block/Order/Invoice/Items.php
+++ b/app/code/core/Mage/Sales/Block/Order/Invoice/Items.php
@@ -62,7 +62,7 @@ class Mage_Sales_Block_Order_Invoice_Items extends Mage_Sales_Block_Items_Abstra
     public function getInvoiceTotalsHtml($invoice)
     {
         $html = '';
-        $totals = $this->getChild('invoice_totals');
+        $totals = $this->getChildBlock('invoice_totals');
         if ($totals) {
             $totals->setInvoice($invoice);
             $html = $totals->toHtml();
@@ -79,7 +79,7 @@ class Mage_Sales_Block_Order_Invoice_Items extends Mage_Sales_Block_Items_Abstra
     public function getInvoiceCommentsHtml($invoice)
     {
         $html = '';
-        $comments = $this->getChild('invoice_comments');
+        $comments = $this->getChildBlock('invoice_comments');
         if ($comments) {
             $comments->setEntity($invoice)
                 ->setTitle(Mage::helper('Mage_Sales_Helper_Data')->__('About Your Invoice'));
diff --git a/app/code/core/Mage/Sales/Block/Order/Print/Creditmemo.php b/app/code/core/Mage/Sales/Block/Order/Print/Creditmemo.php
index 015208c16ee8ae643a4e4db48afffdf01e12f5bf..5c73c6f5ecb2ed0e905a3fe73f76d0d8963f1466 100644
--- a/app/code/core/Mage/Sales/Block/Order/Print/Creditmemo.php
+++ b/app/code/core/Mage/Sales/Block/Order/Print/Creditmemo.php
@@ -84,7 +84,7 @@ class Mage_Sales_Block_Order_Print_Creditmemo extends Mage_Sales_Block_Items_Abs
      */
     public function getTotalsHtml($creditmemo)
     {
-        $totals = $this->getChild('creditmemo_totals');
+        $totals = $this->getChildBlock('creditmemo_totals');
         $html = '';
         if ($totals) {
             $totals->setCreditmemo($creditmemo);
diff --git a/app/code/core/Mage/Sales/Block/Order/Print/Invoice.php b/app/code/core/Mage/Sales/Block/Order/Print/Invoice.php
index ef5c636e6b890e611b976cf4fe84b68de33d0825..a911ce46c01058a3167101682f9effa92d8eccdd 100644
--- a/app/code/core/Mage/Sales/Block/Order/Print/Invoice.php
+++ b/app/code/core/Mage/Sales/Block/Order/Print/Invoice.php
@@ -85,7 +85,7 @@ class Mage_Sales_Block_Order_Print_Invoice extends Mage_Sales_Block_Items_Abstra
     public function getInvoiceTotalsHtml($invoice)
     {
         $html = '';
-        $totals = $this->getChild('invoice_totals');
+        $totals = $this->getChildBlock('invoice_totals');
         if ($totals) {
             $totals->setInvoice($invoice);
             $html = $totals->toHtml();
diff --git a/app/code/core/Mage/Sales/Block/Order/Shipment/Items.php b/app/code/core/Mage/Sales/Block/Order/Shipment/Items.php
index 62e82a733fbbad8acfb6b64b58b26d424d6e7607..3b1d11b879c18852855adc6bd2ff18cb56dbddfa 100644
--- a/app/code/core/Mage/Sales/Block/Order/Shipment/Items.php
+++ b/app/code/core/Mage/Sales/Block/Order/Shipment/Items.php
@@ -60,7 +60,7 @@ class Mage_Sales_Block_Order_Shipment_Items extends Mage_Sales_Block_Items_Abstr
     public function getCommentsHtml($shipment)
     {
         $html = '';
-        $comments = $this->getChild('shipment_comments');
+        $comments = $this->getChildBlock('shipment_comments');
         if ($comments) {
             $comments->setEntity($shipment)
                 ->setTitle(Mage::helper('Mage_Sales_Helper_Data')->__('About Your Shipment'));
diff --git a/app/code/core/Mage/Sales/Block/Order/Totals.php b/app/code/core/Mage/Sales/Block/Order/Totals.php
index 26c9e6d28c527e67929754307c469a9a7c64773d..48f070e9211758c0aa1d1aeafaf1db6d028d4875 100644
--- a/app/code/core/Mage/Sales/Block/Order/Totals.php
+++ b/app/code/core/Mage/Sales/Block/Order/Totals.php
@@ -44,7 +44,7 @@ class Mage_Sales_Block_Order_Totals extends Mage_Core_Block_Template
     protected function _beforeToHtml()
     {
         $this->_initTotals();
-        foreach ($this->getChild() as $child) {
+        foreach ($this->getLayout()->getChildBlocks($this->getNameInLayout()) as $child) {
             if (method_exists($child, 'initTotals')) {
                 $child->initTotals();
             }
diff --git a/app/code/core/Mage/Sales/Block/Recurring/Profile/View.php b/app/code/core/Mage/Sales/Block/Recurring/Profile/View.php
index 86132518e817575c49594e2691e968c93cdab0cd..80946a31d44173b90645161ac77f134618167aea 100644
--- a/app/code/core/Mage/Sales/Block/Recurring/Profile/View.php
+++ b/app/code/core/Mage/Sales/Block/Recurring/Profile/View.php
@@ -409,7 +409,12 @@ class Mage_Sales_Block_Recurring_Profile_View extends Mage_Core_Block_Template
         }
 
         if ($this->hasShouldPrepareInfoTabs()) {
-            foreach ($this->getChildGroup('info_tabs') as $block) {
+            $layout = $this->getLayout();
+            foreach ($this->getGroupChildNames('info_tabs') as $name) {
+                $block = $layout->getBlock($name);
+                if (!$block) {
+                    continue;
+                }
                 $block->setViewUrl(
                     $this->getUrl("*/*/{$block->getViewAction()}", array('profile' => $this->_profile->getId()))
                 );
diff --git a/app/code/core/Mage/Sales/Model/Config/Ordered.php b/app/code/core/Mage/Sales/Model/Config/Ordered.php
new file mode 100644
index 0000000000000000000000000000000000000000..bd89d332946a88d0a807fe3e2fdf7c3d2ffbc690
--- /dev/null
+++ b/app/code/core/Mage/Sales/Model/Config/Ordered.php
@@ -0,0 +1,240 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Configuration class for ordered items
+ *
+ * @category    Mage
+ * @package     Mage_Sales
+ * @author      Magento Core Team <core@magentocommerce.com>
+ */
+abstract class Mage_Sales_Model_Config_Ordered extends Mage_Core_Model_Config_Base
+{
+    /**
+     * Cache key for collectors
+     *
+     * @var string|null
+     */
+    protected $_collectorsCacheKey = null;
+
+    /**
+     * Configuration path where to collect registered totals
+     *
+     * @var string|null
+     */
+    protected $_totalsConfigNode = null;
+
+    /**
+     * Prepared models
+     *
+     * @var array
+     */
+    protected $_models = array();
+
+    /**
+     * Models configuration
+     *
+     * @var array
+     */
+    protected $_modelsConfig = array();
+
+    /**
+     * Sorted models
+     *
+     * @var array
+     */
+    protected $_collectors = array();
+
+    /**
+     * Initialize total models configuration and objects
+     *
+     * @return Mage_Sales_Model_Config_Ordered
+     */
+    protected function _initModels()
+    {
+        $totalsConfig = $this->getNode($this->_totalsConfigNode);
+
+        foreach ($totalsConfig->children() as $totalCode => $totalConfig) {
+            $class = $totalConfig->getClassName();
+            if (!empty($class)) {
+                $this->_models[$totalCode] = $this->_initModelInstance($class, $totalCode, $totalConfig);
+            }
+        }
+        return $this;
+    }
+
+    /**
+     * Init model class by configuration
+     *
+     * @abstract
+     * @param string $class
+     * @param string $totalCode
+     * @param array $totalConfig
+     * @return mixed
+     */
+    abstract protected function _initModelInstance($class, $totalCode, $totalConfig);
+
+    /**
+     * Prepare configuration array for total model
+     *
+     * @param   string $code
+     * @param   Mage_Core_Model_Config_Element $totalConfig
+     * @return  array
+     */
+    protected function _prepareConfigArray($code, $totalConfig)
+    {
+        $totalConfig = (array)$totalConfig;
+        if (isset($totalConfig['before'])) {
+            $totalConfig['before'] = explode(',', $totalConfig['before']);
+        } else {
+            $totalConfig['before'] = array();
+        }
+        if (isset($totalConfig['after'])) {
+            $totalConfig['after'] = explode(',', $totalConfig['after']);
+        } else {
+            $totalConfig['after'] = array();
+        }
+        $totalConfig['_code'] = $code;
+        return $totalConfig;
+    }
+
+    /**
+     * Aggregate before/after information from all items and sort totals based on this data
+     *
+     * @return array
+     */
+    protected function _getSortedCollectorCodes()
+    {
+        if (Mage::app()->useCache('config')) {
+            $cachedData = Mage::app()->loadCache($this->_collectorsCacheKey);
+            if ($cachedData) {
+                return unserialize($cachedData);
+            }
+        }
+        $configArray = $this->_modelsConfig;
+        // invoke simple sorting if the first element contains the "sort_order" key
+        reset($configArray);
+        $element = current($configArray);
+        if (isset($element['sort_order'])) {
+            uasort($configArray, array($this, '_compareSortOrder'));
+        } else {
+            foreach ($configArray as $code => $data) {
+                foreach ($data['before'] as $beforeCode) {
+                    if (!isset($configArray[$beforeCode])) {
+                        continue;
+                    }
+                    $configArray[$code]['before'] = array_unique(array_merge(
+                        $configArray[$code]['before'], $configArray[$beforeCode]['before']
+                    ));
+                    $configArray[$beforeCode]['after'] = array_merge(
+                        $configArray[$beforeCode]['after'], array($code), $data['after']
+                    );
+                    $configArray[$beforeCode]['after'] = array_unique($configArray[$beforeCode]['after']);
+                }
+                foreach ($data['after'] as $afterCode) {
+                    if (!isset($configArray[$afterCode])) {
+                        continue;
+                    }
+                    $configArray[$code]['after'] = array_unique(array_merge(
+                        $configArray[$code]['after'], $configArray[$afterCode]['after']
+                    ));
+                    $configArray[$afterCode]['before'] = array_merge(
+                        $configArray[$afterCode]['before'], array($code), $data['before']
+                    );
+                    $configArray[$afterCode]['before'] = array_unique($configArray[$afterCode]['before']);
+                }
+            }
+            uasort($configArray, array($this, '_compareTotals'));
+        }
+        $sortedCollectors = array_keys($configArray);
+        if (Mage::app()->useCache('config')) {
+            Mage::app()->saveCache(serialize($sortedCollectors), $this->_collectorsCacheKey, array(
+                    Mage_Core_Model_Config::CACHE_TAG
+                )
+            );
+        }
+        return $sortedCollectors;
+    }
+
+    /**
+     * Initialize collectors array.
+     * Collectors array is array of total models ordered based on configuration settings
+     *
+     * @return  Mage_Sales_Model_Config_Ordered
+     */
+    protected function _initCollectors()
+    {
+        $sortedCodes = $this->_getSortedCollectorCodes();
+        foreach ($sortedCodes as $code) {
+            $this->_collectors[$code] = $this->_models[$code];
+        }
+
+        return $this;
+    }
+
+    /**
+     * Callback that uses after/before for comparison
+     *
+     * @param   array $a
+     * @param   array $b
+     * @return  int
+     */
+    protected function _compareTotals($a, $b)
+    {
+        $aCode = $a['_code'];
+        $bCode = $b['_code'];
+        if (in_array($aCode, $b['after']) || in_array($bCode, $a['before'])) {
+            $res = -1;
+        } elseif (in_array($bCode, $a['after']) || in_array($aCode, $b['before'])) {
+            $res = 1;
+        } else {
+            $res = 0;
+        }
+        return $res;
+    }
+
+    /**
+     * Callback that uses sort_order for comparison
+     *
+     * @param array $a
+     * @param array $b
+     * @return int
+     */
+    protected function _compareSortOrder($a, $b)
+    {
+        if (!isset($a['sort_order']) || !isset($b['sort_order'])) {
+            return 0;
+        }
+        if ($a['sort_order'] > $b['sort_order']) {
+            $res = 1;
+        } elseif ($a['sort_order'] < $b['sort_order']) {
+            $res = -1;
+        } else {
+            $res = 0;
+        }
+        return $res;
+    }
+}
diff --git a/app/code/core/Mage/Sales/Model/Observer.php b/app/code/core/Mage/Sales/Model/Observer.php
index 4488b5a2861355e6344945992f65a2a5c256e120..126e765e42f9f9679b2389533de42f4a956d7581 100644
--- a/app/code/core/Mage/Sales/Model/Observer.php
+++ b/app/code/core/Mage/Sales/Model/Observer.php
@@ -434,9 +434,6 @@ class Mage_Sales_Model_Observer
         /** @var $customerHelper Mage_Customer_Helper_Data */
         $customerHelper = Mage::helper('Mage_Customer_Helper_Data');
 
-        $customerAddressId = $quoteAddress->getCustomerAddressId();
-        $customerDefaultAddressId = $this->_getVatRequiredCustomerAddress($customerInstance, $storeId);
-
         $customerCountryCode = $quoteAddress->getCountryId();
         $customerVatNumber = $quoteAddress->getVatId();
 
@@ -487,16 +484,15 @@ class Mage_Sales_Model_Observer
             ));
         }
 
-        if ($customerAddressId != $customerDefaultAddressId || is_null($customerDefaultAddressId)) {
-            $groupId = $customerHelper->getCustomerGroupIdBasedOnVatNumber(
-                $customerCountryCode, $gatewayResponse, $customerInstance->getStore()
-            );
+        // Magento always has to emulate group even if customer uses default billing/shipping address
+        $groupId = $customerHelper->getCustomerGroupIdBasedOnVatNumber(
+            $customerCountryCode, $gatewayResponse, $customerInstance->getStore()
+        );
 
-            if ($groupId) {
-                $quoteAddress->setPrevQuoteCustomerGroupId($quoteInstance->getCustomerGroupId());
-                $customerInstance->setGroupId($groupId);
-                $quoteInstance->setCustomerGroupId($groupId);
-            }
+        if ($groupId) {
+            $quoteAddress->setPrevQuoteCustomerGroupId($quoteInstance->getCustomerGroupId());
+            $customerInstance->setGroupId($groupId);
+            $quoteInstance->setCustomerGroupId($groupId);
         }
     }
 
diff --git a/app/code/core/Mage/Sales/Model/Order.php b/app/code/core/Mage/Sales/Model/Order.php
index 146e20357fcbdb54f07f106f2c6d92344005a07f..5b9fcc5a33bdd96a920f0548eb3c0a3a92b93b95 100644
--- a/app/code/core/Mage/Sales/Model/Order.php
+++ b/app/code/core/Mage/Sales/Model/Order.php
@@ -743,6 +743,27 @@ class Mage_Sales_Model_Order extends Mage_Sales_Model_Abstract
      * @return bool
      */
     public function canReorder()
+    {
+        return $this->_canReorder(false);
+    }
+
+    /**
+     * Check the ability to reorder ignoring the availability in stock or status of the ordered products
+     *
+     * @return bool
+     */
+    public function canReorderIgnoreSalable()
+    {
+        return $this->_canReorder(true);
+    }
+
+    /**
+     * Retrieve order reorder availability
+     *
+     * @param bool $ignoreSalable
+     * @return bool
+     */
+    protected function _canReorder($ignoreSalable = false)
     {
         if ($this->canUnhold() || $this->isPaymentReview() || !$this->getCustomerId()) {
             return false;
@@ -778,7 +799,7 @@ class Mage_Sales_Model_Order extends Mage_Sales_Model_Abstract
                 $product = Mage::getModel('Mage_Catalog_Model_Product')
                     ->setStoreId($this->getStoreId())
                     ->load($productId);
-                if (!$product->getId() || !$product->isSalable()) {
+                if (!$product->getId() || (!$ignoreSalable && !$product->isSalable())) {
                     return false;
                 }
             }
diff --git a/app/code/core/Mage/Sales/Model/Order/Creditmemo/Config.php b/app/code/core/Mage/Sales/Model/Order/Creditmemo/Config.php
index 6b374a8d853e3b30f3d62f3c46b4289398f57b5f..7c80acd8d5ec8c2193cba28721b7cb1951af48db 100644
--- a/app/code/core/Mage/Sales/Model/Order/Creditmemo/Config.php
+++ b/app/code/core/Mage/Sales/Model/Order/Creditmemo/Config.php
@@ -31,32 +31,20 @@
  * @package    Mage_Sales
  * @author      Magento Core Team <core@magentocommerce.com>
  */
-class Mage_Sales_Model_Order_Creditmemo_Config extends Mage_Core_Model_Config_Base
+class Mage_Sales_Model_Order_Creditmemo_Config extends Mage_Sales_Model_Order_Total_Config_Base
 {
-    protected $_totalModels = null;
-
-    public function __construct()
-    {
-        parent::__construct(Mage::getConfig()->getNode('global/sales/order_creditmemo'));
-    }
-
     /**
-     * Retrieve invoice total calculation models
+     * Cache key for collectors
      *
-     * @return array
+     * @var string
      */
-    public function getTotalModels()
+    protected $_collectorsCacheKey = 'sorted_order_creditmemo_collectors';
+
+    /**
+     * Constructor
+     */
+    public function __construct()
     {
-        if (is_null($this->_totalModels)) {
-            $this->_totalModels = array();
-            $totalsConfig = $this->getNode('totals');
-            foreach ($totalsConfig->children() as $totalCode=>$totalConfig) {
-                $class = $totalConfig->getClassName();
-                if ($class && ($model = Mage::getModel($class))) {
-                    $this->_totalModels[] = $model;
-                }
-            }
-        }
-        return $this->_totalModels;
+        parent::__construct(Mage::getConfig()->getNode('global/sales/order_creditmemo'));
     }
 }
diff --git a/app/code/core/Mage/Sales/Model/Order/Creditmemo/Total/Abstract.php b/app/code/core/Mage/Sales/Model/Order/Creditmemo/Total/Abstract.php
index dcdc0b41e61980326f569c191d34be7b6fb65c88..3b029a01d1b3f3f8233826ead6784153e04bdf9c 100644
--- a/app/code/core/Mage/Sales/Model/Order/Creditmemo/Total/Abstract.php
+++ b/app/code/core/Mage/Sales/Model/Order/Creditmemo/Total/Abstract.php
@@ -24,10 +24,22 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
-abstract class Mage_Sales_Model_Order_Creditmemo_Total_Abstract
+/**
+ * Base class for credit memo total
+ *
+ * @category    Mage
+ * @package     Mage_Sales
+ * @author      Magento Core Team <core@magentocommerce.com>
+ */
+abstract class Mage_Sales_Model_Order_Creditmemo_Total_Abstract extends Mage_Sales_Model_Order_Total_Abstract
 {
-    public function collect(Mage_Sales_Model_Order_Creditmemo $invoice)
+    /**
+     * Collect credit memo subtotal
+     *
+     * @param Mage_Sales_Model_Order_Creditmemo $creditmemo
+     * @return Mage_Sales_Model_Order_Creditmemo_Total_Abstract
+     */
+    public function collect(Mage_Sales_Model_Order_Creditmemo $creditmemo)
     {
         return $this;
     }
diff --git a/app/code/core/Mage/Sales/Model/Order/Invoice/Config.php b/app/code/core/Mage/Sales/Model/Order/Invoice/Config.php
index 98ec1dba7f8171ced626b503f4a2266e333edb3d..ce62386259582cc1bb188439d513932dd08ed635 100644
--- a/app/code/core/Mage/Sales/Model/Order/Invoice/Config.php
+++ b/app/code/core/Mage/Sales/Model/Order/Invoice/Config.php
@@ -31,32 +31,20 @@
  * @package    Mage_Sales
  * @author      Magento Core Team <core@magentocommerce.com>
  */
-class Mage_Sales_Model_Order_Invoice_Config extends Mage_Core_Model_Config_Base
+class Mage_Sales_Model_Order_Invoice_Config extends Mage_Sales_Model_Order_Total_Config_Base
 {
-    protected $_totalModels = null;
-
-    public function __construct()
-    {
-        parent::__construct(Mage::getConfig()->getNode('global/sales/order_invoice'));
-    }
-
     /**
-     * Retrieve invoice total calculation models
+     * Cache key for collectors
      *
-     * @return array
+     * @var string
      */
-    public function getTotalModels()
+    protected $_collectorsCacheKey = 'sorted_order_invoice_collectors';
+
+    /**
+     * Constructor
+     */
+    public function __construct()
     {
-        if (is_null($this->_totalModels)) {
-            $this->_totalModels = array();
-            $totalsConfig = $this->getNode('totals');
-            foreach ($totalsConfig->children() as $totalCode=>$totalConfig) {
-                $class = $totalConfig->getClassName();
-                if ($class && ($model = Mage::getModel($class))) {
-                    $this->_totalModels[] = $model;
-                }
-            }
-        }
-        return $this->_totalModels;
+        parent::__construct(Mage::getConfig()->getNode('global/sales/order_invoice'));
     }
 }
diff --git a/app/code/core/Mage/Sales/Model/Order/Invoice/Total/Abstract.php b/app/code/core/Mage/Sales/Model/Order/Invoice/Total/Abstract.php
index b06ae622f271fce02f0955d173f1424ee8903a8a..3a16ce424c39d0f0268d1ae64d2e4df3b282c70f 100644
--- a/app/code/core/Mage/Sales/Model/Order/Invoice/Total/Abstract.php
+++ b/app/code/core/Mage/Sales/Model/Order/Invoice/Total/Abstract.php
@@ -24,9 +24,21 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
-abstract class Mage_Sales_Model_Order_Invoice_Total_Abstract
+/**
+ * Base class for invoice total
+ *
+ * @category    Mage
+ * @package     Mage_Sales
+ * @author      Magento Core Team <core@magentocommerce.com>
+ */
+abstract class Mage_Sales_Model_Order_Invoice_Total_Abstract extends Mage_Sales_Model_Order_Total_Abstract
 {
+    /**
+     * Collect invoice subtotal
+     *
+     * @param Mage_Sales_Model_Order_Invoice $invoice
+     * @return Mage_Sales_Model_Order_Invoice_Total_Abstract
+     */
     public function collect(Mage_Sales_Model_Order_Invoice $invoice)
     {
         return $this;
diff --git a/app/code/core/Mage/Sales/Model/Order/Invoice/Total/Discount.php b/app/code/core/Mage/Sales/Model/Order/Invoice/Total/Discount.php
index 5b0068531df68ee4dfd3995c7c5446f4a2babf42..da63378919143df9c94e6e9c86ff2eaa65b4bc87 100644
--- a/app/code/core/Mage/Sales/Model/Order/Invoice/Total/Discount.php
+++ b/app/code/core/Mage/Sales/Model/Order/Invoice/Total/Discount.php
@@ -54,10 +54,14 @@ class Mage_Sales_Model_Order_Invoice_Total_Discount extends Mage_Sales_Model_Ord
 
         /** @var $item Mage_Sales_Model_Order_Invoice_Item */
         foreach ($invoice->getAllItems() as $item) {
-            if ($item->getOrderItem()->isDummy()) {
-                continue;
-            }
             $orderItem = $item->getOrderItem();
+            $parentOrderItem = $orderItem->getParentItem();
+            if (($orderItem->isDummy() && !$orderItem->getForceApplyDiscountToParentItem())
+                || ($parentOrderItem && $orderItem->getForceApplyDiscountToParentItem())
+            ) {
+                 continue;
+            }
+
             $orderItemDiscount      = (float) $orderItem->getDiscountAmount();
             $baseOrderItemDiscount  = (float) $orderItem->getBaseDiscountAmount();
             $orderItemQty       = $orderItem->getQtyOrdered();
diff --git a/app/code/core/Mage/Sales/Model/Order/Item.php b/app/code/core/Mage/Sales/Model/Order/Item.php
index 317328a224f23bd7a60e97e3472b85594e4d54ed..cb4a7a706f5d86a4fdbf038ced7d15bfeb9dfa9c 100644
--- a/app/code/core/Mage/Sales/Model/Order/Item.php
+++ b/app/code/core/Mage/Sales/Model/Order/Item.php
@@ -642,6 +642,21 @@ class Mage_Sales_Model_Order_Item extends Mage_Core_Model_Abstract
         }
         return false;
     }
+    /**
+     * Check if discount has to be applied to parent item
+     *
+     * @return bool
+     */
+    public function getForceApplyDiscountToParentItem()
+    {
+        if ($this->getParentItem()) {
+            $product = $this->getParentItem()->getProduct();
+        } else {
+            $product = $this->getProduct();
+        }
+
+        return $product->getTypeInstance()->getForceApplyDiscountToParentItem();
+    }
 
     /**
      * Return checking of what shipment
@@ -724,4 +739,19 @@ class Mage_Sales_Model_Order_Item extends Mage_Core_Model_Abstract
         $buyRequest->setQty($this->getQtyOrdered() * 1);
         return $buyRequest;
     }
+
+    /**
+     * Retrieve product
+     *
+     * @return Mage_Catalog_Model_Product
+     */
+    public function getProduct()
+    {
+        if (!$this->getData('product')) {
+            $product = Mage::getModel('Mage_Catalog_Model_Product')->load($this->getProductId());
+            $this->setProduct($product);
+        }
+
+        return $this->getData('product');
+    }
 }
diff --git a/app/code/core/Mage/Sales/Model/Order/Pdf/Abstract.php b/app/code/core/Mage/Sales/Model/Order/Pdf/Abstract.php
index 5fe6c0d968b78a721837b20643277fab47f96d0b..b6a01f03bc639d5626f2085f8f1a7069c2f8beb4 100644
--- a/app/code/core/Mage/Sales/Model/Order/Pdf/Abstract.php
+++ b/app/code/core/Mage/Sales/Model/Order/Pdf/Abstract.php
@@ -24,7 +24,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
 /**
  * Sales Order PDF abstract model
  *
@@ -34,7 +33,13 @@
  */
 abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
 {
+    /**
+     * Y coordinate
+     *
+     * @var int
+     */
     public $y;
+
     /**
      * Item renderers with render type key
      *
@@ -45,9 +50,12 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
      */
     protected $_renderers = array();
 
-    const XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID = 'sales_pdf/invoice/put_order_id';
-    const XML_PATH_SALES_PDF_SHIPMENT_PUT_ORDER_ID = 'sales_pdf/shipment/put_order_id';
-    const XML_PATH_SALES_PDF_CREDITMEMO_PUT_ORDER_ID = 'sales_pdf/creditmemo/put_order_id';
+    /**
+     * Predefined constants
+     */
+    const XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID       = 'sales_pdf/invoice/put_order_id';
+    const XML_PATH_SALES_PDF_SHIPMENT_PUT_ORDER_ID      = 'sales_pdf/shipment/put_order_id';
+    const XML_PATH_SALES_PDF_CREDITMEMO_PUT_ORDER_ID    = 'sales_pdf/creditmemo/put_order_id';
 
     /**
      * Zend PDF object
@@ -56,6 +64,11 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
      */
     protected $_pdf;
 
+    /**
+     * Default total model
+     *
+     * @var string
+     */
     protected $_defaultTotalModel = 'Mage_Sales_Model_Order_Pdf_Total_Default';
 
     /**
@@ -74,9 +87,9 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
      * Similar calculations exist inside the layout manager class, but widths are
      * generally calculated only after determining line fragments.
      *
-     * @param string $string
-     * @param Zend_Pdf_Resource_Font $font
-     * @param float $fontSize Font size in points
+     * @param  string $string
+     * @param  Zend_Pdf_Resource_Font $font
+     * @param  float $fontSize Font size in points
      * @return float
      */
     public function widthForStringUsingFontSize($string, $font, $fontSize)
@@ -99,12 +112,12 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
     /**
      * Calculate coordinates to draw something in a column aligned to the right
      *
-     * @param string $string
-     * @param int $x
-     * @param int $columnWidth
-     * @param Zend_Pdf_Resource_Font $font
-     * @param int $fontSize
-     * @param int $padding
+     * @param  string $string
+     * @param  int $x
+     * @param  int $columnWidth
+     * @param  Zend_Pdf_Resource_Font $font
+     * @param  int $fontSize
+     * @param  int $padding
      * @return int
      */
     public function getAlignRight($string, $x, $columnWidth, Zend_Pdf_Resource_Font $font, $fontSize, $padding = 5)
@@ -116,11 +129,11 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
     /**
      * Calculate coordinates to draw something in a column aligned to the center
      *
-     * @param string $string
-     * @param int $x
-     * @param int $columnWidth
-     * @param Zend_Pdf_Resource_Font $font
-     * @param int $fontSize
+     * @param  string $string
+     * @param  int $x
+     * @param  int $columnWidth
+     * @param  Zend_Pdf_Resource_Font $font
+     * @param  int $fontSize
      * @return int
      */
     public function getAlignCenter($string, $x, $columnWidth, Zend_Pdf_Resource_Font $font, $fontSize)
@@ -129,50 +142,91 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
         return $x + round(($columnWidth - $width) / 2);
     }
 
+    /**
+     * Insert logo to pdf page
+     *
+     * @param Zend_Pdf_Page $page
+     * @param null $store
+     */
     protected function insertLogo(&$page, $store = null)
     {
+        $this->y = $this->y ? $this->y : 815;
         $image = Mage::getStoreConfig('sales/identity/logo', $store);
         if ($image) {
             $image = Mage::getBaseDir('media') . '/sales/store/logo/' . $image;
             if (is_file($image)) {
-                $image = Zend_Pdf_Image::imageWithPath($image);
-                $page->drawImage($image, 25, 800, 125, 825);
+                $image       = Zend_Pdf_Image::imageWithPath($image);
+                $top         = 830; //top border of the page
+                $widthLimit  = 270; //half of the page width
+                $heightLimit = 270; //assuming the image is not a "skyscraper"
+                $width       = $image->getPixelWidth();
+                $height      = $image->getPixelHeight();
+
+                //preserving aspect ratio (proportions)
+                $ratio = $width / $height;
+                if ($ratio > 1 && $width > $widthLimit) {
+                    $width  = $widthLimit;
+                    $height = $width / $ratio;
+                } elseif ($ratio < 1 && $height > $heightLimit) {
+                    $height = $heightLimit;
+                    $width  = $height * $ratio;
+                } elseif ($ratio == 1 && $height > $heightLimit) {
+                    $height = $heightLimit;
+                    $width  = $widthLimit;
+                }
+
+                $y1 = $top - $height;
+                $y2 = $top;
+                $x1 = 25;
+                $x2 = $x1 + $width;
+
+                //coordinates after transformation are rounded by Zend
+                $page->drawImage($image, $x1, $y1, $x2, $y2);
+
+                $this->y = $y1 - 10;
             }
         }
-        //return $page;
     }
 
+    /**
+     * Insert address to pdf page
+     *
+     * @param Zend_Pdf_Page $page
+     * @param null $store
+     */
     protected function insertAddress(&$page, $store = null)
     {
         $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
-        $this->_setFontRegular($page, 5);
-
-        $page->setLineWidth(0.5);
-        $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
-        $page->drawLine(125, 825, 125, 790);
-
+        $font = $this->_setFontRegular($page, 10);
         $page->setLineWidth(0);
-        $this->y = 820;
+        $this->y = $this->y ? $this->y : 815;
+        $top = 815;
         foreach (explode("\n", Mage::getStoreConfig('sales/identity/address', $store)) as $value){
-            if ($value!=='') {
-                $page->drawText(trim(strip_tags($value)), 130, $this->y, 'UTF-8');
-                $this->y -=7;
+            if ($value !== '') {
+                $value = preg_replace('/<br[^>]*>/i', "\n", $value);
+                foreach (Mage::helper('Mage_Core_Helper_String')->str_split($value, 45, true, true) as $_value) {
+                    $page->drawText(trim(strip_tags($_value)),
+                        $this->getAlignRight($_value, 130, 440, $font, 10),
+                        $top,
+                        'UTF-8');
+                    $top -= 10;
+                }
             }
         }
-        //return $page;
+        $this->y = ($this->y > $top) ? $top : $this->y;
     }
 
     /**
      * Format address
      *
-     * @param string $address
+     * @param  string $address
      * @return array
      */
     protected function _formatAddress($address)
     {
         $return = array();
         foreach (explode('|', $address) as $str) {
-            foreach (Mage::helper('Mage_Core_Helper_String')->str_split($str, 65, true, true) as $part) {
+            foreach (Mage::helper('Mage_Core_Helper_String')->str_split($str, 45, true, true) as $part) {
                 if (empty($part)) {
                     continue;
                 }
@@ -182,6 +236,36 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
         return $return;
     }
 
+    /**
+     * Calculate address height
+     *
+     * @param  array $address
+     * @return int Height
+     */
+    protected function _calcAddressHeight($address)
+    {
+        $y = 0;
+        foreach ($address as $value){
+            if ($value !== '') {
+                $text = array();
+                foreach (Mage::helper('Mage_Core_Helper_String')->str_split($value, 55, true, true) as $_value) {
+                    $text[] = $_value;
+                }
+                foreach ($text as $part) {
+                    $y += 15;
+                }
+            }
+        }
+        return $y;
+    }
+
+    /**
+     * Insert order to pdf page
+     *
+     * @param Zend_Pdf_Page $page
+     * @param Mage_Sales_Model_Order $obj
+     * @param bool $putOrderId
+     */
     protected function insertOrder(&$page, $obj, $putOrderId = true)
     {
         if ($obj instanceof Mage_Sales_Model_Order) {
@@ -192,26 +276,36 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
             $order = $shipment->getOrder();
         }
 
-        /* @var $order Mage_Sales_Model_Order */
-        $page->setFillColor(new Zend_Pdf_Color_GrayScale(0.5));
-
-        $page->drawRectangle(25, 790, 570, 755);
+        $this->y = $this->y ? $this->y : 815;
+        $top = $this->y;
 
+        $page->setFillColor(new Zend_Pdf_Color_GrayScale(0.45));
+        $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.45));
+        $page->drawRectangle(25, $top, 570, $top - 55);
         $page->setFillColor(new Zend_Pdf_Color_GrayScale(1));
-        $this->_setFontRegular($page);
-
+        $this->setDocHeaderCoordinates(array(25, $top, 570, $top - 55));
+        $this->_setFontRegular($page, 10);
 
         if ($putOrderId) {
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Order # ').$order->getRealOrderId(), 35, 770, 'UTF-8');
+            $page->drawText(
+                Mage::helper('Mage_Sales_Helper_Data')->__('Order # ') . $order->getRealOrderId(), 35, ($top -= 30), 'UTF-8'
+            );
         }
-        //$page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Order Date: ') . date( 'D M j Y', strtotime( $order->getCreatedAt() ) ), 35, 760, 'UTF-8');
-        $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Order Date: ') . Mage::helper('Mage_Core_Helper_Data')->formatDate($order->getCreatedAtStoreDate(), 'medium', false), 35, 760, 'UTF-8');
+        $page->drawText(
+            Mage::helper('Mage_Sales_Helper_Data')->__('Order Date: ') . Mage::helper('Mage_Core_Helper_Data')->formatDate(
+                $order->getCreatedAtStoreDate(), 'medium', false
+            ),
+            35,
+            ($top -= 15),
+            'UTF-8'
+        );
 
+        $top -= 10;
         $page->setFillColor(new Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
         $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
         $page->setLineWidth(0.5);
-        $page->drawRectangle(25, 755, 275, 730);
-        $page->drawRectangle(275, 755, 570, 730);
+        $page->drawRectangle(25, $top, 275, ($top - 25));
+        $page->drawRectangle(275, $top, 570, ($top - 25));
 
         /* Calculate blocks info */
 
@@ -222,9 +316,10 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
         $paymentInfo = Mage::helper('Mage_Payment_Helper_Data')->getInfoBlock($order->getPayment())
             ->setIsSecureMode(true)
             ->toPdf();
+        $paymentInfo = htmlspecialchars_decode($paymentInfo, ENT_QUOTES);
         $payment = explode('{{pdf_row_separator}}', $paymentInfo);
         foreach ($payment as $key=>$value){
-            if (strip_tags(trim($value))==''){
+            if (strip_tags(trim($value)) == '') {
                 unset($payment[$key]);
             }
         }
@@ -234,58 +329,71 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
         if (!$order->getIsVirtual()) {
             /* Shipping Address */
             $shippingAddress = $this->_formatAddress($order->getShippingAddress()->format('pdf'));
-
             $shippingMethod  = $order->getShippingDescription();
         }
 
         $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
-        $this->_setFontRegular($page);
-        $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('SOLD TO:'), 35, 740 , 'UTF-8');
+        $this->_setFontBold($page, 12);
+        $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Sold to:'), 35, ($top - 15), 'UTF-8');
 
         if (!$order->getIsVirtual()) {
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('SHIP TO:'), 285, 740 , 'UTF-8');
-        }
-        else {
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Payment Method:'), 285, 740 , 'UTF-8');
+            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Ship to:'), 285, ($top - 15), 'UTF-8');
+        } else {
+            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Payment Method:'), 285, ($top - 15), 'UTF-8');
         }
 
-        if (!$order->getIsVirtual()) {
-            $y = 730 - (max(count($billingAddress), count($shippingAddress)) * 10 + 5);
-        }
-        else {
-            $y = 730 - (count($billingAddress) * 10 + 5);
+        $addressesHeight = $this->_calcAddressHeight($billingAddress);
+        if (isset($shippingAddress)) {
+            $addressesHeight = max($addressesHeight, $this->_calcAddressHeight($shippingAddress));
         }
 
         $page->setFillColor(new Zend_Pdf_Color_GrayScale(1));
-        $page->drawRectangle(25, 730, 570, $y);
+        $page->drawRectangle(25, ($top - 25), 570, $top - 33 - $addressesHeight);
         $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
-        $this->_setFontRegular($page);
-        $this->y = 720;
+        $this->_setFontRegular($page, 10);
+        $this->y = $top - 40;
+        $addressesStartY = $this->y;
 
         foreach ($billingAddress as $value){
-            if ($value!=='') {
-                $page->drawText(strip_tags(ltrim($value)), 35, $this->y, 'UTF-8');
-                $this->y -=10;
+            if ($value !== '') {
+                $text = array();
+                foreach (Mage::helper('Mage_Core_Helper_String')->str_split($value, 45, true, true) as $_value) {
+                    $text[] = $_value;
+                }
+                foreach ($text as $part) {
+                    $page->drawText(strip_tags(ltrim($part)), 35, $this->y, 'UTF-8');
+                    $this->y -= 15;
+                }
             }
         }
 
+        $addressesEndY = $this->y;
+
         if (!$order->getIsVirtual()) {
-            $this->y = 720;
+            $this->y = $addressesStartY;
             foreach ($shippingAddress as $value){
                 if ($value!=='') {
-                    $page->drawText(strip_tags(ltrim($value)), 285, $this->y, 'UTF-8');
-                    $this->y -=10;
+                    $text = array();
+                    foreach (Mage::helper('Mage_Core_Helper_String')->str_split($value, 45, true, true) as $_value) {
+                        $text[] = $_value;
+                    }
+                    foreach ($text as $part) {
+                        $page->drawText(strip_tags(ltrim($part)), 285, $this->y, 'UTF-8');
+                        $this->y -= 15;
+                    }
                 }
-
             }
 
+            $addressesEndY = min($addressesEndY, $this->y);
+            $this->y = $addressesEndY;
+
             $page->setFillColor(new Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
             $page->setLineWidth(0.5);
             $page->drawRectangle(25, $this->y, 275, $this->y-25);
             $page->drawRectangle(275, $this->y, 570, $this->y-25);
 
-            $this->y -=15;
-            $this->_setFontBold($page);
+            $this->y -= 15;
+            $this->_setFontBold($page, 12);
             $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
             $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Payment Method'), 35, $this->y, 'UTF-8');
             $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Shipping Method:'), 285, $this->y , 'UTF-8');
@@ -293,36 +401,52 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
             $this->y -=10;
             $page->setFillColor(new Zend_Pdf_Color_GrayScale(1));
 
-            $this->_setFontRegular($page);
+            $this->_setFontRegular($page, 10);
             $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
 
             $paymentLeft = 35;
             $yPayments   = $this->y - 15;
         }
         else {
-            $yPayments   = 720;
+            $yPayments   = $addressesStartY;
             $paymentLeft = 285;
         }
 
         foreach ($payment as $value){
-            if (trim($value)!=='') {
-                $page->drawText(strip_tags(trim($value)), $paymentLeft, $yPayments, 'UTF-8');
-                $yPayments -=10;
+            if (trim($value) != '') {
+                //Printing "Payment Method" lines
+                $value = preg_replace('/<br[^>]*>/i', "\n", $value);
+                foreach (Mage::helper('Mage_Core_Helper_String')->str_split($value, 45, true, true) as $_value) {
+                    $page->drawText(strip_tags(trim($_value)), $paymentLeft, $yPayments, 'UTF-8');
+                    $yPayments -= 15;
+                }
             }
         }
 
-        if (!$order->getIsVirtual()) {
-            $this->y -=15;
-
-            $page->drawText($shippingMethod, 285, $this->y, 'UTF-8');
+        if ($order->getIsVirtual()) {
+            // replacement of Shipments-Payments rectangle block
+            $yPayments = min($addressesEndY, $yPayments);
+            $page->drawLine(25,  ($top - 25), 25,  $yPayments);
+            $page->drawLine(570, ($top - 25), 570, $yPayments);
+            $page->drawLine(25,  $yPayments,  570, $yPayments);
 
-            $yShipments = $this->y;
+            $this->y = $yPayments - 15;
+        } else {
+            $topMargin    = 15;
+            $methodStartY = $this->y;
+            $this->y     -= 15;
 
+            foreach (Mage::helper('Mage_Core_Helper_String')->str_split($shippingMethod, 45, true, true) as $_value) {
+                $page->drawText(strip_tags(trim($_value)), 285, $this->y, 'UTF-8');
+                $this->y -= 15;
+            }
 
-            $totalShippingChargesText = "(" . Mage::helper('Mage_Sales_Helper_Data')->__('Total Shipping Charges') . " " . $order->formatPriceTxt($order->getShippingAmount()) . ")";
+            $yShipments = $this->y;
+            $totalShippingChargesText = "(" . Mage::helper('Mage_Sales_Helper_Data')->__('Total Shipping Charges') . " "
+                . $order->formatPriceTxt($order->getShippingAmount()) . ")";
 
-            $page->drawText($totalShippingChargesText, 285, $yShipments-7, 'UTF-8');
-            $yShipments -=10;
+            $page->drawText($totalShippingChargesText, 285, $yShipments - $topMargin, 'UTF-8');
+            $yShipments -= $topMargin + 10;
 
             $tracks = array();
             if ($shipment) {
@@ -332,27 +456,24 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
                 $page->setFillColor(new Zend_Pdf_Color_Rgb(0.93, 0.92, 0.92));
                 $page->setLineWidth(0.5);
                 $page->drawRectangle(285, $yShipments, 510, $yShipments - 10);
-                $page->drawLine(380, $yShipments, 380, $yShipments - 10);
+                $page->drawLine(400, $yShipments, 400, $yShipments - 10);
                 //$page->drawLine(510, $yShipments, 510, $yShipments - 10);
 
-                $this->_setFontRegular($page);
+                $this->_setFontRegular($page, 9);
                 $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
                 //$page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Carrier'), 290, $yShipments - 7 , 'UTF-8');
                 $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Title'), 290, $yShipments - 7, 'UTF-8');
-                $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Number'), 385, $yShipments - 7, 'UTF-8');
+                $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Number'), 410, $yShipments - 7, 'UTF-8');
 
-                $yShipments -=17;
-                $this->_setFontRegular($page, 6);
+                $yShipments -= 20;
+                $this->_setFontRegular($page, 8);
                 foreach ($tracks as $track) {
 
                     $CarrierCode = $track->getCarrierCode();
-                    if ($CarrierCode!='custom')
-                    {
+                    if ($CarrierCode != 'custom') {
                         $carrier = Mage::getSingleton('Mage_Shipping_Model_Config')->getCarrierInstance($CarrierCode);
                         $carrierTitle = $carrier->getConfigData('title');
-                    }
-                    else
-                    {
+                    } else {
                         $carrierTitle = Mage::helper('Mage_Sales_Helper_Data')->__('Custom Value');
                     }
 
@@ -361,26 +482,48 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
                     $endOfTitle = strlen($track->getTitle()) > $maxTitleLen ? '...' : '';
                     $truncatedTitle = substr($track->getTitle(), 0, $maxTitleLen) . $endOfTitle;
                     //$page->drawText($truncatedCarrierTitle, 285, $yShipments , 'UTF-8');
-                    $page->drawText($truncatedTitle, 300, $yShipments , 'UTF-8');
-                    $page->drawText($track->getNumber(), 395, $yShipments , 'UTF-8');
-                    $yShipments -=7;
+                    $page->drawText($truncatedTitle, 292, $yShipments , 'UTF-8');
+                    $page->drawText($track->getNumber(), 410, $yShipments , 'UTF-8');
+                    $yShipments -= $topMargin - 5;
                 }
             } else {
-                $yShipments -= 7;
+                $yShipments -= $topMargin - 5;
             }
 
             $currentY = min($yPayments, $yShipments);
 
             // replacement of Shipments-Payments rectangle block
-            $page->drawLine(25, $this->y + 15, 25, $currentY);
-            $page->drawLine(25, $currentY, 570, $currentY);
-            $page->drawLine(570, $currentY, 570, $this->y + 15);
+            $page->drawLine(25,  $methodStartY, 25,  $currentY); //left
+            $page->drawLine(25,  $currentY,     570, $currentY); //bottom
+            $page->drawLine(570, $currentY,     570, $methodStartY); //right
 
             $this->y = $currentY;
             $this->y -= 15;
         }
     }
 
+    /**
+     * Insert title and number for concrete document type
+     *
+     * @param  Zend_Pdf_Page $page
+     * @param  string $text
+     * @return void
+     */
+    public function insertDocumentNumber(Zend_Pdf_Page $page, $text)
+    {
+        $page->setFillColor(new Zend_Pdf_Color_GrayScale(1));
+        $this->_setFontRegular($page, 10);
+        $docHeader = $this->getDocHeaderCoordinates();
+        $page->drawText($text, 35, $docHeader[1] - 15, 'UTF-8');
+    }
+
+    /**
+     * Sort totals list
+     *
+     * @param  array $a
+     * @param  array $b
+     * @return int
+     */
     protected function _sortTotalsList($a, $b) {
         if (!isset($a['sort_order']) || !isset($b['sort_order'])) {
             return 0;
@@ -393,6 +536,12 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
         return ($a['sort_order'] > $b['sort_order']) ? 1 : -1;
     }
 
+    /**
+     * Return total list
+     *
+     * @param  Mage_Sales_Model_Abstract $source
+     * @return array
+     */
     protected function _getTotalsList($source)
     {
         $totals = Mage::getConfig()->getNode('global/pdf/totals')->asArray();
@@ -418,6 +567,13 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
         return $totalModels;
     }
 
+    /**
+     * Insert totals to pdf page
+     *
+     * @param  Zend_Pdf_Page $page
+     * @param  Mage_Sales_Model_Abstract $source
+     * @return Zend_Pdf_Page
+     */
     protected function insertTotals($page, $source){
         $order = $source->getOrder();
         $totals = $this->_getTotalsList($source);
@@ -430,6 +586,7 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
                 ->setSource($source);
 
             if ($total->canDisplay()) {
+                $total->setFontSize(10);
                 foreach ($total->getTotalsForDisplay() as $totalData) {
                     $lineBlock['lines'][] = array(
                         array(
@@ -451,10 +608,17 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
             }
         }
 
+        $this->y -= 20;
         $page = $this->drawLineBlocks($page, array($lineBlock));
         return $page;
     }
 
+    /**
+     * Parse item description
+     *
+     * @param  Varien_Object $item
+     * @return array
+     */
     protected function _parseItemDescription($item)
     {
         $matches = array();
@@ -468,7 +632,6 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
 
     /**
      * Before getPdf processing
-     *
      */
     protected function _beforeGetPdf() {
         $translate = Mage::getSingleton('Mage_Core_Model_Translate');
@@ -478,7 +641,6 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
 
     /**
      * After getPdf processing
-     *
      */
     protected function _afterGetPdf() {
         $translate = Mage::getSingleton('Mage_Core_Model_Translate');
@@ -486,6 +648,13 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
         $translate->setTranslateInline(true);
     }
 
+    /**
+     * Format option value process
+     *
+     * @param  array|string $value
+     * @param  Mage_Sales_Model_Order $order
+     * @return string
+     */
     protected function _formatOptionValue($value, $order)
     {
         $resultValue = '';
@@ -505,9 +674,14 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
         }
     }
 
+    /**
+     * Initialize renderer process
+     *
+     * @param string $type
+     */
     protected function _initRenderer($type)
     {
-        $node = Mage::getConfig()->getNode('global/pdf/'.$type);
+        $node = Mage::getConfig()->getNode('global/pdf/' . $type);
         foreach ($node->children() as $renderer) {
             $this->_renderers[$renderer->getName()] = array(
                 'model'     => (string)$renderer,
@@ -519,6 +693,7 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
     /**
      * Retrieve renderer model
      *
+     * @param  string $type
      * @throws Mage_Core_Exception
      * @return Mage_Sales_Model_Order_Pdf_Items_Abstract
      */
@@ -544,7 +719,7 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
      *
      * Retrieve renderer model
      *
-     * @param string $type
+     * @param  string $type
      * @return Mage_Sales_Model_Order_Pdf_Items_Abstract
      */
     public function getRenderer($type)
@@ -555,9 +730,9 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
     /**
      * Draw Item process
      *
-     * @param Varien_Object $item
-     * @param Zend_Pdf_Page $page
-     * @param Mage_Sales_Model_Order $order
+     * @param  Varien_Object $item
+     * @param  Zend_Pdf_Page $page
+     * @param  Mage_Sales_Model_Order $order
      * @return Zend_Pdf_Page
      */
     protected function _drawItem(Varien_Object $item, Zend_Pdf_Page $page, Mage_Sales_Model_Order $order)
@@ -575,6 +750,13 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
         return $renderer->getPage();
     }
 
+    /**
+     * Set font as regular
+     *
+     * @param  Zend_Pdf_Page $object
+     * @param  int $size
+     * @return Zend_Pdf_Resource_Font
+     */
     protected function _setFontRegular($object, $size = 7)
     {
         $font = Zend_Pdf_Font::fontWithPath(Mage::getBaseDir() . '/lib/LinLibertineFont/LinLibertine_Re-4.4.1.ttf');
@@ -582,6 +764,13 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
         return $font;
     }
 
+    /**
+     * Set font as bold
+     *
+     * @param  Zend_Pdf_Page $object
+     * @param  int $size
+     * @return Zend_Pdf_Resource_Font
+     */
     protected function _setFontBold($object, $size = 7)
     {
         $font = Zend_Pdf_Font::fontWithPath(Mage::getBaseDir() . '/lib/LinLibertineFont/LinLibertine_Bd-2.8.1.ttf');
@@ -589,6 +778,13 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
         return $font;
     }
 
+    /**
+     * Set font as italic
+     *
+     * @param  Zend_Pdf_Page $object
+     * @param  int $size
+     * @return Zend_Pdf_Resource_Font
+     */
     protected function _setFontItalic($object, $size = 7)
     {
         $font = Zend_Pdf_Font::fontWithPath(Mage::getBaseDir() . '/lib/LinLibertineFont/LinLibertine_It-2.8.2.ttf');
@@ -599,7 +795,7 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
     /**
      * Set PDF object
      *
-     * @param Zend_Pdf $pdf
+     * @param  Zend_Pdf $pdf
      * @return Mage_Sales_Model_Order_Pdf_Abstract
      */
     protected function _setPdf(Zend_Pdf $pdf)
@@ -626,7 +822,7 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
     /**
      * Create new page and assign to PDF object
      *
-     * @param array $settings
+     * @param  array $settings
      * @return Zend_Pdf_Page
      */
     public function newPage(array $settings = array())
@@ -658,9 +854,9 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
      * align        string; text align (also see feed parametr), optional left, right
      * height       int;line spacing (default 10)
      *
-     * @param Zend_Pdf_Page $page
-     * @param array $draw
-     * @param array $pageSettings
+     * @param  Zend_Pdf_Page $page
+     * @param  array $draw
+     * @param  array $pageSettings
      * @throws Mage_Core_Exception
      * @return Zend_Pdf_Page
      */
@@ -701,12 +897,11 @@ abstract class Mage_Sales_Model_Order_Pdf_Abstract extends Varien_Object
             foreach ($lines as $line) {
                 $maxHeight = 0;
                 foreach ($line as $column) {
-                    $fontSize = empty($column['font_size']) ? 7 : $column['font_size'];
+                    $fontSize = empty($column['font_size']) ? 10 : $column['font_size'];
                     if (!empty($column['font_file'])) {
                         $font = Zend_Pdf_Font::fontWithPath($column['font_file']);
                         $page->setFont($font, $fontSize);
-                    }
-                    else {
+                    } else {
                         $fontStyle = empty($column['font']) ? 'regular' : $column['font'];
                         switch ($fontStyle) {
                             case 'bold':
diff --git a/app/code/core/Mage/Sales/Model/Order/Pdf/Creditmemo.php b/app/code/core/Mage/Sales/Model/Order/Pdf/Creditmemo.php
index b6acea77defb28ed171d58b4cfcdeed96da47a39..de0cd9ed69e297dc33f8c2913260b15c30f636a2 100644
--- a/app/code/core/Mage/Sales/Model/Order/Pdf/Creditmemo.php
+++ b/app/code/core/Mage/Sales/Model/Order/Pdf/Creditmemo.php
@@ -34,6 +34,84 @@
  */
 class Mage_Sales_Model_Order_Pdf_Creditmemo extends Mage_Sales_Model_Order_Pdf_Abstract
 {
+    /**
+     * Draw table header for product items
+     *
+     * @param  Zend_Pdf_Page $page
+     * @return void
+     */
+    protected function _drawHeader(Zend_Pdf_Page $page)
+    {
+        $this->_setFontRegular($page, 10);
+        $page->setFillColor(new Zend_Pdf_Color_RGB(0.93, 0.92, 0.92));
+        $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
+        $page->setLineWidth(0.5);
+        $page->drawRectangle(25, $this->y, 570, $this->y - 30);
+        $this->y -= 10;
+        $page->setFillColor(new Zend_Pdf_Color_RGB(0, 0, 0));
+
+        //columns headers
+        $lines[0][] = array(
+            'text' => Mage::helper('Mage_Sales_Helper_Data')->__('Products'),
+            'feed' => 35,
+        );
+
+        $lines[0][] = array(
+            'text'  => Mage::helper('Mage_Core_Helper_String')->str_split(Mage::helper('Mage_Sales_Helper_Data')->__('SKU'), 12, true, true),
+            'feed'  => 255,
+            'align' => 'right'
+        );
+
+        $lines[0][] = array(
+            'text'  => Mage::helper('Mage_Core_Helper_String')->str_split(Mage::helper('Mage_Sales_Helper_Data')->__('Total (ex)'), 12, true, true),
+            'feed'  => 330,
+            'align' => 'right',
+            //'width' => 50,
+        );
+
+        $lines[0][] = array(
+            'text'  => Mage::helper('Mage_Core_Helper_String')->str_split(Mage::helper('Mage_Sales_Helper_Data')->__('Discount'), 12, true, true),
+            'feed'  => 380,
+            'align' => 'right',
+            //'width' => 50,
+        );
+
+        $lines[0][] = array(
+            'text'  => Mage::helper('Mage_Core_Helper_String')->str_split(Mage::helper('Mage_Sales_Helper_Data')->__('Qty'), 12, true, true),
+            'feed'  => 445,
+            'align' => 'right',
+            //'width' => 30,
+        );
+
+        $lines[0][] = array(
+            'text'  => Mage::helper('Mage_Core_Helper_String')->str_split(Mage::helper('Mage_Sales_Helper_Data')->__('Tax'), 12, true, true),
+            'feed'  => 495,
+            'align' => 'right',
+            //'width' => 45,
+        );
+
+        $lines[0][] = array(
+            'text'  => Mage::helper('Mage_Core_Helper_String')->str_split(Mage::helper('Mage_Sales_Helper_Data')->__('Total (inc)'), 12, true, true),
+            'feed'  => 565,
+            'align' => 'right'
+        );
+
+        $lineBlock = array(
+            'lines'  => $lines,
+            'height' => 10
+        );
+
+        $this->drawLineBlocks($page, array($lineBlock), array('table_header' => true));
+        $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
+        $this->y -= 20;
+    }
+
+    /**
+     * Return PDF document
+     *
+     * @param  array $creditmemos
+     * @return Zend_Pdf
+     */
     public function getPdf($creditmemos = array())
     {
         $this->_beforeGetPdf();
@@ -49,116 +127,56 @@ class Mage_Sales_Model_Order_Pdf_Creditmemo extends Mage_Sales_Model_Order_Pdf_A
                 Mage::app()->getLocale()->emulate($creditmemo->getStoreId());
                 Mage::app()->setCurrentStore($creditmemo->getStoreId());
             }
-            $page = $pdf->newPage(Zend_Pdf_Page::SIZE_A4);
-            $pdf->pages[] = $page;
-
+            $page  = $this->newPage();
             $order = $creditmemo->getOrder();
-
             /* Add image */
             $this->insertLogo($page, $creditmemo->getStore());
-
             /* Add address */
             $this->insertAddress($page, $creditmemo->getStore());
-
             /* Add head */
-            $this->insertOrder($page, $order, Mage::getStoreConfigFlag(self::XML_PATH_SALES_PDF_CREDITMEMO_PUT_ORDER_ID, $order->getStoreId()));
-
-            $page->setFillColor(new Zend_Pdf_Color_GrayScale(1));
-            $this->_setFontRegular($page);
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Credit Memo # ') . $creditmemo->getIncrementId(), 35, 780, 'UTF-8');
-
+            $this->insertOrder(
+                $page,
+                $order,
+                Mage::getStoreConfigFlag(self::XML_PATH_SALES_PDF_CREDITMEMO_PUT_ORDER_ID, $order->getStoreId())
+            );
+            /* Add document text and number */
+            $this->insertDocumentNumber(
+                $page,
+                Mage::helper('Mage_Sales_Helper_Data')->__('Credit Memo # ') . $creditmemo->getIncrementId()
+            );
             /* Add table head */
-            $page->setFillColor(new Zend_Pdf_Color_RGB(0.93, 0.92, 0.92));
-            $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
-            $page->setLineWidth(0.5);
-            $page->drawRectangle(25, $this->y, 570, $this->y-15);
-            $this->y -=10;
-            $page->setFillColor(new Zend_Pdf_Color_RGB(0.4, 0.4, 0.4));
             $this->_drawHeader($page);
-            $this->y -=15;
-
-            $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
-
             /* Add body */
             foreach ($creditmemo->getAllItems() as $item){
                 if ($item->getOrderItem()->getParentItem()) {
                     continue;
                 }
-
-                if ($this->y<20) {
-                    $page = $this->newPage(array('table_header' => true));
-                }
-
                 /* Draw item */
-                $page = $this->_drawItem($item, $page, $order);
+                $this->_drawItem($item, $page, $order);
+                $page = end($pdf->pages);
             }
-
             /* Add totals */
-            $page = $this->insertTotals($page, $creditmemo);
+            $this->insertTotals($page, $creditmemo);
         }
-
         $this->_afterGetPdf();
-
         if ($creditmemo->getStoreId()) {
             Mage::app()->getLocale()->revert();
         }
         return $pdf;
     }
 
-    protected function _drawHeader(Zend_Pdf_Page $page)
-    {
-        $font = $page->getFont();
-        $size = $page->getFontSize();
-
-        $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Products'), $x = 35, $this->y, 'UTF-8');
-        $x += 220;
-
-        $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('SKU'), $x, $this->y, 'UTF-8');
-        $x += 100;
-
-        $text = Mage::helper('Mage_Sales_Helper_Data')->__('Total (ex)');
-        $page->drawText($text, $this->getAlignRight($text, $x, 50, $font, $size), $this->y, 'UTF-8');
-        $x += 50;
-
-        $text = Mage::helper('Mage_Sales_Helper_Data')->__('Discount');
-        $page->drawText($text, $this->getAlignRight($text, $x, 50, $font, $size), $this->y, 'UTF-8');
-        $x += 50;
-
-        $text = Mage::helper('Mage_Sales_Helper_Data')->__('Qty');
-        $page->drawText($text, $this->getAlignCenter($text, $x, 30, $font, $size), $this->y, 'UTF-8');
-        $x += 30;
-
-        $text = Mage::helper('Mage_Sales_Helper_Data')->__('Tax');
-        $page->drawText($text, $this->getAlignRight($text, $x, 45, $font, $size, 10), $this->y, 'UTF-8');
-        $x += 45;
-
-        $text = Mage::helper('Mage_Sales_Helper_Data')->__('Total (inc)');
-        $page->drawText($text, $this->getAlignRight($text, $x, 570 - $x, $font, $size), $this->y, 'UTF-8');
-    }
-
     /**
      * Create new page and assign to PDF object
      *
-     * @param array $settings
+     * @param  array $settings
      * @return Zend_Pdf_Page
      */
     public function newPage(array $settings = array())
     {
         $page = parent::newPage($settings);
-
         if (!empty($settings['table_header'])) {
-            $this->_setFontRegular($page);
-            $page->setFillColor(new Zend_Pdf_Color_RGB(0.93, 0.92, 0.92));
-            $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
-            $page->setLineWidth(0.5);
-            $page->drawRectangle(25, $this->y, 570, $this->y-15);
-            $this->y -=10;
-            $page->setFillColor(new Zend_Pdf_Color_RGB(0.4, 0.4, 0.4));
             $this->_drawHeader($page);
-            $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
-            $this->y -=20;
         }
-
         return $page;
     }
 }
diff --git a/app/code/core/Mage/Sales/Model/Order/Pdf/Invoice.php b/app/code/core/Mage/Sales/Model/Order/Pdf/Invoice.php
index db1600c6247eac1177a47889ed7c9f04ce511635..e03c45b0da85a1b9f0ad4994212c4a89a1ef8345 100644
--- a/app/code/core/Mage/Sales/Model/Order/Pdf/Invoice.php
+++ b/app/code/core/Mage/Sales/Model/Order/Pdf/Invoice.php
@@ -24,7 +24,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
 /**
  * Sales Order Invoice PDF model
  *
@@ -34,6 +33,75 @@
  */
 class Mage_Sales_Model_Order_Pdf_Invoice extends Mage_Sales_Model_Order_Pdf_Abstract
 {
+    /**
+     * Draw header for item table
+     *
+     * @param Zend_Pdf_Page $page
+     * @return void
+     */
+    protected function _drawHeader(Zend_Pdf_Page $page)
+    {
+        /* Add table head */
+        $this->_setFontRegular($page, 10);
+        $page->setFillColor(new Zend_Pdf_Color_RGB(0.93, 0.92, 0.92));
+        $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
+        $page->setLineWidth(0.5);
+        $page->drawRectangle(25, $this->y, 570, $this->y -15);
+        $this->y -= 10;
+        $page->setFillColor(new Zend_Pdf_Color_RGB(0, 0, 0));
+
+        //columns headers
+        $lines[0][] = array(
+            'text' => Mage::helper('Mage_Sales_Helper_Data')->__('Products'),
+            'feed' => 35
+        );
+
+        $lines[0][] = array(
+            'text'  => Mage::helper('Mage_Sales_Helper_Data')->__('SKU'),
+            'feed'  => 290,
+            'align' => 'right'
+        );
+
+        $lines[0][] = array(
+            'text'  => Mage::helper('Mage_Sales_Helper_Data')->__('Qty'),
+            'feed'  => 435,
+            'align' => 'right'
+        );
+
+        $lines[0][] = array(
+            'text'  => Mage::helper('Mage_Sales_Helper_Data')->__('Price'),
+            'feed'  => 360,
+            'align' => 'right'
+        );
+
+        $lines[0][] = array(
+            'text'  => Mage::helper('Mage_Sales_Helper_Data')->__('Tax'),
+            'feed'  => 495,
+            'align' => 'right'
+        );
+
+        $lines[0][] = array(
+            'text'  => Mage::helper('Mage_Sales_Helper_Data')->__('Subtotal'),
+            'feed'  => 565,
+            'align' => 'right'
+        );
+
+        $lineBlock = array(
+            'lines'  => $lines,
+            'height' => 5
+        );
+
+        $this->drawLineBlocks($page, array($lineBlock), array('table_header' => true));
+        $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
+        $this->y -= 20;
+    }
+
+    /**
+     * Return PDF document
+     *
+     * @param  array $invoices
+     * @return Zend_Pdf
+     */
     public function getPdf($invoices = array())
     {
         $this->_beforeGetPdf();
@@ -49,77 +117,48 @@ class Mage_Sales_Model_Order_Pdf_Invoice extends Mage_Sales_Model_Order_Pdf_Abst
                 Mage::app()->getLocale()->emulate($invoice->getStoreId());
                 Mage::app()->setCurrentStore($invoice->getStoreId());
             }
-            $page = $pdf->newPage(Zend_Pdf_Page::SIZE_A4);
-            $pdf->pages[] = $page;
-
+            $page  = $this->newPage();
             $order = $invoice->getOrder();
-
             /* Add image */
             $this->insertLogo($page, $invoice->getStore());
-
             /* Add address */
             $this->insertAddress($page, $invoice->getStore());
-
             /* Add head */
-            $this->insertOrder($page, $order, Mage::getStoreConfigFlag(self::XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID, $order->getStoreId()));
-
-
-            $page->setFillColor(new Zend_Pdf_Color_GrayScale(1));
-            $this->_setFontRegular($page);
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Invoice # ') . $invoice->getIncrementId(), 35, 780, 'UTF-8');
-
+            $this->insertOrder(
+                $page,
+                $order,
+                Mage::getStoreConfigFlag(self::XML_PATH_SALES_PDF_INVOICE_PUT_ORDER_ID, $order->getStoreId())
+            );
+            /* Add document text and number */
+            $this->insertDocumentNumber(
+                $page,
+                Mage::helper('Mage_Sales_Helper_Data')->__('Invoice # ') . $invoice->getIncrementId()
+            );
             /* Add table */
-            $page->setFillColor(new Zend_Pdf_Color_RGB(0.93, 0.92, 0.92));
-            $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
-            $page->setLineWidth(0.5);
-
-            $page->drawRectangle(25, $this->y, 570, $this->y -15);
-            $this->y -=10;
-
-            /* Add table head */
-            $page->setFillColor(new Zend_Pdf_Color_RGB(0.4, 0.4, 0.4));
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Products'), 35, $this->y, 'UTF-8');
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('SKU'), 255, $this->y, 'UTF-8');
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Price'), 380, $this->y, 'UTF-8');
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Qty'), 430, $this->y, 'UTF-8');
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Tax'), 480, $this->y, 'UTF-8');
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Subtotal'), 535, $this->y, 'UTF-8');
-
-            $this->y -=15;
-
-            $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
-
+            $this->_drawHeader($page);
             /* Add body */
             foreach ($invoice->getAllItems() as $item){
                 if ($item->getOrderItem()->getParentItem()) {
                     continue;
                 }
-
-                if ($this->y < 15) {
-                    $page = $this->newPage(array('table_header' => true));
-                }
-
                 /* Draw item */
-                $page = $this->_drawItem($item, $page, $order);
+                $this->_drawItem($item, $page, $order);
+                $page = end($pdf->pages);
             }
-
             /* Add totals */
-            $page = $this->insertTotals($page, $invoice);
-
+            $this->insertTotals($page, $invoice);
             if ($invoice->getStoreId()) {
                 Mage::app()->getLocale()->revert();
             }
         }
-
         $this->_afterGetPdf();
-
         return $pdf;
     }
 
     /**
      * Create new page and assign to PDF object
      *
-     * @param array $settings
+     * @param  array $settings
      * @return Zend_Pdf_Page
      */
     public function newPage(array $settings = array())
@@ -128,27 +167,9 @@ class Mage_Sales_Model_Order_Pdf_Invoice extends Mage_Sales_Model_Order_Pdf_Abst
         $page = $this->_getPdf()->newPage(Zend_Pdf_Page::SIZE_A4);
         $this->_getPdf()->pages[] = $page;
         $this->y = 800;
-
         if (!empty($settings['table_header'])) {
-            $this->_setFontRegular($page);
-            $page->setFillColor(new Zend_Pdf_Color_RGB(0.93, 0.92, 0.92));
-            $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
-            $page->setLineWidth(0.5);
-            $page->drawRectangle(25, $this->y, 570, $this->y-15);
-            $this->y -=10;
-
-            $page->setFillColor(new Zend_Pdf_Color_RGB(0.4, 0.4, 0.4));
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Product'), 35, $this->y, 'UTF-8');
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('SKU'), 255, $this->y, 'UTF-8');
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Price'), 380, $this->y, 'UTF-8');
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Qty'), 430, $this->y, 'UTF-8');
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Tax'), 480, $this->y, 'UTF-8');
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Subtotal'), 535, $this->y, 'UTF-8');
-
-            $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
-            $this->y -=20;
+            $this->_drawHeader($page);
         }
-
         return $page;
     }
 }
diff --git a/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Abstract.php b/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Abstract.php
index adceb806e83cddb839779013da049280a1ebfa6f..d5d51628329e4e71d821a0730c6e295009d0ea85 100644
--- a/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Abstract.php
+++ b/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Abstract.php
@@ -24,7 +24,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
 /**
  * Sales Order Pdf Items renderer Abstract
  *
@@ -72,7 +71,7 @@ abstract class Mage_Sales_Model_Order_Pdf_Items_Abstract extends Mage_Core_Model
     /**
      * Set order model
      *
-     * @param Mage_Sales_Model_Order $order
+     * @param  Mage_Sales_Model_Order $order
      * @return Mage_Sales_Model_Order_Pdf_Items_Abstract
      */
     public function setOrder(Mage_Sales_Model_Order $order)
@@ -84,7 +83,7 @@ abstract class Mage_Sales_Model_Order_Pdf_Items_Abstract extends Mage_Core_Model
     /**
      * Set Source model
      *
-     * @param Mage_Core_Model_Abstract $source
+     * @param  Mage_Core_Model_Abstract $source
      * @return Mage_Sales_Model_Order_Pdf_Items_Abstract
      */
     public function setSource(Mage_Core_Model_Abstract $source)
@@ -96,7 +95,7 @@ abstract class Mage_Sales_Model_Order_Pdf_Items_Abstract extends Mage_Core_Model
     /**
      * Set item object
      *
-     * @param Varien_Object $item
+     * @param  Varien_Object $item
      * @return Mage_Sales_Model_Order_Pdf_Items_Abstract
      */
     public function setItem(Varien_Object $item)
@@ -108,7 +107,7 @@ abstract class Mage_Sales_Model_Order_Pdf_Items_Abstract extends Mage_Core_Model
     /**
      * Set Pdf model
      *
-     * @param Mage_Sales_Model_Order_Pdf_Abstract $pdf
+     * @param  Mage_Sales_Model_Order_Pdf_Abstract $pdf
      * @return Mage_Sales_Model_Order_Pdf_Items_Abstract
      */
     public function setPdf(Mage_Sales_Model_Order_Pdf_Abstract $pdf)
@@ -120,7 +119,7 @@ abstract class Mage_Sales_Model_Order_Pdf_Items_Abstract extends Mage_Core_Model
     /**
      * Set current page
      *
-     * @param Zend_Pdf_Page $page
+     * @param  Zend_Pdf_Page $page
      * @return Mage_Sales_Model_Order_Pdf_Items_Abstract
      */
     public function setPage(Zend_Pdf_Page $page)
@@ -205,6 +204,12 @@ abstract class Mage_Sales_Model_Order_Pdf_Items_Abstract extends Mage_Core_Model
      */
     abstract public function draw();
 
+    /**
+     * Format option value process
+     *
+     * @param  $value
+     * @return string
+     */
     protected function _formatOptionValue($value)
     {
         $order = $this->getOrder();
@@ -268,6 +273,11 @@ abstract class Mage_Sales_Model_Order_Pdf_Items_Abstract extends Mage_Core_Model
         return $prices;
     }
 
+    /**
+     * Retrieve item options
+     *
+     * @return array
+     */
     public function getItemOptions() {
         $result = array();
         if ($options = $this->getItem()->getOrderItem()->getProductOptions()) {
@@ -284,6 +294,12 @@ abstract class Mage_Sales_Model_Order_Pdf_Items_Abstract extends Mage_Core_Model
         return $result;
     }
 
+    /**
+     * Set font as regular
+     *
+     * @param  int $size
+     * @return Zend_Pdf_Resource_Font
+     */
     protected function _setFontRegular($size = 7)
     {
         $font = Zend_Pdf_Font::fontWithPath(Mage::getBaseDir() . '/lib/LinLibertineFont/LinLibertine_Re-4.4.1.ttf');
@@ -291,6 +307,12 @@ abstract class Mage_Sales_Model_Order_Pdf_Items_Abstract extends Mage_Core_Model
         return $font;
     }
 
+    /**
+     * Set font as bold
+     *
+     * @param  int $size
+     * @return Zend_Pdf_Resource_Font
+     */
     protected function _setFontBold($size = 7)
     {
         $font = Zend_Pdf_Font::fontWithPath(Mage::getBaseDir() . '/lib/LinLibertineFont/LinLibertine_Bd-2.8.1.ttf');
@@ -298,6 +320,12 @@ abstract class Mage_Sales_Model_Order_Pdf_Items_Abstract extends Mage_Core_Model
         return $font;
     }
 
+    /**
+     * Set font as italic
+     *
+     * @param  int $size
+     * @return Zend_Pdf_Resource_Font
+     */
     protected function _setFontItalic($size = 7)
     {
         $font = Zend_Pdf_Font::fontWithPath(Mage::getBaseDir() . '/lib/LinLibertineFont/LinLibertine_It-2.8.2.ttf');
@@ -305,6 +333,12 @@ abstract class Mage_Sales_Model_Order_Pdf_Items_Abstract extends Mage_Core_Model
         return $font;
     }
 
+    /**
+     * Return item Sku
+     *
+     * @param  $item
+     * @return mixed
+     */
     public function getSku($item)
     {
         if ($item->getOrderItem()->getProductOptionByCode('simple_sku'))
diff --git a/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Creditmemo/Default.php b/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Creditmemo/Default.php
index 8f22c37fddb320cd838e1965a7cd928b6669ae32..049ab62946f547383644b1822a18f8e28ee9e524 100644
--- a/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Creditmemo/Default.php
+++ b/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Creditmemo/Default.php
@@ -24,7 +24,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
 /**
  * Sales Order Creditmemo Pdf default items renderer
  *
@@ -34,6 +33,9 @@
  */
 class Mage_Sales_Model_Order_Pdf_Items_Creditmemo_Default extends Mage_Sales_Model_Order_Pdf_Items_Abstract
 {
+    /**
+     * Draw process
+     */
     public function draw()
     {
         $order  = $this->getOrder();
@@ -42,25 +44,20 @@ class Mage_Sales_Model_Order_Pdf_Items_Creditmemo_Default extends Mage_Sales_Mod
         $page   = $this->getPage();
         $lines  = array();
 
-        $leftBound  =  35;
-        $rightBound = 565;
-
-        $x = $leftBound;
         // draw Product name
         $stringHelper = Mage::helper('Mage_Core_Helper_String');
         $lines[0] = array(array(
-            'text' => $stringHelper->str_split($item->getName(), 60, true, true),
-            'feed' => $x,
+            'text' => Mage::helper('Mage_Core_Helper_String')->str_split($item->getName(), 35, true, true),
+            'feed' => 35,
         ));
 
-        $x += 220;
         // draw SKU
         $lines[0][] = array(
-            'text'  => $stringHelper->str_split($this->getSku($item), 25),
-            'feed'  => $x
+            'text'  => Mage::helper('Mage_Core_Helper_String')->str_split($this->getSku($item), 17),
+            'feed'  => 255,
+            'align' => 'right'
         );
 
-        $x += 100;
         // draw Total (ex)
         $i = 0;
         $prices = $this->getItemPricesForDisplay();
@@ -69,7 +66,7 @@ class Mage_Sales_Model_Order_Pdf_Items_Creditmemo_Default extends Mage_Sales_Mod
                 // draw Subtotal label
                 $lines[$i][] = array(
                     'text'  => $priceData['label'],
-                    'feed'  => $x,
+                    'feed'  => 330,
                     'align' => 'right',
                     'width' => 50,
                 );
@@ -78,51 +75,43 @@ class Mage_Sales_Model_Order_Pdf_Items_Creditmemo_Default extends Mage_Sales_Mod
             // draw Subtotal
             $lines[$i][] = array(
                 'text'  => $priceData['subtotal'],
-                'feed'  => $x,
+                'feed'  => 330,
                 'font'  => 'bold',
                 'align' => 'right',
-                'width' => 50,
             );
             $i++;
         }
 
-        $x += 50;
         // draw Discount
         $lines[0][] = array(
             'text'  => $order->formatPriceTxt(-$item->getDiscountAmount()),
-            'feed'  => $x,
+            'feed'  => 380,
             'font'  => 'bold',
-            'align' => 'right',
-            'width' => 50,
+            'align' => 'right'
         );
 
-        $x += 50;
         // draw QTY
         $lines[0][] = array(
-            'text'  => $item->getQty()*1,
-            'feed'  => $x,
+            'text'  => $item->getQty() * 1,
+            'feed'  => 445,
             'font'  => 'bold',
-            'align' => 'center',
-            'width' => 30,
+            'align' => 'right',
         );
 
-        $x += 30;
         // draw Tax
         $lines[0][] = array(
             'text'  => $order->formatPriceTxt($item->getTaxAmount()),
-            'feed'  => $x,
+            'feed'  => 495,
             'font'  => 'bold',
-            'align' => 'right',
-            'width' => 45,
+            'align' => 'right'
         );
 
-        $x += 45;
         // draw Subtotal
         $subtotal = $item->getRowTotal()
             + $item->getTaxAmount() + $item->getHiddenTaxAmount() - $item->getDiscountAmount();
         $lines[0][] = array(
             'text'  => $order->formatPriceTxt($subtotal),
-            'feed'  => $rightBound,
+            'feed'  => 565,
             'font'  => 'bold',
             'align' => 'right'
         );
@@ -133,23 +122,23 @@ class Mage_Sales_Model_Order_Pdf_Items_Creditmemo_Default extends Mage_Sales_Mod
             foreach ($options as $option) {
                 // draw options label
                 $lines[][] = array(
-                    'text' => $stringHelper->str_split(strip_tags($option['label']), 70, true, true),
+                    'text' => Mage::helper('Mage_Core_Helper_String')->str_split(strip_tags($option['label']), 40, true, true),
                     'font' => 'italic',
-                    'feed' => $leftBound
+                    'feed' => 35
                 );
 
                 // draw options value
                 $_printValue = isset($option['print_value']) ? $option['print_value'] : strip_tags($option['value']);
                 $lines[][] = array(
-                    'text' => $stringHelper->str_split($_printValue, 50, true, true),
-                    'feed' => $leftBound + 5
+                    'text' => Mage::helper('Mage_Core_Helper_String')->str_split($_printValue, 30, true, true),
+                    'feed' => 40
                 );
             }
         }
 
         $lineBlock = array(
             'lines'  => $lines,
-            'height' => 10
+            'height' => 20
         );
 
         $page = $pdf->drawLineBlocks($page, array($lineBlock), array('table_header' => true));
diff --git a/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Creditmemo/Grouped.php b/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Creditmemo/Grouped.php
index 2133347a7e86fda947b75b50c56f1a13b378f576..498a2ecf31ae446eac62caf1b0a21ba7190a9e15 100644
--- a/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Creditmemo/Grouped.php
+++ b/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Creditmemo/Grouped.php
@@ -24,7 +24,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
 /**
  * Sales Order Creditmemo Pdf grouped items renderer
  *
@@ -34,6 +33,9 @@
  */
 class Mage_Sales_Model_Order_Pdf_Items_Creditmemo_Grouped extends Mage_Sales_Model_Order_Pdf_Items_Creditmemo_Default
 {
+    /**
+     * Draw process
+     */
     public function draw()
     {
         $type = $this->getItem()->getOrderItem()->getRealProductType();
diff --git a/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Invoice/Default.php b/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Invoice/Default.php
index 9a836eb47ca486877363a98cec82245a5cb42e3f..512dfbae2e4ccc8a33a4f74316a896bd294510aa 100644
--- a/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Invoice/Default.php
+++ b/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Invoice/Default.php
@@ -24,7 +24,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
 /**
  * Sales Order Invoice Pdf default items renderer
  *
@@ -36,7 +35,6 @@ class Mage_Sales_Model_Order_Pdf_Items_Invoice_Default extends Mage_Sales_Model_
 {
     /**
      * Draw item line
-     *
      */
     public function draw()
     {
@@ -49,20 +47,22 @@ class Mage_Sales_Model_Order_Pdf_Items_Invoice_Default extends Mage_Sales_Model_
         // draw Product name
         $stringHelper = Mage::helper('Mage_Core_Helper_String');
         $lines[0] = array(array(
-            'text' => $stringHelper->str_split($item->getName(), 60, true, true),
+            'text' => Mage::helper('Mage_Core_Helper_String')->str_split($item->getName(), 35, true, true),
             'feed' => 35,
         ));
 
         // draw SKU
         $lines[0][] = array(
-            'text'  => $stringHelper->str_split($this->getSku($item), 25),
-            'feed'  => 255
+            'text'  => Mage::helper('Mage_Core_Helper_String')->str_split($this->getSku($item), 17),
+            'feed'  => 290,
+            'align' => 'right'
         );
 
         // draw QTY
         $lines[0][] = array(
-            'text'  => $item->getQty()*1,
-            'feed'  => 435
+            'text'  => $item->getQty() * 1,
+            'feed'  => 435,
+            'align' => 'right'
         );
 
         // draw item Prices
@@ -73,13 +73,13 @@ class Mage_Sales_Model_Order_Pdf_Items_Invoice_Default extends Mage_Sales_Model_
                 // draw Price label
                 $lines[$i][] = array(
                     'text'  => $priceData['label'],
-                    'feed'  => 395,
+                    'feed'  => 360,
                     'align' => 'right'
                 );
                 // draw Subtotal label
                 $lines[$i][] = array(
                     'text'  => $priceData['label'],
-                    'feed'  => 565,
+                    'feed'  => 530,
                     'align' => 'right'
                 );
                 $i++;
@@ -87,14 +87,14 @@ class Mage_Sales_Model_Order_Pdf_Items_Invoice_Default extends Mage_Sales_Model_
             // draw Price
             $lines[$i][] = array(
                 'text'  => $priceData['price'],
-                'feed'  => 395,
+                'feed'  => 360,
                 'font'  => 'bold',
                 'align' => 'right'
             );
             // draw Subtotal
             $lines[$i][] = array(
                 'text'  => $priceData['subtotal'],
-                'feed'  => 565,
+                'feed'  => 530,
                 'font'  => 'bold',
                 'align' => 'right'
             );
@@ -115,7 +115,7 @@ class Mage_Sales_Model_Order_Pdf_Items_Invoice_Default extends Mage_Sales_Model_
             foreach ($options as $option) {
                 // draw options label
                 $lines[][] = array(
-                    'text' => $stringHelper->str_split(strip_tags($option['label']), 70, true, true),
+                    'text' => Mage::helper('Mage_Core_Helper_String')->str_split(strip_tags($option['label']), 40, true, true),
                     'font' => 'italic',
                     'feed' => 35
                 );
@@ -129,7 +129,7 @@ class Mage_Sales_Model_Order_Pdf_Items_Invoice_Default extends Mage_Sales_Model_
                     $values = explode(', ', $_printValue);
                     foreach ($values as $value) {
                         $lines[][] = array(
-                            'text' => $stringHelper->str_split($value, 50, true, true),
+                            'text' => Mage::helper('Mage_Core_Helper_String')->str_split($value, 30, true, true),
                             'feed' => 40
                         );
                     }
@@ -139,7 +139,7 @@ class Mage_Sales_Model_Order_Pdf_Items_Invoice_Default extends Mage_Sales_Model_
 
         $lineBlock = array(
             'lines'  => $lines,
-            'height' => 10
+            'height' => 20
         );
 
         $page = $pdf->drawLineBlocks($page, array($lineBlock), array('table_header' => true));
diff --git a/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Invoice/Grouped.php b/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Invoice/Grouped.php
index 71d764fe76a1e53d35138840e29bb4b8a5209330..fb857a01a252a1236752e24928e74fb15c3a68b5 100644
--- a/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Invoice/Grouped.php
+++ b/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Invoice/Grouped.php
@@ -24,7 +24,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
 /**
  * Sales Order Invoice Pdf grouped items renderer
  *
@@ -34,6 +33,9 @@
  */
 class Mage_Sales_Model_Order_Pdf_Items_Invoice_Grouped extends Mage_Sales_Model_Order_Pdf_Items_Invoice_Default
 {
+    /**
+     * Draw process
+     */
     public function draw()
     {
         $type = $this->getItem()->getOrderItem()->getRealProductType();
diff --git a/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Shipment/Default.php b/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Shipment/Default.php
index fadd9ecaa33a877f2070969316cd533478d2f9d8..00da9dbaf4b7e6ce0c9835845a31bea1812c3958 100644
--- a/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Shipment/Default.php
+++ b/app/code/core/Mage/Sales/Model/Order/Pdf/Items/Shipment/Default.php
@@ -24,7 +24,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
 /**
  * Sales Order Shipment Pdf default items renderer
  *
@@ -36,7 +35,6 @@ class Mage_Sales_Model_Order_Pdf_Items_Shipment_Default extends Mage_Sales_Model
 {
     /**
      * Draw item line
-     *
      */
     public function draw()
     {
@@ -48,8 +46,8 @@ class Mage_Sales_Model_Order_Pdf_Items_Shipment_Default extends Mage_Sales_Model
         // draw Product name
         $stringHelper = Mage::helper('Mage_Core_Helper_String');
         $lines[0] = array(array(
-            'text' => $stringHelper->str_split($item->getName(), 60, true, true),
-            'feed' => 60,
+            'text' => Mage::helper('Mage_Core_Helper_String')->str_split($item->getName(), 60, true, true),
+            'feed' => 100,
         ));
 
         // draw QTY
@@ -60,8 +58,9 @@ class Mage_Sales_Model_Order_Pdf_Items_Shipment_Default extends Mage_Sales_Model
 
         // draw SKU
         $lines[0][] = array(
-            'text'  => $stringHelper->str_split($this->getSku($item), 25),
-            'feed'  => 440
+            'text'  => Mage::helper('Mage_Core_Helper_String')->str_split($this->getSku($item), 25),
+            'feed'  => 565,
+            'align' => 'right'
         );
 
         // Custom options
@@ -72,17 +71,19 @@ class Mage_Sales_Model_Order_Pdf_Items_Shipment_Default extends Mage_Sales_Model
                 $lines[][] = array(
                     'text' => $stringHelper->str_split(strip_tags($option['label']), 70, true, true),
                     'font' => 'italic',
-                    'feed' => 60
+                    'feed' => 110
                 );
 
                 // draw options value
                 if ($option['value']) {
-                    $_printValue = isset($option['print_value']) ? $option['print_value'] : strip_tags($option['value']);
+                    $_printValue = isset($option['print_value'])
+                        ? $option['print_value']
+                        : strip_tags($option['value']);
                     $values = explode(', ', $_printValue);
                     foreach ($values as $value) {
                         $lines[][] = array(
-                            'text' => $stringHelper->str_split($value, 50, true, true),
-                            'feed' => 65
+                            'text' => Mage::helper('Mage_Core_Helper_String')->str_split($value, 50, true, true),
+                            'feed' => 115
                         );
                     }
                 }
@@ -91,7 +92,7 @@ class Mage_Sales_Model_Order_Pdf_Items_Shipment_Default extends Mage_Sales_Model
 
         $lineBlock = array(
             'lines'  => $lines,
-            'height' => 10
+            'height' => 20
         );
 
         $page = $pdf->drawLineBlocks($page, array($lineBlock), array('table_header' => true));
diff --git a/app/code/core/Mage/Sales/Model/Order/Pdf/Shipment.php b/app/code/core/Mage/Sales/Model/Order/Pdf/Shipment.php
index e9c3b2f1ba6e8eb1031c2bff132766316b3d4eeb..e6e7cd625db01a62bfa28a82b619d8376cf2426b 100644
--- a/app/code/core/Mage/Sales/Model/Order/Pdf/Shipment.php
+++ b/app/code/core/Mage/Sales/Model/Order/Pdf/Shipment.php
@@ -24,7 +24,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
 /**
  * Sales Order Shipment PDF model
  *
@@ -34,6 +33,56 @@
  */
 class Mage_Sales_Model_Order_Pdf_Shipment extends Mage_Sales_Model_Order_Pdf_Abstract
 {
+    /**
+     * Draw table header for product items
+     *
+     * @param  Zend_Pdf_Page $page
+     * @return void
+     */
+    protected function _drawHeader(Zend_Pdf_Page $page)
+    {
+        /* Add table head */
+        $this->_setFontRegular($page, 10);
+        $page->setFillColor(new Zend_Pdf_Color_RGB(0.93, 0.92, 0.92));
+        $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
+        $page->setLineWidth(0.5);
+        $page->drawRectangle(25, $this->y, 570, $this->y-15);
+        $this->y -= 10;
+        $page->setFillColor(new Zend_Pdf_Color_RGB(0, 0, 0));
+
+        //columns headers
+        $lines[0][] = array(
+            'text' => Mage::helper('Mage_Sales_Helper_Data')->__('Products'),
+            'feed' => 100,
+        );
+
+        $lines[0][] = array(
+            'text'  => Mage::helper('Mage_Sales_Helper_Data')->__('Qty'),
+            'feed'  => 35
+        );
+
+        $lines[0][] = array(
+            'text'  => Mage::helper('Mage_Sales_Helper_Data')->__('SKU'),
+            'feed'  => 565,
+            'align' => 'right'
+        );
+
+        $lineBlock = array(
+            'lines'  => $lines,
+            'height' => 10
+        );
+
+        $this->drawLineBlocks($page, array($lineBlock), array('table_header' => true));
+        $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
+        $this->y -= 20;
+    }
+
+    /**
+     * Return PDF document
+     *
+     * @param  array $shipments
+     * @return Zend_Pdf
+     */
     public function getPdf($shipments = array())
     {
         $this->_beforeGetPdf();
@@ -48,59 +97,36 @@ class Mage_Sales_Model_Order_Pdf_Shipment extends Mage_Sales_Model_Order_Pdf_Abs
                 Mage::app()->getLocale()->emulate($shipment->getStoreId());
                 Mage::app()->setCurrentStore($shipment->getStoreId());
             }
-            $page = $pdf->newPage(Zend_Pdf_Page::SIZE_A4);
-            $pdf->pages[] = $page;
-
+            $page  = $this->newPage();
             $order = $shipment->getOrder();
-
             /* Add image */
             $this->insertLogo($page, $shipment->getStore());
-
             /* Add address */
             $this->insertAddress($page, $shipment->getStore());
-
             /* Add head */
-            $this->insertOrder($page, $shipment, Mage::getStoreConfigFlag(self::XML_PATH_SALES_PDF_SHIPMENT_PUT_ORDER_ID, $order->getStoreId()));
-
-            $page->setFillColor(new Zend_Pdf_Color_GrayScale(1));
-            $this->_setFontRegular($page);
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Packingslip # ') . $shipment->getIncrementId(), 35, 780, 'UTF-8');
-
+            $this->insertOrder(
+                $page,
+                $shipment,
+                Mage::getStoreConfigFlag(self::XML_PATH_SALES_PDF_SHIPMENT_PUT_ORDER_ID, $order->getStoreId())
+            );
+            /* Add document text and number */
+            $this->insertDocumentNumber(
+                $page,
+                Mage::helper('Mage_Sales_Helper_Data')->__('Packingslip # ') . $shipment->getIncrementId()
+            );
             /* Add table */
-            $page->setFillColor(new Zend_Pdf_Color_RGB(0.93, 0.92, 0.92));
-            $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
-            $page->setLineWidth(0.5);
-
-
-            /* Add table head */
-            $page->drawRectangle(25, $this->y, 570, $this->y-15);
-            $this->y -=10;
-            $page->setFillColor(new Zend_Pdf_Color_RGB(0.4, 0.4, 0.4));
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Qty'), 35, $this->y, 'UTF-8');
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Products'), 60, $this->y, 'UTF-8');
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('SKU'), 470, $this->y, 'UTF-8');
-
-            $this->y -=15;
-
-            $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
-
+            $this->_drawHeader($page);
             /* Add body */
-            foreach ($shipment->getAllItems() as $item){
+            foreach ($shipment->getAllItems() as $item) {
                 if ($item->getOrderItem()->getParentItem()) {
                     continue;
                 }
-
-                if ($this->y<15) {
-                    $page = $this->newPage(array('table_header' => true));
-                }
-
                 /* Draw item */
-                $page = $this->_drawItem($item, $page, $order);
+                $this->_drawItem($item, $page, $order);
+                $page = end($pdf->pages);
             }
         }
-
         $this->_afterGetPdf();
-
         if ($shipment->getStoreId()) {
             Mage::app()->getLocale()->revert();
         }
@@ -110,7 +136,7 @@ class Mage_Sales_Model_Order_Pdf_Shipment extends Mage_Sales_Model_Order_Pdf_Abs
     /**
      * Create new page and assign to PDF object
      *
-     * @param array $settings
+     * @param  array $settings
      * @return Zend_Pdf_Page
      */
     public function newPage(array $settings = array())
@@ -119,24 +145,9 @@ class Mage_Sales_Model_Order_Pdf_Shipment extends Mage_Sales_Model_Order_Pdf_Abs
         $page = $this->_getPdf()->newPage(Zend_Pdf_Page::SIZE_A4);
         $this->_getPdf()->pages[] = $page;
         $this->y = 800;
-
         if (!empty($settings['table_header'])) {
-            $this->_setFontRegular($page);
-            $page->setFillColor(new Zend_Pdf_Color_RGB(0.93, 0.92, 0.92));
-            $page->setLineColor(new Zend_Pdf_Color_GrayScale(0.5));
-            $page->setLineWidth(0.5);
-            $page->drawRectangle(25, $this->y, 570, $this->y-15);
-            $this->y -=10;
-
-            $page->setFillColor(new Zend_Pdf_Color_RGB(0.4, 0.4, 0.4));
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Qty'), 35, $this->y, 'UTF-8');
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('Products'), 60, $this->y, 'UTF-8');
-            $page->drawText(Mage::helper('Mage_Sales_Helper_Data')->__('SKU'), 470, $this->y, 'UTF-8');
-
-            $page->setFillColor(new Zend_Pdf_Color_GrayScale(0));
-            $this->y -=20;
+            $this->_drawHeader($page);
         }
-
         return $page;
     }
 }
diff --git a/app/code/core/Mage/Sales/Model/Order/Pdf/Shipment/Packaging.php b/app/code/core/Mage/Sales/Model/Order/Pdf/Shipment/Packaging.php
index 9ab66985130dd5028675939a7b6a219d3e0a2057..21d7269aaab71e0dc674515e9b5606a52e05e5a7 100644
--- a/app/code/core/Mage/Sales/Model/Order/Pdf/Shipment/Packaging.php
+++ b/app/code/core/Mage/Sales/Model/Order/Pdf/Shipment/Packaging.php
@@ -24,7 +24,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
 /**
  * Sales Order Shipment PDF model
  *
@@ -37,7 +36,7 @@ class Mage_Sales_Model_Order_Pdf_Shipment_Packaging extends Mage_Sales_Model_Ord
     /**
      * Format pdf file
      *
-     * @param null $shipment
+     * @param  null $shipment
      * @return Zend_Pdf
      */
     public function getPdf($shipment = null)
@@ -46,8 +45,8 @@ class Mage_Sales_Model_Order_Pdf_Shipment_Packaging extends Mage_Sales_Model_Ord
         $this->_initRenderer('shipment');
 
         $pdf = new Zend_Pdf();
-        $page = $pdf->newPage(Zend_Pdf_Page::SIZE_A4);
-        $pdf->pages[] = $page;
+        $this->_setPdf($pdf);
+        $page = $this->newPage();
 
         if ($shipment->getStoreId()) {
             Mage::app()->getLocale()->emulate($shipment->getStoreId());
@@ -71,7 +70,7 @@ class Mage_Sales_Model_Order_Pdf_Shipment_Packaging extends Mage_Sales_Model_Ord
     /**
      * Draw header block
      *
-     * @param Zend_Pdf_Page $page
+     * @param  Zend_Pdf_Page $page
      * @return Mage_Sales_Model_Order_Pdf_Shipment_Packaging
      */
     protected function _drawHeaderBlock(Zend_Pdf_Page $page) {
@@ -89,7 +88,7 @@ class Mage_Sales_Model_Order_Pdf_Shipment_Packaging extends Mage_Sales_Model_Ord
     /**
      * Draw packages block
      *
-     * @param Zend_Pdf_Page $page
+     * @param  Zend_Pdf_Page $page
      * @return Mage_Sales_Model_Order_Pdf_Shipment_Packaging
      */
     protected function _drawPackageBlock(Zend_Pdf_Page $page)
diff --git a/app/code/core/Mage/Sales/Model/Order/Pdf/Total/Default.php b/app/code/core/Mage/Sales/Model/Order/Pdf/Total/Default.php
index d96c93747e143d7c9136064215e158a752037b53..24d36a3d298bbcf031cd68e34310bd68cc76f5cc 100644
--- a/app/code/core/Mage/Sales/Model/Order/Pdf/Total/Default.php
+++ b/app/code/core/Mage/Sales/Model/Order/Pdf/Total/Default.php
@@ -24,6 +24,13 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
+/**
+ * Sales Order Total PDF model
+ *
+ * @category   Mage
+ * @package    Mage_Sales
+ * @author     Magento Core Team <core@magentocommerce.com>
+ */
 class Mage_Sales_Model_Order_Pdf_Total_Default extends Varien_Object
 {
     /**
diff --git a/app/code/core/Mage/Adminhtml/controllers/Rss/OrderController.php b/app/code/core/Mage/Sales/Model/Order/Total/Abstract.php
similarity index 61%
rename from app/code/core/Mage/Adminhtml/controllers/Rss/OrderController.php
rename to app/code/core/Mage/Sales/Model/Order/Total/Abstract.php
index 9760fd1a79d05e06c04c3480732d42756c3c87e0..760f7aca9ce0f2a949c1e5a57b5d068158e05bf7 100644
--- a/app/code/core/Mage/Adminhtml/controllers/Rss/OrderController.php
+++ b/app/code/core/Mage/Sales/Model/Order/Total/Abstract.php
@@ -19,33 +19,29 @@
  * needs please refer to http://www.magentocommerce.com for more information.
  *
  * @category    Mage
- * @package     Mage_Adminhtml
+ * @package     Mage_Sales
  * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
 /**
- * Customer reviews controller
+ * Base class for configure totals order
  *
- * @category   Mage
- * @package    Mage_Rss
+ * @category    Mage
+ * @package     Mage_Sales
  * @author      Magento Core Team <core@magentocommerce.com>
  */
-
-class Mage_Adminhtml_Rss_OrderController extends Mage_Adminhtml_Controller_Action
+abstract class Mage_Sales_Model_Order_Total_Abstract extends Varien_Object
 {
-    public function preDispatch()
-    {
-        Mage::helper('Mage_Adminhtml_Helper_Rss')->authAdmin('catalog/reviews_ratings');
-        parent::preDispatch();
-        return $this;
-    }
-
-    public function newAction()
+    /**
+     * Process model configuration array.
+     * This method can be used for changing models apply sort order
+     *
+     * @param   array $config
+     * @return  array
+     */
+    public function processConfigArray($config)
     {
-        Mage::helper('Mage_Rss_Helper_Data')->authAdmin('sales/order');
-        $this->getResponse()->setHeader('Content-type', 'text/xml; charset=UTF-8');
-        $this->loadLayout(false);
-        $this->renderLayout();
+        return $config;
     }
 }
diff --git a/app/code/core/Mage/Sales/Model/Order/Total/Config/Base.php b/app/code/core/Mage/Sales/Model/Order/Total/Config/Base.php
new file mode 100644
index 0000000000000000000000000000000000000000..270a85ae420eeb79c67d90f8ebbbfc8edb65e274
--- /dev/null
+++ b/app/code/core/Mage/Sales/Model/Order/Total/Config/Base.php
@@ -0,0 +1,94 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Configuration class for totals
+ *
+ *
+ * @category    Mage
+ * @package     Mage_Sales
+ * @author      Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_Sales_Model_Order_Total_Config_Base extends Mage_Sales_Model_Config_Ordered
+{
+    /**
+     * Cache key for collectors
+     *
+     * @var string
+     */
+    protected $_collectorsCacheKey = 'sorted_collectors';
+
+    /**
+     * Total models list
+     *
+     * @var array
+     */
+    protected $_totalModels = array();
+
+    /**
+     * Configuration path where to collect registered totals
+     *
+     * @var string
+     */
+    protected $_totalsConfigNode = 'totals';
+
+    /**
+     * Init model class by configuration
+     *
+     * @param string $class
+     * @param string $totalCode
+     * @param array $totalConfig
+     * @return Mage_Sales_Model_Order_Total_Abstract
+     */
+    protected function _initModelInstance($class, $totalCode, $totalConfig)
+    {
+        $model = Mage::getModel($class);
+        if (!$model instanceof Mage_Sales_Model_Order_Total_Abstract) {
+            Mage::throwException(Mage::helper('Mage_Sales_Helper_Data')->__('Total model should be extended from Mage_Sales_Model_Order_Total_Abstract.'));
+        }
+
+        $model->setCode($totalCode);
+        $model->setTotalConfigNode($totalConfig);
+        $this->_modelsConfig[$totalCode] = $this->_prepareConfigArray($totalCode, $totalConfig);
+        $this->_modelsConfig[$totalCode] = $model->processConfigArray($this->_modelsConfig[$totalCode]);
+        return $model;
+    }
+
+    /**
+     * Retrieve total calculation models
+     *
+     * @return array
+     */
+    public function getTotalModels()
+    {
+        if (empty($this->_totalModels)) {
+            $this->_initModels();
+            $this->_initCollectors();
+            $this->_totalModels = $this->_collectors;
+        }
+        return $this->_totalModels;
+    }
+}
diff --git a/app/code/core/Mage/Sales/Model/Quote.php b/app/code/core/Mage/Sales/Model/Quote.php
index 1a4f80357537cc3194baf0e5398dff2daa2e0dbc..f58df52ea805be35ca8d7428c90f5127e0ab8416 100644
--- a/app/code/core/Mage/Sales/Model/Quote.php
+++ b/app/code/core/Mage/Sales/Model/Quote.php
@@ -69,8 +69,8 @@
  * @method float getBaseGrandTotal()
  * @method Mage_Sales_Model_Quote setBaseGrandTotal(float $value)
  * @method Mage_Sales_Model_Quote setCheckoutMethod(string $value)
- * @method int|null getCustomerId()
- * @method Mage_Sales_Model_Quote setCustomerId(int|null $value)
+ * @method int getCustomerId()
+ * @method Mage_Sales_Model_Quote setCustomerId(int $value)
  * @method Mage_Sales_Model_Quote setCustomerTaxClassId(int $value)
  * @method Mage_Sales_Model_Quote setCustomerGroupId(int $value)
  * @method string getCustomerEmail()
@@ -818,8 +818,12 @@ class Mage_Sales_Model_Quote extends Mage_Core_Model_Abstract
      */
     public function removeAllItems()
     {
-        foreach ($this->getItemsCollection() as $item) {
-            $item->isDeleted(true);
+        foreach ($this->getItemsCollection() as $itemId => $item) {
+            if (is_null($item->getId())) {
+                $this->getItemsCollection()->removeItemByKey($itemId);
+            } else {
+                $item->isDeleted(true);
+            }
         }
         return $this;
     }
@@ -922,7 +926,10 @@ class Mage_Sales_Model_Quote extends Mage_Core_Model_Abstract
 
             // collect errors instead of throwing first one
             if ($item->getHasError()) {
-                $errors[] = $item->getMessage();
+                $message = $item->getMessage();
+                if (!in_array($message, $errors)) { // filter duplicate messages
+                    $errors[] = $message;
+                }
             }
         }
         if (!empty($errors)) {
diff --git a/app/code/core/Mage/Sales/Model/Quote/Address/Total/Collector.php b/app/code/core/Mage/Sales/Model/Quote/Address/Total/Collector.php
index 03522620f6ac2cf2509764923f9260ec4e5d281a..37a2245e43e95ef3fcadefc74405da831dba8cd2 100644
--- a/app/code/core/Mage/Sales/Model/Quote/Address/Total/Collector.php
+++ b/app/code/core/Mage/Sales/Model/Quote/Address/Total/Collector.php
@@ -31,34 +31,13 @@
  * @package     Mage_Core
  * @author      Magento Core Team <core@magentocommerce.com>
  */
-class Mage_Sales_Model_Quote_Address_Total_Collector
+class Mage_Sales_Model_Quote_Address_Total_Collector extends Mage_Sales_Model_Config_Ordered
 {
     /**
      * Path to sort order values of checkout totals
      */
     const XML_PATH_SALES_TOTALS_SORT = 'sales/totals_sort';
 
-    /**
-     * Total models array
-     *
-     * @var array
-     */
-    protected $_models = array();
-
-    /**
-     * Total models configuration
-     *
-     * @var array
-     */
-    protected $_modelsConfig = array();
-
-    /**
-     * Total models array ordered for right calculation logic
-     *
-     * @var array
-     */
-    protected $_collectors = array();
-
     /**
      * Total models array ordered for right display sequence
      *
@@ -125,173 +104,48 @@ class Mage_Sales_Model_Quote_Address_Total_Collector
     }
 
     /**
-     * Initialize total models configuration and objects
-     *
-     * @return Mage_Sales_Model_Quote_Address_Total_Collector
-     */
-    protected function _initModels()
-    {
-        $totalsConfig = Mage::getConfig()->getNode($this->_totalsConfigNode);
-
-        foreach ($totalsConfig->children() as $totalCode=>$totalConfig) {
-            $class = $totalConfig->getClassName();
-            if ($class) {
-                $model = Mage::getModel($class);
-                if ($model instanceof Mage_Sales_Model_Quote_Address_Total_Abstract) {
-                    $model->setCode($totalCode);
-                    $this->_modelsConfig[$totalCode]= $this->_prepareConfigArray($totalCode, $totalConfig);
-                    $this->_modelsConfig[$totalCode]= $model->processConfigArray(
-                        $this->_modelsConfig[$totalCode],
-                        $this->_store
-                    );
-                    $this->_models[$totalCode]      = $model;
-                } else {
-                    Mage::throwException(
-                        Mage::helper('Mage_Sales_Helper_Data')->__('The address total model should be extended from Mage_Sales_Model_Quote_Address_Total_Abstract.')
-                    );
-                }
-            }
-        }
-        return $this;
-    }
-
-    /**
-     * Prepare configuration array for total model
-     *
-     * @param   string $code
-     * @param   Mage_Core_Model_Config_Element $totalConfig
-     * @return  array
-     */
-    protected function _prepareConfigArray($code, $totalConfig)
-    {
-        $totalConfig = (array) $totalConfig;
-        if (isset($totalConfig['before'])) {
-            $totalConfig['before'] = explode(',',$totalConfig['before']);
-        } else {
-            $totalConfig['before'] = array();
-        }
-        if (isset($totalConfig['after'])) {
-            $totalConfig['after'] = explode(',',$totalConfig['after']);
-        } else {
-            $totalConfig['after'] = array();
-        }
-        $totalConfig['_code'] = $code;
-        return $totalConfig;
-    }
-
-    /**
-     * Aggregate before/after information from all items and sort totals based on this data
+     * Init model class by configuration
      *
-     * @return array
+     * @param string $class
+     * @param string $totalCode
+     * @param array $totalConfig
+     * @return Mage_Sales_Model_Quote_Address_Total_Abstract
      */
-    protected function _getSortedCollectorCodes()
+    protected function _initModelInstance($class, $totalCode, $totalConfig)
     {
-        if (Mage::app()->useCache('config')) {
-            $cachedData = Mage::app()->loadCache($this->_collectorsCacheKey);
-            if ($cachedData) {
-                return unserialize($cachedData);
-            }
-        }
-        $configArray = $this->_modelsConfig;
-        // invoke simple sorting if the first element contains the "sort_order" key
-        reset($configArray); $element = current($configArray);
-        if (isset($element['sort_order'])) {
-            uasort($configArray, array($this, '_compareSortOrder'));
-        } else {
-            foreach ($configArray as $code => $data) {
-                foreach ($data['before'] as $beforeCode) {
-                    if (!isset($configArray[$beforeCode])) {
-                        continue;
-                    }
-                    $configArray[$code]['before'] = array_merge(
-                        $configArray[$code]['before'], $configArray[$beforeCode]['before']
-                    );
-                    $configArray[$beforeCode]['after']  = array_merge(
-                        $configArray[$beforeCode]['after'], array($code), $data['after']
-                    );
-                    $configArray[$beforeCode]['after']  = array_unique($configArray[$beforeCode]['after']);
-                }
-                foreach ($data['after'] as $afterCode) {
-                    if (!isset($configArray[$afterCode])) {
-                        continue;
-                    }
-                    $configArray[$code]['after'] = array_merge(
-                        $configArray[$code]['after'], $configArray[$afterCode]['after']
-                    );
-                    $configArray[$afterCode]['before'] = array_merge(
-                        $configArray[$afterCode]['before'], array($code), $data['before']
-                    );
-                    $configArray[$afterCode]['before'] = array_unique($configArray[$afterCode]['before']);
-                }
-            }
-            uasort($configArray, array($this, '_compareTotals'));
+        $model = Mage::getModel($class);
+        if (!$model instanceof Mage_Sales_Model_Quote_Address_Total_Abstract) {
+            Mage::throwException(
+                Mage::helper('Mage_Sales_Helper_Data')->__('The address total model should be extended from Mage_Sales_Model_Quote_Address_Total_Abstract.')
+            );
         }
-        $sortedCollectors = array_keys($configArray);
-        if (Mage::app()->useCache('config')) {
-            Mage::app()->saveCache(serialize($sortedCollectors), $this->_collectorsCacheKey, array(
-                Mage_Core_Model_Config::CACHE_TAG
-            ));
-        }
-        return $sortedCollectors;
-    }
 
-    /**
-     * Initialize collectors array.
-     * Collectors array is array of total models ordered based on configuration settings
-     *
-     * @return  Mage_Sales_Model_Quote_Address_Total_Collector
-     */
-    protected function _initCollectors()
-    {
-        $sortedCodes = $this->_getSortedCollectorCodes();
-        foreach ($sortedCodes as $code) {
-            $this->_collectors[$code] = $this->_models[$code];
-        }
+        $model->setCode($totalCode);
+        $this->_modelsConfig[$totalCode]= $this->_prepareConfigArray($totalCode, $totalConfig);
+        $this->_modelsConfig[$totalCode]= $model->processConfigArray(
+            $this->_modelsConfig[$totalCode],
+            $this->_store
+        );
 
-        return $this;
+        return $model;
     }
 
     /**
-     * uasort callback function
+     * Initialize total models configuration and objects
      *
-     * @param   array $a
-     * @param   array $b
-     * @return  int
+     * @return Mage_Sales_Model_Quote_Address_Total_Collector
      */
-    protected function _compareTotals($a, $b)
+    protected function _initModels()
     {
-        $aCode = $a['_code'];
-        $bCode = $b['_code'];
-        if (in_array($aCode, $b['after']) || in_array($bCode, $a['before'])) {
-            $res = -1;
-        } elseif (in_array($bCode, $a['after']) || in_array($aCode, $b['before'])) {
-            $res = 1;
-        } else {
-            $res = 0;
-        }
-        return $res;
-    }
+        $totalsConfig = Mage::getConfig()->getNode($this->_totalsConfigNode);
 
-    /**
-     * uasort() callback that uses sort_order for comparison
-     *
-     * @param array $a
-     * @param array $b
-     * @return int
-     */
-    protected function _compareSortOrder($a, $b)
-    {
-        if (!isset($a['sort_order']) || !isset($b['sort_order'])) {
-            return 0;
-        }
-        if ($a['sort_order'] > $b['sort_order']) {
-            $res = 1;
-        } elseif ($a['sort_order'] < $b['sort_order']) {
-            $res = -1;
-        } else {
-            $res = 0;
+        foreach ($totalsConfig->children() as $totalCode => $totalConfig) {
+            $class = $totalConfig->getClassName();
+            if (!empty($class)) {
+                $this->_models[$totalCode] = $this->_initModelInstance($class, $totalCode, $totalConfig);
+            }
         }
-        return $res;
+        return $this;
     }
 
     /**
diff --git a/app/code/core/Mage/Sales/Model/Quote/Address/Total/Nominal/RecurringAbstract.php b/app/code/core/Mage/Sales/Model/Quote/Address/Total/Nominal/RecurringAbstract.php
index 820a27e08ef16b2b39068f72f47aa6231f7d8471..5c11e993dce754f82857a16ff45112038bb7e450 100644
--- a/app/code/core/Mage/Sales/Model/Quote/Address/Total/Nominal/RecurringAbstract.php
+++ b/app/code/core/Mage/Sales/Model/Quote/Address/Total/Nominal/RecurringAbstract.php
@@ -65,7 +65,10 @@ abstract class Mage_Sales_Model_Quote_Address_Total_Nominal_RecurringAbstract
             if ($item->getProduct()->isRecurring()) {
                 $profileData = $item->getProduct()->getRecurringProfile();
                 if (!empty($profileData[$this->_profileDataKey])) {
-                    $item->setData($this->_itemRowTotalKey, $profileData[$this->_profileDataKey]);
+                    $item->setData(
+                        $this->_itemRowTotalKey,
+                        $address->getQuote()->getStore()->convertPrice($profileData[$this->_profileDataKey])
+                    );
                     $this->_afterCollectSuccess($address, $item);
                 }
             }
diff --git a/app/code/core/Mage/Sales/Model/Quote/Address/Total/Tax.php b/app/code/core/Mage/Sales/Model/Quote/Address/Total/Tax.php
index e2cb1b2d550141bc2fde9ddf145011c5ae17264f..a69158851300f26cf1a9f04930ff94c454b07225 100644
--- a/app/code/core/Mage/Sales/Model/Quote/Address/Total/Tax.php
+++ b/app/code/core/Mage/Sales/Model/Quote/Address/Total/Tax.php
@@ -51,7 +51,12 @@ class Mage_Sales_Model_Quote_Address_Total_Tax extends Mage_Sales_Model_Quote_Ad
 
         $taxCalculationModel = Mage::getSingleton('Mage_Tax_Model_Calculation');
         /* @var $taxCalculationModel Mage_Tax_Model_Calculation */
-        $request = $taxCalculationModel->getRateRequest($address, $address->getQuote()->getBillingAddress(), $custTaxClassId, $store);
+        $request = $taxCalculationModel->getRateRequest(
+            $address,
+            $address->getQuote()->getBillingAddress(),
+            $custTaxClassId,
+            $store
+        );
 
         foreach ($items as $item) {
             /**
@@ -69,17 +74,27 @@ class Mage_Sales_Model_Quote_Address_Total_Tax extends Mage_Sales_Model_Quote_Ad
                     $discountBefore = $item->getDiscountAmount();
                     $baseDiscountBefore = $item->getBaseDiscountAmount();
 
-                    $rate = $taxCalculationModel->getRate($request->setProductClassId($child->getProduct()->getTaxClassId()));
+                    $rate = $taxCalculationModel->getRate(
+                        $request->setProductClassId($child->getProduct()->getTaxClassId())
+                    );
 
                     $child->setTaxPercent($rate);
                     $child->calcTaxAmount();
 
                     if ($discountBefore != $item->getDiscountAmount()) {
-                        $address->setDiscountAmount($address->getDiscountAmount()+($item->getDiscountAmount()-$discountBefore));
-                        $address->setBaseDiscountAmount($address->getBaseDiscountAmount()+($item->getBaseDiscountAmount()-$baseDiscountBefore));
-
-                        $address->setGrandTotal($address->getGrandTotal() - ($item->getDiscountAmount()-$discountBefore));
-                        $address->setBaseGrandTotal($address->getBaseGrandTotal() - ($item->getBaseDiscountAmount()-$baseDiscountBefore));
+                        $address->setDiscountAmount(
+                            $address->getDiscountAmount() + ($item->getDiscountAmount() - $discountBefore)
+                        );
+                        $address->setBaseDiscountAmount(
+                            $address->getBaseDiscountAmount() + ($item->getBaseDiscountAmount() - $baseDiscountBefore)
+                        );
+
+                        $address->setGrandTotal(
+                            $address->getGrandTotal() - ($item->getDiscountAmount() - $discountBefore)
+                        );
+                        $address->setBaseGrandTotal(
+                            $address->getBaseGrandTotal() - ($item->getBaseDiscountAmount() - $baseDiscountBefore)
+                        );
                     }
 
                     $this->_saveAppliedTaxes(
@@ -90,28 +105,42 @@ class Mage_Sales_Model_Quote_Address_Total_Tax extends Mage_Sales_Model_Quote_Ad
                        $rate
                     );
                 }
-                $address->setTaxAmount($address->getTaxAmount() + $item->getTaxAmount());
-                $address->setBaseTaxAmount($address->getBaseTaxAmount() + $item->getBaseTaxAmount());
+                $itemTaxAmount = $item->getTaxAmount() + $item->getDiscountTaxCompensation();
+                $address->setTaxAmount($address->getTaxAmount() + $itemTaxAmount);
+                $itemBaseTaxAmount = $item->getBaseTaxAmount() + $item->getBaseDiscountTaxCompensation();
+                $address->setBaseTaxAmount($address->getBaseTaxAmount() + $itemBaseTaxAmount);
             }
             else {
                 $discountBefore = $item->getDiscountAmount();
                 $baseDiscountBefore = $item->getBaseDiscountAmount();
 
-                $rate = $taxCalculationModel->getRate($request->setProductClassId($item->getProduct()->getTaxClassId()));
+                $rate = $taxCalculationModel->getRate(
+                    $request->setProductClassId($item->getProduct()->getTaxClassId())
+                );
 
                 $item->setTaxPercent($rate);
                 $item->calcTaxAmount();
 
                 if ($discountBefore != $item->getDiscountAmount()) {
-                    $address->setDiscountAmount($address->getDiscountAmount()+($item->getDiscountAmount()-$discountBefore));
-                    $address->setBaseDiscountAmount($address->getBaseDiscountAmount()+($item->getBaseDiscountAmount()-$baseDiscountBefore));
+                    $address->setDiscountAmount(
+                        $address->getDiscountAmount() + ($item->getDiscountAmount() - $discountBefore)
+                    );
+                    $address->setBaseDiscountAmount(
+                        $address->getBaseDiscountAmount() + ($item->getBaseDiscountAmount() - $baseDiscountBefore)
+                    );
 
-                    $address->setGrandTotal($address->getGrandTotal() - ($item->getDiscountAmount()-$discountBefore));
-                    $address->setBaseGrandTotal($address->getBaseGrandTotal() - ($item->getBaseDiscountAmount()-$baseDiscountBefore));
+                    $address->setGrandTotal(
+                        $address->getGrandTotal() - ($item->getDiscountAmount() - $discountBefore)
+                    );
+                    $address->setBaseGrandTotal(
+                        $address->getBaseGrandTotal() - ($item->getBaseDiscountAmount() - $baseDiscountBefore)
+                    );
                 }
 
-                $address->setTaxAmount($address->getTaxAmount() + $item->getTaxAmount());
-                $address->setBaseTaxAmount($address->getBaseTaxAmount() + $item->getBaseTaxAmount());
+                $itemTaxAmount = $item->getTaxAmount() + $item->getDiscountTaxCompensation();
+                $address->setTaxAmount($address->getTaxAmount() + $itemTaxAmount);
+                $itemBaseTaxAmount = $item->getBaseTaxAmount() + $item->getBaseDiscountTaxCompensation();
+                $address->setBaseTaxAmount($address->getBaseTaxAmount() + $itemBaseTaxAmount);
 
                 $applied = $taxCalculationModel->getAppliedRates($request);
                 $this->_saveAppliedTaxes(
diff --git a/app/code/core/Mage/Sales/Model/Quote/Item.php b/app/code/core/Mage/Sales/Model/Quote/Item.php
index 9528b56bda75c557c39f43dc467673d26c0d0196..f992e765d2524ce2f089700c6348617fe68e79a1 100644
--- a/app/code/core/Mage/Sales/Model/Quote/Item.php
+++ b/app/code/core/Mage/Sales/Model/Quote/Item.php
@@ -314,7 +314,9 @@ class Mage_Sales_Model_Quote_Item extends Mage_Sales_Model_Quote_Item_Abstract
             $qtyOptions = array();
             foreach ($this->getOptions() as $option) {
                 /** @var $option Mage_Sales_Model_Quote_Item_Option */
-                if (is_object($option->getProduct()) && $option->getProduct()->getId() != $this->getProduct()->getId()) {
+                if (is_object($option->getProduct())
+                    && $option->getProduct()->getId() != $this->getProduct()->getId()
+                ) {
                     $productIds[$option->getProduct()->getId()] = $option->getProduct()->getId();
                 }
             }
@@ -490,7 +492,8 @@ class Mage_Sales_Model_Quote_Item extends Mage_Sales_Model_Quote_Item_Abstract
                         $itemOptionValue = $_itemOptionValue;
                         $optionValue     = $_optionValue;
                         // looks like it does not break bundle selection qty
-                        unset($itemOptionValue['qty'], $itemOptionValue['uenc'], $optionValue['qty'], $optionValue['uenc']);
+                        unset($itemOptionValue['qty'], $itemOptionValue['uenc']);
+                        unset($optionValue['qty'], $optionValue['uenc']);
                     }
                 }
 
@@ -584,7 +587,7 @@ class Mage_Sales_Model_Quote_Item extends Mage_Sales_Model_Quote_Item_Abstract
     /**
      * Add option to item
      *
-     * @param   Mage_Sales_Model_Quote_Item_Option $option
+     * @param   Mage_Sales_Model_Quote_Item_Option|Varien_Object $option
      * @return  Mage_Sales_Model_Quote_Item
      */
     public function addOption($option)
diff --git a/app/code/core/Mage/Sales/Model/Quote/Item/Abstract.php b/app/code/core/Mage/Sales/Model/Quote/Item/Abstract.php
index 878a967f39f6b592672bc9c4573a002f6d8ed227..95b214c774df0d5fc12036b2c2111805ee651943 100644
--- a/app/code/core/Mage/Sales/Model/Quote/Item/Abstract.php
+++ b/app/code/core/Mage/Sales/Model/Quote/Item/Abstract.php
@@ -559,6 +559,21 @@ abstract class Mage_Sales_Model_Quote_Item_Abstract extends Mage_Core_Model_Abst
         return false;
     }
 
+    /**
+     * Check if force discount apply to parent item
+     *
+     * @return bool
+     */
+    public function getForceApplyDiscountToParentItem()
+    {
+        if ($this->getParentItem()) {
+            $product = $this->getParentItem()->getProduct();
+        } else {
+            $product = $this->getProduct();
+        }
+
+        return $product->getTypeInstance()->getForceApplyDiscountToParentItem();
+    }
 
     /**
      * Checking can we ship product separatelly (each child separately)
diff --git a/app/code/core/Mage/Sales/Model/Resource/Order/Grid/Collection.php b/app/code/core/Mage/Sales/Model/Resource/Order/Grid/Collection.php
index 0a3a68e6e7c51bca73ee997a8fa832cf486fb887..434adb290ae52ef30608b128d592096fcd65a692 100755
--- a/app/code/core/Mage/Sales/Model/Resource/Order/Grid/Collection.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Order/Grid/Collection.php
@@ -50,7 +50,7 @@ class Mage_Sales_Model_Resource_Order_Grid_Collection extends Mage_Sales_Model_R
 
     /**
      * Customer mode flag
-     * 
+     *
      * @var bool
      */
     protected $_customerModeFlag = false;
@@ -72,17 +72,21 @@ class Mage_Sales_Model_Resource_Order_Grid_Collection extends Mage_Sales_Model_R
      */
     public function getSelectCountSql()
     {
-        $this->_renderFilters();
+        if ($this->getIsCustomerMode()) {
+            $this->_renderFilters();
 
-        $unionSelect = clone $this->getSelect();
+            $unionSelect = clone $this->getSelect();
 
-        $unionSelect->reset(Zend_Db_Select::ORDER);
-        $unionSelect->reset(Zend_Db_Select::LIMIT_COUNT);
-        $unionSelect->reset(Zend_Db_Select::LIMIT_OFFSET);
+            $unionSelect->reset(Zend_Db_Select::ORDER);
+            $unionSelect->reset(Zend_Db_Select::LIMIT_COUNT);
+            $unionSelect->reset(Zend_Db_Select::LIMIT_OFFSET);
 
-        $countSelect = clone $this->getSelect();
-        $countSelect->reset();
-        $countSelect->from(array('a' => $unionSelect), 'COUNT(*)');
+            $countSelect = clone $this->getSelect();
+            $countSelect->reset();
+            $countSelect->from(array('a' => $unionSelect), 'COUNT(*)');
+        } else {
+            $countSelect = parent::getSelectCountSql();
+        }
 
         return $countSelect;
     }
diff --git a/app/code/core/Mage/Sales/Model/Resource/Quote.php b/app/code/core/Mage/Sales/Model/Resource/Quote.php
index 0720547245ccdd97f270fd3de37e7f00bd5fe29d..49d48dc8d572d3fac6b381b07187d7c1b2af5e5b 100755
--- a/app/code/core/Mage/Sales/Model/Resource/Quote.php
+++ b/app/code/core/Mage/Sales/Model/Resource/Quote.php
@@ -181,20 +181,23 @@ class Mage_Sales_Model_Resource_Quote extends Mage_Sales_Model_Resource_Abstract
      */
     public function markQuotesRecollectOnCatalogRules()
     {
-        $readAdapter     = $this->_getReadAdapter();
-        $selectProductId = $readAdapter->select()
-            ->from($this->getTable('catalogrule_product_price'), 'product_id')
-            ->distinct();
-
-        $selectQuoteId = $readAdapter->select()
-            ->from($this->getTable('sales_flat_quote_item'), 'quote_id')
-            ->where('product_id IN(?)', $selectProductId)
-            ->distinct();
+        $tableQuote = $this->getTable('sales_flat_quote');
+        $subSelect = $this->_getReadAdapter()
+            ->select()
+            ->from(array('t2' => $this->getTable('sales_flat_quote_item')), array('entity_id' => 'quote_id'))
+            ->from(array('t3' => $this->getTable('catalogrule_product_price')), array())
+            ->where('t2.product_id = t3.product_id')
+            ->group('quote_id');
+
+        $select = $this->_getReadAdapter()->select()->join(
+            array('t2' => $subSelect),
+            't1.entity_id = t2.entity_id',
+            array('trigger_recollect' => new Zend_Db_Expr('1'))
+        );
 
-        $data  = array('trigger_recollect' => 1);
-        $where = array('entity_id IN(?)' => $selectQuoteId);
+        $updateQuery = $select->crossUpdateFromSelect(array('t1' => $tableQuote));
 
-        $this->_getWriteAdapter()->update($this->getTable('sales_flat_quote'), $data, $where);
+        $this->_getWriteAdapter()->query($updateQuery);
 
         return $this;
     }
@@ -239,19 +242,26 @@ class Mage_Sales_Model_Resource_Quote extends Mage_Sales_Model_Resource_Abstract
     /**
      * Mark recollect contain product(s) quotes
      *
-     * @param array|int $productIds
+     * @param array|int|Zend_Db_Expr $productIds
      * @return Mage_Sales_Model_Resource_Quote
      */
     public function markQuotesRecollect($productIds)
     {
-        $select = $this->_getReadAdapter()->select()
-            ->from($this->getTable('sales_flat_quote_item'), 'quote_id')
-            ->where('product_id IN(?)', $productIds)
-            ->distinct(true);
-
-        $data  = array('trigger_recollect' => 1);
-        $where = array('entity_id IN(?)' => $select);
-        $this->_getWriteAdapter()->update($this->getTable('sales_flat_quote'), $data, $where);
+        $tableQuote = $this->getTable('sales_flat_quote');
+        $tableItem = $this->getTable('sales_flat_quote_item');
+        $subSelect = $this->_getReadAdapter()
+            ->select()
+            ->from($tableItem, array('entity_id' => 'quote_id'))
+            ->where('product_id IN ( ? )', $productIds)
+            ->group('quote_id');
+
+        $select = $this->_getReadAdapter()->select()->join(
+            array('t2' => $subSelect),
+            't1.entity_id = t2.entity_id',
+            array('trigger_recollect' => new Zend_Db_Expr('1'))
+        );
+        $updateQuery = $select->crossUpdateFromSelect(array('t1' => $tableQuote));
+        $this->_getWriteAdapter()->query($updateQuery);
 
         return $this;
     }
diff --git a/app/code/core/Mage/Sales/Model/Service/Order.php b/app/code/core/Mage/Sales/Model/Service/Order.php
index 27d0559581875fa7c383f3c0c367068d51767db5..7384470eb13ecb8cb29c9a92eaa32ed5719ad062 100644
--- a/app/code/core/Mage/Sales/Model/Service/Order.php
+++ b/app/code/core/Mage/Sales/Model/Service/Order.php
@@ -187,6 +187,7 @@ class Mage_Sales_Model_Service_Order
             $item = $this->_convertor->itemToCreditmemoItem($orderItem);
             if ($orderItem->isDummy()) {
                 $qty = 1;
+                $orderItem->setLockedDoShip(true);
             } else {
                 if (isset($qtys[$orderItem->getId()])) {
                     $qty = (float) $qtys[$orderItem->getId()];
diff --git a/app/code/core/Mage/Sales/etc/adminhtml.xml b/app/code/core/Mage/Sales/etc/adminhtml.xml
index 12d955d6f8d99516c2cb5c427c72b946950cf2e6..f3ca64d888184b87fcc23a1c00700efa702ccec8 100644
--- a/app/code/core/Mage/Sales/etc/adminhtml.xml
+++ b/app/code/core/Mage/Sales/etc/adminhtml.xml
@@ -101,7 +101,7 @@
                                             <review_payment translate="title"><title>Accept or Deny Payment</title></review_payment>
                                             <capture translate="title"><title>Capture</title></capture>
                                             <invoice translate="title"><title>Invoice</title></invoice>
-                                            <creditmemo translate="title"><title>Creditmemo</title></creditmemo>
+                                            <creditmemo translate="title"><title>Credit Memos</title></creditmemo>
                                             <hold translate="title"><title>Hold</title></hold>
                                             <unhold translate="title"><title>Unhold</title></unhold>
                                             <ship translate="title"><title>Ship</title></ship>
diff --git a/app/code/core/Mage/Sales/etc/config.xml b/app/code/core/Mage/Sales/etc/config.xml
index 4bdc265eddba6af57193f91ea4b227520a885cc1..6da3492970a9910cc4be52241ed3bd0695c57f78 100644
--- a/app/code/core/Mage/Sales/etc/config.xml
+++ b/app/code/core/Mage/Sales/etc/config.xml
@@ -303,18 +303,25 @@
                     </subtotal>
                     <discount>
                         <class>Mage_Sales_Model_Order_Invoice_Total_Discount</class>
+                        <after>subtotal</after>
                     </discount>
                     <shipping>
                         <class>Mage_Sales_Model_Order_Invoice_Total_Shipping</class>
+                        <after>subtotal,discount</after>
+                        <before>grand_total,tax</before>
                     </shipping>
                     <tax>
                         <class>Mage_Sales_Model_Order_Invoice_Total_Tax</class>
+                        <after>subtotal</after>
                     </tax>
                     <grand_total>
                         <class>Mage_Sales_Model_Order_Invoice_Total_Grand</class>
+                        <after>shipping</after>
                     </grand_total>
                     <cost_total>
                         <class>Mage_Sales_Model_Order_Invoice_Total_Cost</class>
+                        <after>discount</after>
+                        <before>grand_total</before>
                     </cost_total>
                 </totals>
             </order_invoice>
@@ -325,18 +332,25 @@
                     </subtotal>
                     <shipping>
                         <class>Mage_Sales_Model_Order_Creditmemo_Total_Shipping</class>
+                        <after>subtotal,discount</after>
+                        <before>grand_total,tax</before>
                     </shipping>
                     <tax>
                         <class>Mage_Sales_Model_Order_Creditmemo_Total_Tax</class>
+                        <after>subtotal</after>
                     </tax>
                     <discount>
                         <class>Mage_Sales_Model_Order_Creditmemo_Total_Discount</class>
+                        <after>subtotal</after>
                     </discount>
                     <grand_total>
                         <class>Mage_Sales_Model_Order_Creditmemo_Total_Grand</class>
+                        <after>shipping,subtotal</after>
                     </grand_total>
                     <cost_total>
                         <class>Mage_Sales_Model_Order_Creditmemo_Total_Cost</class>
+                        <after>discount</after>
+                        <before>grand_total</before>
                     </cost_total>
                 </totals>
             </order_creditmemo>
diff --git a/app/code/core/Mage/Sales/etc/system.xml b/app/code/core/Mage/Sales/etc/system.xml
index 307e8846299d506462cdaa9fa424324c5516be53..8d2b06e66883958979e34aca4024e3e6b80e468a 100644
--- a/app/code/core/Mage/Sales/etc/system.xml
+++ b/app/code/core/Mage/Sales/etc/system.xml
@@ -43,6 +43,25 @@
             <show_in_website>1</show_in_website>
             <show_in_store>1</show_in_store>
             <groups>
+                <general translate="label">
+                    <label>General</label>
+                    <frontend_type>text</frontend_type>
+                    <sort_order>5</sort_order>
+                    <show_in_default>1</show_in_default>
+                    <show_in_website>1</show_in_website>
+                    <show_in_store>1</show_in_store>
+                    <fields>
+                        <hide_customer_ip translate="label comment">
+                            <label>Hide Customer IP</label>
+                            <comment>Controls whether customer IP is shown in orders, invoices, shipments, credit memos.</comment>
+                            <frontend_type>select</frontend_type>
+                            <source_model>Mage_Adminhtml_Model_System_Config_Source_Yesno</source_model>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>1</show_in_store>
+                        </hide_customer_ip>
+                    </fields>
+                </general>
                 <totals_sort translate="label">
                     <label>Checkout Totals Sort Order</label>
                     <frontend_type>text</frontend_type>
@@ -129,7 +148,7 @@
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
                             <show_in_store>1</show_in_store>
-                            <comment>Default logo, will be used in PDF and HTML documents.&lt;br /&gt;(jpeg, tiff, png)</comment>
+                            <comment>Default logo, will be used in PDF and HTML documents.&lt;br /&gt;(jpeg, tiff, png) If you see image distortion in PDF, try to use larger image</comment>
                         </logo>
                         <logo_html translate="label comment">
                             <label>Logo for HTML Print View</label>
diff --git a/app/code/core/Mage/Sales/etc/widget.xml b/app/code/core/Mage/Sales/etc/widget.xml
index c8eb0aa15695ab5bcda5326dc94f59f09dad3dc6..559a97d775c657f915b811df64cab15b6b28bf7d 100644
--- a/app/code/core/Mage/Sales/etc/widget.xml
+++ b/app/code/core/Mage/Sales/etc/widget.xml
@@ -45,19 +45,19 @@
                 </values>
             </template>
         </parameters>
-        <supported_blocks>
+        <supported_containers>
             <left_column>
-                <block_name>left</block_name>
+                <container_name>left</container_name>
                 <template>
                     <default>default_template</default>
                 </template>
             </left_column>
             <right_column>
-                <block_name>right</block_name>
+                <container_name>right</container_name>
                 <template>
                     <default>default_template</default>
                 </template>
             </right_column>
-        </supported_blocks>
+        </supported_containers>
     </sales_widget_guestfrom>
 </widgets>
diff --git a/app/code/core/Mage/Sales/view/adminhtml/recurring/profile/view.phtml b/app/code/core/Mage/Sales/view/adminhtml/recurring/profile/view.phtml
index f749b6cc4d478c87dd72f3160f06db760ed7e5e7..6339a5207627fd4e2d810d64067ed32f0bbad040 100644
--- a/app/code/core/Mage/Sales/view/adminhtml/recurring/profile/view.phtml
+++ b/app/code/core/Mage/Sales/view/adminhtml/recurring/profile/view.phtml
@@ -26,12 +26,15 @@
 ?>
 <?php /* @var $this Mage_Sales_Block_Adminhtml_Recurring_Profile_View_Tab_Info */ ?>
 
+<?php $layout = $this->getLayout(); ?>
 <?php for ($i = 1; $i <= 5; $i++):?>
-    <?php $infoBlocks = $this->getChildGroup("info_blocks_row_{$i}"); ?>
+    <?php $infoBlocks = $this->getGroupChildNames("info_blocks_row_{$i}"); ?>
     <?php if ($infoBlocks):?>
 <div>
         <?php for ($j = 1; $j <= 2; $j++):?>
-            <?php foreach ($infoBlocks as $alias => $block):?>
+            <?php foreach ($infoBlocks as $name):?>
+        <?php $block = $layout->getBlock($name); ?>
+        <?php if (!$block) continue; ?>
 <?php if ($j == $this->getObjectData($block, 'view_column')):?>
     <div class="box-<?php echo $j == 1 ? 'left' : 'right'?>">
         <div class="entry-edit">
@@ -39,7 +42,7 @@
                 <h4 class="icon-head"><?php echo $this->escapeHtml($this->getObjectData($block, 'view_label')) ?></h4>
             </div>
             <div class="fieldset">
-                <?php $html = $this->getChildHtml($alias) ?>
+                <?php $html = $layout->renderElement($name); ?>
                 <?php echo ($html ? $html : $this->__('No information available.')) ; ?>
             </div>
         </div>
diff --git a/app/code/core/Mage/Sales/view/email/creditmemo_new.html b/app/code/core/Mage/Sales/view/email/creditmemo_new.html
index ae54f92632743f1ed7e6b010007b0a5fcd9c5a52..aab214bbb7aefdda78e22fceedd27a2291862760 100644
--- a/app/code/core/Mage/Sales/view/email/creditmemo_new.html
+++ b/app/code/core/Mage/Sales/view/email/creditmemo_new.html
@@ -1,7 +1,8 @@
 <!--@subject {{var store.getFrontendName()}}: Credit Memo # {{var creditmemo.increment_id}} for Order # {{var order.increment_id}} @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "escapehtml var=$order.getCustomerName()":"Customer Name",
 "var store.getFrontendName()":"Store Name",
 "store url=\"customer/account/\"":"Customer Account Url",
@@ -26,7 +27,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
         <!-- [ header starts here] -->
         <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
             <tr>
-                <td valign="top"><a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a></td>
+                <td valign="top"><a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a></td>
             </tr>
         <!-- [ middle starts here] -->
             <tr>
diff --git a/app/code/core/Mage/Sales/view/email/creditmemo_new_guest.html b/app/code/core/Mage/Sales/view/email/creditmemo_new_guest.html
index b3ae3b9d48f44cc4674be68767e3530af715db70..7bc69c3af1fb462cc2c4ca726cce121b3be6617f 100644
--- a/app/code/core/Mage/Sales/view/email/creditmemo_new_guest.html
+++ b/app/code/core/Mage/Sales/view/email/creditmemo_new_guest.html
@@ -1,7 +1,8 @@
 <!--@subject {{var store.getFrontendName()}}: Credit Memo # {{var creditmemo.increment_id}} for Order # {{var order.increment_id}} @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "escapehtml var=$billing.getName()":"Guest Customer Name (Billing)",
 "var store.getFrontendName()":"Store Name",
 "var creditmemo.increment_id":"Credit Memo Id",
@@ -25,7 +26,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
         <!-- [ header starts here] -->
         <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
             <tr>
-                <td valign="top"><a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a></td>
+                <td valign="top"><a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a></td>
             </tr>
         <!-- [ middle starts here] -->
             <tr>
diff --git a/app/code/core/Mage/Sales/view/email/creditmemo_update.html b/app/code/core/Mage/Sales/view/email/creditmemo_update.html
index 63c96b167898feeb5e4ae9abf8fbe63ee3945a66..e09c093366ae0472a0b653285c2c118fc393d74e 100644
--- a/app/code/core/Mage/Sales/view/email/creditmemo_update.html
+++ b/app/code/core/Mage/Sales/view/email/creditmemo_update.html
@@ -1,7 +1,8 @@
 <!--@subject {{var store.getFrontendName()}}: Credit Memo # {{var creditmemo.increment_id}} update @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "escapehtml var=$order.getCustomerName()":"Customer Name",
 "var order.increment_id":"Order Id",
 "var order.getStatusLabel()":"Order Status",
@@ -21,7 +22,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
         <!-- [ header starts here] -->
         <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
             <tr>
-                <td valign="top"><a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a></td>
+                <td valign="top"><a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a></td>
             </tr>
             <!-- [ middle starts here] -->
             <tr>
diff --git a/app/code/core/Mage/Sales/view/email/creditmemo_update_guest.html b/app/code/core/Mage/Sales/view/email/creditmemo_update_guest.html
index f87e3678bfc85073670b5c00d7ec7c27536e9a6f..495dea9d850ccb4a15e22c6a9b9573e2f6668a2e 100644
--- a/app/code/core/Mage/Sales/view/email/creditmemo_update_guest.html
+++ b/app/code/core/Mage/Sales/view/email/creditmemo_update_guest.html
@@ -1,7 +1,8 @@
 <!--@subject {{var store.getFrontendName()}}: Credit Memo # {{var creditmemo.increment_id}} update @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 
 "escapehtml var=$billing.getName()":"Guest Customer Name",
 "var order.increment_id":"Order Id",
@@ -21,7 +22,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
         <!-- [ header starts here] -->
         <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
             <tr>
-                <td valign="top"><a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a></td>
+                <td valign="top"><a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a></td>
             </tr>
             <!-- [ middle starts here] -->
             <tr>
diff --git a/app/code/core/Mage/Sales/view/email/invoice_new.html b/app/code/core/Mage/Sales/view/email/invoice_new.html
index 890b9bfc5401952b028fe8ef1062f4769b02d94e..138a5169aaa6f52a9022804e4222e653eaf2c703 100644
--- a/app/code/core/Mage/Sales/view/email/invoice_new.html
+++ b/app/code/core/Mage/Sales/view/email/invoice_new.html
@@ -1,7 +1,8 @@
 <!--@subject  {{var store.getFrontendName()}}: Invoice # {{var invoice.increment_id}} for Order # {{var order.increment_id}} @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "escapehtml var=$order.getCustomerName()":"Customer Name",
 "var store.getFrontendName()":"Store Name",
 "store url=\"customer/account/\"":"Customer Account Url",
@@ -26,7 +27,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
         <!-- [ header starts here] -->
         <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
             <tr>
-                <td valign="top"><a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a></td>
+                <td valign="top"><a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a></td>
             </tr>
         <!-- [ middle starts here] -->
             <tr>
diff --git a/app/code/core/Mage/Sales/view/email/invoice_new_guest.html b/app/code/core/Mage/Sales/view/email/invoice_new_guest.html
index a745925f0cc479f051eec5bb8f91ef62c53369fe..38695b5e81923ad6436f1c6c09d7d799f4c913e0 100644
--- a/app/code/core/Mage/Sales/view/email/invoice_new_guest.html
+++ b/app/code/core/Mage/Sales/view/email/invoice_new_guest.html
@@ -1,7 +1,8 @@
 <!--@subject  {{var store.getFrontendName()}}: Invoice # {{var invoice.increment_id}} for Order # {{var order.increment_id}} @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "escapehtml var=$billing.getName()":"Guest Customer Name",
 "var store.getFrontendName()":"Store Name",
 "var invoice.increment_id":"Invoice Id",
@@ -25,7 +26,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
         <!-- [ header starts here] -->
         <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
             <tr>
-                <td valign="top"><a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a></td>
+                <td valign="top"><a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a></td>
             </tr>
         <!-- [ middle starts here] -->
             <tr>
diff --git a/app/code/core/Mage/Sales/view/email/invoice_update.html b/app/code/core/Mage/Sales/view/email/invoice_update.html
index 1199b0f57dc41a9c82967c6afa249bc0b3c5f376..983efd31804b84d900a102178c4483e055239080 100644
--- a/app/code/core/Mage/Sales/view/email/invoice_update.html
+++ b/app/code/core/Mage/Sales/view/email/invoice_update.html
@@ -1,7 +1,8 @@
 <!--@subject {{var store.getFrontendName()}}: Invoice # {{var invoice.increment_id}} update @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "escapehtml var=$order.getCustomerName()":"Customer Name",
 "var order.increment_id":"Order Id",
 "var order.getStatusLabel()":"Order Status",
@@ -21,7 +22,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
         <!-- [ header starts here] -->
         <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
             <tr>
-                <td valign="top"><a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a></td>
+                <td valign="top"><a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a></td>
             </tr>
             <!-- [ middle starts here] -->
             <tr>
diff --git a/app/code/core/Mage/Sales/view/email/invoice_update_guest.html b/app/code/core/Mage/Sales/view/email/invoice_update_guest.html
index 3d9683c26fd9eb24b79bc3603f4084ced5514710..a6dd649c140b50dd61073a62bd222be6a034a10d 100644
--- a/app/code/core/Mage/Sales/view/email/invoice_update_guest.html
+++ b/app/code/core/Mage/Sales/view/email/invoice_update_guest.html
@@ -1,7 +1,8 @@
 <!--@subject {{var store.getFrontendName()}}: Invoice # {{var invoice.increment_id}} update @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "escapehtml var=$billing.getName()":"Guest Customer Name",
 "var order.increment_id":"Order Id",
 "var order.getStatusLabel()":"Order Status",
@@ -20,7 +21,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
         <!-- [ header starts here] -->
         <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
             <tr>
-                <td valign="top"><a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a></td>
+                <td valign="top"><a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a></td>
             </tr>
             <!-- [ middle starts here] -->
             <tr>
diff --git a/app/code/core/Mage/Sales/view/email/order_new.html b/app/code/core/Mage/Sales/view/email/order_new.html
index bc825c07c5949b8e91ff9a60cacd26d2e819f8b2..d936a507f341d6223380f86e67bffd8632bf42a2 100644
--- a/app/code/core/Mage/Sales/view/email/order_new.html
+++ b/app/code/core/Mage/Sales/view/email/order_new.html
@@ -1,7 +1,8 @@
 <!--@subject {{var store.getFrontendName()}}: New Order # {{var order.increment_id}} @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "escapehtml var=$order.getCustomerName()":"Customer Name",
 "var store.getFrontendName()":"Store Name",
 "store url=\"customer/account/\"":"Customer Account Url",
@@ -26,7 +27,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
         <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
             <!-- [ header starts here] -->
             <tr>
-                <td valign="top"><a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a></td>
+                <td valign="top"><a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a></td>
             </tr>
             <!-- [ middle starts here] -->
             <tr>
diff --git a/app/code/core/Mage/Sales/view/email/order_new_guest.html b/app/code/core/Mage/Sales/view/email/order_new_guest.html
index cf2bf5493604e34daefa364f57d8e4d65586cc35..33c949a4e5d62191e572d1acf71ceefdc7ad9dec 100644
--- a/app/code/core/Mage/Sales/view/email/order_new_guest.html
+++ b/app/code/core/Mage/Sales/view/email/order_new_guest.html
@@ -1,7 +1,8 @@
 <!--@subject {{var store.getFrontendName()}}: New Order # {{var order.increment_id}} @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "escapehtml var=$order.getBillingAddress().getName()":"Guest Customer Name",
 "var store.getFrontendName()":"Store Name",
 "var order.increment_id":"Order Id",
@@ -25,7 +26,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
         <!-- [ header starts here] -->
         <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
             <tr>
-                <td valign="top"><a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a></td>
+                <td valign="top"><a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a></td>
             </tr>
         <!-- [ middle starts here] -->
             <tr>
diff --git a/app/code/core/Mage/Sales/view/email/order_update.html b/app/code/core/Mage/Sales/view/email/order_update.html
index ee45e22d134d24b7e0a169030c2b29e04dc8d613..211ebb1c6b991595ce200a074be32f0b7da9d46e 100644
--- a/app/code/core/Mage/Sales/view/email/order_update.html
+++ b/app/code/core/Mage/Sales/view/email/order_update.html
@@ -1,7 +1,8 @@
 <!--@subject {{var store.getFrontendName()}}: Order # {{var order.increment_id}} update @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "escapehtml var=$order.getCustomerName()":"Customer Name",
 "var order.increment_id":"Order Id",
 "var order.getStatusLabel()":"Order Status",
@@ -21,7 +22,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
         <!-- [ header starts here] -->
         <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
             <tr>
-                <td valign="top"><a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a></td>
+                <td valign="top"><a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a></td>
             </tr>
             <!-- [ middle starts here] -->
             <tr>
diff --git a/app/code/core/Mage/Sales/view/email/order_update_guest.html b/app/code/core/Mage/Sales/view/email/order_update_guest.html
index 1e2287f1464a229ff9d02ddafa0ac21a0e8056e3..716a1c6cabd844a80f30490e38450f03acf14a5b 100644
--- a/app/code/core/Mage/Sales/view/email/order_update_guest.html
+++ b/app/code/core/Mage/Sales/view/email/order_update_guest.html
@@ -1,7 +1,8 @@
 <!--@subject {{var store.getFrontendName()}}: Order # {{var order.increment_id}} update @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "escapehtml var=$billing.getName()":"Guest Customer Name",
 "var order.increment_id":"Order Id",
 "var order.getStatusLabel()":"Order Status",
@@ -20,7 +21,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
         <!-- [ header starts here] -->
         <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
             <tr>
-                <td valign="top"><a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a></td>
+                <td valign="top"><a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a></td>
             </tr>
             <!-- [ middle starts here] -->
             <tr>
diff --git a/app/code/core/Mage/Sales/view/email/shipment_new.html b/app/code/core/Mage/Sales/view/email/shipment_new.html
index 700a735098dee6304d05043250f18a6631dbe902..1aef576f8aa77a9226662754a68daf5831285134 100644
--- a/app/code/core/Mage/Sales/view/email/shipment_new.html
+++ b/app/code/core/Mage/Sales/view/email/shipment_new.html
@@ -1,7 +1,8 @@
 <!--@subject {{var store.getFrontendName()}}: Shipment # {{var shipment.increment_id}} for Order # {{var order.increment_id}} @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "escapehtml var=$order.getCustomerName()":"Customer Name",
 "var store.getFrontendName()":"Store Name",
 "store url=\"customer/account/\"":"Customer Account Url",
@@ -27,7 +28,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
         <!-- [ header starts here] -->
         <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
             <tr>
-                <td valign="top"><a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a></td>
+                <td valign="top"><a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a></td>
             </tr>
         <!-- [ middle starts here] -->
             <tr>
diff --git a/app/code/core/Mage/Sales/view/email/shipment_new_guest.html b/app/code/core/Mage/Sales/view/email/shipment_new_guest.html
index 4a1205acbf0e6c44b8a586f56dddb4aed790ba77..c41b40760035594af19aa20ca4739bc418bef68e 100644
--- a/app/code/core/Mage/Sales/view/email/shipment_new_guest.html
+++ b/app/code/core/Mage/Sales/view/email/shipment_new_guest.html
@@ -1,7 +1,8 @@
 <!--@subject {{var store.getFrontendName()}}: Shipment # {{var shipment.increment_id}} for Order # {{var order.increment_id}} @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "escapehtml var=$billing.getName()":"Guest Customer Name",
 "var store.getFrontendName()":"Store Name",
 "var shipment.increment_id":"Shipment Id",
@@ -26,7 +27,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
         <!-- [ header starts here] -->
         <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
             <tr>
-                <td valign="top"><a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a></td>
+                <td valign="top"><a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a></td>
             </tr>
         <!-- [ middle starts here] -->
             <tr>
diff --git a/app/code/core/Mage/Sales/view/email/shipment_update.html b/app/code/core/Mage/Sales/view/email/shipment_update.html
index 6a1fc53ecd443a29ff4012916d22b76b945c95d8..a5781ad21061eb82bba0798c1685b147a99907ce 100644
--- a/app/code/core/Mage/Sales/view/email/shipment_update.html
+++ b/app/code/core/Mage/Sales/view/email/shipment_update.html
@@ -1,7 +1,8 @@
 <!--@subject {{var store.getFrontendName()}}: Shipment # {{var shipment.increment_id}} update @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "escapehtml var=$order.getCustomerName()":"Customer Name",
 "var order.increment_id":"Order Id",
 "var order.getStatusLabel()":"Order Status",
@@ -21,7 +22,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
         <!-- [ header starts here] -->
         <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
             <tr>
-                <td valign="top"><a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a></td>
+                <td valign="top"><a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a></td>
             </tr>
             <!-- [ middle starts here] -->
             <tr>
diff --git a/app/code/core/Mage/Sales/view/email/shipment_update_guest.html b/app/code/core/Mage/Sales/view/email/shipment_update_guest.html
index 8edf713b1fc617c7d5e61c5b701cc1f1056fb9c5..e62589c59b49c28ba0f63d62e0ce46732f180c63 100644
--- a/app/code/core/Mage/Sales/view/email/shipment_update_guest.html
+++ b/app/code/core/Mage/Sales/view/email/shipment_update_guest.html
@@ -1,7 +1,8 @@
 <!--@subject {{var store.getFrontendName()}}: Shipment # {{var shipment.increment_id}} update @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "escapehtml var=$billing.getName()":"Guest Customer Name",
 "var order.increment_id":"Order Id",
 "var order.getStatusLabel()":"Order Status",
@@ -20,7 +21,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
         <!-- [ header starts here] -->
         <table bgcolor="#FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
             <tr>
-                <td valign="top"><a href="{{store url=""}}"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}"  style="margin-bottom:10px;" border="0"/></a></td>
+                <td valign="top"><a href="{{store url=""}}"><img src="{{var logo_url}}" alt="{{var logo_alt}}" style="margin-bottom:10px;" border="0"/></a></td>
             </tr>
             <!-- [ middle starts here] -->
             <tr>
diff --git a/app/code/core/Mage/Sales/view/frontend/billing_agreement.xml b/app/code/core/Mage/Sales/view/frontend/billing_agreement.xml
index 2178e685135f52658cc4538799357b4f7376f315..184e2fe052f6153115a88380b4bc94d99e2e7687 100644
--- a/app/code/core/Mage/Sales/view/frontend/billing_agreement.xml
+++ b/app/code/core/Mage/Sales/view/frontend/billing_agreement.xml
@@ -27,7 +27,8 @@
 
 -->
 <layout version="0.1.0">
-    <sales_billing_agreement_index>
+    <sales_billing_agreement_index translate="label" type="page" parent="customer_account_index">
+        <label>Billing Agreement</label>
         <update handle="customer_account"/>
         <reference name="root">
             <action method="setTemplate"><template>2columns-left.phtml</template></action>
@@ -37,7 +38,8 @@
         </reference>
     </sales_billing_agreement_index>
 
-    <sales_billing_agreement_view>
+    <sales_billing_agreement_view translate="label" type="page" parent="sales_billing_agreement_index">
+        <label>Billing Agreement View</label>
         <update handle="customer_account"/>
         <reference name="root">
             <action method="setTemplate"><template>2columns-left.phtml</template></action>
diff --git a/app/code/core/Mage/Sales/view/frontend/email/items.phtml b/app/code/core/Mage/Sales/view/frontend/email/items.phtml
index b92a5788128de793214aba850e119ab4e6fb76ec..f4a0e1e981f3108ba4a85e7029a10448c22ac480 100644
--- a/app/code/core/Mage/Sales/view/frontend/email/items.phtml
+++ b/app/code/core/Mage/Sales/view/frontend/email/items.phtml
@@ -25,6 +25,7 @@
  */
 ?>
 <?php $_order = $this->getOrder() ?>
+<?php if ($_order): ?>
 <table cellspacing="0" cellpadding="0" border="0" width="650" style="border:1px solid #EAEAEA;">
     <thead>
         <tr>
@@ -70,3 +71,4 @@
 </table>
     <?php endif; ?>
 <?php endif; ?>
+<?php endif; ?>
diff --git a/app/code/core/Mage/Sales/view/frontend/layout.xml b/app/code/core/Mage/Sales/view/frontend/layout.xml
index 6edf1d1ca31d55bcc5be2bf861892c97845d3098..06f16df8b556fa5991f4b2e804311fdef67449cb 100644
--- a/app/code/core/Mage/Sales/view/frontend/layout.xml
+++ b/app/code/core/Mage/Sales/view/frontend/layout.xml
@@ -31,13 +31,12 @@
 <!--
 Customer account pages, rendered for all tabs in dashboard
 -->
-
-
-    <customer_logged_in>
+    <default>
         <reference name="right">
             <block type="Mage_Sales_Block_Reorder_Sidebar" name="sale.reorder.sidebar" as="reorder" template="reorder/sidebar.phtml"/>
         </reference>
-    </customer_logged_in>
+    </default>
+
     <checkout_onepage_index>
         <remove name="sale.reorder.sidebar"/>
     </checkout_onepage_index>
@@ -71,21 +70,19 @@ Customer account home dashboard layout
 
     </customer_account_index>
 
-    <sales_order_history translate="label">
+    <sales_order_history translate="label" type="page" parent="sales_order_view">
         <label>Customer My Account Order History</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
             <block type="Mage_Sales_Block_Order_History" name="sales.order.history">
-                <block type="Mage_Core_Block_Text_List" name="sales.order.history.info" as="info" translate="label">
-                    <label>Order History Info</label>
-                </block>
+                <container name="sales.order.history.info" as="info" label="Order History Info"/>
             </block>
             <block type="Mage_Customer_Block_Account_Dashboard" name="customer.account.link.back" template="account/link/back.phtml"/>
         </reference>
     </sales_order_history>
 
 
-    <sales_order_view translate="label">
+    <sales_order_view translate="label" type="page" parent="default">
         <label>Customer My Account Order View</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
@@ -110,12 +107,10 @@ Customer account home dashboard layout
             <action method="addLink" translate="label" module="Mage_Sales"><name>shipment</name><path>*/*/shipment</path><label>Shipments</label></action>
             <action method="addLink" translate="label" module="Mage_Sales"><name>creditmemo</name><path>*/*/creditmemo</path><label>Refunds</label></action>
         </reference>
-        <block type="Mage_Core_Block_Text_List" name="additional.product.info" translate="label">
-            <label>Additional Product Info</label>
-        </block>
+        <container name="additional.product.info" label="Additional Product Info"/>
     </sales_order_view>
 
-    <sales_order_invoice translate="label">
+    <sales_order_invoice translate="label" type="page" parent="sales_order_view">
         <label>Customer My Account Order Invoice View</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
@@ -141,10 +136,10 @@ Customer account home dashboard layout
             <action method="addLink" translate="label" module="Mage_Sales"><name>shipment</name><path>*/*/shipment</path><label>Shipments</label></action>
             <action method="addLink" translate="label" module="Mage_Sales"><name>creditmemo</name><path>*/*/creditmemo</path><label>Refunds</label></action>
         </reference>
-        <block type="Mage_Core_Block_Text_List" name="additional.product.info" />
+        <container name="additional.product.info" label="Additional Product Info"/>
     </sales_order_invoice>
 
-    <sales_order_shipment translate="label">
+    <sales_order_shipment translate="label" type="page" parent="sales_order_view">
         <label>Customer My Account Order Shipment View</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
@@ -164,10 +159,10 @@ Customer account home dashboard layout
             <action method="addLink" translate="label" module="Mage_Sales"><name>shipment</name><path></path><label>Shipments</label></action>
             <action method="addLink" translate="label" module="Mage_Sales"><name>creditmemo</name><path>*/*/creditmemo</path><label>Refunds</label></action>
         </reference>
-        <block type="Mage_Core_Block_Text_List" name="additional.product.info" />
+        <container name="additional.product.info" label="Additional Product Info"/>
     </sales_order_shipment>
 
-    <sales_order_creditmemo translate="label">
+    <sales_order_creditmemo translate="label" type="page" parent="sales_order_view">
         <label>Customer My Account Order Creditmemo View</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
@@ -193,17 +188,18 @@ Customer account home dashboard layout
             <action method="addLink" translate="label" module="Mage_Sales"><name>shipment</name><path>*/*/shipment</path><label>Shipments</label></action>
             <action method="addLink" translate="label" module="Mage_Sales"><name>creditmemo</name><path></path><label>Refunds</label></action>
         </reference>
-        <block type="Mage_Core_Block_Text_List" name="additional.product.info" />
+        <container name="additional.product.info" label="Additional Product Info"/>
     </sales_order_creditmemo>
 
-    <sales_order_reorder>
+    <sales_order_reorder translate="label" type="page" parent="sales_order_view">
+        <label>Sales Reorder</label>
         <update handle="customer_account"/>
         <reference name="content">
             <block type="Mage_Sales_Block_Order_View" name="sales.order.view"/>
         </reference>
     </sales_order_reorder>
 
-    <sales_order_print translate="label">
+    <sales_order_print translate="label" type="page" parent="print">
         <label>Sales Order Print View</label>
         <reference name="content">
             <block type="Mage_Sales_Block_Order_Print" name="sales.order.print" template="order/print.phtml">
@@ -218,10 +214,10 @@ Customer account home dashboard layout
                 </block>
             </block>
         </reference>
-        <block type="Mage_Core_Block_Text_List" name="additional.product.info" />
+        <container name="additional.product.info" label="Additional Product Info"/>
     </sales_order_print>
 
-    <sales_order_printinvoice translate="label">
+    <sales_order_printinvoice translate="label" type="page" parent="sales_order_print">
         <label>Sales Invoice Print View</label>
         <reference name="content">
             <block type="Mage_Sales_Block_Order_Print_Invoice" name="sales.order.print.invoice" template="order/print/invoice.phtml">
@@ -234,20 +230,21 @@ Customer account home dashboard layout
                 </block>
             </block>
         </reference>
-        <block type="Mage_Core_Block_Text_List" name="additional.product.info" />
+        <container name="additional.product.info" label="Additional Product Info"/>
     </sales_order_printinvoice>
 
-    <sales_order_printshipment translate="label">
+    <sales_order_printshipment translate="label" type="page" parent="sales_order_print">
         <label>Sales Shipment Print View</label>
         <reference name="content">
             <block type="Mage_Sales_Block_Order_Print_Shipment" name="sales.order.print.shipment" template="order/print/shipment.phtml">
                 <action method="addItemRender"><type>default</type><block>Mage_Sales_Block_Order_Item_Renderer_Default</block><template>order/shipment/items/renderer/default.phtml</template></action>
             </block>
         </reference>
-        <block type="Mage_Core_Block_Text_List" name="additional.product.info" />
+        <container name="additional.product.info" label="Additional Product Info"/>
     </sales_order_printshipment>
 
-    <sales_order_printcreditmemo>
+    <sales_order_printcreditmemo translate="label" type="page" parent="sales_order_print">
+        <label>Sales Creditmemo Print View</label>
         <reference name="content">
             <block type="Mage_Sales_Block_Order_Print_Creditmemo" name="sales.order.print.creditmemo" template="order/print/creditmemo.phtml">
                 <action method="addItemRender"><type>default</type><block>Mage_Sales_Block_Order_Item_Renderer_Default</block><template>order/creditmemo/items/renderer/default.phtml</template></action>
@@ -259,13 +256,14 @@ Customer account home dashboard layout
                 </block>
             </block>
         </reference>
-        <block type="Mage_Core_Block_Text_List" name="additional.product.info" />
+        <container name="additional.product.info" label="Additional Product Info"/>
     </sales_order_printcreditmemo>
 
 <!--
 Email layouts section
 -->
-    <sales_email_order_items>
+    <sales_email_order_items translate="label" type="page" parent="sales_order_view">
+        <label>Email Order Items List</label>
         <block type="Mage_Sales_Block_Order_Email_Items" name="items" template="email/items.phtml">
             <action method="addItemRender"><type>default</type><block>Mage_Sales_Block_Order_Email_Items_Order_Default</block><template>email/items/order/default.phtml</template></action>
             <action method="addItemRender"><type>grouped</type><block>Mage_Sales_Block_Order_Email_Items_Order_Grouped</block><template>email/items/order/default.phtml</template></action>
@@ -277,10 +275,11 @@ Email layouts section
                 </block>
             </block>
         </block>
-        <block type="Mage_Core_Block_Text_List" name="additional.product.info" />
+        <container name="additional.product.info" label="Additional Product Info"/>
     </sales_email_order_items>
 
-    <sales_email_order_invoice_items>
+    <sales_email_order_invoice_items translate="label" type="page" parent="sales_order_invoice">
+        <label>Email Invoice Items List</label>
         <block type="Mage_Sales_Block_Order_Email_Invoice_Items" name="items" template="email/invoice/items.phtml">
             <action method="addItemRender"><type>default</type><block>Mage_Sales_Block_Order_Email_Items_Default</block><template>email/items/invoice/default.phtml</template></action>
             <action method="addItemRender"><type>grouped</type><block>Mage_Sales_Block_Order_Email_Items_Order_Grouped</block><template>email/items/invoice/default.phtml</template></action>
@@ -290,17 +289,19 @@ Email layouts section
                 <block type="Mage_Tax_Block_Sales_Order_Tax" name="tax" template="order/tax.phtml"/>
             </block>
         </block>
-        <block type="Mage_Core_Block_Text_List" name="additional.product.info" />
+        <container name="additional.product.info" label="Additional Product Info"/>
     </sales_email_order_invoice_items>
 
-    <sales_email_order_shipment_items>
+    <sales_email_order_shipment_items translate="label" type="page" parent="sales_order_shipment">
+        <label>Email Shipment Items List</label>
         <block type="Mage_Sales_Block_Order_Email_Shipment_Items" name="items" template="email/shipment/items.phtml">
             <action method="addItemRender"><type>default</type><block>Mage_Sales_Block_Order_Email_Items_Default</block><template>email/items/shipment/default.phtml</template></action>
         </block>
-        <block type="Mage_Core_Block_Text_List" name="additional.product.info" />
+        <container name="additional.product.info" label="Additional Product Info"/>
     </sales_email_order_shipment_items>
 
-    <sales_email_order_creditmemo_items>
+    <sales_email_order_creditmemo_items translate="label" type="page" parent="sales_order_creditmemo">
+        <label>Email Creditmemo Items List</label>
         <block type="Mage_Sales_Block_Order_Email_Creditmemo_Items" name="items" template="email/creditmemo/items.phtml">
             <action method="addItemRender"><type>default</type><block>Mage_Sales_Block_Order_Email_Items_Default</block><template>email/items/creditmemo/default.phtml</template></action>
             <action method="addItemRender"><type>grouped</type><block>Mage_Sales_Block_Order_Email_Items_Order_Grouped</block><template>email/items/creditmemo/default.phtml</template></action>
@@ -310,14 +311,14 @@ Email layouts section
                 <block type="Mage_Tax_Block_Sales_Order_Tax" name="tax" template="order/tax.phtml"/>
             </block>
         </block>
-        <block type="Mage_Core_Block_Text_List" name="additional.product.info" />
+        <container name="additional.product.info" label="Additional Product Info"/>
     </sales_email_order_creditmemo_items>
 
 <!--
 Guest
 -->
 
-    <sales_guest_form translate="label">
+    <sales_guest_form translate="label" type="page" parent="sales_guest_view">
         <label>Returns</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -328,7 +329,7 @@ Guest
     </sales_guest_form>
 
 
-    <sales_guest_view translate="label">
+    <sales_guest_view translate="label" type="page" parent="default">
         <label>Customer My Account Order View</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -357,7 +358,7 @@ Guest
         </reference>
     </sales_guest_view>
 
-    <sales_guest_invoice translate="label">
+    <sales_guest_invoice translate="label" type="page" parent="sales_guest_view">
         <label>Customer My Account Order Invoice View</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -387,7 +388,7 @@ Guest
         </reference>
     </sales_guest_invoice>
 
-    <sales_guest_shipment translate="label">
+    <sales_guest_shipment translate="label" type="page" parent="sales_guest_view">
         <label>Customer My Account Order Shipment View</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -411,7 +412,7 @@ Guest
         </reference>
     </sales_guest_shipment>
 
-    <sales_guest_creditmemo translate="label">
+    <sales_guest_creditmemo translate="label" type="page" parent="sales_guest_view">
         <label>Customer My Account Order Creditmemo View</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -441,7 +442,8 @@ Guest
         </reference>
     </sales_guest_creditmemo>
 
-    <sales_guest_reorder>
+    <sales_guest_reorder translate="label" type="page" parent="sales_guest_view">
+        <label>Sales Guest Reorder</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
         </reference>
@@ -450,7 +452,7 @@ Guest
         </reference>
     </sales_guest_reorder>
 
-    <sales_guest_print translate="label">
+    <sales_guest_print translate="label" type="page" parent="print">
         <label>Sales Order Print View</label>
         <reference name="content">
             <block type="Mage_Sales_Block_Order_Print" name="sales.order.print" template="order/print.phtml">
@@ -467,7 +469,7 @@ Guest
         </reference>
     </sales_guest_print>
 
-    <sales_guest_printinvoice translate="label">
+    <sales_guest_printinvoice translate="label" type="page" parent="sales_guest_print">
         <label>Sales Invoice Print View</label>
         <reference name="content">
             <block type="Mage_Sales_Block_Order_Print_Invoice" name="sales.order.print.invoice" template="order/print/invoice.phtml">
@@ -482,7 +484,7 @@ Guest
         </reference>
     </sales_guest_printinvoice>
 
-    <sales_guest_printshipment translate="label">
+    <sales_guest_printshipment translate="label" type="page" parent="sales_guest_print">
         <label>Sales Shipment Print View</label>
         <reference name="content">
             <block type="Mage_Sales_Block_Order_Print_Shipment" name="sales.order.print.shipment" template="order/print/shipment.phtml">
@@ -491,7 +493,8 @@ Guest
         </reference>
     </sales_guest_printshipment>
 
-    <sales_guest_printcreditmemo>
+    <sales_guest_printcreditmemo translate="label" type="page" parent="sales_guest_print">
+        <label>Sales Creditmemo Print View</label>
         <reference name="content">
             <block type="Mage_Sales_Block_Order_Print_Creditmemo" name="sales.order.print.creditmemo" template="order/print/creditmemo.phtml">
                 <action method="addItemRender"><type>default</type><block>Mage_Sales_Block_Order_Item_Renderer_Default</block><template>order/creditmemo/items/renderer/default.phtml</template></action>
diff --git a/app/code/core/Mage/Sales/view/frontend/order/info.phtml b/app/code/core/Mage/Sales/view/frontend/order/info.phtml
index a0f535d6bee18f1ebd99c2437bbab68e6e7fe0b9..c270da8aee0f9cc845ee54ed9498c956d5ccbade 100644
--- a/app/code/core/Mage/Sales/view/frontend/order/info.phtml
+++ b/app/code/core/Mage/Sales/view/frontend/order/info.phtml
@@ -24,7 +24,8 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 ?>
-<?php  $_order = $this->getOrder() ?>
+<?php /** @var $this Mage_Sales_Block_Order_Info */ ?>
+<?php $_order = $this->getOrder() ?>
 <?php echo $this->getMessagesBlock()->getGroupedHtml() ?>
 <div class="page-title title-buttons">
     <h1><?php echo $this->__('Order #%s - %s', $_order->getRealOrderId(), $_order->getStatusLabel()) ?></h1>
@@ -63,11 +64,11 @@
     <div class="col-2">
         <div class="box">
             <div class="box-title">
-                <h2><?php echo $this->__('Shipping Method') ?><?php /* | <a href="#"><?php echo $this->__('Track Order') ?></a>*/ ?></h2>
+                <h2><?php echo $this->__('Shipping Method') ?></h2>
             </div>
             <div class="box-content">
                 <?php if ($_order->getShippingDescription()): ?>
-                    <?php echo $_order->getShippingDescription() ?>
+                    <?php echo $this->escapeHtml($_order->getShippingDescription()) ?>
                 <?php else: ?>
                     <p><?php echo $this->helper('Mage_Sales_Helper_Data')->__('No shipping information available'); ?></p>
                 <?php endif; ?>
diff --git a/app/code/core/Mage/Sales/view/frontend/recurring/profile/view.phtml b/app/code/core/Mage/Sales/view/frontend/recurring/profile/view.phtml
index 1aafd0f1d70c01ed7e18f81c132363eb5bdd1503..929e7758126ceec7b4e6aab575d64d63c20edc03 100644
--- a/app/code/core/Mage/Sales/view/frontend/recurring/profile/view.phtml
+++ b/app/code/core/Mage/Sales/view/frontend/recurring/profile/view.phtml
@@ -48,12 +48,15 @@
 <?php echo $this->getMessagesBlock()->getGroupedHtml() ?>
 
 <!-- info tabs -->
-<?php $infoTabs = $this->getChildGroup('info_tabs'); ?>
+<?php $layout = $this->getLayout(); ?>
+<?php $infoTabs = $this->getGroupChildNames('info_tabs'); ?>
 <dl class="order-info">
     <dt><?php echo $this->__('About This Profile:') ?></dt>
     <dd>
         <ul id="order-info-tabs">
-        <?php foreach ($infoTabs as $block): ?>
+        <?php foreach ($infoTabs as $elementName): ?>
+            <?php $block = $layout->getBlock($elementName); ?>
+            <?php if (!$block) continue; ?>
             <?php if ($this->getObjectData($block, 'is_view_current')): ?>
                 <li class="current"><strong><?php echo $this->escapeHtml($this->getObjectData($block, 'view_label')) ?></strong></li>
             <?php else: ?>
@@ -66,11 +69,13 @@
 
 <!-- info blocks in 2 columns -->
 <?php for ($i = 1; $i <= 5; $i++):?>
-    <?php $infoBlocks = $this->getChildGroup("info_blocks_row_{$i}"); ?>
+    <?php $infoBlocks = $this->getGroupChildNames("info_blocks_row_{$i}"); ?>
     <?php if ($infoBlocks):?>
 <div class="col2-set order-info-box">
         <?php for ($j = 1; $j <= 2; $j++):?>
-            <?php foreach ($infoBlocks as $alias => $block):?>
+            <?php foreach ($infoBlocks as $elementName):?>
+        <?php $block = $layout->getBlock($elementName); ?>
+        <?php if (!$block) continue; ?>
 <?php if ($j == $this->getObjectData($block, 'view_column')):?>
     <div class="col-<?php echo $j?>">
         <div class="info-box">
@@ -78,7 +83,7 @@
                 <h2><?php echo $this->escapeHtml($this->getObjectData($block, 'view_label')) ?></h2>
             </div>
             <div class="box-content">
-                <?php $html = $this->getChildHtml($alias) ?>
+                <?php $html = $layout->renderElement($elementName); ?>
                 <?php echo ($html ? $html : $this->__('No information available.')) ; ?>
             </div>
         </div>
@@ -91,7 +96,7 @@
 <?php endfor;?>
 
 <!-- table data block -->
-<?php $table = $this->getChild('table') ?>
+<?php $table = $this->getChildBlock('table') ?>
 <?php if ($table):?>
 <div>
     <h2 class="table-caption"><?php echo $this->escapeHtml($this->getObjectData($table, 'view_label')) ?></h2>
diff --git a/app/code/core/Mage/Sales/view/frontend/recurring_profile.xml b/app/code/core/Mage/Sales/view/frontend/recurring_profile.xml
index 90cc063eb664f7034f7873ee59599f855cd06043..252fffca4c3377ff82956d80580c0eb2f6e66bf4 100644
--- a/app/code/core/Mage/Sales/view/frontend/recurring_profile.xml
+++ b/app/code/core/Mage/Sales/view/frontend/recurring_profile.xml
@@ -33,7 +33,8 @@
         </reference>
     </customer_account>
 
-    <sales_recurring_profile_index>
+    <sales_recurring_profile_index translate="label" type="page" parent="customer_account_index">
+        <label>Recurring Profile</label>
         <update handle="customer_account"/>
         <reference name="root">
             <action method="setTemplate"><template>2columns-left.phtml</template></action>
@@ -49,7 +50,8 @@
         </reference>
     </sales_recurring_profile_index>
 
-    <sales_recurring_profile_view__tabs>
+    <sales_recurring_profile_view__tabs translate="label" type="page" parent="sales_recurring_profile_index">
+        <label>Recurring Profile View Tabs</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-left.phtml</template></action>
         </reference>
@@ -85,7 +87,8 @@
         </reference>
     </sales_recurring_profile_view__tabs>
 
-    <sales_recurring_profile_view>
+    <sales_recurring_profile_view translate="label" type="page" parent="sales_recurring_profile_view__tabs">
+        <label>Recurring Profile View</label>
         <update handle="customer_account"/>
         <update handle="sales_recurring_profile_view__tabs"/>
         <reference name="sales.recurring.profile.view.tab.profile">
@@ -142,7 +145,8 @@
     </sales_recurring_profile_history>
 -->
 
-    <sales_recurring_profile_orders>
+    <sales_recurring_profile_orders translate="label" type="page" parent="sales_recurring_profile_view__tabs">
+        <label>Recurring Profile Orders List</label>
         <update handle="customer_account"/>
         <update handle="sales_recurring_profile_view__tabs"/>
         <reference name="sales.recurring.profile.view.tab.orders">
diff --git a/app/code/core/Mage/SalesRule/Model/Quote/Discount.php b/app/code/core/Mage/SalesRule/Model/Quote/Discount.php
index 2515a75c17ade5ff0dd41bae90d248b833d6b1f1..b32dafd96f575b8413e39edfbe553ad2aea90f04 100644
--- a/app/code/core/Mage/SalesRule/Model/Quote/Discount.php
+++ b/app/code/core/Mage/SalesRule/Model/Quote/Discount.php
@@ -85,7 +85,9 @@ class Mage_SalesRule_Model_Quote_Discount extends Mage_Sales_Model_Quote_Address
                 $eventArgs['item'] = $item;
                 Mage::dispatchEvent('sales_quote_address_discount_item', $eventArgs);
 
-                if ($item->getHasChildren() && $item->isChildrenCalculated()) {
+                if ($item->getHasChildren() && $item->isChildrenCalculated()
+                    && !$item->getForceApplyDiscountToParentItem()
+                ) {
                     foreach ($item->getChildren() as $child) {
                         $this->_calculator->process($child);
                         $eventArgs['item'] = $child;
@@ -152,4 +154,4 @@ class Mage_SalesRule_Model_Quote_Discount extends Mage_Sales_Model_Quote_Address
         }
         return $this;
     }
-}
\ No newline at end of file
+}
diff --git a/app/code/core/Mage/SalesRule/Model/Resource/Rule.php b/app/code/core/Mage/SalesRule/Model/Resource/Rule.php
index f515b2f28ad9c43e0e1d209911237e1160ec6037..8e950974345e301d14ab17499b476de7317c8a8b 100755
--- a/app/code/core/Mage/SalesRule/Model/Resource/Rule.php
+++ b/app/code/core/Mage/SalesRule/Model/Resource/Rule.php
@@ -126,8 +126,8 @@ class Mage_SalesRule_Model_Resource_Rule extends Mage_Rule_Model_Resource_Abstra
 
         // Save product attributes used in rule
         $ruleProductAttributes = array_merge(
-            $this->getProductAttributes($object->getConditionsSerialized()),
-            $this->getProductAttributes($object->getActionsSerialized())
+            $this->getProductAttributes(serialize($object->getConditions()->asArray())),
+            $this->getProductAttributes(serialize($object->getActions()->asArray()))
         );
         if (count($ruleProductAttributes)) {
             $this->setActualProductAttributes($object, $ruleProductAttributes);
diff --git a/app/code/core/Mage/SalesRule/Model/Resource/Rule/Collection.php b/app/code/core/Mage/SalesRule/Model/Resource/Rule/Collection.php
index 24d12d5805969971d91c010a2676e0f14316100d..90774b5e92a652707019b42d12586e972ef1487a 100755
--- a/app/code/core/Mage/SalesRule/Model/Resource/Rule/Collection.php
+++ b/app/code/core/Mage/SalesRule/Model/Resource/Rule/Collection.php
@@ -119,7 +119,7 @@ class Mage_SalesRule_Model_Resource_Rule_Collection extends Mage_Rule_Model_Reso
      * @param string|null $now
      * @use $this->addWebsiteFilter()
      *
-     * @return Mage_SalesRule_Model_Mysql4_Rule_Collection
+     * @return Mage_SalesRule_Model_Resource_Rule_Collection
      */
     public function addWebsiteGroupDateFilter($websiteId, $customerGroupId, $now = null)
     {
diff --git a/app/code/core/Mage/SalesRule/etc/adminhtml.xml b/app/code/core/Mage/SalesRule/etc/adminhtml.xml
index 9dec343e92467363ad66a6ec19553e6e540ee3b7..9dcf6c63842588a2afe01670fb07bc4320b90864 100644
--- a/app/code/core/Mage/SalesRule/etc/adminhtml.xml
+++ b/app/code/core/Mage/SalesRule/etc/adminhtml.xml
@@ -41,6 +41,13 @@
         <resources>
             <admin>
                 <children>
+                    <promo>
+                        <children>
+                            <quote translate="title" module="Mage_SalesRule">
+                                <title>Shopping Cart Price Rules</title>
+                            </quote>
+                        </children>
+                    </promo>
                     <system>
                         <children>
                             <config>
diff --git a/app/code/core/Mage/Sendfriend/view/frontend/layout.xml b/app/code/core/Mage/Sendfriend/view/frontend/layout.xml
index 9b065c4f3b3570c7d8584d959661648a5ede66d2..5bb61ee4227e84a8bce168e862d60d09d1630d8a 100644
--- a/app/code/core/Mage/Sendfriend/view/frontend/layout.xml
+++ b/app/code/core/Mage/Sendfriend/view/frontend/layout.xml
@@ -26,7 +26,7 @@
  */
 -->
 <layout version="0.1.0">
-    <sendfriend_product_send translate="label">
+    <sendfriend_product_send translate="label" type="page" parent="catalog_product_view">
         <label>Catalog Product Email to a Friend</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
diff --git a/app/code/core/Mage/Shipping/Model/Carrier/Abstract.php b/app/code/core/Mage/Shipping/Model/Carrier/Abstract.php
index 9b137bf819167c9d84834291618bf7120d1d1991..560fa66012e04f6c77325f59d380791c182b9f0d 100644
--- a/app/code/core/Mage/Shipping/Model/Carrier/Abstract.php
+++ b/app/code/core/Mage/Shipping/Model/Carrier/Abstract.php
@@ -521,11 +521,12 @@ abstract class Mage_Shipping_Model_Carrier_Abstract extends Varien_Object
     }
 
     /**
-     * Check if zip code option required
+     * Determine whether zip-code is required for the country of destination
      *
-     * @return boolean
+     * @param Mage_Shipping_Model_Rate_Request|null $request
+     * @return bool
      */
-    public function isZipCodeRequired()
+    public function isZipCodeRequired(Mage_Shipping_Model_Rate_Request $request = null)
     {
         return false;
     }
diff --git a/app/code/core/Mage/Shipping/Model/Rate/Result.php b/app/code/core/Mage/Shipping/Model/Rate/Result.php
index 25615659060be2e41375543b3659be5b62f79c74..63d9035463b2bac0821bf4baf88f461e208cd898 100644
--- a/app/code/core/Mage/Shipping/Model/Rate/Result.php
+++ b/app/code/core/Mage/Shipping/Model/Rate/Result.php
@@ -27,11 +27,24 @@
 
 class Mage_Shipping_Model_Rate_Result
 {
+    /**
+     * Shippin method rates
+     *
+     * @var array
+     */
     protected $_rates = array();
+
+    /**
+     * Shipping errors
+     *
+     * @var null|bool
+     */
     protected $_error = null;
 
     /**
      * Reset result
+     *
+     * @return Mage_Shipping_Model_Rate_Result
      */
     public function reset()
     {
@@ -39,11 +52,22 @@ class Mage_Shipping_Model_Rate_Result
         return $this;
     }
 
+    /**
+     * Set Error
+     *
+     * @param bool $error
+     * @return void
+     */
     public function setError($error)
     {
         $this->_error = $error;
     }
 
+    /**
+     * Get Error
+     *
+     * @return null|bool;
+     */
     public function getError()
     {
         return $this->_error;
@@ -53,6 +77,7 @@ class Mage_Shipping_Model_Rate_Result
      * Add a rate to the result
      *
      * @param Mage_Shipping_Model_Rate_Result_Abstract|Mage_Shipping_Model_Rate_Result $result
+     * @return Mage_Shipping_Model_Rate_Result
      */
     public function append($result)
     {
@@ -73,6 +98,8 @@ class Mage_Shipping_Model_Rate_Result
 
     /**
      * Return all quotes in the result
+     *
+     * @return array
      */
     public function getAllRates()
     {
@@ -81,6 +108,9 @@ class Mage_Shipping_Model_Rate_Result
 
     /**
      * Return rate by id in array
+     *
+     * @param int $id
+     * @return Mage_Shipping_Model_Rate_Result_Method|null
      */
     public function getRateById($id)
     {
@@ -90,19 +120,25 @@ class Mage_Shipping_Model_Rate_Result
     /**
      * Return quotes for specified type
      *
-     * @param string $type
+     * @param string $carrier
+     * @return array
      */
     public function getRatesByCarrier($carrier)
     {
         $result = array();
         foreach ($this->_rates as $rate) {
-            if ($rate->getCarrier()===$carrier) {
+            if ($rate->getCarrier() === $carrier) {
                 $result[] = $rate;
             }
         }
         return $result;
     }
 
+    /**
+     * Converts object to array
+     *
+     * @return array
+     */
     public function asArray()
     {
         $currencyFilter = Mage::app()->getStore()->getPriceFilter();
@@ -111,20 +147,25 @@ class Mage_Shipping_Model_Rate_Result
         foreach ($allRates as $rate) {
             $rates[$rate->getCarrier()]['title'] = $rate->getCarrierTitle();
             $rates[$rate->getCarrier()]['methods'][$rate->getMethod()] = array(
-                'title'=>$rate->getMethodTitle(),
-                'price'=>$rate->getPrice(),
-                'price_formatted'=>$currencyFilter->filter($rate->getPrice()),
+                'title' => $rate->getMethodTitle(),
+                'price' => $rate->getPrice(),
+                'price_formatted' => $currencyFilter->filter($rate->getPrice()),
             );
         }
         return $rates;
     }
 
+    /**
+     * Get cheapest rate
+     *
+     * @return null|Mage_Shipping_Model_Rate_Result_Method
+     */
     public function getCheapestRate()
     {
         $cheapest = null;
         $minPrice = 100000;
         foreach ($this->getAllRates() as $rate) {
-            if (is_numeric($rate->getPrice()) && $rate->getPrice()<$minPrice) {
+            if (is_numeric($rate->getPrice()) && $rate->getPrice() < $minPrice) {
                 $cheapest = $rate;
                 $minPrice = $rate->getPrice();
             }
@@ -133,11 +174,11 @@ class Mage_Shipping_Model_Rate_Result
     }
 
     /**
-     *  Sort rates by price from min to max
+     * Sort rates by price from min to max
      *
-     *  @return	  Mage_Shipping_Model_Rate_Result
+     * @return Mage_Shipping_Model_Rate_Result
      */
-    public function sortRatesByPrice ()
+    public function sortRatesByPrice()
     {
         if (!is_array($this->_rates) || !count($this->_rates)) {
             return $this;
@@ -157,4 +198,21 @@ class Mage_Shipping_Model_Rate_Result
         $this->_rates = $result;
         return $this;
     }
+
+    /**
+     * Set price for each rate according to count of packages
+     *
+     * @param int $packageCount
+     * @return Mage_Shipping_Model_Rate_Result
+     */
+    public function updateRatePrice($packageCount)
+    {
+        if ($packageCount > 1) {
+            foreach ($this->_rates as $rate) {
+                $rate->setPrice($rate->getPrice() * $packageCount);
+            }
+        }
+
+        return $this;
+    }
 }
diff --git a/app/code/core/Mage/Shipping/Model/Resource/Carrier/Tablerate.php b/app/code/core/Mage/Shipping/Model/Resource/Carrier/Tablerate.php
index 99495a4a955e12bbeb35263d84d30cca5b7af6f6..aae5623c2d273e9129100d3395b61b42a9490e05 100755
--- a/app/code/core/Mage/Shipping/Model/Resource/Carrier/Tablerate.php
+++ b/app/code/core/Mage/Shipping/Model/Resource/Carrier/Tablerate.php
@@ -267,7 +267,7 @@ class Mage_Shipping_Model_Resource_Carrier_Tablerate extends Mage_Core_Model_Res
         $adapter->commit();
 
         if ($this->_importErrors) {
-            $error = Mage::helper('Mage_Shipping_Helper_Data')->__('%1$d records have been imported. See the following list of errors for each record that has not been imported: %2$s', $this->_importedRows, implode(" \n", $this->_importErrors));
+            $error = Mage::helper('Mage_Shipping_Helper_Data')->__('File has not been imported. See the following list of errors: %s', implode(" \n", $this->_importErrors));
             Mage::throwException($error);
         }
 
diff --git a/app/code/core/Mage/Shipping/Model/Shipping.php b/app/code/core/Mage/Shipping/Model/Shipping.php
index 1bb9cb4118271ba3f899f89fa0b7bb7960315a96..96604211c0f8e98afc6fae7095fb4c4bf71b5a78 100644
--- a/app/code/core/Mage/Shipping/Model/Shipping.php
+++ b/app/code/core/Mage/Shipping/Model/Shipping.php
@@ -169,7 +169,43 @@ class Mage_Shipping_Model_Shipping
         */
         if (false !== $result){
             if (!$result instanceof Mage_Shipping_Model_Rate_Result_Error) {
-                $result = $carrier->collectRates($request);
+                if ($carrier->getConfigData('shipment_requesttype')) {
+                    $packages = $this->composePackagesForCarrier($carrier, $request);
+                    if (!empty($packages)) {
+                        $sumResults = array();
+                        foreach ($packages as $weight => $packageCount) {
+                            $request->setPackageWeight($weight);
+                            $result = $carrier->collectRates($request);
+                            if (!$result) {
+                                return $this;
+                            } else {
+                                $result->updateRatePrice($packageCount);
+                            }
+                            $sumResults[] = $result;
+                        }
+                        if (!empty($sumResults) && count($sumResults) > 1) {
+                            $result = array();
+                            foreach ($sumResults as $res) {
+                                if (empty($result)) {
+                                    $result = $res;
+                                    continue;
+                                }
+                                foreach ($res->getAllRates() as $method) {
+                                    foreach ($result->getAllRates() as $resultMethod) {
+                                        if ($method->getMethod() == $resultMethod->getMethod()) {
+                                            $resultMethod->setPrice($method->getPrice() + $resultMethod->getPrice());
+                                            continue;
+                                        }
+                                    }
+                                }
+                            }
+                        }
+                    } else {
+                        $result = $carrier->collectRates($request);
+                    }
+                } else {
+                    $result = $carrier->collectRates($request);
+                }
                 if (!$result) {
                     return $this;
                 }
@@ -186,6 +222,141 @@ class Mage_Shipping_Model_Shipping
         return $this;
     }
 
+    /**
+     * Compose Packages For Carrier.
+     * Devides order into items and items into parts if it's neccesary
+     *
+     * @param Mage_Shipping_Model_Carrier_Abstract $carrier
+     * @param Mage_Shipping_Model_Rate_Request $request
+     * @return array [int, float]
+     */
+    public function composePackagesForCarrier($carrier, $request)
+    {
+        $allItems   = $request->getAllItems();
+        $fullItems  = array();
+
+        $maxWeight  = (float) $carrier->getConfigData('max_package_weight');
+
+        foreach ($allItems as $item) {
+            if ($item->getProductType() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE
+                && $item->getProduct()->getShipmentType()
+            ) {
+                continue;
+            }
+
+            $qty            = $item->getQty();
+            $changeQty      = true;
+            $checkWeight    = true;
+            $decimalItems   = array();
+
+            if ($item->getParentItem()) {
+                if (!$item->getParentItem()->getProduct()->getShipmentType()) {
+                    continue;
+                }
+                $qty = $item->getIsQtyDecimal()
+                    ? $item->getParentItem()->getQty()
+                    : $item->getParentItem()->getQty() * $item->getQty();
+            }
+
+            $itemWeight = $item->getWeight();
+            if ($item->getIsQtyDecimal() && $item->getProductType() != Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) {
+                $stockItem = $item->getProduct()->getStockItem();
+                if ($stockItem->getIsDecimalDivided()) {
+                   if ($stockItem->getEnableQtyIncrements() && $stockItem->getQtyIncrements()) {
+                        $itemWeight = $itemWeight * $stockItem->getQtyIncrements();
+                        $qty        = round(($item->getWeight() / $itemWeight) * $qty);
+                        $changeQty  = false;
+                   } else {
+                       $itemWeight = $itemWeight * $item->getQty();
+                       if ($itemWeight > $maxWeight) {
+                           $qtyItem = floor($itemWeight / $maxWeight);
+                           $decimalItems[] = array('weight' => $maxWeight, 'qty' => $qtyItem);
+                           $weightItem = Mage::helper('Mage_Core_Helper_Data')->getExactDivision($itemWeight, $maxWeight);
+                           if ($weightItem) {
+                               $decimalItems[] = array('weight' => $weightItem, 'qty' => 1);
+                           }
+                           $checkWeight = false;
+                       } else {
+                           $itemWeight = $itemWeight * $item->getQty();
+                       }
+                   }
+                } else {
+                    $itemWeight = $itemWeight * $item->getQty();
+                }
+            }
+
+            if ($checkWeight && $maxWeight && $itemWeight > $maxWeight) {
+                return array();
+            }
+
+            if ($changeQty && !$item->getParentItem() && $item->getIsQtyDecimal()
+                && $item->getProductType() != Mage_Catalog_Model_Product_Type::TYPE_BUNDLE
+            ) {
+                $qty = 1;
+            }
+
+            if (!empty($decimalItems)) {
+                foreach ($decimalItems as $decimalItem) {
+                    $fullItems = array_merge($fullItems,
+                        array_fill(0, $decimalItem['qty'] * $qty, $decimalItem['weight'])
+                    );
+                }
+            } else {
+                $fullItems = array_merge($fullItems, array_fill(0, $qty, $itemWeight));
+            }
+        }
+        sort($fullItems);
+
+        return $this->_makePieces($fullItems, $maxWeight);
+    }
+
+    /**
+     * Make pieces
+     * Compose packeges list based on given items, so that each package is as heavy as possible
+     *
+     * @param array $items
+     * @param float $maxWeight
+     * @return array
+     */
+    protected function _makePieces($items, $maxWeight)
+    {
+        $pieces = array();
+        if (!empty($items)) {
+            $sumWeight = 0;
+
+            $reverseOrderItems = $items;
+            arsort($reverseOrderItems);
+
+            foreach ($reverseOrderItems as $key => $weight) {
+                if (!isset($items[$key])) {
+                    continue;
+                }
+                unset($items[$key]);
+                $sumWeight = $weight;
+                foreach ($items as $key => $weight) {
+                    if (($sumWeight + $weight) < $maxWeight) {
+                        unset($items[$key]);
+                        $sumWeight += $weight;
+                    } elseif (($sumWeight + $weight) > $maxWeight) {
+                        $pieces[] = (string)(float)$sumWeight;
+                        break;
+                    } else {
+                        unset($items[$key]);
+                        $pieces[] = (string)(float)($sumWeight + $weight);
+                        $sumWeight = 0;
+                        break;
+                    }
+                }
+            }
+            if ($sumWeight > 0) {
+                $pieces[] = (string)(float)$sumWeight;
+            }
+            $pieces = array_count_values($pieces);
+        }
+
+        return $pieces;
+    }
+
     /**
      * Collect rates by address
      *
@@ -317,7 +488,7 @@ class Mage_Shipping_Model_Shipping
         $request->setRecipientAddressStreet1($address->getStreet1());
         $request->setRecipientAddressStreet2($address->getStreet2());
         $request->setRecipientAddressCity($address->getCity());
-        $request->setRecipientAddressStateOrProvinceCode($address->getRegion());
+        $request->setRecipientAddressStateOrProvinceCode($address->getRegionCode());
         $request->setRecipientAddressRegionCode($recipientRegionCode);
         $request->setRecipientAddressPostalCode($address->getPostcode());
         $request->setRecipientAddressCountryCode($address->getCountryId());
diff --git a/app/code/core/Mage/Shipping/controllers/TrackingController.php b/app/code/core/Mage/Shipping/controllers/TrackingController.php
index 72543193cf7373ce86a9767b710c712582cef110..903fa9dbe83f3f341eb719c3b30860d85b31fd57 100644
--- a/app/code/core/Mage/Shipping/controllers/TrackingController.php
+++ b/app/code/core/Mage/Shipping/controllers/TrackingController.php
@@ -47,7 +47,6 @@ class Mage_Shipping_TrackingController extends Mage_Core_Controller_Front_Action
             $className = Mage::getConfig()->getBlockClassName('Mage_Core_Block_Template');
             $block = new $className();
             $block->setType('Mage_Core_Block_Template')
-                ->setIsAnonymous(true)
                 ->setTemplate('order/trackinginfo.phtml');
 
             foreach ($tracks as $track){
diff --git a/app/code/core/Mage/Shipping/etc/system.xml b/app/code/core/Mage/Shipping/etc/system.xml
index a0436182896e553e687ae3d0b95f552e5824b1b3..dd2d39f2d844a21c37cb601c9c3225bfb319bcb7 100644
--- a/app/code/core/Mage/Shipping/etc/system.xml
+++ b/app/code/core/Mage/Shipping/etc/system.xml
@@ -56,6 +56,7 @@
                         <checkout_multiple_maximum_qty translate="label">
                             <label>Maximum Qty Allowed for Shipping to Multiple Addresses</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number</validate>
                             <sort_order>2</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -162,6 +163,7 @@
                         <price translate="label">
                             <label>Price</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>5</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -179,6 +181,7 @@
                         <handling_fee translate="label">
                             <label>Handling Fee</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>8</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -268,6 +271,7 @@
                         <free_shipping_subtotal translate="label">
                             <label>Minimum Order Amount</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>4</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -356,6 +360,7 @@
                         <handling_fee translate="label">
                             <label>Handling Fee</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>8</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
diff --git a/app/code/core/Mage/Shipping/view/frontend/layout.xml b/app/code/core/Mage/Shipping/view/frontend/layout.xml
index 7f3fb1c04c56ea8bb1e59bbc449db0790f988253..d33ac549ee928aa8a97ee1c8864075eb1fed4243 100644
--- a/app/code/core/Mage/Shipping/view/frontend/layout.xml
+++ b/app/code/core/Mage/Shipping/view/frontend/layout.xml
@@ -28,7 +28,8 @@
 -->
 <layout version="0.1.0">
 
-    <shipping_tracking_ajax>
+    <shipping_tracking_ajax translate="label" type="page" parent="checkout_onepage_shippingmethod">
+        <label>Shipment Tracking Ajax</label>
         <reference name="root">
             <action method="setTemplate"><template></template></action>
         </reference>
@@ -36,7 +37,8 @@
             <block type="Mage_Shipping_Block_Tracking_Ajax" name="shipping.tracking.ajax" template="tracking/ajax.phtml" />
         </reference>
     </shipping_tracking_ajax>
-    <shipping_tracking_popup translate="label">
+
+    <shipping_tracking_popup translate="label" type="page" parent="checkout_onepage_shippingmethod">
         <label>Shipment Tracking Popup</label>
         <reference name="root">
             <action method="setTemplate"><template>popup.phtml</template></action>
diff --git a/app/code/core/Mage/Shipping/view/frontend/tracking/popup.phtml b/app/code/core/Mage/Shipping/view/frontend/tracking/popup.phtml
index 0337d5842fcfbf9374224892b1a42a9cd520e51c..abe7448594fca512a4b62093249621ffbf8fc07a 100644
--- a/app/code/core/Mage/Shipping/view/frontend/tracking/popup.phtml
+++ b/app/code/core/Mage/Shipping/view/frontend/tracking/popup.phtml
@@ -23,9 +23,9 @@
  * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
-/* @var $this Mage_Shipping_Block_Tracking_Popup */
 ?>
-<?php  $_results = $this->getTrackingInfo() ?>
+<?php /** @var $this Mage_Shipping_Block_Tracking_Popup */ ?>
+<?php $_results = $this->getTrackingInfo(); ?>
 <div class="page-title title-buttons">
     <h1><?php echo $this->__('Tracking Information'); ?></h1>
     <button class="button" onclick="window.close(); window.opener.focus();"><span><span><?php echo $this->__('Close Window') ?></span></span></button>
@@ -45,12 +45,12 @@
                 <?php if(is_object($track)): ?>
                     <tr>
                         <th class="label"><?php echo $this->__('Tracking Number:'); ?></th>
-                        <td class="value"><?php echo $track->getTracking(); ?></td>
+                        <td class="value"><?php echo $this->escapeHtml($track->getTracking()); ?></td>
                     </tr>
                     <?php if ($track->getCarrierTitle()): ?>
                     <tr>
                         <th class="label"><?php echo $this->__('Carrier:'); ?></th>
-                        <td class="value"><?php echo $track->getCarrierTitle(); ?></td>
+                        <td class="value"><?php echo $this->escapeHtml($track->getCarrierTitle()); ?></td>
                     </tr>
                     <?php endif; ?>
                     <?php if($track->getErrorMessage()): ?>
@@ -66,7 +66,7 @@
                     <?php elseif($track->getUrl()): ?>
                     <tr>
                         <th class="label"><?php echo $this->__('Track:'); ?></th>
-                        <td class="value"><a href="<?php echo $track->getUrl(); ?>" onclick="this.target='_blank'"><?php echo $track->getUrl(); ?></a></td>
+                        <td class="value"><a href="<?php echo $this->escapeHtml($track->getUrl()); ?>" onclick="this.target='_blank'"><?php echo $this->escapeHtml($track->getUrl()); ?></a></td>
                     </tr>
                     <?php else: ?>
                         <?php if ($track->getStatus()): ?>
diff --git a/app/code/core/Mage/Tag/Block/Customer/View.php b/app/code/core/Mage/Tag/Block/Customer/View.php
index 4d8e05a5e4bef468e2c68f03e9ea5b70f936ae6c..34c9258932528b6d08cb314123c6b5519831c5f0 100644
--- a/app/code/core/Mage/Tag/Block/Customer/View.php
+++ b/app/code/core/Mage/Tag/Block/Customer/View.php
@@ -135,7 +135,7 @@ class Mage_Tag_Block_Customer_View extends Mage_Catalog_Block_Product_Abstract
      */
     public function getMode()
     {
-        return $this->getChild('toolbar')->getCurrentMode();
+        return $this->getChildBlock('toolbar')->getCurrentMode();
     }
 
     /**
diff --git a/app/code/core/Mage/Tag/Block/Product/Result.php b/app/code/core/Mage/Tag/Block/Product/Result.php
index 4d312b651de1af70841ca20a0f326fc47454a304..6d7d34de6e08bc4fd93dfa0ceb639315dda92ecc 100644
--- a/app/code/core/Mage/Tag/Block/Product/Result.php
+++ b/app/code/core/Mage/Tag/Block/Product/Result.php
@@ -51,7 +51,7 @@ class Mage_Tag_Block_Product_Result extends Mage_Catalog_Block_Product_Abstract
     }
 
     public function setListOrders() {
-        $this->getChild('search_result_list')
+        $this->getChildBlock('search_result_list')
             ->setAvailableOrders(array(
                 'name' => Mage::helper('Mage_Tag_Helper_Data')->__('Name'),
                 'price'=>Mage::helper('Mage_Tag_Helper_Data')->__('Price'))
@@ -59,7 +59,7 @@ class Mage_Tag_Block_Product_Result extends Mage_Catalog_Block_Product_Abstract
     }
 
     public function setListModes() {
-        $this->getChild('search_result_list')
+        $this->getChildBlock('search_result_list')
             ->setModes(array(
                 'grid' => Mage::helper('Mage_Tag_Helper_Data')->__('Grid'),
                 'list' => Mage::helper('Mage_Tag_Helper_Data')->__('List'))
@@ -67,7 +67,7 @@ class Mage_Tag_Block_Product_Result extends Mage_Catalog_Block_Product_Abstract
     }
 
     public function setListCollection() {
-        $this->getChild('search_result_list')
+        $this->getChildBlock('search_result_list')
            ->setCollection($this->_getProductCollection());
     }
 
diff --git a/app/code/core/Mage/Tag/view/frontend/layout.xml b/app/code/core/Mage/Tag/view/frontend/layout.xml
index 7756237437f9cd4a94bef4ea90bc280680fb87de..5552a09f7253ff32a9915a13d5465b5cda401cd6 100644
--- a/app/code/core/Mage/Tag/view/frontend/layout.xml
+++ b/app/code/core/Mage/Tag/view/frontend/layout.xml
@@ -63,15 +63,11 @@ Customer account home dashboard layout
         </reference>
     </customer_account_index>
 
-    <catalog_product_view translate="label">
-        <label>Catalog Product View</label>
+    <catalog_product_view>
          <!-- Mage_Tag -->
         <reference name="product.info.additional">
             <block type="Mage_Tag_Block_Product_List" name="product_tag_list" before="-" template="list.phtml">
-                <block type="Mage_Page_Block_Html_Wrapper" name="product.tag.list.list.before" as="list_before" translate="label">
-                    <label>Tags List Before</label>
-                    <action method="setMayBeInvisible"><value>1</value></action>
-                </block>
+                <container name="product.tag.list.list.before" as="list_before" label="Tags List Before" htmlTag="div"/>
             </block>
         </reference>
     </catalog_product_view>
@@ -80,7 +76,7 @@ Customer account home dashboard layout
 All tags page
 -->
 
-    <tag_list_index translate="label">
+    <tag_list_index translate="label" type="page" parent="default">
         <label>Tags List (All Available)</label>
         <!-- Mage_Tag -->
         <reference name="root">
@@ -91,7 +87,7 @@ All tags page
         </reference>
     </tag_list_index>
 
-    <tag_product_list translate="label">
+    <tag_product_list translate="label" type="page" parent="tag_list_index">
         <label>Tagged Products List</label>
         <!-- Mage_Tag -->
         <reference name="content">
@@ -109,7 +105,7 @@ All tags page
         </reference>
     </tag_product_list>
 
-    <tag_customer_index translate="label">
+    <tag_customer_index translate="label" type="page" parent="tag_list_index">
         <label>Customer My Account My Tags List</label>
         <update handle="customer_account"/>
         <reference name="root">
@@ -120,7 +116,7 @@ All tags page
         </reference>
     </tag_customer_index>
 
-    <tag_customer_view translate="label">
+    <tag_customer_view translate="label" type="page" parent="tag_customer_index">
         <label>Customer My Account Tag View</label>
         <update handle="customer_account"/>
         <reference name="root">
diff --git a/app/code/core/Mage/Tax/Model/Sales/Total/Quote/Subtotal.php b/app/code/core/Mage/Tax/Model/Sales/Total/Quote/Subtotal.php
index 6ddb12bb96663fc58f168aa9ddc63dd0f3b693e4..2c44a755e421d409b3934fd24d65bd2a354dfb44 100644
--- a/app/code/core/Mage/Tax/Model/Sales/Total/Quote/Subtotal.php
+++ b/app/code/core/Mage/Tax/Model/Sales/Total/Quote/Subtotal.php
@@ -273,10 +273,8 @@ class Mage_Tax_Model_Sales_Total_Quote_Subtotal extends Mage_Sales_Model_Quote_A
             $item->getOriginalPrice();
             $item->setCustomPrice($price);
             $item->setBaseCustomPrice($basePrice);
-        } else {
-            $item->setConvertedPrice($price);
         }
-        $item->setPrice($price);
+        $item->setPrice($basePrice);
         $item->setBasePrice($basePrice);
         $item->setRowTotal($subtotal);
         $item->setBaseRowTotal($baseSubtotal);
@@ -386,10 +384,8 @@ class Mage_Tax_Model_Sales_Total_Quote_Subtotal extends Mage_Sales_Model_Quote_A
             $item->getOriginalPrice();
             $item->setCustomPrice($price);
             $item->setBaseCustomPrice($basePrice);
-        } else {
-            $item->setConvertedPrice($price);
         }
-        $item->setPrice($price);
+        $item->setPrice($basePrice);
         $item->setBasePrice($basePrice);
         $item->setRowTotal($subtotal);
         $item->setBaseRowTotal($baseSubtotal);
diff --git a/app/code/core/Mage/Tax/Model/Sales/Total/Quote/Tax.php b/app/code/core/Mage/Tax/Model/Sales/Total/Quote/Tax.php
index cd70c72b4ab11ea05d599bb30663bd68563055aa..0874086ef893d29c4a14bcfc27a34d672426e200 100644
--- a/app/code/core/Mage/Tax/Model/Sales/Total/Quote/Tax.php
+++ b/app/code/core/Mage/Tax/Model/Sales/Total/Quote/Tax.php
@@ -567,7 +567,6 @@ class Mage_Tax_Model_Sales_Total_Quote_Tax extends Mage_Sales_Model_Quote_Addres
         $taxGroups      = array();
         $itemTaxGroups  = array();
 
-        $inclTax = false;
         foreach ($items as $item) {
             if ($item->getParentItem()) {
                 continue;
@@ -579,8 +578,8 @@ class Mage_Tax_Model_Sales_Total_Quote_Tax extends Mage_Sales_Model_Quote_Addres
                     $rate = $this->_calculator->getRate($taxRateRequest);
                     $applied_rates = $this->_calculator->getAppliedRates($taxRateRequest);
                     $taxGroups[(string)$rate]['applied_rates'] = $applied_rates;
+                    $taxGroups[(string)$rate]['incl_tax'] = $child->getIsPriceInclTax();
                     $this->_aggregateTaxPerRate($child, $rate, $taxGroups);
-                    $inclTax = $child->getIsPriceInclTax();
                     if ($rate > 0) {
                         $itemTaxGroups[$child->getId()] = $applied_rates;
                     }
@@ -591,8 +590,8 @@ class Mage_Tax_Model_Sales_Total_Quote_Tax extends Mage_Sales_Model_Quote_Addres
                 $rate = $this->_calculator->getRate($taxRateRequest);
                 $applied_rates = $this->_calculator->getAppliedRates($taxRateRequest);
                 $taxGroups[(string)$rate]['applied_rates'] = $applied_rates;
+                $taxGroups[(string)$rate]['incl_tax'] = $item->getIsPriceInclTax();
                 $this->_aggregateTaxPerRate($item, $rate, $taxGroups);
-                $inclTax = $item->getIsPriceInclTax();
                 if ($rate > 0) {
                     $itemTaxGroups[$item->getId()] = $applied_rates;
                 }
@@ -606,6 +605,7 @@ class Mage_Tax_Model_Sales_Total_Quote_Tax extends Mage_Sales_Model_Quote_Addres
 
         foreach ($taxGroups as $rateKey => $data) {
             $rate = (float) $rateKey;
+            $inclTax = $data['incl_tax'];
             $totalTax = $this->_calculator->calcTaxAmount(array_sum($data['totals']), $rate, $inclTax);
             $baseTotalTax = $this->_calculator->calcTaxAmount(array_sum($data['base_totals']), $rate, $inclTax);
             $this->_addAmount($totalTax);
@@ -658,6 +658,21 @@ class Mage_Tax_Model_Sales_Total_Quote_Tax extends Mage_Sales_Model_Quote_Addres
                 $baseTaxSubtotal    = max($baseSubtotal - $baseDiscount, 0);
                 $rowTax             = $this->_calculator->calcTaxAmount($taxSubtotal, $rate, $inclTax, false);
                 $baseRowTax         = $this->_calculator->calcTaxAmount($baseTaxSubtotal, $rate, $inclTax, false);
+                if (!$item->getNoDiscount() && $item->getWeeeTaxApplied()) {
+                    $rowTaxBeforeDiscount = $this->_calculator->calcTaxAmount(
+                        $subtotal,
+                        $rate,
+                        $inclTax,
+                        false
+                    );
+                    $baseRowTaxBeforeDiscount = $this->_calculator->calcTaxAmount(
+                        $baseSubtotal,
+                        $rate,
+                        $inclTax,
+                        false
+                    );
+                }
+
                 if ($inclTax && $discount > 0) {
                     $hiddenTax      = $this->_calculator->calcTaxAmount($discount, $rate, $inclTax, false);
                     $baseHiddenTax  = $this->_calculator->calcTaxAmount($baseDiscount, $rate, $inclTax, false);
@@ -678,6 +693,20 @@ class Mage_Tax_Model_Sales_Total_Quote_Tax extends Mage_Sales_Model_Quote_Addres
         $item->setTaxAmount(max(0, $rowTax));
         $item->setBaseTaxAmount(max(0, $baseRowTax));
 
+        if (isset($rowTaxBeforeDiscount) && isset($baseRowTaxBeforeDiscount)) {
+            $taxBeforeDiscount = max(
+                0,
+                $this->_deltaRound($rowTaxBeforeDiscount, $rateKey, $inclTax)
+            );
+            $baseTaxBeforeDiscount = max(
+                0,
+                $this->_deltaRound($baseRowTaxBeforeDiscount, $rateKey, $inclTax, 'base')
+            );
+
+            $item->setDiscountTaxCompensation($taxBeforeDiscount - max(0, $rowTax));
+            $item->setBaseDiscountTaxCompensation($baseTaxBeforeDiscount - max(0, $baseRowTax));
+        }
+
         $taxGroups[$rateKey]['totals'][]        = max(0, $taxSubtotal);
         $taxGroups[$rateKey]['base_totals'][]   = max(0, $baseTaxSubtotal);
         return $this;
@@ -786,12 +815,20 @@ class Mage_Tax_Model_Sales_Total_Quote_Tax extends Mage_Sales_Model_Quote_Addres
         $applied    = $address->getAppliedTaxes();
         $store      = $address->getQuote()->getStore();
         $amount     = $address->getTaxAmount();
+
+        $items = $this->_getAddressItems($address);
+        $discountTaxCompensation = 0;
+        foreach ($items as $item) {
+            $discountTaxCompensation += $item->getDiscountTaxCompensation();
+        }
+        $taxAmount = $amount + $discountTaxCompensation;
+
         $area       = null;
         if ($this->_config->displayCartTaxWithGrandTotal($store) && $address->getGrandTotal()) {
             $area   = 'taxes';
         }
 
-        if (($amount!=0) || ($this->_config->displayCartZeroTax($store))) {
+        if (($amount != 0) || ($this->_config->displayCartZeroTax($store))) {
             $address->addTotal(array(
                 'code'      => $this->getCode(),
                 'title'     => Mage::helper('Mage_Tax_Helper_Data')->__('Tax'),
@@ -809,7 +846,7 @@ class Mage_Tax_Model_Sales_Total_Quote_Tax extends Mage_Sales_Model_Quote_Addres
             if ($address->getSubtotalInclTax() > 0) {
                 $subtotalInclTax = $address->getSubtotalInclTax();
             } else {
-                $subtotalInclTax = $address->getSubtotal()+$address->getTaxAmount()-$address->getShippingTaxAmount();
+                $subtotalInclTax = $address->getSubtotal() + $taxAmount - $address->getShippingTaxAmount();
             }
 
             $address->addTotal(array(
diff --git a/app/code/core/Mage/Tax/etc/system.xml b/app/code/core/Mage/Tax/etc/system.xml
index df7c16b1299f750bf7d776b1d731cd2cbf13ad0c..d32370cfbbbf9a61970ae91d7c6bd0f9c23be869 100644
--- a/app/code/core/Mage/Tax/etc/system.xml
+++ b/app/code/core/Mage/Tax/etc/system.xml
@@ -267,7 +267,7 @@
                     </fields>
                 </cart_display>
                 <sales_display translate="label">
-                    <label>Orders, Invoices, Creditmemos Display Settings</label>
+                    <label>Orders, Invoices, Credit Memos Display Settings</label>
                     <sort_order>60</sort_order>
                     <show_in_default>1</show_in_default>
                     <show_in_website>1</show_in_website>
diff --git a/app/code/core/Mage/Tax/sql/tax_setup/mysql4-upgrade-1.4.0.1-1.4.0.2.php b/app/code/core/Mage/Tax/sql/tax_setup/mysql4-upgrade-1.4.0.1-1.4.0.2.php
new file mode 100644
index 0000000000000000000000000000000000000000..613f09b64e41670f27aef7cdc4bbfb9b5b859b1c
--- /dev/null
+++ b/app/code/core/Mage/Tax/sql/tax_setup/mysql4-upgrade-1.4.0.1-1.4.0.2.php
@@ -0,0 +1,36 @@
+<?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_Tax
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/* @var $installer Mage_Core_Model_Resource_Setup */
+$installer = $this;
+$installer->startSetup();
+$installer->getConnection()->changeColumn(
+    $installer->getTable('tax_calculation_rate'),
+    'tax_postcode',
+    'tax_postcode',
+    'VARCHAR(21) NULL DEFAULT NULL'
+);
+$installer->endSetup();
diff --git a/app/code/core/Mage/Tax/view/frontend/checkout/shipping.phtml b/app/code/core/Mage/Tax/view/frontend/checkout/shipping.phtml
index 7df994d508cb33a135801d50eecf891548d530a3..0745c97f0d4a1001fa22dd8f5d96f473d05b4756 100644
--- a/app/code/core/Mage/Tax/view/frontend/checkout/shipping.phtml
+++ b/app/code/core/Mage/Tax/view/frontend/checkout/shipping.phtml
@@ -57,7 +57,7 @@
 <?php else:?>
 <tr>
     <td style="<?php echo $this->getStyle() ?>" class="a-right" colspan="<?php echo $this->getColspan(); ?>">
-        <?php echo $this->getTotal()->getTitle() ?>
+        <?php echo $this->escapeHtml($this->getTotal()->getTitle()) ?>
     </td>
     <td style="<?php echo $this->getStyle() ?>" class="a-right">
         <?php echo $this->helper('Mage_Checkout_Helper_Data')->formatPrice($this->getShippingExcludeTax()) ?>
diff --git a/app/code/core/Mage/Tax/view/frontend/checkout/tax.phtml b/app/code/core/Mage/Tax/view/frontend/checkout/tax.phtml
index 2a757fcd29654659c6be66ad0fa9eff05cd51351..84d7022af630819076ae407f9522f8bcefde7415 100644
--- a/app/code/core/Mage/Tax/view/frontend/checkout/tax.phtml
+++ b/app/code/core/Mage/Tax/view/frontend/checkout/tax.phtml
@@ -45,7 +45,7 @@
         <?php foreach ($rates as $rate): ?>
         <tr class="summary-details-<?php echo $taxIter; ?> summary-details<?php if ($isTop): echo ' summary-details-first'; endif; ?>" style="display:none;">
             <td class="a-right" style="<?php echo $_style ?>" colspan="<?php echo $this->getColspan(); ?>">
-                <?php echo $rate['title']; ?>
+                <?php echo $this->escapeHtml($rate['title']); ?>
                 <?php if (!is_null($rate['percent'])): ?>
                     (<?php echo (float)$rate['percent']; ?>%)
                 <?php endif; ?>
diff --git a/app/code/core/Mage/Tax/view/frontend/order/tax.phtml b/app/code/core/Mage/Tax/view/frontend/order/tax.phtml
index 8aa6562581cba2fdc0b0d04e0d0dcd933d79baa4..d0302e745bf8aa252506e45cfd4dabca87f5325f 100644
--- a/app/code/core/Mage/Tax/view/frontend/order/tax.phtml
+++ b/app/code/core/Mage/Tax/view/frontend/order/tax.phtml
@@ -45,7 +45,7 @@
         <?php foreach ($rates as $rate): ?>
         <tr class="summary-details-<?php echo $taxIter; ?> summary-details<?php if ($isTop): echo ' summary-details-first'; endif; ?>"<?php if (!$this->getIsPlaneMode()):?> style="display:none;"<?php endif;?>>
             <td <?php echo $this->getLabelProperties()?>>
-                <?php echo $rate['title']; ?>
+                <?php echo $this->escapeHtml($rate['title']); ?>
                 <?php if (!is_null($rate['percent'])): ?>
                     (<?php echo (float)$rate['percent']; ?>%)
                 <?php endif; ?>
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract.php
index a6da8c6ee1adc10f83c4f9ad109c4a6e4337f45f..23f99fc0a8dca570ef3bbed3a4605be4d9a8ef47 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract.php
@@ -108,12 +108,16 @@ abstract class Mage_Usa_Model_Shipping_Carrier_Abstract extends Mage_Shipping_Mo
     }
 
     /**
-     * Check if zip code option required
+     * Determine whether zip-code is required for the country of destination
      *
-     * @return boolean
+     * @param Mage_Shipping_Model_Rate_Request|null $request
+     * @return bool
      */
-    public function isZipCodeRequired()
+    public function isZipCodeRequired(Mage_Shipping_Model_Rate_Request $request = null)
     {
+        if ($request instanceof Mage_Shipping_Model_Rate_Request) {
+            return !Mage::helper('Mage_Directory_Helper_Data')->isZipCodeOptional($request->getDestCountryId());
+        }
         return true;
     }
 
@@ -128,14 +132,37 @@ abstract class Mage_Usa_Model_Shipping_Carrier_Abstract extends Mage_Shipping_Mo
     }
 
     /**
-     * Some carriers need to override this method to get the correct quote
+     * Return items for further shipment rate evaluation. We need to pass children of a bundle instead passing the
+     * bundle itself, otherwise we may not get a rate at all (e.g. when total weight of a bundle exceeds max weight
+     * despite each item by itself is not)
      *
      * @param Mage_Shipping_Model_Rate_Request $request
      * @return array
      */
     public function getAllItems(Mage_Shipping_Model_Rate_Request $request)
     {
-        return $request->getAllItems();
+        $items = array();
+        if ($request->getAllItems()) {
+            foreach ($request->getAllItems() as $item) {
+                /* @var $item Mage_Sales_Model_Quote_Item */
+                if ($item->getProduct()->isVirtual() || $item->getParentItem()) {
+                    // Don't process children here - we will process (or already have processed) them below
+                    continue;
+                }
+
+                if ($item->getHasChildren() && $item->isShipSeparately()) {
+                    foreach ($item->getChildren() as $child) {
+                        if (!$child->getFreeShipping() && !$child->getProduct()->isVirtual()) {
+                            $items[] = $child;
+                        }
+                    }
+                } else {
+                    // Ship together - count compound item as one solid
+                    $items[] = $item;
+                }
+            }
+        }
+        return $items;
     }
 
     /**
@@ -151,22 +178,36 @@ abstract class Mage_Usa_Model_Shipping_Carrier_Abstract extends Mage_Shipping_Mo
             return $this;
         }
 
-        $maxAllowedWeight = (float) $this->getConfigData('max_package_weight');
-        $errorMsg = '';
-        $configErrorMsg = $this->getConfigData('specificerrmsg');
-        $defaultErrorMsg = Mage::helper('Mage_Shipping_Helper_Data')->__('The shipping module is not available.');
-        $showMethod = $this->getConfigData('showmethod');
+        $maxAllowedWeight   = (float) $this->getConfigData('max_package_weight');
+        $errorMsg           = '';
+        $configErrorMsg     = $this->getConfigData('specificerrmsg');
+        $defaultErrorMsg    = Mage::helper('Mage_Shipping_Helper_Data')->__('The shipping module is not available.');
+        $showMethod         = $this->getConfigData('showmethod');
 
         foreach ($this->getAllItems($request) as $item) {
             if ($item->getProduct() && $item->getProduct()->getId()) {
-                if ($item->getProduct()->getWeight() * $item->getQty() > $maxAllowedWeight) {
+                $weight         = $item->getProduct()->getWeight();
+                $stockItem      = $item->getProduct()->getStockItem();
+                $doValidation   = true;
+
+                if ($stockItem->getIsQtyDecimal() && $stockItem->getIsDecimalDivided()) {
+                    if ($stockItem->getEnableQtyIncrements() && $stockItem->getQtyIncrements()) {
+                        $weight = $weight * $stockItem->getQtyIncrements();
+                    } else {
+                        $doValidation = false;
+                    }
+                } elseif ($stockItem->getIsQtyDecimal() && !$stockItem->getIsDecimalDivided()) {
+                    $weight = $weight * $item->getQty();
+                }
+
+                if ($doValidation && $weight > $maxAllowedWeight) {
                     $errorMsg = ($configErrorMsg) ? $configErrorMsg : $defaultErrorMsg;
                     break;
                 }
             }
         }
 
-        if (!$errorMsg && !$request->getDestPostcode() && $this->isZipCodeRequired()) {
+        if (!$errorMsg && !$request->getDestPostcode() && $this->isZipCodeRequired($request)) {
             $errorMsg = Mage::helper('Mage_Shipping_Helper_Data')->__('This shipping method is not available, please specify ZIP-code');
         }
 
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups/Source/Mode.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract/Source/Mode.php
similarity index 83%
rename from app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups/Source/Mode.php
rename to app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract/Source/Mode.php
index 0a2dafa7d3947da722f0b251efd36d0ff512ffda..69882e392828f3227aedc3b352bf0ddc365e0b6e 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups/Source/Mode.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract/Source/Mode.php
@@ -25,19 +25,25 @@
  */
 
 /**
- * UPS (UPS XML) Modesource model
+ * Shippers Modesource model
  *
  * @category Mage
  * @package Mage_Usa
- * @author      Magento Core Team <core@magentocommerce.com>
+ * @author Magento Core Team <core@magentocommerce.com>
  */
-class Mage_Usa_Model_Shipping_Carrier_Ups_Source_Mode
+
+class Mage_Usa_Model_Shipping_Carrier_Abstract_Source_Mode
 {
+    /**
+     * Returns array to be used in packages request type on back-end
+     *
+     * @return array
+     */
     public function toOptionArray()
     {
         return array(
-            array('value' => '1', 'label' => Mage::helper('Mage_Usa_Helper_Data')->__('Live')),
             array('value' => '0', 'label' => Mage::helper('Mage_Usa_Helper_Data')->__('Development')),
+            array('value' => '1', 'label' => Mage::helper('Mage_Usa_Helper_Data')->__('Live')),
         );
     }
 }
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract/Source/Requesttype.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract/Source/Requesttype.php
new file mode 100644
index 0000000000000000000000000000000000000000..c9d340e3893c5cc6d4dd633d2393aa35cacc3cd0
--- /dev/null
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Abstract/Source/Requesttype.php
@@ -0,0 +1,48 @@
+<?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_Usa
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Source model for Shippers Request Type
+ *
+ * @category   Mage
+ * @package    Mage_Usa
+ * @author     Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_Usa_Model_Shipping_Carrier_Abstract_Source_Requesttype
+{
+    /**
+     * Returns array to be used in packages request type on back-end
+     *
+     * @return array
+     */
+    public function toOptionArray()
+    {
+        return array(
+            array('value' => 0, 'label' => Mage::helper('Mage_Shipping_Helper_Data')->__('Divide to equal weight (one request)')),
+            array('value' => 1, 'label' => Mage::helper('Mage_Shipping_Helper_Data')->__('Use origin weight (few requests)')),
+        );
+    }
+}
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/International.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/International.php
index 56f60bb1731aa3df58280a760788362294e43199..a2a027b509e30506dfa22d81487c6369b8cc9877 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/International.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/International.php
@@ -574,7 +574,10 @@ class Mage_Usa_Model_Shipping_Carrier_Dhl_International
                 continue;
             }
 
-            $qty = $item->getQty();
+            $qty            = $item->getQty();
+            $changeQty      = true;
+            $checkWeight    = true;
+            $decimalItems   = array();
 
             if ($item->getParentItem()) {
                 if (!$item->getParentItem()->getProduct()->getShipmentType()) {
@@ -587,19 +590,51 @@ class Mage_Usa_Model_Shipping_Carrier_Dhl_International
 
             $itemWeight = $item->getWeight();
             if ($item->getIsQtyDecimal() && $item->getProductType() != Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) {
-                $itemWeight = $itemWeight * $item->getQty();
+                $stockItem = $item->getProduct()->getStockItem();
+                if ($stockItem->getIsDecimalDivided()) {
+                   if ($stockItem->getEnableQtyIncrements() && $stockItem->getQtyIncrements()) {
+                        $itemWeight = $itemWeight * $stockItem->getQtyIncrements();
+                        $qty        = round(($item->getWeight() / $itemWeight) * $qty);
+                        $changeQty  = false;
+                   } else {
+                       $itemWeight = $this->_getWeight($itemWeight * $item->getQty());
+                       $maxWeight  = $this->_getWeight($this->_maxWeight, true);
+                       if ($itemWeight > $maxWeight) {
+                           $qtyItem = floor($itemWeight / $maxWeight);
+                           $decimalItems[] = array('weight' => $maxWeight, 'qty' => $qtyItem);
+                           $weightItem = Mage::helper('Mage_Core_Helper_Data')->getExactDivision($itemWeight, $maxWeight);
+                           if ($weightItem) {
+                               $decimalItems[] = array('weight' => $weightItem, 'qty' => 1);
+                           }
+                           $checkWeight = false;
+                       } else {
+                           $itemWeight = $itemWeight * $item->getQty();
+                       }
+                   }
+                } else {
+                    $itemWeight = $itemWeight * $item->getQty();
+                }
             }
 
-            if ($this->_getWeight($itemWeight) > $this->_getWeight($this->_maxWeight, true)) {
+            if ($checkWeight && $this->_getWeight($itemWeight) > $this->_getWeight($this->_maxWeight, true)) {
                 return array();
             }
 
-            if (!$item->getParentItem() && $item->getIsQtyDecimal()
+            if ($changeQty && !$item->getParentItem() && $item->getIsQtyDecimal()
                 && $item->getProductType() != Mage_Catalog_Model_Product_Type::TYPE_BUNDLE
             ) {
                 $qty = 1;
             }
-            $fullItems = array_merge($fullItems, array_fill(0, $qty, $this->_getWeight($itemWeight)));
+
+            if (!empty($decimalItems)) {
+                foreach ($decimalItems as $decimalItem) {
+                    $fullItems = array_merge($fullItems,
+                        array_fill(0, $decimalItem['qty'] * $qty, $decimalItem['weight'])
+                    );
+                }
+            } else {
+                $fullItems = array_merge($fullItems, array_fill(0, $qty, $this->_getWeight($itemWeight)));
+            }
         }
         sort($fullItems);
 
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex.php
index 99bc8b480ae02c2e0dcb8352933fcb643bdb18e6..ac5021d119b0cb9121e2ccd2f72389ce4e71b852 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex.php
@@ -29,7 +29,7 @@
  *
  * @category   Mage
  * @package    Mage_Usa
- * @author      Magento Core Team <core@magentocommerce.com>
+ * @author     Magento Core Team <core@magentocommerce.com>
  */
 class Mage_Usa_Model_Shipping_Carrier_Fedex
     extends Mage_Usa_Model_Shipping_Carrier_Abstract
@@ -43,6 +43,20 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex
      */
     const CODE = 'fedex';
 
+    /**
+     * Purpose of rate request
+     *
+     * @var string
+     */
+    const RATE_REQUEST_GENERAL = 'general';
+
+    /**
+     * Purpose of rate request
+     *
+     * @var string
+     */
+    const RATE_REQUEST_SMARTPOST = 'SMART_POST';
+
     /**
      * Code of the carrier
      *
@@ -103,8 +117,8 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex
     {
         parent::__construct();
         $wsdlBasePath = Mage::getModuleDir('etc', 'Mage_Usa')  . DS . 'wsdl' . DS . 'FedEx' . DS;
-        $this->_shipServiceWsdl = $wsdlBasePath . 'ShipService_v9.wsdl';
-        $this->_rateServiceWsdl = $wsdlBasePath . 'RateService_v9.wsdl';
+        $this->_shipServiceWsdl = $wsdlBasePath . 'ShipService_v10.wsdl';
+        $this->_rateServiceWsdl = $wsdlBasePath . 'RateService_v10.wsdl';
         $this->_trackServiceWsdl = $wsdlBasePath . 'TrackService_v5.wsdl';
     }
 
@@ -167,10 +181,11 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex
         if (!$this->getConfigFlag($this->_activeFlag)) {
             return false;
         }
+        $this->_result = Mage::getModel('Mage_Shipping_Model_Rate_Result');
 
         $this->setRequest($request);
 
-        $this->_result = $this->_getQuotes();
+        $this->_getQuotes();
 
         $this->_updateFreeMethodQuote($request);
 
@@ -287,18 +302,19 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex
     {
         return array(
             'ServiceId'    => 'crs',
-            'Major'        => '9',
+            'Major'        => '10',
             'Intermediate' => '0',
             'Minor'        => '0'
         );
     }
 
     /**
-     * Do remote request for  and handle errors
+     * Forming request for rate estimation depending to the purpose
      *
-     * @return Mage_Shipping_Model_Rate_Result
+     * @param string $purpose
+     * @return array
      */
-    protected function _getQuotes()
+    protected function _formRateRequest($purpose)
     {
         $r = $this->_rawRequest;
         $ratesRequest = array(
@@ -359,11 +375,38 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex
                         'InsuredValue' => array(
                             'Amount'  => $r->getValue(),
                             'Currency' => $this->getCurrencyCode()
-                        )
+                        ),
+                        'GroupPackageCount' => 1,
                     )
                 )
             )
         );
+
+        if ($purpose == self::RATE_REQUEST_GENERAL) {
+            $ratesRequest['RequestedShipment']['RequestedPackageLineItems'][0]['InsuredValue'] = array(
+                'Amount'  => $r->getValue(),
+                'Currency' => $this->getCurrencyCode()
+            );
+        } else if ($purpose == self::RATE_REQUEST_SMARTPOST) {
+            $ratesRequest['RequestedShipment']['ServiceType'] = self::RATE_REQUEST_SMARTPOST;
+            $ratesRequest['RequestedShipment']['SmartPostDetail'] = array(
+                'Indicia' => ((float)$r->getWeight() >= 1) ? 'PARCEL_SELECT' : 'PRESORTED_STANDARD',
+                'HubId' => $this->getConfigData('smartpost_hubid')
+            );
+        }
+
+        return $ratesRequest;
+    }
+
+    /**
+     * Makes remote request to the carrier and returns a response
+     *
+     * @param string $purpose
+     * @return mixed
+     */
+    protected function _doRatesRequest($purpose)
+    {
+        $ratesRequest = $this->_formRateRequest($purpose);
         $requestString = serialize($ratesRequest);
         $response = $this->_getCachedQuotes($requestString);
         $debugData = array('request' => $ratesRequest);
@@ -382,7 +425,31 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex
             $debugData['result'] = $response;
         }
         $this->_debug($debugData);
-        return $this->_prepareRateResponse($response);
+        return $response;
+    }
+
+    /**
+     * Do remote request for and handle errors
+     *
+     * @return void
+     */
+    protected function _getQuotes()
+    {
+        // make separate request for Smart Post method
+        $allowedMethods = explode(',', $this->getConfigData('allowed_methods'));
+        if (in_array(self::RATE_REQUEST_SMARTPOST, $allowedMethods)) {
+            $response = $this->_doRatesRequest(self::RATE_REQUEST_SMARTPOST);
+            $preparedSmartpost = $this->_prepareRateResponse($response);
+            if (!$preparedSmartpost->getError()) {
+                $this->_result->append($preparedSmartpost);
+            }
+        }
+        // make general request for all methods
+        $response = $this->_doRatesRequest(self::RATE_REQUEST_GENERAL);
+        $preparedGeneral = $this->_prepareRateResponse($response);
+        if (!$preparedGeneral->getError() || ($this->_result->getError() && $preparedGeneral->getError())) {
+            $this->_result->append($preparedGeneral);
+        }
     }
 
     /**
@@ -426,10 +493,9 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex
         }
 
         $result = Mage::getModel('Mage_Shipping_Model_Rate_Result');
-        $defaults = $this->getDefaults();
         if (empty($priceArr)) {
             $error = Mage::getModel('Mage_Shipping_Model_Rate_Result_Error');
-            $error->setCarrier('fedex');
+            $error->setCarrier($this->_code);
             $error->setCarrierTitle($this->getConfigData('title'));
             $error->setErrorMessage($errorTitle);
             $error->setErrorMessage($this->getConfigData('specificerrmsg'));
@@ -437,7 +503,7 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex
         } else {
             foreach ($priceArr as $method=>$price) {
                 $rate = Mage::getModel('Mage_Shipping_Model_Rate_Result_Method');
-                $rate->setCarrier('fedex');
+                $rate->setCarrier($this->_code);
                 $rate->setCarrierTitle($this->getConfigData('title'));
                 $rate->setMethod($method);
                 $rate->setMethodTitle($this->getCode('method', $method));
@@ -458,19 +524,29 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex
     protected function _getRateAmountOriginBased($rate)
     {
         $amount = null;
+        $rateTypeAmounts = array();
+
         if (is_object($rate)) {
-            foreach($rate->RatedShipmentDetails as $ratedShipmentDetail) {
-                $shipmentRateDetail = $ratedShipmentDetail->ShipmentRateDetail;
-                // The "RATED..." rates are expressed in the currency of the origin country
-                if ((string)$shipmentRateDetail->RateType == 'RATED_ACCOUNT_SHIPMENT') {
-                    $amount = (string)$shipmentRateDetail->TotalNetCharge->Amount;
+            // The "RATED..." rates are expressed in the currency of the origin country
+            foreach ($rate->RatedShipmentDetails as $ratedShipmentDetail) {
+                $netAmount = (string)$ratedShipmentDetail->ShipmentRateDetail->TotalNetCharge->Amount;
+                $rateType = (string)$ratedShipmentDetail->ShipmentRateDetail->RateType;
+                $rateTypeAmounts[$rateType] = $netAmount;
+            }
+
+            // Order is important
+            foreach (array('RATED_ACCOUNT_SHIPMENT', 'RATED_LIST_SHIPMENT', 'RATED_LIST_PACKAGE') as $rateType) {
+                if (!empty($rateTypeAmounts[$rateType])) {
+                    $amount = $rateTypeAmounts[$rateType];
+                    break;
                 }
             }
+
             if (is_null($amount)) {
-                $amount = (string)$rate->RatedShipmentDetails[0]->ShipmentRateDetail
-                    ->TotalNetCharge->Amount;
+                $amount = (string)$rate->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount;
             }
         }
+
         return $amount;
     }
 
@@ -532,7 +608,7 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex
 
         if ($this->getConfigData('residence_delivery')) {
             $specialServices = $xml->addChild('SpecialServices');
-                 $specialServices->addChild('ResidentialDelivery', 'true');
+            $specialServices->addChild('ResidentialDelivery', 'true');
         }
 
         $xml->addChild('PackageCount', '1');
@@ -613,7 +689,6 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex
         }
 
         $result = Mage::getModel('Mage_Shipping_Model_Rate_Result');
-        $defaults = $this->getDefaults();
         if (empty($priceArr)) {
             $error = Mage::getModel('Mage_Shipping_Model_Rate_Result_Error');
             $error->setCarrier('fedex');
@@ -670,6 +745,7 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex
                 'FEDEX_1_DAY_FREIGHT'                 => Mage::helper('Mage_Usa_Helper_Data')->__('1 Day Freight'),
                 'FEDEX_2_DAY_FREIGHT'                 => Mage::helper('Mage_Usa_Helper_Data')->__('2 Day Freight'),
                 'FEDEX_2_DAY'                         => Mage::helper('Mage_Usa_Helper_Data')->__('2 Day'),
+                'FEDEX_2_DAY_AM'                      => Mage::helper('Mage_Usa_Helper_Data')->__('2 Day AM'),
                 'FEDEX_3_DAY_FREIGHT'                 => Mage::helper('Mage_Usa_Helper_Data')->__('3 Day Freight'),
                 'FEDEX_EXPRESS_SAVER'                 => Mage::helper('Mage_Usa_Helper_Data')->__('Express Saver'),
                 'FEDEX_GROUND'                        => Mage::helper('Mage_Usa_Helper_Data')->__('Ground'),
@@ -711,6 +787,7 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex
                             'method' => array(
                                 'FEDEX_EXPRESS_SAVER',
                                 'FEDEX_2_DAY',
+                                'FEDEX_2_DAY_AM',
                                 'STANDARD_OVERNIGHT',
                                 'PRIORITY_OVERNIGHT',
                                 'FIRST_OVERNIGHT',
@@ -731,6 +808,7 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex
                         'within_us' => array(
                             'method' => array(
                                 'FEDEX_2_DAY',
+                                'FEDEX_2_DAY_AM',
                                 'STANDARD_OVERNIGHT',
                                 'PRIORITY_OVERNIGHT',
                                 'FIRST_OVERNIGHT',
@@ -767,6 +845,7 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex
                                 'SMART_POST',
                                 'FEDEX_EXPRESS_SAVER',
                                 'FEDEX_2_DAY',
+                                'FEDEX_2_DAY_AM',
                                 'STANDARD_OVERNIGHT',
                                 'PRIORITY_OVERNIGHT',
                                 'FIRST_OVERNIGHT',
@@ -806,7 +885,7 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex
 
         if (!isset($codes[$type])) {
             return false;
-        } elseif (''===$code) {
+        } elseif ('' === $code) {
             return $codes[$type];
         }
 
@@ -1023,11 +1102,11 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex
             }
         }
 
-        if(!$this->_result){
+        if (!$this->_result) {
             $this->_result = Mage::getModel('Mage_Shipping_Model_Tracking_Result');
         }
 
-        if(isset($resultArray)) {
+        if (isset($resultArray)) {
             $tracking = Mage::getModel('Mage_Shipping_Model_Tracking_Result_Status');
             $tracking->setCarrier('fedex');
             $tracking->setCarrierTitle($this->getConfigData('title'));
@@ -1052,14 +1131,14 @@ class Mage_Usa_Model_Shipping_Carrier_Fedex
     public function getResponse()
     {
         $statuses = '';
-        if ($this->_result instanceof Mage_Shipping_Model_Tracking_Result){
+        if ($this->_result instanceof Mage_Shipping_Model_Tracking_Result) {
             if ($trackings = $this->_result->getAllTrackings()) {
                 foreach ($trackings as $tracking){
                     if($data = $tracking->getAllData()){
                         if (!empty($data['status'])) {
-                            $statuses .= Mage::helper('Mage_Usa_Helper_Data')->__($data['status'])."\n<br/>";
+                            $statuses .= Mage::helper('Mage_Usa_Helper_Data')->__($data['status']) . "\n<br/>";
                         } else {
-                            $statuses .= Mage::helper('Mage_Usa_Helper_Data')->__('Empty response')."\n<br/>";
+                            $statuses .= Mage::helper('Mage_Usa_Helper_Data')->__('Empty response') . "\n<br/>";
                         }
                     }
                 }
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex/Source/Dropoff.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex/Source/Dropoff.php
index 7ee4c376b39de89fd11c29853f826ed4d5823e02..9c244749243026fa67915b528d92799c6dd33167 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex/Source/Dropoff.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex/Source/Dropoff.php
@@ -24,15 +24,21 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
+/**
+ * Fedex dropoff source implementation
+ *
+ * @category   Mage
+ * @package    Mage_Usa
+ * @author     Magento Core Team <core@magentocommerce.com>
+ */
 class Mage_Usa_Model_Shipping_Carrier_Fedex_Source_Dropoff
 {
     public function toOptionArray()
     {
         $fedex = Mage::getSingleton('Mage_Usa_Model_Shipping_Carrier_Fedex');
         $arr = array();
-        foreach ($fedex->getCode('dropoff') as $k=>$v) {
-            $arr[] = array('value'=>$k, 'label'=>$v);
+        foreach ($fedex->getCode('dropoff') as $k => $v) {
+            $arr[] = array('value' => $k, 'label' => $v);
         }
         return $arr;
     }
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex/Source/Freemethod.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex/Source/Freemethod.php
index 6860c22205b13a126d5aad2eef3d78e60a1139ad..d057f2c446ff4c5212825e7e574523961e54cb68 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex/Source/Freemethod.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex/Source/Freemethod.php
@@ -24,13 +24,20 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
-class Mage_Usa_Model_Shipping_Carrier_Fedex_Source_Freemethod extends Mage_Usa_Model_Shipping_Carrier_Fedex_Source_Method
+/**
+ * Fedex freemethod source implementation
+ *
+ * @category   Mage
+ * @package    Mage_Usa
+ * @author     Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_Usa_Model_Shipping_Carrier_Fedex_Source_Freemethod
+    extends Mage_Usa_Model_Shipping_Carrier_Fedex_Source_Method
 {
     public function toOptionArray()
     {
         $arr = parent::toOptionArray();
-        array_unshift($arr, array('value'=>'', 'label'=>Mage::helper('Mage_Shipping_Helper_Data')->__('None')));
+        array_unshift($arr, array('value' => '', 'label' => Mage::helper('Mage_Shipping_Helper_Data')->__('None')));
         return $arr;
     }
 }
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex/Source/Method.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex/Source/Method.php
index 4ca22b6f0bbf222d809c91db30989d651b517e24..2ebeff9cf39f1b3e9c54fd5a074ee8f5e563c424 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex/Source/Method.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex/Source/Method.php
@@ -24,15 +24,21 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
+/**
+ * Fedex method source implementation
+ *
+ * @category   Mage
+ * @package    Mage_Usa
+ * @author     Magento Core Team <core@magentocommerce.com>
+ */
 class Mage_Usa_Model_Shipping_Carrier_Fedex_Source_Method
 {
     public function toOptionArray()
     {
         $fedex = Mage::getSingleton('Mage_Usa_Model_Shipping_Carrier_Fedex');
         $arr = array();
-        foreach ($fedex->getCode('method') as $k=>$v) {
-            $arr[] = array('value'=>$k, 'label'=>$v);
+        foreach ($fedex->getCode('method') as $k => $v) {
+            $arr[] = array('value' => $k, 'label' => $v);
         }
         return $arr;
     }
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex/Source/Packaging.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex/Source/Packaging.php
index b672460f725f0db9c58cf669c8a8f259830e3e77..cdd719f7612153ec42fe491bf2db4e04b54ea19b 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex/Source/Packaging.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex/Source/Packaging.php
@@ -24,15 +24,21 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
+/**
+ * Fedex packaging source implementation
+ *
+ * @category   Mage
+ * @package    Mage_Usa
+ * @author     Magento Core Team <core@magentocommerce.com>
+ */
 class Mage_Usa_Model_Shipping_Carrier_Fedex_Source_Packaging
 {
     public function toOptionArray()
     {
         $fedex = Mage::getSingleton('Mage_Usa_Model_Shipping_Carrier_Fedex');
         $arr = array();
-        foreach ($fedex->getCode('packaging') as $k=>$v) {
-            $arr[] = array('value'=>$k, 'label'=>$v);
+        foreach ($fedex->getCode('packaging') as $k => $v) {
+            $arr[] = array('value' => $k, 'label' => $v);
         }
         return $arr;
     }
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups.php
index 9f24786511af14609af2f20a3bf4c49750e36dd8..5514d3832877e76067336360e25fce4da8be9984 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups.php
@@ -1806,38 +1806,4 @@ XMLAuth;
 
         return self::DELIVERY_CONFIRMATION_SHIPMENT;
     }
-
-    /**
-     * Return items for further shipment rate evaluation. We need to pass children of a bundle instead passing the
-     * bundle itself, otherwise we may not get a rate at all (e.g. when total weight of a bundle exceeds max weight
-     * despite each item by itself is not)
-     *
-     * @param Mage_Shipping_Model_Rate_Request $request
-     * @return array
-     */
-    public function getAllItems(Mage_Shipping_Model_Rate_Request $request)
-    {
-        $items = array();
-        if ($request->getAllItems()) {
-            foreach ($request->getAllItems() as $item) {
-                /* @var $item Mage_Sales_Model_Quote_Item */
-                if ($item->getProduct()->isVirtual() || $item->getParentItem()) {
-                    // Don't process children here - we will process (or already have processed) them below
-                    continue;
-                }
-
-                if ($item->getHasChildren() && $item->isShipSeparately()) {
-                    foreach ($item->getChildren() as $child) {
-                        if (!$child->getFreeShipping() && !$child->getProduct()->isVirtual()) {
-                            $items[] = $child;
-                        }
-                    }
-                } else {
-                    // Ship together - count compound item as one solid
-                    $items[] = $item;
-                }
-            }
-        }
-        return $items;
-    }
 }
diff --git a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Usps.php b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Usps.php
index 0c81e47668ed879dc72ffbd3d477b4d6419d9569..aaaa22268ed4163a5d91ea3a2098ee551632c187 100644
--- a/app/code/core/Mage/Usa/Model/Shipping/Carrier/Usps.php
+++ b/app/code/core/Mage/Usa/Model/Shipping/Carrier/Usps.php
@@ -53,7 +53,7 @@ class Mage_Usa_Model_Shipping_Carrier_Usps
     const SIZE_LARGE   = 'LARGE';
 
     /**
-     * Destination Zip Code required flag
+     * Default api revision
      *
      * @var int
      */
@@ -79,9 +79,10 @@ class Mage_Usa_Model_Shipping_Carrier_Usps
     protected $_code = self::CODE;
 
     /**
-     * Is zip code required
+     * Destination Zip Code required flag
      *
-     * @var bool
+     * @var boolean
+     * @deprecated since 1.7.0 functionality implemented in Mage_Usa_Model_Shipping_Carrier_Abstract
      */
     protected $_isZipCodeRequired;
 
@@ -120,34 +121,6 @@ class Mage_Usa_Model_Shipping_Carrier_Usps
      */
     protected $_customizableContainerTypes = array('VARIABLE', 'RECTANGULAR', 'NONRECTANGULAR');
 
-    /**
-     * Check is Zip Code Required
-     *
-     * @return boolean
-     */
-    public function isZipCodeRequired()
-    {
-        if (!is_null($this->_isZipCodeRequired)) {
-            return $this->_isZipCodeRequired;
-        }
-
-        return parent::isZipCodeRequired();
-    }
-
-    /**
-     * Processing additional validation to check is carrier applicable.
-     *
-     * @param Mage_Shipping_Model_Rate_Request $request
-     * @return Mage_Shipping_Model_Carrier_Abstract|Mage_Shipping_Model_Rate_Result_Error|boolean
-     */
-    public function proccessAdditionalValidation(Mage_Shipping_Model_Rate_Request $request)
-    {
-        // zip code required for US
-        $this->_isZipCodeRequired = $this->_isUSCountry($request->getDestCountryId());
-
-        return parent::proccessAdditionalValidation($request);
-    }
-
     /**
      * Collect and get rates
      *
@@ -581,6 +554,7 @@ class Mage_Usa_Model_Shipping_Carrier_Usps
                 'First-Class Mail International Large Envelope' => 'FIRST CLASS',
                 'First-Class Mail International Letter'         => 'FIRST CLASS',
                 'First-Class Mail International Package'        => 'FIRST CLASS',
+                'First-Class Mail International Parcel'         => 'FIRST CLASS',
                 'First-Class Mail'                 => 'FIRST CLASS',
                 'First-Class Mail Flat'            => 'FIRST CLASS',
                 'First-Class Mail Large Envelope'  => 'FIRST CLASS',
@@ -1327,7 +1301,11 @@ class Mage_Usa_Model_Shipping_Carrier_Usps
         list($fromZip5, $fromZip4) = $this->_parseZip($request->getShipperAddressPostalCode());
         list($toZip5, $toZip4) = $this->_parseZip($request->getRecipientAddressPostalCode(), true);
 
-        $rootNode = 'SigConfirmCertifyV3.0Request';
+        if ($this->getConfigData('mode')) {
+            $rootNode = 'SignatureConfirmationV3.0Request';
+        } else {
+            $rootNode = 'SigConfirmCertifyV3.0Request';
+        }
         // the wrap node needs for remove xml declaration above
         $xmlWrap = new SimpleXMLElement('<?xml version = "1.0" encoding = "UTF-8"?><wrap/>');
         $xml = $xmlWrap->addChild($rootNode);
@@ -1628,7 +1606,11 @@ class Mage_Usa_Model_Shipping_Carrier_Usps
             $api = 'ExpressMailLabel';
         } else if ($recipientUSCountry) {
             $requestXml = $this->_formUsSignatureConfirmationShipmentRequest($request, $service);
-            $api = 'SignatureConfirmationCertifyV3';
+            if ($this->getConfigData('mode')) {
+                $api = 'SignatureConfirmationV3';
+            } else {
+                $api = 'SignatureConfirmationCertifyV3';
+            }
         } else if ($service == 'FIRST CLASS') {
             $requestXml = $this->_formIntlShipmentRequest($request);
             $api = 'FirstClassMailIntl';
diff --git a/app/code/core/Mage/Usa/etc/config.xml b/app/code/core/Mage/Usa/etc/config.xml
index 06d27ed54206efec5995516595160c507a4a4037..aafb8a7cb934b441d5fc4ccf48ba503099923262 100644
--- a/app/code/core/Mage/Usa/etc/config.xml
+++ b/app/code/core/Mage/Usa/etc/config.xml
@@ -93,7 +93,7 @@
                 <account/>
                 <active>0</active>
                 <sallowspecific>0</sallowspecific>
-                <allowed_methods>E,N,S,G,IE,E SAT,E 10:30AM</allowed_methods>
+                <allowed_methods>IE,E SAT,E 10:30AM,E,N,S,G</allowed_methods>
                 <contentdesc>Big Box</contentdesc>
                 <cutoff_cost/>
                 <dutypaymenttype>R</dutypaymenttype>
@@ -102,6 +102,7 @@
                 <id backend_model="Mage_Adminhtml_Model_System_Config_Backend_Encrypted"/>
                 <model>Mage_Usa_Model_Shipping_Carrier_Dhl</model>
                 <password backend_model="Mage_Adminhtml_Model_System_Config_Backend_Encrypted"/>
+                <shipment_requesttype>0</shipment_requesttype>
                 <shipment_type>P</shipment_type>
                 <shipping_key backend_model="Mage_Adminhtml_Model_System_Config_Backend_Encrypted"/>
                 <shipping_intlkey backend_model="Mage_Adminhtml_Model_System_Config_Backend_Encrypted"/>
@@ -120,9 +121,10 @@
                 <key backend_model="Mage_Adminhtml_Model_System_Config_Backend_Encrypted"/>
                 <password backend_model="Mage_Adminhtml_Model_System_Config_Backend_Encrypted"/>
                 <sandbox_mode>0</sandbox_mode>
+                <shipment_requesttype>0</shipment_requesttype>
                 <active>0</active>
                 <sallowspecific>0</sallowspecific>
-                <allowed_methods>EUROPE_FIRST_INTERNATIONAL_PRIORITY,FEDEX_1_DAY_FREIGHT,FEDEX_2_DAY_FREIGHT,FEDEX_2_DAY,FEDEX_3_DAY_FREIGHT,FEDEX_EXPRESS_SAVER,FEDEX_GROUND,FIRST_OVERNIGHT,GROUND_HOME_DELIVERY,INTERNATIONAL_ECONOMY,INTERNATIONAL_ECONOMY_FREIGHT,INTERNATIONAL_FIRST,INTERNATIONAL_GROUNDINTERNATIONAL_PRIORITY,INTERNATIONAL_PRIORITY_FREIGHT,PRIORITY_OVERNIGHT,SMART_POSTSTANDARD_OVERNIGHT</allowed_methods>
+                <allowed_methods>EUROPE_FIRST_INTERNATIONAL_PRIORITY,FEDEX_1_DAY_FREIGHT,FEDEX_2_DAY_FREIGHT,FEDEX_2_DAY,FEDEX_2_DAY_AM,FEDEX_3_DAY_FREIGHT,FEDEX_EXPRESS_SAVER,FEDEX_GROUND,FIRST_OVERNIGHT,GROUND_HOME_DELIVERY,INTERNATIONAL_ECONOMY,INTERNATIONAL_ECONOMY_FREIGHT,INTERNATIONAL_FIRST,INTERNATIONAL_GROUND,INTERNATIONAL_PRIORITY,INTERNATIONAL_PRIORITY_FREIGHT,PRIORITY_OVERNIGHT,SMART_POST,STANDARD_OVERNIGHT,FEDEX_FREIGHT,FEDEX_NATIONAL_FREIGHT</allowed_methods>
                 <cutoff_cost/>
                 <dropoff>REGULAR_PICKUP</dropoff>
                 <free_method>FEDEX_GROUND</free_method>
@@ -139,8 +141,9 @@
                 <access_license_number backend_model="Mage_Adminhtml_Model_System_Config_Backend_Encrypted"/>
                 <active>0</active>
                 <sallowspecific>0</sallowspecific>
-                <allowed_methods>1DM,1DML,1DA,1DAL,1DAPI,1DP,1DPL,2DM,2DML,2DA,2DAL,3DS,GND,GNDCOM,GNDRES,STD,XPR,WXS,XPRL,XDM,XDML,XPD</allowed_methods>
+                <allowed_methods>1DM,1DML,1DA,1DAL,1DAPI,1DP,1DPL,2DM,2DML,2DA,2DAL,3DS,GND,GNDCOM,GNDRES,STD,XPR,WXS,XPRL,XDM,XDML,XPD,01,02,03,07,08,11,12,14,54,59,65</allowed_methods>
                 <origin_shipment>Shipments Originating in United States</origin_shipment>
+                <shipment_requesttype>0</shipment_requesttype>
                 <container>CP</container>
                 <cutoff_cost/>
                 <dest_type>RES</dest_type>
@@ -167,20 +170,22 @@
             <usps>
                 <active>0</active>
                 <sallowspecific>0</sallowspecific>
-                <allowed_methods>Bound Printed Matter,Express Mail,Express Mail Flat Rate Envelope,Express Mail Flat Rate Envelope Hold For Pickup,Express Mail Flat-Rate Envelope Sunday/Holiday Guarantee,Express Mail Hold For Pickup,Express Mail International,Express Mail International Flat Rate Envelope,Express Mail PO to PO,Express Mail Sunday/Holiday Guarantee,First-Class Mail International Large Envelope,First-Class Mail International Letters,First-Class Mail International Package,First-Class,First-Class Mail,First-Class Mail Flat,First-Class Mail Large Envelope,First-Class Mail International,First-Class Mail Letter,First-Class Mail Parcel,First-Class Mail Package,Global Express Guaranteed (GXG),Global Express Guaranteed Non-Document Non-Rectangular,Global Express Guaranteed Non-Document Rectangular,Library Mail,Media Mail,Parcel Post,Priority Mail,Priority Mail Small Flat Rate Box,Priority Mail Medium Flat Rate Box,Priority Mail Large Flat Rate Box,Priority Mail Flat Rate Box,Priority Mail Flat Rate Envelope,Priority Mail International,Priority Mail International Flat Rate Box,Priority Mail International Flat Rate Envelope,Priority Mail International Small Flat Rate Box,Priority Mail International Medium Flat Rate Box,Priority Mail International Large Flat Rate Box,USPS GXG Envelopes</allowed_methods>
+                <allowed_methods>Bound Printed Matter,Express Mail,Express Mail Flat Rate Envelope,Express Mail Flat Rate Envelope Hold For Pickup,Express Mail Flat-Rate Envelope Sunday/Holiday Guarantee,Express Mail Hold For Pickup,Express Mail International,Express Mail International Flat Rate Envelope,Express Mail PO to PO,Express Mail Sunday/Holiday Guarantee,First-Class Mail International Large Envelope,First-Class Mail International Letters,First-Class Mail International Package,First-Class Mail International Parcel,First-Class,First-Class Mail,First-Class Mail Flat,First-Class Mail Large Envelope,First-Class Mail International,First-Class Mail Letter,First-Class Mail Parcel,First-Class Mail Package,Global Express Guaranteed (GXG),Global Express Guaranteed Non-Document Non-Rectangular,Global Express Guaranteed Non-Document Rectangular,Library Mail,Media Mail,Parcel Post,Priority Mail,Priority Mail Small Flat Rate Box,Priority Mail Medium Flat Rate Box,Priority Mail Large Flat Rate Box,Priority Mail Flat Rate Box,Priority Mail Flat Rate Envelope,Priority Mail International,Priority Mail International Flat Rate Box,Priority Mail International Flat Rate Envelope,Priority Mail International Small Flat Rate Box,Priority Mail International Medium Flat Rate Box,Priority Mail International Large Flat Rate Box,USPS GXG Envelopes</allowed_methods>
                 <container>VARIABLE</container>
                 <cutoff_cost/>
                 <free_method/>
                 <gateway_url>http://production.shippingapis.com/ShippingAPI.dll</gateway_url>
                 <gateway_secure_url>https://secure.shippingapis.com/ShippingAPI.dll</gateway_secure_url>
+                <shipment_requesttype>0</shipment_requesttype>
                 <handling/>
                 <machinable>true</machinable>
-                <methods>Bound Printed Matter,Express Mail,Express Mail Flat Rate Envelope,Express Mail Flat Rate Envelope Hold For Pickup,Express Mail Flat-Rate Envelope Sunday/Holiday Guarantee,Express Mail Hold For Pickup,Express Mail International,Express Mail International Flat Rate Envelope,Express Mail PO to PO,Express Mail Sunday/Holiday Guarantee,First-Class Mail International Large Envelope,First-Class Mail International Letters,First-Class Mail International Package,First-Class,First-Class Mail,First-Class Mail Flat,First-Class Mail Large Envelope,First-Class Mail International,First-Class Mail Letter,First-Class Mail Parcel,First-Class Mail Package,Global Express Guaranteed (GXG),Global Express Guaranteed Non-Document Non-Rectangular,Global Express Guaranteed Non-Document Rectangular,Library Mail,Media Mail,Parcel Post,Priority Mail,Priority Mail Small Flat Rate Box,Priority Mail Medium Flat Rate Box,Priority Mail Large Flat Rate Box,Priority Mail Flat Rate Box,Priority Mail Flat Rate Envelope,Priority Mail International,Priority Mail International Flat Rate Box,Priority Mail International Flat Rate Envelope,Priority Mail International Small Flat Rate Box,Priority Mail International Medium Flat Rate Box,Priority Mail International Large Flat Rate Box,USPS GXG Envelopes</methods>
+                <methods>Bound Printed Matter,Express Mail,Express Mail Flat Rate Envelope,Express Mail Flat Rate Envelope Hold For Pickup,Express Mail Flat-Rate Envelope Sunday/Holiday Guarantee,Express Mail Hold For Pickup,Express Mail International,Express Mail International Flat Rate Envelope,Express Mail PO to PO,Express Mail Sunday/Holiday Guarantee,First-Class Mail International Large Envelope,First-Class Mail International Letters,First-Class Mail International Package,First-Class Mail International Parcel,First-Class,First-Class Mail,First-Class Mail Flat,First-Class Mail Large Envelope,First-Class Mail International,First-Class Mail Letter,First-Class Mail Parcel,First-Class Mail Package,Global Express Guaranteed (GXG),Global Express Guaranteed Non-Document Non-Rectangular,Global Express Guaranteed Non-Document Rectangular,Library Mail,Media Mail,Parcel Post,Priority Mail,Priority Mail Small Flat Rate Box,Priority Mail Medium Flat Rate Box,Priority Mail Large Flat Rate Box,Priority Mail Flat Rate Box,Priority Mail Flat Rate Envelope,Priority Mail International,Priority Mail International Flat Rate Box,Priority Mail International Flat Rate Envelope,Priority Mail International Small Flat Rate Box,Priority Mail International Medium Flat Rate Box,Priority Mail International Large Flat Rate Box,USPS GXG Envelopes</methods>
                 <model>Mage_Usa_Model_Shipping_Carrier_Usps</model>
                 <size>REGULAR</size>
                 <title>United States Postal Service</title>
                 <userid backend_model="Mage_Adminhtml_Model_System_Config_Backend_Encrypted"/>
                 <password backend_model="Mage_Adminhtml_Model_System_Config_Backend_Encrypted"/>
+                <isproduction>0</isproduction>
                 <specificerrmsg>This shipping method is currently unavailable. If you would like to ship using this shipping method, please contact us.</specificerrmsg>
                 <max_package_weight>70</max_package_weight>
                 <handling_type>F</handling_type>
@@ -192,7 +197,8 @@
                 <active>0</active>
                 <title>DHL</title>
                 <sallowspecific>0</sallowspecific>
-                <allowed_methods>1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y</allowed_methods>
+                <nondoc_methods>1,3,4,8,P,Q,E,F,H,J,M,V,Y</nondoc_methods>
+                <doc_methods>2,5,6,7,9,B,C,D,U,K,L,G,W,I,N,O,R,S,T,X</doc_methods>
                 <free_method>G</free_method>
                 <gateway_url>https://xmlpitest-ea.dhl.com/XMLShippingServlet</gateway_url>
                 <id backend_model="Mage_Adminhtml_Model_System_Config_Backend_Encrypted"/>
diff --git a/app/code/core/Mage/Usa/etc/system.xml b/app/code/core/Mage/Usa/etc/system.xml
index f68cf10c97fdf5e7bbfef46582ba0a3ca1c1a659..6bf96a9b119ce755f932db0006b0931675f94594 100644
--- a/app/code/core/Mage/Usa/etc/system.xml
+++ b/app/code/core/Mage/Usa/etc/system.xml
@@ -88,6 +88,7 @@
                         <free_shipping_subtotal translate="label">
                             <label>Minimum Order Amount for Free Shipping</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>1220</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -150,6 +151,7 @@
                         <handling_fee translate="label">
                             <label>Handling Fee</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>120</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -158,6 +160,7 @@
                         <max_package_weight translate="label">
                             <label>Maximum Package Weight (Please consult your shipping carrier for maximum supported shipping weight)</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>130</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -181,6 +184,15 @@
                             <show_in_website>1</show_in_website>
                             <show_in_store>0</show_in_store>
                         </password>
+                        <shipment_requesttype translate="label">
+                            <label>Packages Request Type</label>
+                            <frontend_type>select</frontend_type>
+                            <source_model>Mage_Usa_Model_Shipping_Carrier_Abstract_Source_Requesttype</source_model>
+                            <sort_order>85</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </shipment_requesttype>
                         <shipment_type translate="label">
                             <label>Shipment Type</label>
                             <frontend_type>select</frontend_type>
@@ -275,6 +287,7 @@
                         <additional_protection_min_value translate="label">
                             <label>Additional Protection Min Subtotal</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>1310</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -446,7 +459,16 @@
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
                             <show_in_store>0</show_in_store>
-                       </sandbox_mode>
+                        </sandbox_mode>
+                        <shipment_requesttype translate="label">
+                            <label>Packages Request Type</label>
+                            <frontend_type>select</frontend_type>
+                            <source_model>Mage_Usa_Model_Shipping_Carrier_Abstract_Source_Requesttype</source_model>
+                            <sort_order>77</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </shipment_requesttype>
                         <packaging translate="label">
                             <label>Packaging</label>
                             <frontend_type>select</frontend_type>
@@ -468,6 +490,7 @@
                         <max_package_weight translate="label">
                             <label>Maximum Package Weight (Please consult your shipping carrier for maximum supported shipping weight)</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>100</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -494,6 +517,7 @@
                         <handling_fee translate="label">
                             <label>Handling Fee</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>130</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -518,6 +542,15 @@
                             <show_in_store>0</show_in_store>
                             <can_be_empty>1</can_be_empty>
                         </allowed_methods>
+                        <smartpost_hubid translate="label comment">
+                            <label>Hub ID</label>
+                            <frontend_type>text</frontend_type>
+                            <sort_order>155</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                            <comment>The field is applicable if the Smart Post method is selected.</comment>
+                        </smartpost_hubid>
                         <free_method translate="label">
                             <label>Free Method</label>
                             <frontend_type>select</frontend_type>
@@ -540,6 +573,7 @@
                         <free_shipping_subtotal translate="label">
                             <label>Minimum Order Amount for Free Shipping</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>180</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -638,6 +672,15 @@
                             <show_in_store>0</show_in_store>
                             <can_be_empty>1</can_be_empty>
                         </allowed_methods>
+                        <shipment_requesttype translate="label">
+                            <label>Packages Request Type</label>
+                            <frontend_type>select</frontend_type>
+                            <source_model>Mage_Usa_Model_Shipping_Carrier_Abstract_Source_Requesttype</source_model>
+                            <sort_order>47</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </shipment_requesttype>
                         <container translate="label">
                             <label>Container</label>
                             <frontend_type>select</frontend_type>
@@ -659,6 +702,7 @@
                         <free_shipping_subtotal translate="label">
                             <label>Minimum Order Amount for Free Shipping</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>220</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -720,6 +764,7 @@
                         <handling_fee translate="label">
                             <label>Handling Fee</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>130</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -728,6 +773,7 @@
                         <max_package_weight translate="label">
                             <label>Maximum Package Weight (Please consult your shipping carrier for maximum supported shipping weight)</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>80</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -736,6 +782,7 @@
                         <min_package_weight translate="label">
                             <label>Minimum Package Weight (Please consult your shipping carrier for minimum supported shipping weight)</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>90</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -879,7 +926,7 @@
                             <label>Mode</label>
                             <comment>Enables/Disables SSL verification of Magento server by UPS.</comment>
                             <frontend_type>select</frontend_type>
-                            <source_model>Mage_Usa_Model_Shipping_Carrier_Ups_Source_Mode</source_model>
+                            <source_model>Mage_Usa_Model_Shipping_Carrier_Abstract_Source_Mode</source_model>
                             <sort_order>30</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -950,11 +997,29 @@
                             <label>Password</label>
                             <frontend_type>obscure</frontend_type>
                             <backend_model>Mage_Adminhtml_Model_System_Config_Backend_Encrypted</backend_model>
-                            <sort_order>54</sort_order>
+                            <sort_order>53</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
                             <show_in_store>0</show_in_store>
                         </password>
+                        <mode translate="label">
+                            <label>Mode</label>
+                            <frontend_type>select</frontend_type>
+                            <sort_order>54</sort_order>
+                            <source_model>Mage_Usa_Model_Shipping_Carrier_Abstract_Source_Mode</source_model>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </mode>
+                        <shipment_requesttype translate="label">
+                            <label>Packages Request Type</label>
+                            <frontend_type>select</frontend_type>
+                            <source_model>Mage_Usa_Model_Shipping_Carrier_Abstract_Source_Requesttype</source_model>
+                            <sort_order>55</sort_order>
+                            <show_in_default>1</show_in_default>
+                            <show_in_website>1</show_in_website>
+                            <show_in_store>0</show_in_store>
+                        </shipment_requesttype>
                         <container translate="label">
                             <label>Container</label>
                             <frontend_type>select</frontend_type>
@@ -1021,6 +1086,7 @@
                         <max_package_weight translate="label">
                             <label>Maximum Package Weight (Please consult your shipping carrier for maximum supported shipping weight)</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>90</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -1047,6 +1113,7 @@
                         <handling_fee translate="label">
                             <label>Handling Fee</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>120</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -1084,6 +1151,7 @@
                         <free_shipping_subtotal translate="label">
                             <label>Minimum Order Amount for Free Shipping</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>160</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -1236,6 +1304,7 @@
                         <handling_fee translate="label">
                             <label>Handling Fee</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>120</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
@@ -1372,6 +1441,7 @@
                         <free_shipping_subtotal translate="label">
                             <label>Minimum Order Amount for Free Shipping</label>
                             <frontend_type>text</frontend_type>
+                            <validate>validate-number validate-zero-or-greater</validate>
                             <sort_order>1220</sort_order>
                             <show_in_default>1</show_in_default>
                             <show_in_website>1</show_in_website>
diff --git a/app/code/core/Mage/Usa/etc/wsdl/FedEx/RateService_v10.wsdl b/app/code/core/Mage/Usa/etc/wsdl/FedEx/RateService_v10.wsdl
new file mode 100644
index 0000000000000000000000000000000000000000..d7e635a52547b054c0bf6c2343e8b925a4b3ae4b
--- /dev/null
+++ b/app/code/core/Mage/Usa/etc/wsdl/FedEx/RateService_v10.wsdl
@@ -0,0 +1,4870 @@
+<definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:ns="http://fedex.com/ws/rate/v10" xmlns:s1="http://schemas.xmlsoap.org/wsdl/soap/" targetNamespace="http://fedex.com/ws/rate/v10" name="RateServiceDefinitions">
+  <types>
+    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://fedex.com/ws/rate/v10">
+      <xs:element name="RateReply" type="ns:RateReply"/>
+      <xs:element name="RateRequest" type="ns:RateRequest"/>
+      <xs:complexType name="AdditionalLabelsDetail">
+        <xs:annotation>
+          <xs:documentation>Specifies additional labels to be produced. All required labels for shipments will be produced without the need to request additional labels. These are only available as thermal labels.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Type" type="ns:AdditionalLabelsType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The type of additional labels to return.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Count" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The number of this type label to return</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="AdditionalLabelsType">
+        <xs:annotation>
+          <xs:documentation>Identifies the type of additional labels.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BROKER"/>
+          <xs:enumeration value="CONSIGNEE"/>
+          <xs:enumeration value="CUSTOMS"/>
+          <xs:enumeration value="DESTINATION"/>
+          <xs:enumeration value="MANIFEST"/>
+          <xs:enumeration value="ORIGIN"/>
+          <xs:enumeration value="RECIPIENT"/>
+          <xs:enumeration value="SHIPPER"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Address">
+        <xs:annotation>
+          <xs:documentation>Descriptive data for a physical location. May be used as an actual physical address (place to which one could go), or as a container of "address parts" which should be handled as a unit (such as a city-state-ZIP combination within the US).</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="StreetLines" type="xs:string" minOccurs="0" maxOccurs="2">
+            <xs:annotation>
+              <xs:documentation>Combination of number, street name, etc. At least one line is required for a valid physical address; empty lines should not be included.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="City" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Name of city, town, etc.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="StateOrProvinceCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifying abbreviation for US state, Canada province, etc. Format and presence of this field will vary, depending on country.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PostalCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identification of a region (usually small) for mail/package delivery. Format and presence of this field will vary, depending on country.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="UrbanizationCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Relevant only to addresses in Puerto Rico.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CountryCode" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The two-letter code used to identify a country.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Residential" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates whether this address residential (as opposed to commercial).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="B13AFilingOptionType">
+        <xs:annotation>
+          <xs:documentation>
+            Specifies which filing option is being exercised by the customer.
+            Required for non-document shipments originating in Canada destined for any country other than Canada, the United States, Puerto Rico or the U.S. Virgin Islands.
+          </xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="FILED_ELECTRONICALLY"/>
+          <xs:enumeration value="MANUALLY_ATTACHED"/>
+          <xs:enumeration value="NOT_REQUIRED"/>
+          <xs:enumeration value="SUMMARY_REPORTING"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="BarcodeSymbologyType">
+        <xs:annotation>
+          <xs:documentation>Identification of the type of barcode (symbology) used on FedEx documents and labels.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CODABAR"/>
+          <xs:enumeration value="CODE128"/>
+          <xs:enumeration value="CODE128B"/>
+          <xs:enumeration value="CODE128C"/>
+          <xs:enumeration value="CODE39"/>
+          <xs:enumeration value="CODE93"/>
+          <xs:enumeration value="I2OF5"/>
+          <xs:enumeration value="MANUAL"/>
+          <xs:enumeration value="PDF417"/>
+          <xs:enumeration value="POSTNET"/>
+          <xs:enumeration value="UCC128"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="CarrierCodeType">
+        <xs:annotation>
+          <xs:documentation>Identification of a FedEx operating company (transportation).</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="FDXC"/>
+          <xs:enumeration value="FDXE"/>
+          <xs:enumeration value="FDXG"/>
+          <xs:enumeration value="FXCC"/>
+          <xs:enumeration value="FXFR"/>
+          <xs:enumeration value="FXSP"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="CertificateOfOriginDetail">
+        <xs:annotation>
+          <xs:documentation>The instructions indicating how to print the Certificate of Origin ( e.g. whether or not to include the instructions, image type, etc ...)</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="DocumentFormat" type="ns:ShippingDocumentFormat" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies characteristics of a shipping document to be produced.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomerImageUsages" type="ns:CustomerImageUsage" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies the usage and identification of customer supplied images to be used on this document.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="ChargeBasisLevelType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CURRENT_PACKAGE"/>
+          <xs:enumeration value="SUM_OF_PACKAGES"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="ClearanceBrokerageType">
+        <xs:annotation>
+          <xs:documentation>Specifies the type of brokerage to be applied to a shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BROKER_INCLUSIVE"/>
+          <xs:enumeration value="BROKER_INCLUSIVE_NON_RESIDENT_IMPORTER"/>
+          <xs:enumeration value="BROKER_SELECT"/>
+          <xs:enumeration value="BROKER_SELECT_NON_RESIDENT_IMPORTER"/>
+          <xs:enumeration value="BROKER_UNASSIGNED"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="ClientDetail">
+        <xs:annotation>
+          <xs:documentation>Descriptive data for the client submitting a transaction.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="AccountNumber" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The FedEx account number associated with this transaction.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="MeterNumber" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>This number is assigned by FedEx and identifies the unique device from which the request is originating</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="IntegratorId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Only used in transactions which require identification of the Fed Ex Office integrator.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Region" type="ns:ExpressRegionCode" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates the region from which the transaction is submitted.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Localization" type="ns:Localization" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The language to be used for human-readable Notification.localizedMessages in responses to the request containing this ClientDetail object. Different requests from the same client may contain different Localization data. (Contrast with TransactionDetail.localization, which governs data payload language/translation.)</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="CodAddTransportationChargeBasisType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="COD_SURCHARGE"/>
+          <xs:enumeration value="NET_CHARGE"/>
+          <xs:enumeration value="NET_FREIGHT"/>
+          <xs:enumeration value="TOTAL_CUSTOMER_CHARGE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="CodAddTransportationChargesDetail">
+        <xs:sequence>
+          <xs:element name="RateTypeBasis" type="ns:RateTypeBasisType" minOccurs="0"/>
+          <xs:element name="ChargeBasis" type="ns:CodAddTransportationChargeBasisType" minOccurs="0"/>
+          <xs:element name="ChargeBasisLevel" type="ns:ChargeBasisLevelType" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="CodCollectionType">
+        <xs:annotation>
+          <xs:documentation>Identifies the type of funds FedEx should collect upon shipment delivery.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ANY"/>
+          <xs:enumeration value="CASH"/>
+          <xs:enumeration value="GUARANTEED_FUNDS"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="CodDetail">
+        <xs:annotation>
+          <xs:documentation>Descriptive data required for a FedEx COD (Collect-On-Delivery) shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="CodCollectionAmount" type="ns:Money" minOccurs="0"/>
+          <xs:element name="AddTransportationChargesDetail" type="ns:CodAddTransportationChargesDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies the details of the charges are to be added to the COD collect amount.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CollectionType" type="ns:CodCollectionType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the type of funds FedEx should collect upon package delivery</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CodRecipient" type="ns:Party" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>For Express this is the descriptive data that is used for the recipient of the FedEx Letter containing the COD payment. For Ground this is the descriptive data for the party to receive the payment that prints the COD receipt.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ReferenceIndicator" type="ns:CodReturnReferenceIndicatorType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates which type of reference information to include on the COD return shipping label.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="CodReturnReferenceIndicatorType">
+        <xs:annotation>
+          <xs:documentation>Indicates which type of reference information to include on the COD return shipping label.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="INVOICE"/>
+          <xs:enumeration value="PO"/>
+          <xs:enumeration value="REFERENCE"/>
+          <xs:enumeration value="TRACKING"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="CommercialInvoice">
+        <xs:annotation>
+          <xs:documentation>CommercialInvoice element is required for electronic upload of CI data. It will serve to create/transmit an Electronic Commercial Invoice through the FedEx Systems. Customers are responsible for printing their own Commercial Invoice.If you would likeFedEx to generate a Commercial Invoice and transmit it to Customs. for clearance purposes, you need to specify that in the ShippingDocumentSpecification element. If you would like a copy of the Commercial Invoice that FedEx generated returned to you in reply it needs to be specified in the ETDDetail/RequestedDocumentCopies element. Commercial Invoice support consists of maximum of 99 commodity line items.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Comments" type="xs:string" minOccurs="0" maxOccurs="99">
+            <xs:annotation>
+              <xs:documentation>Any comments that need to be communicated about this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FreightCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Any freight charges that are associated with this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TaxesOrMiscellaneousCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Any taxes or miscellaneous charges(other than Freight charges or Insurance charges) that are associated with this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TaxesOrMiscellaneousChargeType" type="ns:TaxesOrMiscellaneousChargeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies which kind of charge is being recorded in the preceding field.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PackingCosts" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Any packing costs that are associated with this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="HandlingCosts" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Any handling costs that are associated with this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SpecialInstructions" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Free-form text.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DeclarationStatment" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Free-form text.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PaymentTerms" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Free-form text.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Purpose" type="ns:PurposeOfShipmentType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The reason for the shipment. Note: SOLD is not a valid purpose for a Proforma Invoice.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomerInvoiceNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Customer assigned Invoice number</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="OriginatorName" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Name of the International Expert that completed the Commercial Invoice different from Sender.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TermsOfSale" type="ns:TermsOfSaleType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Required for dutiable international Express or Ground shipment. This field is not applicable to an international PIB(document) or a non-document which does not require a Commercial Invoice</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CommercialInvoiceDetail">
+        <xs:annotation>
+          <xs:documentation>The instructions indicating how to print the Commercial Invoice( e.g. image type) Specifies characteristics of a shipping document to be produced.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Format" type="ns:ShippingDocumentFormat" minOccurs="0"/>
+          <xs:element name="CustomerImageUsages" type="ns:CustomerImageUsage" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies the usage and identification of a customer supplied image to be used on this document.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CommitDetail">
+        <xs:annotation>
+          <xs:documentation>Information about the transit time and delivery commitment date and time.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="CommodityName" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The Commodity applicable to this commitment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ServiceType" type="ns:ServiceType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The FedEx service type applicable to this commitment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AppliedOptions" type="ns:ServiceOptionType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Shows the specific combination of service options combined with the service type that produced this committment in the set returned to the caller.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AppliedSubOptions" type="ns:ServiceSubOptionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Supporting detail for applied options identified in preceding field.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CommitTimestamp" type="xs:dateTime" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>THe delivery commitment date/time. Express Only.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DayOfWeek" type="ns:DayOfWeekType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The delivery commitment day of the week.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TransitTime" type="ns:TransitTimeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The number of transit days; applies to Ground and LTL Freight; indicates minimum transit time for SmartPost.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="MaximumTransitTime" type="ns:TransitTimeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Maximum number of transit days, for SmartPost shipments.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DestinationServiceArea" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The service area code for the destination of this shipment. Express only.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BrokerAddress" type="ns:Address" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The address of the broker to be used for this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BrokerLocationId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The FedEx location identifier for the broker.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BrokerCommitTimestamp" type="xs:dateTime" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The delivery commitment date/time the shipment will arrive at the border.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BrokerCommitDayOfWeek" type="ns:DayOfWeekType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The delivery commitment day of the week the shipment will arrive at the border.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BrokerToDestinationDays" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The number of days it will take for the shipment to make it from broker to destination</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ProofOfDeliveryDate" type="xs:date" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The delivery commitment date for shipment served by GSP (Global Service Provider)</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ProofOfDeliveryDayOfWeek" type="ns:DayOfWeekType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The delivery commitment day of the week for the shipment served by GSP (Global Service Provider)</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CommitMessages" type="ns:Notification" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Messages concerning the ability to provide an accurate delivery commitment on an International commit quote. These could be messages providing information about why a commitment could not be returned or a successful message such as "REQUEST COMPLETED"</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DeliveryMessages" type="xs:string" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Messages concerning the delivery commitment on an International commit quote such as "0:00 A.M. IF NO CUSTOMS DELAY"</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DelayDetails" type="ns:DelayDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Information about why a shipment delivery is delayed and at what level (country/service etc.).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DocumentContent" type="ns:InternationalDocumentContentType" minOccurs="0"/>
+          <xs:element name="RequiredDocuments" type="ns:RequiredShippingDocumentType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Required documentation for this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FreightCommitDetail" type="ns:FreightCommitDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Freight origin and destination city center information and total distance between origin and destination city centers.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="CommitmentDelayType">
+        <xs:annotation>
+          <xs:documentation>The type of delay this shipment will encounter.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="HOLIDAY"/>
+          <xs:enumeration value="NON_WORKDAY"/>
+          <xs:enumeration value="NO_CITY_DELIVERY"/>
+          <xs:enumeration value="NO_HOLD_AT_LOCATION"/>
+          <xs:enumeration value="NO_LOCATION_DELIVERY"/>
+          <xs:enumeration value="NO_SERVICE_AREA_DELIVERY"/>
+          <xs:enumeration value="NO_SERVICE_AREA_SPECIAL_SERVICE_DELIVERY"/>
+          <xs:enumeration value="NO_SPECIAL_SERVICE_DELIVERY"/>
+          <xs:enumeration value="NO_ZIP_DELIVERY"/>
+          <xs:enumeration value="WEEKEND"/>
+          <xs:enumeration value="WEEKEND_SPECIAL"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Commodity">
+        <xs:annotation>
+          <xs:documentation>
+            For international multiple piece shipments, commodity information must be passed in the Master and on each child transaction.
+            If this shipment cotains more than four commodities line items, the four highest valued should be included in the first 4 occurances for this request.
+          </xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Name" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>total number of pieces of this commodity</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NumberOfPieces" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>total number of pieces of this commodity</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Description" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Complete and accurate description of this commodity.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>450</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CountryOfManufacture" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Country code where commodity contents were produced or manufactured in their final form.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>2</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="HarmonizedCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>
+                Unique alpha/numeric representing commodity item.
+                At least one occurrence is required for US Export shipments if the Customs Value is greater than $2500 or if a valid US Export license is required.
+              </xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>14</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Weight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Total weight of this commodity. 1 explicit decimal position. Max length 11 including decimal.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Quantity" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Number of units of a commodity in total number of pieces for this line item. Max length is 9</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="QuantityUnits" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Unit of measure used to express the quantity of this commodity line item.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>3</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AdditionalMeasures" type="ns:Measure" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Contains only additional quantitative information other than weight and quantity to calculate duties and taxes.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="UnitPrice" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Value of each unit in Quantity. Six explicit decimal positions, Max length 18 including decimal.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomsValue" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>
+                Total customs value for this line item.
+                It should equal the commodity unit quantity times commodity unit value.
+                Six explicit decimal positions, max length 18 including decimal.
+              </xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ExciseConditions" type="ns:EdtExciseCondition" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Defines additional characteristic of commodity used to calculate duties and taxes</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ExportLicenseNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Applicable to US export shipping only.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>12</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ExportLicenseExpirationDate" type="xs:date" minOccurs="0"/>
+          <xs:element name="CIMarksAndNumbers" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>
+                An identifying mark or number used on the packaging of a shipment to help customers identify a particular shipment.
+              </xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>15</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NaftaDetail" type="ns:NaftaCommodityDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>All data required for this commodity in NAFTA Certificate of Origin.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ConfigurableLabelReferenceEntry">
+        <xs:annotation>
+          <xs:documentation>Defines additional data to print in the Configurable portion of the label, this allows you to print the same type information on the label that can also be printed on the doc tab.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="ZoneNumber" type="xs:positiveInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>1 of 12 possible zones to  position data.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Header" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The identifiying text for the data in this zone.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DataField" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>A reference to a field in either the request or reply to print in this zone following the header.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LiteralValue" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>A literal value to print after the header in this zone.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="Contact">
+        <xs:annotation>
+          <xs:documentation>The descriptive data for a point-of-contact person.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="ContactId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Client provided identifier corresponding to this contact information.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PersonName" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the contact person's name.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Title" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the contact person's title.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CompanyName" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the company this contact is associated with.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PhoneNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the phone number associated with this contact.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PhoneExtension" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the phone extension associated with this contact.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PagerNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the pager number associated with this contact.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FaxNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the fax number associated with this contact.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EMailAddress" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the email address associated with this contact.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ContactAndAddress">
+        <xs:sequence>
+          <xs:element name="Contact" type="ns:Contact" minOccurs="0"/>
+          <xs:element name="Address" type="ns:Address" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ContentRecord">
+        <xs:sequence>
+          <xs:element name="PartNumber" type="xs:string" minOccurs="0"/>
+          <xs:element name="ItemNumber" type="xs:string" minOccurs="0"/>
+          <xs:element name="ReceivedQuantity" type="xs:nonNegativeInteger" minOccurs="0"/>
+          <xs:element name="Description" type="xs:string" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CurrencyExchangeRate">
+        <xs:annotation>
+          <xs:documentation>Specifies the currency exchange performed on financial amounts for this rate.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="FromCurrency" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The currency code for the original (converted FROM) currency.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="IntoCurrency" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The currency code for the final (converted INTO) currency.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Rate" type="xs:decimal" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Multiplier used to convert fromCurrency units to intoCurrency units.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CustomDeliveryWindowDetail">
+        <xs:sequence>
+          <xs:element name="Type" type="ns:CustomDeliveryWindowType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates the type of custom delivery being requested.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RequestTime" type="xs:time" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Time by which delivery is requested.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RequestRange" type="ns:DateRange" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Range of dates for custom delivery request; only used if type is BETWEEN.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RequestDate" type="xs:date" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Date for custom delivery request; only used for types of ON, BETWEEN, or AFTER.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="CustomDeliveryWindowType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="AFTER"/>
+          <xs:enumeration value="BEFORE"/>
+          <xs:enumeration value="BETWEEN"/>
+          <xs:enumeration value="ON"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="CustomDocumentDetail">
+        <xs:annotation>
+          <xs:documentation>Data required to produce a custom-specified document, either at shipment or package level.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Format" type="ns:ShippingDocumentFormat" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Common information controlling document production.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LabelPrintingOrientation" type="ns:LabelPrintingOrientationType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Applicable only to documents produced on thermal printers with roll stock.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LabelRotation" type="ns:LabelRotationType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Applicable only to documents produced on thermal printers with roll stock.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SpecificationId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the formatting specification used to construct this custom document.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CustomLabelBarcodeEntry">
+        <xs:annotation>
+          <xs:documentation>Constructed string, based on format and zero or more data fields, printed in specified barcode symbology.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Position" type="ns:CustomLabelPosition" minOccurs="0"/>
+          <xs:element name="Format" type="xs:string" minOccurs="0"/>
+          <xs:element name="DataFields" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="BarHeight" type="xs:int" minOccurs="0"/>
+          <xs:element name="ThinBarWidth" type="xs:int" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Width of thinnest bar/space element in the barcode.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BarcodeSymbology" type="ns:BarcodeSymbologyType" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CustomLabelBoxEntry">
+        <xs:annotation>
+          <xs:documentation>Solid (filled) rectangular area on label.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="TopLeftCorner" type="ns:CustomLabelPosition" minOccurs="1"/>
+          <xs:element name="BottomRightCorner" type="ns:CustomLabelPosition" minOccurs="1"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="CustomLabelCoordinateUnits">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="MILS"/>
+          <xs:enumeration value="PIXELS"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="CustomLabelDetail">
+        <xs:sequence>
+          <xs:element name="CoordinateUnits" type="ns:CustomLabelCoordinateUnits" minOccurs="0"/>
+          <xs:element name="TextEntries" type="ns:CustomLabelTextEntry" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="GraphicEntries" type="ns:CustomLabelGraphicEntry" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="BoxEntries" type="ns:CustomLabelBoxEntry" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="BarcodeEntries" type="ns:CustomLabelBarcodeEntry" minOccurs="0" maxOccurs="unbounded"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CustomLabelGraphicEntry">
+        <xs:annotation>
+          <xs:documentation>Image to be included from printer's memory, or from a local file for offline clients.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Position" type="ns:CustomLabelPosition" minOccurs="0"/>
+          <xs:element name="PrinterGraphicId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Printer-specific index of graphic image to be printed.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FileGraphicFullName" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Fully-qualified path and file name for graphic image to be printed.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CustomLabelPosition">
+        <xs:sequence>
+          <xs:element name="X" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Horizontal position, relative to left edge of custom area.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Y" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Vertical position, relative to top edge of custom area.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CustomLabelTextEntry">
+        <xs:annotation>
+          <xs:documentation>Constructed string, based on format and zero or more data fields, printed in specified printer font (for thermal labels) or generic font/size (for plain paper labels).</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Position" type="ns:CustomLabelPosition" minOccurs="0"/>
+          <xs:element name="Format" type="xs:string" minOccurs="0"/>
+          <xs:element name="DataFields" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="ThermalFontId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Printer-specific font name for use with thermal printer labels.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FontName" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Generic font name for use with plain paper labels.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FontSize" type="xs:positiveInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Generic font size for use with plain paper labels.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CustomerImageUsage">
+        <xs:sequence>
+          <xs:element name="Type" type="ns:CustomerImageUsageType" minOccurs="0"/>
+          <xs:element name="Id" type="ns:ImageId" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="CustomerImageUsageType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="LETTER_HEAD"/>
+          <xs:enumeration value="SIGNATURE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="CustomerReference">
+        <xs:annotation>
+          <xs:documentation>Reference information to be associated with this package.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="CustomerReferenceType" type="ns:CustomerReferenceType" minOccurs="1"/>
+          <xs:element name="Value" type="xs:string" minOccurs="1"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="CustomerReferenceType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BILL_OF_LADING"/>
+          <xs:enumeration value="CUSTOMER_REFERENCE"/>
+          <xs:enumeration value="DEPARTMENT_NUMBER"/>
+          <xs:enumeration value="ELECTRONIC_PRODUCT_CODE"/>
+          <xs:enumeration value="INTRACOUNTRY_REGULATORY_REFERENCE"/>
+          <xs:enumeration value="INVOICE_NUMBER"/>
+          <xs:enumeration value="PACKING_SLIP_NUMBER"/>
+          <xs:enumeration value="P_O_NUMBER"/>
+          <xs:enumeration value="SHIPMENT_INTEGRITY"/>
+          <xs:enumeration value="STORE_NUMBER"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="CustomerSpecifiedLabelDetail">
+        <xs:annotation>
+          <xs:documentation>Allows customer-specified control of label content.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="DocTabContent" type="ns:DocTabContent" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>If omitted, no doc tab will be produced (i.e. default = former NONE type).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomContent" type="ns:CustomLabelDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Defines any custom content to print on the label.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ConfigurableReferenceEntries" type="ns:ConfigurableLabelReferenceEntry" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Defines additional data to print in the Configurable portion of the label, this allows you to print the same type information on the label that can also be printed on the doc tab.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="MaskedData" type="ns:LabelMaskableDataType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Controls which data/sections will be suppressed.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SecondaryBarcode" type="ns:SecondaryBarcodeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>For customers producing their own Ground labels, this field specifies which secondary barcode will be printed on the label; so that the primary barcode produced by FedEx has the corect SCNC.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TermsAndConditionsLocalization" type="ns:Localization" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The language to use when printing the terms and conditions on the label.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AdditionalLabels" type="ns:AdditionalLabelsDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Controls the number of additional copies of supplemental labels.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AirWaybillSuppressionCount" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This value reduces the default quantity of destination/consignee air waybill labels. A value of zero indicates no change to default. A minimum of one copy will always be produced.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CustomsClearanceDetail">
+        <xs:sequence>
+          <xs:element name="Broker" type="ns:Party" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>
+                Descriptive data identifying the Broker responsible for the shipmet.
+                Required if BROKER_SELECT_OPTION is requested in Special Services.
+              </xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ClearanceBrokerage" type="ns:ClearanceBrokerageType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Interacts both with properties of the shipment and contractual relationship with the shipper.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ImporterOfRecord" type="ns:Party" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>
+                Applicable only for Commercial Invoice. If the consignee and importer are not the same, the Following importer fields are required.
+                Importer/Contact/PersonName
+                Importer/Contact/CompanyName
+                Importer/Contact/PhoneNumber
+                Importer/Address/StreetLine[0]
+                Importer/Address/City
+                Importer/Address/StateOrProvinceCode - if Importer Country Code is US or CA
+                Importer/Address/PostalCode - if Importer Country Code is US or CA
+                Importer/Address/CountryCode
+              </xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RecipientCustomsId" type="ns:RecipientCustomsId" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies how the recipient is identified for customs purposes; the requirements on this information vary with destination country.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DutiesPayment" type="ns:Payment" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates how payment of duties for the shipment will be made.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DocumentContent" type="ns:InternationalDocumentContentType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates whether this shipment contains documents only or non-documents.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomsValue" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The total customs value for the shipment. This total will rrepresent th esum of the values of all commodities, and may include freight, miscellaneous, and insurance charges. Must contain 2 explicit decimal positions with a max length of 17 including the decimal. For Express International MPS, the Total Customs Value is in the master transaction and all child transactions</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FreightOnValue" type="ns:FreightOnValueType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies responsibilities with respect to loss, damage, etc.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="InsuranceCharges" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Documents amount paid to third party for coverage of shipment content.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PartiesToTransactionAreRelated" type="xs:boolean" minOccurs="0"/>
+          <xs:element name="CommercialInvoice" type="ns:CommercialInvoice" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>CommercialInvoice element is required for electronic upload of CI data. It will serve to create/transmit an Electronic Commercial Invoice through FedEx System. Customers are responsible for printing their own Commercial Invoice. Commercial Invoice support consists of a maximum of 20 commodity line items.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Commodities" type="ns:Commodity" minOccurs="0" maxOccurs="99">
+            <xs:annotation>
+              <xs:documentation>
+                For international multiple piece shipments, commodity information must be passed in the Master and on each child transaction.
+                If this shipment cotains more than four commodities line items, the four highest valued should be included in the first 4 occurances for this request.
+              </xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ExportDetail" type="ns:ExportDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Country specific details of an International shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RegulatoryControls" type="ns:RegulatoryControlType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>FOOD_OR_PERISHABLE is required by FDA/BTA; must be true for food/perishable items coming to US or PR from non-US/non-PR origin.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="DangerousGoodsAccessibilityType">
+        <xs:annotation>
+          <xs:documentation>Identifies whether or not the products being shipped are required to be accessible during delivery.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ACCESSIBLE"/>
+          <xs:enumeration value="INACCESSIBLE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="DangerousGoodsDetail">
+        <xs:annotation>
+          <xs:documentation>The descriptive data required for a FedEx shipment containing dangerous goods (hazardous materials).</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Accessibility" type="ns:DangerousGoodsAccessibilityType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies whether or not the products being shipped are required to be accessible during delivery.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CargoAircraftOnly" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Shipment is packaged/documented for movement ONLY on cargo aircraft.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Options" type="ns:HazardousCommodityOptionType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Indicates which kinds of hazardous content are in the current package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="HazardousCommodities" type="ns:HazardousCommodityContent" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Documents the kinds and quantities of all hazardous commodities in the current package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Packaging" type="ns:HazardousCommodityPackagingDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Description of the packaging of this commodity, suitable for use on OP-900 and OP-950 forms.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EmergencyContactNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Telephone number to use for contact in the event of an emergency.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Offeror" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Offeror's name or contract number, per DOT regulation.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="DateRange">
+        <xs:sequence>
+          <xs:element name="Begins" type="xs:date" minOccurs="1"/>
+          <xs:element name="Ends" type="xs:date" minOccurs="1"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="DayOfWeekType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="FRI"/>
+          <xs:enumeration value="MON"/>
+          <xs:enumeration value="SAT"/>
+          <xs:enumeration value="SUN"/>
+          <xs:enumeration value="THU"/>
+          <xs:enumeration value="TUE"/>
+          <xs:enumeration value="WED"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="DelayDetail">
+        <xs:annotation>
+          <xs:documentation>Information about why a shipment delivery is delayed and at what level( country/service etc.).</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Date" type="xs:date" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The date of the delay</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DayOfWeek" type="ns:DayOfWeekType" minOccurs="0"/>
+          <xs:element name="Level" type="ns:DelayLevelType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The attribute of the shipment that caused the delay(e.g. Country, City, LocationId, Zip, service area, special handling )</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Point" type="ns:DelayPointType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The point where the delay is occurring (e.g. Origin, Destination, Broker location)</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Type" type="ns:CommitmentDelayType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The reason for the delay (e.g. holiday, weekend, etc.).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Description" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The name of the holiday in that country that is causing the delay.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="DelayLevelType">
+        <xs:annotation>
+          <xs:documentation>The attribute of the shipment that caused the delay(e.g. Country, City, LocationId, Zip, service area, special handling )</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CITY"/>
+          <xs:enumeration value="COUNTRY"/>
+          <xs:enumeration value="LOCATION"/>
+          <xs:enumeration value="POSTAL_CODE"/>
+          <xs:enumeration value="SERVICE_AREA"/>
+          <xs:enumeration value="SERVICE_AREA_SPECIAL_SERVICE"/>
+          <xs:enumeration value="SPECIAL_SERVICE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="DelayPointType">
+        <xs:annotation>
+          <xs:documentation>The point where the delay is occurring ( e.g. Origin, Destination, Broker location).</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BROKER"/>
+          <xs:enumeration value="DESTINATION"/>
+          <xs:enumeration value="ORIGIN"/>
+          <xs:enumeration value="ORIGIN_DESTINATION_PAIR"/>
+          <xs:enumeration value="PROOF_OF_DELIVERY_POINT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="DestinationControlDetail">
+        <xs:annotation>
+          <xs:documentation>Data required to complete the Destionation Control Statement for US exports.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="StatementTypes" type="ns:DestinationControlStatementType" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="DestinationCountries" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Comma-separated list of up to four country codes, required for DEPARTMENT_OF_STATE statement.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EndUser" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Name of end user, required for DEPARTMENT_OF_STATE statement.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="DestinationControlStatementType">
+        <xs:annotation>
+          <xs:documentation>Used to indicate whether the Destination Control Statement is of type Department of Commerce, Department of State or both.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="DEPARTMENT_OF_COMMERCE"/>
+          <xs:enumeration value="DEPARTMENT_OF_STATE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Dimensions">
+        <xs:annotation>
+          <xs:documentation>The dimensions of this package and the unit type used for the measurements.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Length" type="xs:nonNegativeInteger" minOccurs="1"/>
+          <xs:element name="Width" type="xs:nonNegativeInteger" minOccurs="1"/>
+          <xs:element name="Height" type="xs:nonNegativeInteger" minOccurs="1"/>
+          <xs:element name="Units" type="ns:LinearUnits" minOccurs="1"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="Distance">
+        <xs:annotation>
+          <xs:documentation>Driving or other transportation distances, distinct from dimension measurements.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Value" type="xs:decimal" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the distance quantity.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Units" type="ns:DistanceUnits" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the unit of measure for the distance value.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="DistanceUnits">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="KM"/>
+          <xs:enumeration value="MI"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="DocTabContent">
+        <xs:sequence>
+          <xs:element name="DocTabContentType" type="ns:DocTabContentType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The DocTabContentType options available.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Zone001" type="ns:DocTabContentZone001" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The DocTabContentType should be set to ZONE001 to specify additional Zone details.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Barcoded" type="ns:DocTabContentBarcoded" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The DocTabContentType should be set to BARCODED to specify additional BarCoded details.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="DocTabContentBarcoded">
+        <xs:sequence>
+          <xs:element name="Symbology" type="ns:BarcodeSymbologyType" minOccurs="0"/>
+          <xs:element name="Specification" type="ns:DocTabZoneSpecification" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="DocTabContentType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BARCODED"/>
+          <xs:enumeration value="MINIMUM"/>
+          <xs:enumeration value="STANDARD"/>
+          <xs:enumeration value="ZONE001"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="DocTabContentZone001">
+        <xs:sequence>
+          <xs:element name="DocTabZoneSpecifications" type="ns:DocTabZoneSpecification" minOccurs="1" maxOccurs="12"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="DocTabZoneJustificationType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="LEFT"/>
+          <xs:enumeration value="RIGHT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="DocTabZoneSpecification">
+        <xs:sequence>
+          <xs:element name="ZoneNumber" type="xs:positiveInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Zone number can be between 1 and 12.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Header" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Header value on this zone.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DataField" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Reference path to the element in the request/reply whose value should be printed on this zone.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LiteralValue" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Free form-text to be printed in this zone.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Justification" type="ns:DocTabZoneJustificationType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Justification for the text printed on this zone.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="DropoffType">
+        <xs:annotation>
+          <xs:documentation>Identifies the method by which the package is to be tendered to FedEx. This element does not dispatch a courier for package pickup.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BUSINESS_SERVICE_CENTER"/>
+          <xs:enumeration value="DROP_BOX"/>
+          <xs:enumeration value="REGULAR_PICKUP"/>
+          <xs:enumeration value="REQUEST_COURIER"/>
+          <xs:enumeration value="STATION"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="EMailLabelDetail">
+        <xs:annotation>
+          <xs:documentation>Specific information about the delivery of the email and options for the shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="NotificationEMailAddress" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Email address to send the URL to.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NotificationMessage" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>A message to be inserted into the email.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="EMailNotificationDetail">
+        <xs:annotation>
+          <xs:documentation>Information describing email notifications that will be sent in relation to events that occur during package movement</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="PersonalMessage" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>A message that will be included in the email notifications</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Recipients" type="ns:EMailNotificationRecipient" minOccurs="0" maxOccurs="6">
+            <xs:annotation>
+              <xs:documentation>Information describing the destination of the email, format of the email and events to be notified on</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="EMailNotificationEventType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ON_DELIVERY"/>
+          <xs:enumeration value="ON_EXCEPTION"/>
+          <xs:enumeration value="ON_SHIPMENT"/>
+          <xs:enumeration value="ON_TENDER"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="EMailNotificationFormatType">
+        <xs:annotation>
+          <xs:documentation>The format of the email</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="HTML"/>
+          <xs:enumeration value="TEXT"/>
+          <xs:enumeration value="WIRELESS"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="EMailNotificationRecipient">
+        <xs:annotation>
+          <xs:documentation>The descriptive data for a FedEx email notification recipient.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="EMailNotificationRecipientType" type="ns:EMailNotificationRecipientType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the relationship this email recipient has to the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EMailAddress" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The email address to send the notification to</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NotificationEventsRequested" type="ns:EMailNotificationEventType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>The types of email notifications being requested for this recipient.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Format" type="ns:EMailNotificationFormatType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The format of the email notification.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Localization" type="ns:Localization" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The language/locale to be used in this email notification.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="EMailNotificationRecipientType">
+        <xs:annotation>
+          <xs:documentation>Identifies the set of valid email notification recipient types. For SHIPPER, RECIPIENT and BROKER the email address asssociated with their definitions will be used, any email address sent with the email notification for these three email notification recipient types will be ignored.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BROKER"/>
+          <xs:enumeration value="OTHER"/>
+          <xs:enumeration value="RECIPIENT"/>
+          <xs:enumeration value="SHIPPER"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="EdtCommodityTax">
+        <xs:sequence>
+          <xs:element name="HarmonizedCode" type="xs:string" minOccurs="0"/>
+          <xs:element name="Taxes" type="ns:EdtTaxDetail" minOccurs="0" maxOccurs="unbounded"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="EdtExciseCondition">
+        <xs:sequence>
+          <xs:element name="Category" type="xs:string" minOccurs="0"/>
+          <xs:element name="Value" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Customer-declared value, with data type and legal values depending on excise condition, used in defining the taxable value of the item.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="EdtRequestType">
+        <xs:annotation>
+          <xs:documentation>Specifies the types of Estimated Duties and Taxes to be included in a rate quotation for an international shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ALL"/>
+          <xs:enumeration value="NONE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="EdtTaxDetail">
+        <xs:sequence>
+          <xs:element name="TaxType" type="ns:EdtTaxType" minOccurs="0"/>
+          <xs:element name="EffectiveDate" type="xs:date" minOccurs="0"/>
+          <xs:element name="Name" type="xs:string" minOccurs="0"/>
+          <xs:element name="TaxableValue" type="ns:Money" minOccurs="0"/>
+          <xs:element name="Description" type="xs:string" minOccurs="0"/>
+          <xs:element name="Formula" type="xs:string" minOccurs="0"/>
+          <xs:element name="Amount" type="ns:Money" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="EdtTaxType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ADDITIONAL_TAXES"/>
+          <xs:enumeration value="CONSULAR_INVOICE_FEE"/>
+          <xs:enumeration value="CUSTOMS_SURCHARGES"/>
+          <xs:enumeration value="DUTY"/>
+          <xs:enumeration value="EXCISE_TAX"/>
+          <xs:enumeration value="FOREIGN_EXCHANGE_TAX"/>
+          <xs:enumeration value="GENERAL_SALES_TAX"/>
+          <xs:enumeration value="IMPORT_LICENSE_FEE"/>
+          <xs:enumeration value="INTERNAL_ADDITIONAL_TAXES"/>
+          <xs:enumeration value="INTERNAL_SENSITIVE_PRODUCTS_TAX"/>
+          <xs:enumeration value="OTHER"/>
+          <xs:enumeration value="SENSITIVE_PRODUCTS_TAX"/>
+          <xs:enumeration value="STAMP_TAX"/>
+          <xs:enumeration value="STATISTICAL_TAX"/>
+          <xs:enumeration value="TRANSPORT_FACILITIES_TAX"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="EtdDetail">
+        <xs:annotation>
+          <xs:documentation>Electronic Trade document references used with the ETD special service.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="RequestedDocumentCopies" type="ns:RequestedShippingDocumentType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Indicates the types of shipping documents produced for the shipper by FedEx (see ShippingDocumentSpecification) which should be copied back to the shipper in the shipment result data.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Documents" type="ns:UploadDocumentDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Currently not supported.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DocumentReferences" type="ns:UploadDocumentReferenceDetail" minOccurs="0" maxOccurs="unbounded"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ExportDetail">
+        <xs:annotation>
+          <xs:documentation>Country specific details of an International shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="B13AFilingOption" type="ns:B13AFilingOptionType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>
+                Specifies which filing option is being exercised by the customer.
+                Required for non-document shipments originating in Canada destined for any country other than Canada, the United States, Puerto Rico or the U.S. Virgin Islands.
+              </xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ExportComplianceStatement" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>General field for exporting-country-specific export data (e.g. B13A for CA, FTSR Exemption or AES Citation for US).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PermitNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This field is applicable only to Canada export non-document shipments of any value to any destination. No special characters allowed. </xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>10</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DestinationControlDetail" type="ns:DestinationControlDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Department of Commerce/Department of State information about this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ExpressFreightDetail">
+        <xs:annotation>
+          <xs:documentation>Details specific to an Express freight shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="PackingListEnclosed" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates whether or nor a packing list is enclosed.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ShippersLoadAndCount" type="xs:positiveInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>
+                Total shipment pieces.
+                ie. 3 boxes and 3 pallets of 100 pieces each = Shippers Load and Count of 303.
+                Applicable to International Priority Freight and International Economy Freight.
+                Values must be in the range of 1 - 99999
+              </xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BookingConfirmationNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Required for International Freight shipping. Values must be 8- 12 characters in length.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>12</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ReferenceLabelRequested" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Currently not supported.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BeforeDeliveryContact" type="ns:ExpressFreightDetailContact" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Currently not supported.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="UndeliverableContact" type="ns:ExpressFreightDetailContact" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Currently not supported.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ExpressFreightDetailContact">
+        <xs:annotation>
+          <xs:documentation>Currently not supported. Delivery contact information for an Express freight shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Name" type="xs:string" minOccurs="0"/>
+          <xs:element name="Phone" type="xs:string" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="ExpressRegionCode">
+        <xs:annotation>
+          <xs:documentation>Indicates a FedEx Express operating region.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="APAC"/>
+          <xs:enumeration value="CA"/>
+          <xs:enumeration value="EMEA"/>
+          <xs:enumeration value="LAC"/>
+          <xs:enumeration value="US"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="FedExLocationType">
+        <xs:annotation>
+          <xs:documentation>Identifies a kind of FedEx facility.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="FEDEX_EXPRESS_STATION"/>
+          <xs:enumeration value="FEDEX_GROUND_TERMINAL"/>
+          <xs:enumeration value="FEDEX_OFFICE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="FlatbedTrailerDetail">
+        <xs:annotation>
+          <xs:documentation>Specifies the optional features/characteristics requested for a Freight shipment utilizing a flatbed trailer.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Options" type="ns:FlatbedTrailerOption" minOccurs="0" maxOccurs="unbounded"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="FlatbedTrailerOption">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="OVER_DIMENSION"/>
+          <xs:enumeration value="TARP"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="FreightAccountPaymentType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="COLLECT"/>
+          <xs:enumeration value="PREPAID"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="FreightBaseCharge">
+        <xs:annotation>
+          <xs:documentation>Individual charge which contributes to the total base charge for the shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="FreightClass" type="ns:FreightClassType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Freight class for this line item.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RatedAsClass" type="ns:FreightClassType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Effective freight class used for rating this line item.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NmfcCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>NMFC Code for commodity.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Description" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Customer-provided description for this commodity or class line.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Weight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Weight for this commodity or class line.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ChargeRate" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Rate or factor applied to this line item.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ChargeBasis" type="ns:FreightChargeBasisType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the manner in which the chargeRate for this line item was applied.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ExtendedAmount" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The net or extended charge for this line item.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="FreightBaseChargeCalculationType">
+        <xs:annotation>
+          <xs:documentation>Specifies the way in which base charges for a Freight shipment or shipment leg are calculated.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="LINE_ITEMS"/>
+          <xs:enumeration value="UNIT_PRICING"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="FreightChargeBasisType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CWT"/>
+          <xs:enumeration value="FLAT"/>
+          <xs:enumeration value="MINIMUM"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="FreightClassType">
+        <xs:annotation>
+          <xs:documentation>These values represent the industry-standard freight classes used for FedEx Freight and FedEx National Freight shipment description. (Note: The alphabetic prefixes are required to distinguish these values from decimal numbers on some client platforms.)</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CLASS_050"/>
+          <xs:enumeration value="CLASS_055"/>
+          <xs:enumeration value="CLASS_060"/>
+          <xs:enumeration value="CLASS_065"/>
+          <xs:enumeration value="CLASS_070"/>
+          <xs:enumeration value="CLASS_077_5"/>
+          <xs:enumeration value="CLASS_085"/>
+          <xs:enumeration value="CLASS_092_5"/>
+          <xs:enumeration value="CLASS_100"/>
+          <xs:enumeration value="CLASS_110"/>
+          <xs:enumeration value="CLASS_125"/>
+          <xs:enumeration value="CLASS_150"/>
+          <xs:enumeration value="CLASS_175"/>
+          <xs:enumeration value="CLASS_200"/>
+          <xs:enumeration value="CLASS_250"/>
+          <xs:enumeration value="CLASS_300"/>
+          <xs:enumeration value="CLASS_400"/>
+          <xs:enumeration value="CLASS_500"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="FreightCommitDetail">
+        <xs:annotation>
+          <xs:documentation>Information about the Freight Service Centers associated with this shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="OriginDetail" type="ns:FreightServiceCenterDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Information about the origin Freight Service Center.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DestinationDetail" type="ns:FreightServiceCenterDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Information about the destination Freight Service Center.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalDistance" type="ns:Distance" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The distance between the origin and destination FreightService Centers</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="FreightGuaranteeDetail">
+        <xs:sequence>
+          <xs:element name="Type" type="ns:FreightGuaranteeType" minOccurs="0"/>
+          <xs:element name="Date" type="xs:date" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Date for all Freight guarantee types.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="FreightGuaranteeType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="GUARANTEED_DATE"/>
+          <xs:enumeration value="GUARANTEED_MORNING"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="FreightOnValueType">
+        <xs:annotation>
+          <xs:documentation>Identifies responsibilities with respect to loss, damage, etc.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CARRIER_RISK"/>
+          <xs:enumeration value="OWN_RISK"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="FreightRateDetail">
+        <xs:annotation>
+          <xs:documentation>Rate data specific to FedEx Freight or FedEx National Freight services.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="QuoteNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>A unique identifier for a specific rate quotation.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BaseChargeCalculation" type="ns:FreightBaseChargeCalculationType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies how total base charge is determined.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BaseCharges" type="ns:FreightBaseCharge" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Freight charges which accumulate to the total base charge for the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Notations" type="ns:FreightRateNotation" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Human-readable descriptions of additional information on this shipment rating.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="FreightRateNotation">
+        <xs:annotation>
+          <xs:documentation>Additional non-monetary data returned with Freight rates.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Code" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Unique identifier for notation.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Description" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Human-readable explanation of notation.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="FreightServiceCenterDetail">
+        <xs:annotation>
+          <xs:documentation>This class describes the relationship between a customer-specified address and the FedEx Freight / FedEx National Freight Service Center that supports that address.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="InterlineCarrierCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Freight Industry standard non-FedEx carrier identification</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="InterlineCarrierName" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The name of the Interline carrier.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AdditionalDays" type="xs:int" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Additional time it might take at the origin or destination to pickup or deliver the freight. This is usually due to the remoteness of the location. This time is included in the total transit time.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LocalService" type="ns:ServiceType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Service branding which may be used for local pickup or delivery, distinct from service used for line-haul of customer's shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LocalDistance" type="ns:Distance" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Distance between customer address (pickup or delivery) and the supporting Freight / National Freight service center.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LocalDuration" type="xs:duration" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Time to travel between customer address (pickup or delivery) and the supporting Freight / National Freight service center.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LocalServiceScheduling" type="ns:FreightServiceSchedulingType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies when/how the customer can arrange for pickup or delivery.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LimitedServiceDays" type="ns:DayOfWeekType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies days of operation if localServiceScheduling is LIMITED.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="GatewayLocationId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Freight service center that is a gateway on the border of Canada or Mexico.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Location" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Alphabetical code identifying a Freight Service Center</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ContactAndAddress" type="ns:ContactAndAddress" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Freight service center Contact and Address</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="FreightServiceSchedulingType">
+        <xs:annotation>
+          <xs:documentation>Specifies the type of service scheduling offered from a Freight or National Freight Service Center to a customer-supplied address.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="LIMITED"/>
+          <xs:enumeration value="STANDARD"/>
+          <xs:enumeration value="WILL_CALL"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="FreightShipmentDetail">
+        <xs:annotation>
+          <xs:documentation>Data applicable to shipments using FEDEX_FREIGHT and FEDEX_NATIONAL_FREIGHT services.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="FedExFreightAccountNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Account number used with FEDEX_FREIGHT service.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FedExFreightBillingContactAndAddress" type="ns:ContactAndAddress" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Used for validating FedEx Freight account number and (optionally) identifying third party payment on the bill of lading.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FedExNationalFreightAccountNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Account number used with FEDEX_NATIONAL_FREIGHT service.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FedExNationalFreightBillingContactAndAddress" type="ns:ContactAndAddress" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Used for validating FedEx National Freight account number and (optionally) identifying third party payment on the bill of lading.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Role" type="ns:FreightShipmentRoleType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates the role of the party submitting the transaction.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PaymentType" type="ns:FreightAccountPaymentType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Designates which of the requester's tariffs will be used for rating.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DeclaredValuePerUnit" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the declared value for the shipment</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DeclaredValueUnits" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the declared value units corresponding to the above defined declared value</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LiabilityCoverageDetail" type="ns:LiabilityCoverageDetail" minOccurs="0"/>
+          <xs:element name="Coupons" type="xs:string" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Identifiers for promotional discounts offered to customers.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalHandlingUnits" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Total number of individual handling units in the entire shipment (for unit pricing).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ClientDiscountPercent" type="xs:decimal" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Estimated discount rate provided by client for unsecured rate quote.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PalletWeight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Total weight of pallets used in shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ShipmentDimensions" type="ns:Dimensions" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Overall shipment dimensions.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Comment" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Description for the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SpecialServicePayments" type="ns:FreightSpecialServicePayment" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies which party will pay surcharges for any special services which support split billing.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LineItems" type="ns:FreightShipmentLineItem" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Details of the commodities in the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="FreightShipmentLineItem">
+        <xs:annotation>
+          <xs:documentation>Description of an individual commodity or class of content in a shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="FreightClass" type="ns:FreightClassType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Freight class for this line item.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Packaging" type="ns:PhysicalPackagingType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specification of handling-unit packaging for this commodity or class line.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Description" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Customer-provided description for this commodity or class line.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Weight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Weight for this commodity or class line.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Dimensions" type="ns:Dimensions" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>FED EX INTERNAL USE ONLY - Individual line item dimensions.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Volume" type="ns:Volume" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Volume (cubic measure) for this commodity or class line.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="FreightShipmentRoleType">
+        <xs:annotation>
+          <xs:documentation>Indicates the role of the party submitting the transaction.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CONSIGNEE"/>
+          <xs:enumeration value="SHIPPER"/>
+          <xs:enumeration value="THIRD_PARTY"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="FreightSpecialServicePayment">
+        <xs:annotation>
+          <xs:documentation>Specifies which party will be responsible for payment of any surcharges for Freight special services for which split billing is allowed.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="SpecialService" type="ns:ShipmentSpecialServiceType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the special service.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PaymentType" type="ns:FreightAccountPaymentType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates who will pay for the special service.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="GeneralAgencyAgreementDetail">
+        <xs:annotation>
+          <xs:documentation>Data required to produce a General Agency Agreement document. Remaining content (business data) to be defined once requirements have been completed.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Format" type="ns:ShippingDocumentFormat" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="HazardousCommodityContent">
+        <xs:annotation>
+          <xs:documentation>Documents the kind and quantity of an individual hazardous commodity in a package.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Description" type="ns:HazardousCommodityDescription" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies and describes an individual hazardous commodity.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Quantity" type="ns:HazardousCommodityQuantityDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies the amount of the commodity in alternate units.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Options" type="ns:HazardousCommodityOptionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Customer-provided specifications for handling individual commodities.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="HazardousCommodityDescription">
+        <xs:annotation>
+          <xs:documentation>Identifies and describes an individual hazardous commodity. For 201001 load, this is based on data from the FedEx Ground Hazardous Materials Shipping Guide.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Id" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Regulatory identifier for a commodity (e.g. "UN ID" value).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PackingGroup" type="ns:HazardousCommodityPackingGroupType" minOccurs="0"/>
+          <xs:element name="ProperShippingName" type="xs:string" minOccurs="0"/>
+          <xs:element name="TechnicalName" type="xs:string" minOccurs="0"/>
+          <xs:element name="HazardClass" type="xs:string" minOccurs="0"/>
+          <xs:element name="SubsidiaryClasses" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="LabelText" type="xs:string" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="HazardousCommodityLabelTextOptionType">
+        <xs:annotation>
+          <xs:documentation>Specifies how the commodity is to be labeled.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="APPEND"/>
+          <xs:enumeration value="OVERRIDE"/>
+          <xs:enumeration value="STANDARD"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="HazardousCommodityOptionDetail">
+        <xs:annotation>
+          <xs:documentation>Customer-provided specifications for handling individual commodities.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="LabelTextOption" type="ns:HazardousCommodityLabelTextOptionType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies how the customer wishes the label text to be handled for this commodity in this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomerSuppliedLabelText" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Text used in labeling the commodity under control of the labelTextOption field.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="HazardousCommodityOptionType">
+        <xs:annotation>
+          <xs:documentation>Indicates which kind of hazardous content (as defined by DOT) is being reported.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="HAZARDOUS_MATERIALS"/>
+          <xs:enumeration value="LITHIUM_BATTERY_EXCEPTION"/>
+          <xs:enumeration value="ORM_D"/>
+          <xs:enumeration value="REPORTABLE_QUANTITIES"/>
+          <xs:enumeration value="SMALL_QUANTITY_EXCEPTION"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="HazardousCommodityPackagingDetail">
+        <xs:annotation>
+          <xs:documentation>Identifies number and type of packaging units for hazardous commodities.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Count" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Number of units of the type below.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Units" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Units in which the hazardous commodity is packaged.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="HazardousCommodityPackingGroupType">
+        <xs:annotation>
+          <xs:documentation>Identifies DOT packing group for a hazardous commodity.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="I"/>
+          <xs:enumeration value="II"/>
+          <xs:enumeration value="III"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="HazardousCommodityQuantityDetail">
+        <xs:annotation>
+          <xs:documentation>Identifies amount and units for quantity of hazardous commodities.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Amount" type="xs:decimal" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Number of units of the type below.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Units" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Units by which the hazardous commodity is measured.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="HoldAtLocationDetail">
+        <xs:annotation>
+          <xs:documentation>Descriptive data required for a FedEx shipment that is to be held at the destination FedEx location for pickup by the recipient.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="PhoneNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Contact phone number for recipient of shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LocationContactAndAddress" type="ns:ContactAndAddress" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Contact and address of FedEx facility at which shipment is to be held.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LocationType" type="ns:FedExLocationType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Type of facility at which package/shipment is to be held.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LocationId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Location identification (for facilities identified by an alphanumeric location code).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LocationNumber" type="xs:int" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Location identification (for facilities identified by an numeric location code).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="HomeDeliveryPremiumDetail">
+        <xs:annotation>
+          <xs:documentation>The descriptive data required by FedEx for home delivery services.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="HomeDeliveryPremiumType" type="ns:HomeDeliveryPremiumType" minOccurs="1"/>
+          <xs:element name="Date" type="xs:date" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Required for Date Certain Home Delivery.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PhoneNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Required for Date Certain and Appointment Home Delivery.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>15</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="HomeDeliveryPremiumType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="APPOINTMENT"/>
+          <xs:enumeration value="DATE_CERTAIN"/>
+          <xs:enumeration value="EVENING"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="ImageId">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="IMAGE_1"/>
+          <xs:enumeration value="IMAGE_2"/>
+          <xs:enumeration value="IMAGE_3"/>
+          <xs:enumeration value="IMAGE_4"/>
+          <xs:enumeration value="IMAGE_5"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="InternationalDocumentContentType">
+        <xs:annotation>
+          <xs:documentation>The type of International shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="DOCUMENTS_ONLY"/>
+          <xs:enumeration value="NON_DOCUMENTS"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="LabelFormatType">
+        <xs:annotation>
+          <xs:documentation>Specifies the type of label to be returned.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="COMMON2D"/>
+          <xs:enumeration value="LABEL_DATA_ONLY"/>
+          <xs:enumeration value="MAILROOM"/>
+          <xs:enumeration value="NO_LABEL"/>
+          <xs:enumeration value="OPERATIONAL_LABEL"/>
+          <xs:enumeration value="PRE_COMMON2D"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="LabelMaskableDataType">
+        <xs:annotation>
+          <xs:documentation>Names for data elements / areas which may be suppressed from printing on labels.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CUSTOMS_VALUE"/>
+          <xs:enumeration value="DIMENSIONS"/>
+          <xs:enumeration value="DUTIES_AND_TAXES_PAYOR_ACCOUNT_NUMBER"/>
+          <xs:enumeration value="FREIGHT_PAYOR_ACCOUNT_NUMBER"/>
+          <xs:enumeration value="PACKAGE_SEQUENCE_AND_COUNT"/>
+          <xs:enumeration value="SHIPPER_ACCOUNT_NUMBER"/>
+          <xs:enumeration value="SUPPLEMENTAL_LABEL_DOC_TAB"/>
+          <xs:enumeration value="TERMS_AND_CONDITIONS"/>
+          <xs:enumeration value="TOTAL_WEIGHT"/>
+          <xs:enumeration value="TRANSPORTATION_CHARGES_PAYOR_ACCOUNT_NUMBER"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="LabelPrintingOrientationType">
+        <xs:annotation>
+          <xs:documentation>This indicates if the top or bottom of the label comes out of the printer first.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BOTTOM_EDGE_OF_TEXT_FIRST"/>
+          <xs:enumeration value="TOP_EDGE_OF_TEXT_FIRST"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="LabelRotationType">
+        <xs:annotation>
+          <xs:documentation>Relative to normal orientation for the printer.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="LEFT"/>
+          <xs:enumeration value="NONE"/>
+          <xs:enumeration value="RIGHT"/>
+          <xs:enumeration value="UPSIDE_DOWN"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="LabelSpecification">
+        <xs:annotation>
+          <xs:documentation>Description of shipping label to be returned in the reply</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="LabelFormatType" type="ns:LabelFormatType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specify type of label to be returned</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ImageType" type="ns:ShippingDocumentImageType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>
+                The type of image or printer commands the label is to be formatted in.
+                DPL = Unimark thermal printer language
+                EPL2 = Eltron thermal printer language
+                PDF = a label returned as a pdf image
+                PNG = a label returned as a png image
+                ZPLII = Zebra thermal printer language
+              </xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LabelStockType" type="ns:LabelStockType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>For thermal printer lables this indicates the size of the label and the location of the doc tab if present.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LabelPrintingOrientation" type="ns:LabelPrintingOrientationType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This indicates if the top or bottom of the label comes out of the printer first.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LabelRotation" type="ns:LabelRotationType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Relative to normal orientation for the printer. RIGHT=90 degrees clockwise, UPSIDE_DOWN=180 degrees, LEFT=90 degrees counterclockwise.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PrintedLabelOrigin" type="ns:ContactAndAddress" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>If present, this contact and address information will replace the return address information on the label.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomerSpecifiedDetail" type="ns:CustomerSpecifiedLabelDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Allows customer-specified control of label content.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="LabelStockType">
+        <xs:annotation>
+          <xs:documentation>For thermal printer labels this indicates the size of the label and the location of the doc tab if present.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="PAPER_4X6"/>
+          <xs:enumeration value="PAPER_4X8"/>
+          <xs:enumeration value="PAPER_4X9"/>
+          <xs:enumeration value="PAPER_7X4.75"/>
+          <xs:enumeration value="PAPER_8.5X11_BOTTOM_HALF_LABEL"/>
+          <xs:enumeration value="PAPER_8.5X11_TOP_HALF_LABEL"/>
+          <xs:enumeration value="STOCK_4X6"/>
+          <xs:enumeration value="STOCK_4X6.75_LEADING_DOC_TAB"/>
+          <xs:enumeration value="STOCK_4X6.75_TRAILING_DOC_TAB"/>
+          <xs:enumeration value="STOCK_4X8"/>
+          <xs:enumeration value="STOCK_4X9_LEADING_DOC_TAB"/>
+          <xs:enumeration value="STOCK_4X9_TRAILING_DOC_TAB"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="LiabilityCoverageDetail">
+        <xs:sequence>
+          <xs:element name="CoverageType" type="ns:LiabilityCoverageType" minOccurs="0"/>
+          <xs:element name="CoverageAmount" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the Liability Coverage Amount. For Jan 2010 this value represents coverage amount per pound</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="LiabilityCoverageType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="NEW"/>
+          <xs:enumeration value="USED_OR_RECONDITIONED"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="LinearMeasure">
+        <xs:annotation>
+          <xs:documentation>Represents a one-dimensional measurement in small units (e.g. suitable for measuring a package or document), contrasted with Distance, which represents a large one-dimensional measurement (e.g. distance between cities).</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Value" type="xs:decimal" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The numerical quantity of this measurement.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Units" type="ns:LinearUnits" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The units for this measurement.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="LinearUnits">
+        <xs:annotation>
+          <xs:documentation>CM = centimeters, IN = inches</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CM"/>
+          <xs:enumeration value="IN"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Localization">
+        <xs:annotation>
+          <xs:documentation>Identifies the representation of human-readable text.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="LanguageCode" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Two-letter code for language (e.g. EN, FR, etc.)</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LocaleCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Two-letter code for the region (e.g. us, ca, etc..).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="Measure">
+        <xs:sequence>
+          <xs:element name="Quantity" type="xs:decimal" minOccurs="0"/>
+          <xs:element name="Units" type="xs:string" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="MinimumChargeType">
+        <xs:annotation>
+          <xs:documentation>Internal FedEx use only.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CUSTOMER"/>
+          <xs:enumeration value="CUSTOMER_FREIGHT_WEIGHT"/>
+          <xs:enumeration value="EARNED_DISCOUNT"/>
+          <xs:enumeration value="MIXED"/>
+          <xs:enumeration value="RATE_SCALE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Money">
+        <xs:sequence>
+          <xs:element name="Currency" type="xs:string" minOccurs="0"/>
+          <xs:element name="Amount" type="xs:decimal" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="NaftaCertificateOfOriginDetail">
+        <xs:annotation>
+          <xs:documentation>Data required to produce a Certificate of Origin document. Remaining content (business data) to be defined once requirements have been completed.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Format" type="ns:ShippingDocumentFormat" minOccurs="0"/>
+          <xs:element name="BlanketPeriod" type="ns:DateRange" minOccurs="0"/>
+          <xs:element name="ImporterSpecification" type="ns:NaftaImporterSpecificationType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates which Party (if any) from the shipment is to be used as the source of importer data on the NAFTA COO form.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SignatureContact" type="ns:Contact" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Contact information for "Authorized Signature" area of form.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ProducerSpecification" type="ns:NaftaProducerSpecificationType" minOccurs="0"/>
+          <xs:element name="Producers" type="ns:NaftaProducer" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="CustomerImageUsages" type="ns:CustomerImageUsage" minOccurs="0" maxOccurs="unbounded"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="NaftaCommodityDetail">
+        <xs:sequence>
+          <xs:element name="PreferenceCriterion" type="ns:NaftaPreferenceCriterionCode" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Defined by NAFTA regulations.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ProducerDetermination" type="ns:NaftaProducerDeterminationCode" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Defined by NAFTA regulations.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ProducerId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identification of which producer is associated with this commodity (if multiple producers are used in a single shipment).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NetCostMethod" type="ns:NaftaNetCostMethodCode" minOccurs="0"/>
+          <xs:element name="NetCostDateRange" type="ns:DateRange" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Date range over which RVC net cost was calculated.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="NaftaImporterSpecificationType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="IMPORTER_OF_RECORD"/>
+          <xs:enumeration value="RECIPIENT"/>
+          <xs:enumeration value="UNKNOWN"/>
+          <xs:enumeration value="VARIOUS"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="NaftaNetCostMethodCode">
+        <xs:annotation>
+          <xs:documentation>
+            Net cost method used.
+          </xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="NC"/>
+          <xs:enumeration value="NO"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="NaftaPreferenceCriterionCode">
+        <xs:annotation>
+          <xs:documentation>See instructions for NAFTA Certificate of Origin for code definitions.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="A"/>
+          <xs:enumeration value="B"/>
+          <xs:enumeration value="C"/>
+          <xs:enumeration value="D"/>
+          <xs:enumeration value="E"/>
+          <xs:enumeration value="F"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="NaftaProducer">
+        <xs:sequence>
+          <xs:element name="Id" type="xs:string" minOccurs="0"/>
+          <xs:element name="Producer" type="ns:Party" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="NaftaProducerDeterminationCode">
+        <xs:annotation>
+          <xs:documentation>See instructions for NAFTA Certificate of Origin for code definitions.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="NO_1"/>
+          <xs:enumeration value="NO_2"/>
+          <xs:enumeration value="NO_3"/>
+          <xs:enumeration value="YES"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="NaftaProducerSpecificationType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="AVAILABLE_UPON_REQUEST"/>
+          <xs:enumeration value="MULTIPLE_SPECIFIED"/>
+          <xs:enumeration value="SAME"/>
+          <xs:enumeration value="SINGLE_SPECIFIED"/>
+          <xs:enumeration value="UNKNOWN"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Notification">
+        <xs:annotation>
+          <xs:documentation>The descriptive data regarding the result of the submitted transaction.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Severity" type="ns:NotificationSeverityType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The severity of this notification. This can indicate success or failure or some other information about the request. The values that can be returned are SUCCESS - Your transaction succeeded with no other applicable information. NOTE - Additional information that may be of interest to you about your transaction. WARNING - Additional information that you need to know about your transaction that you may need to take action on. ERROR - Information about an error that occurred while processing your transaction. FAILURE - FedEx was unable to process your transaction at this time due to a system failure. Please try again later</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Source" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates the source of this notification. Combined with the Code it uniquely identifies this notification</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Code" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>A code that represents this notification. Combined with the Source it uniquely identifies this notification.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Message" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Human-readable text that explains this notification.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LocalizedMessage" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The translated message. The language and locale specified in the ClientDetail. Localization are used to determine the representation. Currently only supported in a TrackReply.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="MessageParameters" type="ns:NotificationParameter" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>A collection of name/value pairs that provide specific data to help the client determine the nature of an error (or warning, etc.) witout having to parse the message string.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="NotificationParameter">
+        <xs:sequence>
+          <xs:element name="Id" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the type of data contained in Value (e.g. SERVICE_TYPE, PACKAGE_SEQUENCE, etc..).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Value" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The value of the parameter (e.g. PRIORITY_OVERNIGHT, 2, etc..).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="NotificationSeverityType">
+        <xs:annotation>
+          <xs:documentation>Identifies the set of severity values for a Notification.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ERROR"/>
+          <xs:enumeration value="FAILURE"/>
+          <xs:enumeration value="NOTE"/>
+          <xs:enumeration value="SUCCESS"/>
+          <xs:enumeration value="WARNING"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Op900Detail">
+        <xs:annotation>
+          <xs:documentation>The instructions indicating how to print the OP-900 form for hazardous materials packages.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Format" type="ns:ShippingDocumentFormat" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies characteristics of a shipping document to be produced.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Reference" type="ns:CustomerReferenceType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies which reference type (from the package's customer references) is to be used as the source for the reference on this OP-900.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomerImageUsages" type="ns:CustomerImageUsage" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies the usage and identification of customer supplied images to be used on this document.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SignatureName" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Data field to be used when a name is to be printed in the document instead of (or in addition to) a signature image.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="OversizeClassType">
+        <xs:annotation>
+          <xs:documentation>The Oversize classification for a package.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="OVERSIZE_1"/>
+          <xs:enumeration value="OVERSIZE_2"/>
+          <xs:enumeration value="OVERSIZE_3"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="PackageRateDetail">
+        <xs:annotation>
+          <xs:documentation>Data for a package's rates, as calculated per a specific rate type.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="RateType" type="ns:ReturnedRateType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Type used for this specific set of rate data.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RatedWeightMethod" type="ns:RatedWeightMethod" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates which weight was used.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="MinimumChargeType" type="ns:MinimumChargeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>INTERNAL FEDEX USE ONLY.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BillingWeight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The weight that was used to calculate the rate.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DimWeight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The dimensional weight of this package (if greater than actual).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="OversizeWeight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The oversize weight of this package (if the package is oversize).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BaseCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The transportation charge only (prior to any discounts applied) for this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalFreightDiscounts" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The sum of all discounts on this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NetFreight" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This package's baseCharge - totalFreightDiscounts.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalSurcharges" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The sum of all surcharges on this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NetFedExCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This package's netFreight + totalSurcharges (not including totalTaxes).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalTaxes" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The sum of all taxes on this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NetCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This package's netFreight + totalSurcharges + totalTaxes.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalRebates" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The total sum of all rebates applied to this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FreightDiscounts" type="ns:RateDiscount" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All rate discounts that apply to this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Rebates" type="ns:Rebate" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All rebates that apply to this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Surcharges" type="ns:Surcharge" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All surcharges that apply to this package (either because of characteristics of the package itself, or because it is carrying per-shipment surcharges for the shipment of which it is a part).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Taxes" type="ns:Tax" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All taxes applicable (or distributed to) this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="VariableHandlingCharges" type="ns:VariableHandlingCharges" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The variable handling charges calculated based on the type variable handling charges requested.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="PackageSpecialServiceType">
+        <xs:annotation>
+          <xs:documentation>Identifies the collection of special services offered by FedEx.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ALCOHOL"/>
+          <xs:enumeration value="APPOINTMENT_DELIVERY"/>
+          <xs:enumeration value="COD"/>
+          <xs:enumeration value="DANGEROUS_GOODS"/>
+          <xs:enumeration value="DRY_ICE"/>
+          <xs:enumeration value="NON_STANDARD_CONTAINER"/>
+          <xs:enumeration value="PRIORITY_ALERT"/>
+          <xs:enumeration value="SIGNATURE_OPTION"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="PackageSpecialServicesRequested">
+        <xs:annotation>
+          <xs:documentation>These special services are available at the package level for some or all service types. If the shipper is requesting a special service which requires additional data, the package special service type must be present in the specialServiceTypes collection, and the supporting detail must be provided in the appropriate sub-object below.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="SpecialServiceTypes" type="ns:PackageSpecialServiceType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>The types of all special services requested for the enclosing shipment or package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CodDetail" type="ns:CodDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>For use with FedEx Ground services only; COD must be present in shipment's special services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DangerousGoodsDetail" type="ns:DangerousGoodsDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data required for a FedEx shipment containing dangerous materials. This element is required when SpecialServiceType.DANGEROUS_GOODS or HAZARDOUS_MATERIAL is present in the SpecialServiceTypes collection.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DryIceWeight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data required for a FedEx shipment containing dry ice. This element is required when SpecialServiceType.DRY_ICE is present in the SpecialServiceTypes collection.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SignatureOptionDetail" type="ns:SignatureOptionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The descriptive data required for FedEx signature services. This element is required when SpecialServiceType.SIGNATURE_OPTION is present in the SpecialServiceTypes collection.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PriorityAlertDetail" type="ns:PriorityAlertDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>To be filled.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="PackagingType">
+        <xs:annotation>
+          <xs:documentation>Identifies the packaging used by the requestor for the package. See PackagingType for list of valid enumerated values.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="FEDEX_10KG_BOX"/>
+          <xs:enumeration value="FEDEX_25KG_BOX"/>
+          <xs:enumeration value="FEDEX_BOX"/>
+          <xs:enumeration value="FEDEX_ENVELOPE"/>
+          <xs:enumeration value="FEDEX_PAK"/>
+          <xs:enumeration value="FEDEX_TUBE"/>
+          <xs:enumeration value="YOUR_PACKAGING"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Party">
+        <xs:annotation>
+          <xs:documentation>The descriptive data for a person or company entitiy doing business with FedEx.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="AccountNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the FedEx account number assigned to the customer.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>12</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Tins" type="ns:TaxpayerIdentification" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Descriptive data for taxpayer identification information.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Contact" type="ns:Contact" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data identifying the point-of-contact person.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Address" type="ns:Address" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The descriptive data for a physical location.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="Payment">
+        <xs:annotation>
+          <xs:documentation>The descriptive data for the monetary compensation given to FedEx for services rendered to the customer.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="PaymentType" type="ns:PaymentType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the method of payment for a service. See PaymentType for list of valid enumerated values.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Payor" type="ns:Payor" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data identifying the party responsible for payment for a service.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="PaymentType">
+        <xs:annotation>
+          <xs:documentation>Identifies the method of payment for a service.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="SENDER"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Payor">
+        <xs:annotation>
+          <xs:documentation>Descriptive data identifying the party responsible for payment for a service.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="AccountNumber" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the FedEx account number assigned to the payor.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>12</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CountryCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the country of the payor.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="PendingShipmentDetail">
+        <xs:annotation>
+          <xs:documentation>This information describes the kind of pending shipment being requested.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Type" type="ns:PendingShipmentType" minOccurs="1"/>
+          <xs:element name="ExpirationDate" type="xs:date" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Date after which the pending shipment will no longer be available for completion.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EmailLabelDetail" type="ns:EMailLabelDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Only used with type of EMAIL.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="PendingShipmentType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="EMAIL"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="PhysicalPackagingType">
+        <xs:annotation>
+          <xs:documentation>This enumeration rationalizes the former FedEx Express international "admissibility package" types (based on ANSI X.12) and the FedEx Freight packaging types. The values represented are those common to both carriers.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BAG"/>
+          <xs:enumeration value="BARREL"/>
+          <xs:enumeration value="BASKET"/>
+          <xs:enumeration value="BOX"/>
+          <xs:enumeration value="BUCKET"/>
+          <xs:enumeration value="BUNDLE"/>
+          <xs:enumeration value="CARTON"/>
+          <xs:enumeration value="CASE"/>
+          <xs:enumeration value="CONTAINER"/>
+          <xs:enumeration value="CRATE"/>
+          <xs:enumeration value="CYLINDER"/>
+          <xs:enumeration value="DRUM"/>
+          <xs:enumeration value="ENVELOPE"/>
+          <xs:enumeration value="HAMPER"/>
+          <xs:enumeration value="OTHER"/>
+          <xs:enumeration value="PAIL"/>
+          <xs:enumeration value="PALLET"/>
+          <xs:enumeration value="PIECE"/>
+          <xs:enumeration value="REEL"/>
+          <xs:enumeration value="ROLL"/>
+          <xs:enumeration value="SKID"/>
+          <xs:enumeration value="TANK"/>
+          <xs:enumeration value="TUBE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="PickupDetail">
+        <xs:annotation>
+          <xs:documentation>This class describes the pickup characteristics of a shipment (e.g. for use in a tag request).</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="ReadyDateTime" type="xs:dateTime" minOccurs="0"/>
+          <xs:element name="LatestPickupDateTime" type="xs:dateTime" minOccurs="0"/>
+          <xs:element name="CourierInstructions" type="xs:string" minOccurs="0"/>
+          <xs:element name="RequestType" type="ns:PickupRequestType" minOccurs="0"/>
+          <xs:element name="RequestSource" type="ns:PickupRequestSourceType" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="PickupRequestSourceType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="AUTOMATION"/>
+          <xs:enumeration value="CUSTOMER_SERVICE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="PickupRequestType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="FUTURE_DAY"/>
+          <xs:enumeration value="SAME_DAY"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="PricingCodeType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ACTUAL"/>
+          <xs:enumeration value="ALTERNATE"/>
+          <xs:enumeration value="BASE"/>
+          <xs:enumeration value="HUNDREDWEIGHT"/>
+          <xs:enumeration value="HUNDREDWEIGHT_ALTERNATE"/>
+          <xs:enumeration value="INTERNATIONAL_DISTRIBUTION"/>
+          <xs:enumeration value="INTERNATIONAL_ECONOMY_SERVICE"/>
+          <xs:enumeration value="LTL_FREIGHT"/>
+          <xs:enumeration value="PACKAGE"/>
+          <xs:enumeration value="SHIPMENT"/>
+          <xs:enumeration value="SHIPMENT_FIVE_POUND_OPTIONAL"/>
+          <xs:enumeration value="SHIPMENT_OPTIONAL"/>
+          <xs:enumeration value="SPECIAL"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="PriorityAlertDetail">
+        <xs:annotation>
+          <xs:documentation>Currently not supported.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Content" type="xs:string" minOccurs="0" maxOccurs="3"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="PurposeOfShipmentType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="GIFT"/>
+          <xs:enumeration value="NOT_SOLD"/>
+          <xs:enumeration value="PERSONAL_EFFECTS"/>
+          <xs:enumeration value="REPAIR_AND_RETURN"/>
+          <xs:enumeration value="SAMPLE"/>
+          <xs:enumeration value="SOLD"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="RateDimensionalDivisorType">
+        <xs:annotation>
+          <xs:documentation>Indicates the reason that a dim divisor value was chose.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="COUNTRY"/>
+          <xs:enumeration value="CUSTOMER"/>
+          <xs:enumeration value="OTHER"/>
+          <xs:enumeration value="PRODUCT"/>
+          <xs:enumeration value="WAIVED"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="RateDiscount">
+        <xs:annotation>
+          <xs:documentation>Identifies a discount applied to the shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="RateDiscountType" type="ns:RateDiscountType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the type of discount applied to the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Description" type="xs:string" minOccurs="0"/>
+          <xs:element name="Amount" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The amount of the discount applied to the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Percent" type="xs:decimal" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The percentage of the discount applied to the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="RateDiscountType">
+        <xs:annotation>
+          <xs:documentation>Identifies the type of discount applied to the shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BONUS"/>
+          <xs:enumeration value="COUPON"/>
+          <xs:enumeration value="EARNED"/>
+          <xs:enumeration value="OTHER"/>
+          <xs:enumeration value="VOLUME"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="RateElementBasisType">
+        <xs:annotation>
+          <xs:documentation>Selects the value from a set of rate data to which the percentage is applied.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BASE_CHARGE"/>
+          <xs:enumeration value="NET_CHARGE"/>
+          <xs:enumeration value="NET_CHARGE_EXCLUDING_TAXES"/>
+          <xs:enumeration value="NET_FREIGHT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="RateReply">
+        <xs:annotation>
+          <xs:documentation>The response to a RateRequest. The Notifications indicate whether the request was successful or not.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="HighestSeverity" type="ns:NotificationSeverityType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>This indicates the highest level of severity of all the notifications returned in this reply.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Notifications" type="ns:Notification" minOccurs="1" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>The descriptive data regarding the results of the submitted transaction.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TransactionDetail" type="ns:TransactionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Contains the CustomerTransactionId that was sent in the request.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Version" type="ns:VersionId" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The version of this reply.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RateReplyDetails" type="ns:RateReplyDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Each element contains all rate data for a single service. If service was specified in the request, there will be a single entry in this array; if service was omitted in the request, there will be a separate entry in this array for each service being compared.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="RateReplyDetail">
+        <xs:sequence>
+          <xs:element name="ServiceType" type="ns:ServiceType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the FedEx service to use in shipping the package. See ServiceType for list of valid enumerated values.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PackagingType" type="ns:PackagingType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the packaging used by the requestor for the package. See PackagingType for list of valid enumerated values.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AppliedOptions" type="ns:ServiceOptionType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Shows the specific combination of service options combined with the service type that produced this committment in the set returned to the caller.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AppliedSubOptions" type="ns:ServiceSubOptionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Supporting detail for applied options identified in preceding field.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DeliveryStation" type="xs:string" minOccurs="0"/>
+          <xs:element name="DeliveryDayOfWeek" type="ns:DayOfWeekType" minOccurs="0"/>
+          <xs:element name="DeliveryTimestamp" type="xs:dateTime" minOccurs="0"/>
+          <xs:element name="CommitDetails" type="ns:CommitDetail" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="DestinationAirportId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identification of an airport, using standard three-letter abbreviations.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="IneligibleForMoneyBackGuarantee" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates whether or not this shipment is eligible for a money back guarantee.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="OriginServiceArea" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Commitment code for the origin.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DestinationServiceArea" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Commitment code for the destination.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TransitTime" type="ns:TransitTimeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Time in transit from pickup to delivery.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="MaximumTransitTime" type="ns:TransitTimeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Maximum expected transit time</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SignatureOption" type="ns:SignatureOptionType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The signature option for this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ActualRateType" type="ns:ReturnedRateType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The actual rate type of the charges for this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RatedShipmentDetails" type="ns:RatedShipmentDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Each element contains all rate data for a single rate type.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="RateRequest">
+        <xs:annotation>
+          <xs:documentation>Descriptive data sent to FedEx by a customer in order to rate a package/shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="WebAuthenticationDetail" type="ns:WebAuthenticationDetail" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data to be used in authentication of the sender's identity (and right to use FedEx web services).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ClientDetail" type="ns:ClientDetail" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data identifying the client submitting the transaction.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TransactionDetail" type="ns:TransactionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data for this customer transaction. The TransactionDetail from the request is echoed back to the caller in the corresponding reply.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Version" type="ns:VersionId" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the version/level of a service operation expected by a caller (in each request) and performed by the callee (in each reply).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ReturnTransitAndCommit" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Allows the caller to specify that the transit time and commit data are to be returned in the reply.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CarrierCodes" type="ns:CarrierCodeType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Candidate carriers for rate-shopping use case. This field is only considered if requestedShipment/serviceType is omitted.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="VariableOptions" type="ns:ServiceOptionType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Contains zero or more service options whose combinations are to be considered when replying with available services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RequestedShipment" type="ns:RequestedShipment" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The shipment for which a rate quote (or rate-shopping comparison) is desired.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="RateRequestType">
+        <xs:annotation>
+          <xs:documentation>Indicates the type of rates to be returned.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ACCOUNT"/>
+          <xs:enumeration value="LIST"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="RateTypeBasisType">
+        <xs:annotation>
+          <xs:documentation>Select the type of rate from which the element is to be selected.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ACCOUNT"/>
+          <xs:enumeration value="LIST"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="RatedPackageDetail">
+        <xs:annotation>
+          <xs:documentation>If requesting rates using the PackageDetails element (one package at a time) in the request, the rates for each package will be returned in this element. Currently total piece total weight rates are also retuned in this element.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="TrackingIds" type="ns:TrackingId" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Echoed from the corresponding package in the rate request (if provided).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="GroupNumber" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Used with request containing PACKAGE_GROUPS, to identify which group of identical packages was used to produce a reply item.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EffectiveNetDiscount" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The difference between "list" and "account" net charge.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AdjustedCodCollectionAmount" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Ground COD is shipment level.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="OversizeClass" type="ns:OversizeClassType" minOccurs="0"/>
+          <xs:element name="PackageRateDetail" type="ns:PackageRateDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Rate data that are tied to a specific package and rate type combination.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="RatedShipmentDetail">
+        <xs:annotation>
+          <xs:documentation>This class groups the shipment and package rating data for a specific rate type for use in a rating reply, which groups result data by rate type.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="EffectiveNetDiscount" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The difference between "list" and "account" total net charge.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AdjustedCodCollectionAmount" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Express COD is shipment level.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ShipmentRateDetail" type="ns:ShipmentRateDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The shipment-level totals for this rate type.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RatedPackages" type="ns:RatedPackageDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>The package-level data for this rate type.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="RatedWeightMethod">
+        <xs:annotation>
+          <xs:documentation>The method used to calculate the weight to be used in rating the package..</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ACTUAL"/>
+          <xs:enumeration value="AVERAGE_PACKAGE_WEIGHT_MINIMUM"/>
+          <xs:enumeration value="BALLOON"/>
+          <xs:enumeration value="DIM"/>
+          <xs:enumeration value="FREIGHT_MINIMUM"/>
+          <xs:enumeration value="MIXED"/>
+          <xs:enumeration value="OVERSIZE"/>
+          <xs:enumeration value="OVERSIZE_1"/>
+          <xs:enumeration value="OVERSIZE_2"/>
+          <xs:enumeration value="OVERSIZE_3"/>
+          <xs:enumeration value="PACKAGING_MINIMUM"/>
+          <xs:enumeration value="WEIGHT_BREAK"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Rebate">
+        <xs:annotation>
+          <xs:documentation>Identifies a discount applied to the shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="RebateType" type="ns:RebateType" minOccurs="0"/>
+          <xs:element name="Description" type="xs:string" minOccurs="0"/>
+          <xs:element name="Amount" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The amount of the discount applied to the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Percent" type="xs:decimal" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The percentage of the discount applied to the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="RebateType">
+        <xs:annotation>
+          <xs:documentation>Identifies the type of discount applied to the shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BONUS"/>
+          <xs:enumeration value="EARNED"/>
+          <xs:enumeration value="OTHER"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="RecipientCustomsId">
+        <xs:annotation>
+          <xs:documentation>Specifies how the recipient is identified for customs purposes; the requirements on this information vary with destination country.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Type" type="ns:RecipientCustomsIdType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies the kind of identification being used.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Value" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Contains the actual ID value, of the type specified above.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="RecipientCustomsIdType">
+        <xs:annotation>
+          <xs:documentation>Type of Brazilian taxpayer identifier provided in Recipient/TaxPayerIdentification/Number. For shipments bound for Brazil this overrides the value in Recipient/TaxPayerIdentification/TinType</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="COMPANY"/>
+          <xs:enumeration value="INDIVIDUAL"/>
+          <xs:enumeration value="PASSPORT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="RegulatoryControlType">
+        <xs:annotation>
+          <xs:documentation>FOOD_OR_PERISHABLE is required by FDA/BTA; must be true for food/perishable items coming to US or PR from non-US/non-PR origin</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="EU_CIRCULATION"/>
+          <xs:enumeration value="FOOD_OR_PERISHABLE"/>
+          <xs:enumeration value="NAFTA"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="RequestedPackageLineItem">
+        <xs:annotation>
+          <xs:documentation>This class rationalizes RequestedPackage and RequestedPackageSummary from previous interfaces. The way in which it is uses within a RequestedShipment depends on the RequestedPackageDetailType value specified for that shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="SequenceNumber" type="xs:positiveInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Used only with INDIVIDUAL_PACKAGE, as a unique identifier of each requested package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="GroupNumber" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Used only with PACKAGE_GROUPS, as a unique identifier of each group of identical packages.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="GroupPackageCount" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Used only with PACKAGE_GROUPS, as a count of packages within a group of identical packages.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="VariableHandlingChargeDetail" type="ns:VariableHandlingChargeDetail" minOccurs="0"/>
+          <xs:element name="InsuredValue" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Only used for INDIVIDUAL_PACKAGES and PACKAGE_GROUPS. Ignored for PACKAGE_SUMMARY, in which case totalInsuredValue and packageCount on the shipment will be used to determine this value.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Weight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Only used for INDIVIDUAL_PACKAGES and PACKAGE_GROUPS. Ignored for PACKAGE_SUMMARY, in which case totalweight and packageCount on the shipment will be used to determine this value.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Dimensions" type="ns:Dimensions" minOccurs="0"/>
+          <xs:element name="PhysicalPackaging" type="ns:PhysicalPackagingType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Provides additional detail on how the customer has physically packaged this item. As of June 2009, required for packages moving under international and SmartPost services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ItemDescription" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Human-readable text describing the package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomerReferences" type="ns:CustomerReference" minOccurs="0" maxOccurs="3"/>
+          <xs:element name="SpecialServicesRequested" type="ns:PackageSpecialServicesRequested" minOccurs="0"/>
+          <xs:element name="ContentRecords" type="ns:ContentRecord" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Only used for INDIVIDUAL_PACKAGES and PACKAGE_GROUPS.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="RequestedShipment">
+        <xs:annotation>
+          <xs:documentation>The descriptive data for the shipment being tendered to FedEx.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="ShipTimestamp" type="xs:dateTime" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the date and time the package is tendered to FedEx. Both the date and time portions of the string are expected to be used. The date should not be a past date or a date more than 10 days in the future. The time is the local time of the shipment based on the shipper's time zone. The date component must be in the format: YYYY-MM-DD (e.g. 2006-06-26). The time component must be in the format: HH:MM:SS using a 24 hour clock (e.g. 11:00 a.m. is 11:00:00, whereas 5:00 p.m. is 17:00:00). The date and time parts are separated by the letter T (e.g. 2006-06-26T17:00:00). There is also a UTC offset component indicating the number of hours/mainutes from UTC (e.g 2006-06-26T17:00:00-0400 is defined form June 26, 2006 5:00 pm Eastern Time).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DropoffType" type="ns:DropoffType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the method by which the package is to be tendered to FedEx. This element does not dispatch a courier for package pickup. See DropoffType for list of valid enumerated values.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ServiceType" type="ns:ServiceType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the FedEx service to use in shipping the package. See ServiceType for list of valid enumerated values.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PackagingType" type="ns:PackagingType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the packaging used by the requestor for the package. See PackagingType for list of valid enumerated values.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalWeight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the total weight of the shipment being conveyed to FedEx.This is only applicable to International shipments and should only be used on the first package of a mutiple piece shipment.This value contains 1 explicit decimal position</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalInsuredValue" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Total insured amount.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Shipper" type="ns:Party" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data identifying the party responsible for shipping the package. Shipper and Origin should have the same address.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Recipient" type="ns:Party" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data identifying the party receiving the package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RecipientLocationNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>A unique identifier for a recipient location</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>10</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Origin" type="ns:ContactAndAddress" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Physical starting address for the shipment, if different from shipper's address.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ShippingChargesPayment" type="ns:Payment" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data indicating the method and means of payment to FedEx for providing shipping services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SpecialServicesRequested" type="ns:ShipmentSpecialServicesRequested" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data regarding special services requested by the shipper for this shipment. If the shipper is requesting a special service which requires additional data (e.g. COD), the special service type must be present in the specialServiceTypes collection, and the supporting detail must be provided in the appropriate sub-object. For example, to request COD, "COD" must be included in the SpecialServiceTypes collection and the CodDetail object must contain the required data.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ExpressFreightDetail" type="ns:ExpressFreightDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Details specific to an Express freight shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FreightShipmentDetail" type="ns:FreightShipmentDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Data applicable to shipments using FEDEX_FREIGHT and FEDEX_NATIONAL_FREIGHT services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DeliveryInstructions" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Used with Ground Home Delivery and Freight.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="VariableHandlingChargeDetail" type="ns:VariableHandlingChargeDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Details about how to calculate variable handling charges at the shipment level.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomsClearanceDetail" type="ns:CustomsClearanceDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Customs clearance data, used for both international and intra-country shipping.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PickupDetail" type="ns:PickupDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>For use in "process tag" transaction.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SmartPostDetail" type="ns:SmartPostShipmentDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies the characteristics of a shipment pertaining to SmartPost services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BlockInsightVisibility" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>If true, only the shipper/payor will have visibility of this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LabelSpecification" type="ns:LabelSpecification" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Details about the image format and printer type the label is to returned in.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ShippingDocumentSpecification" type="ns:ShippingDocumentSpecification" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Contains data used to create additional (non-label) shipping documents.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RateRequestTypes" type="ns:RateRequestType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies whether and what kind of rates the customer wishes to have quoted on this shipment. The reply will also be constrained by other data on the shipment and customer.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EdtRequestType" type="ns:EdtRequestType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies whether the customer wishes to have Estimated Duties and Taxes provided with the rate quotation on this shipment. Only applies with shipments moving under international services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PackageCount" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The total number of packages in the entire shipment (even when the shipment spans multiple transactions.)</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ShipmentOnlyFields" type="ns:ShipmentOnlyFieldsType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies which package-level data values are provided at the shipment-level only. The package-level data values types specified here will not be provided at the package-level.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RequestedPackageLineItems" type="ns:RequestedPackageLineItem" minOccurs="0" maxOccurs="999">
+            <xs:annotation>
+              <xs:documentation>One or more package-attribute descriptions, each of which describes an individual package, a group of identical packages, or (for the total-piece-total-weight case) common characteristics all packages in the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="RequestedShippingDocumentType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CERTIFICATE_OF_ORIGIN"/>
+          <xs:enumeration value="COMMERCIAL_INVOICE"/>
+          <xs:enumeration value="CUSTOMER_SPECIFIED_LABELS"/>
+          <xs:enumeration value="GENERAL_AGENCY_AGREEMENT"/>
+          <xs:enumeration value="LABEL"/>
+          <xs:enumeration value="NAFTA_CERTIFICATE_OF_ORIGIN"/>
+          <xs:enumeration value="PRO_FORMA_INVOICE"/>
+          <xs:enumeration value="RETURN_INSTRUCTIONS"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="RequiredShippingDocumentType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CANADIAN_B13A"/>
+          <xs:enumeration value="CERTIFICATE_OF_ORIGIN"/>
+          <xs:enumeration value="COMMERCIAL_INVOICE"/>
+          <xs:enumeration value="INTERNATIONAL_AIRWAY_BILL"/>
+          <xs:enumeration value="MAIL_SERVICE_AIRWAY_BILL"/>
+          <xs:enumeration value="SHIPPERS_EXPORT_DECLARATION"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="ReturnEMailAllowedSpecialServiceType">
+        <xs:annotation>
+          <xs:documentation>These values are used to control the availability of certain special services at the time when a customer uses the e-mail label link to create a return shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="SATURDAY_DELIVERY"/>
+          <xs:enumeration value="SATURDAY_PICKUP"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="ReturnEMailDetail">
+        <xs:sequence>
+          <xs:element name="MerchantPhoneNumber" type="xs:string" minOccurs="0"/>
+          <xs:element name="AllowedSpecialServices" type="ns:ReturnEMailAllowedSpecialServiceType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Identifies the allowed (merchant-authorized) special services which may be selected when the subsequent shipment is created. Only services represented in EMailLabelAllowedSpecialServiceType will be controlled by this list.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ReturnShipmentDetail">
+        <xs:annotation>
+          <xs:documentation>Information relating to a return shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="ReturnType" type="ns:ReturnType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The type of return shipment that is being requested. At present the only type of retrun shipment that is supported is PRINT_RETURN_LABEL. With this option you can print a return label to insert into the box of an outbound shipment. This option can not be used to print an outbound label.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Rma" type="ns:Rma" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Return Merchant Authorization</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ReturnEMailDetail" type="ns:ReturnEMailDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specific information about the delivery of the email and options for the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="ReturnType">
+        <xs:annotation>
+          <xs:documentation>The type of return shipment that is being requested.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="FEDEX_TAG"/>
+          <xs:enumeration value="PENDING"/>
+          <xs:enumeration value="PRINT_RETURN_LABEL"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="ReturnedRateType">
+        <xs:annotation>
+          <xs:documentation>The "PAYOR..." rates are expressed in the currency identified in the payor's rate table(s). The "RATED..." rates are expressed in the currency of the origin country. Former "...COUNTER..." values have become "...RETAIL..." values, except for PAYOR_COUNTER and RATED_COUNTER, which have been removed.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="PAYOR_ACCOUNT_PACKAGE"/>
+          <xs:enumeration value="PAYOR_ACCOUNT_SHIPMENT"/>
+          <xs:enumeration value="PAYOR_LIST_PACKAGE"/>
+          <xs:enumeration value="PAYOR_LIST_SHIPMENT"/>
+          <xs:enumeration value="RATED_ACCOUNT_PACKAGE"/>
+          <xs:enumeration value="RATED_ACCOUNT_SHIPMENT"/>
+          <xs:enumeration value="RATED_LIST_PACKAGE"/>
+          <xs:enumeration value="RATED_LIST_SHIPMENT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Rma">
+        <xs:annotation>
+          <xs:documentation>Return Merchant Authorization</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Number" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Return Merchant Authorization Number</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>20</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Reason" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The reason for the return.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>60</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="SecondaryBarcodeType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="COMMON_2D"/>
+          <xs:enumeration value="NONE"/>
+          <xs:enumeration value="SSCC_18"/>
+          <xs:enumeration value="USPS"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="ServiceOptionType">
+        <xs:annotation>
+          <xs:documentation>These values control the optional features of service that may be combined in a commitment/rate comparision transaction.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="FREIGHT_GUARANTEE"/>
+          <xs:enumeration value="SATURDAY_DELIVERY"/>
+          <xs:enumeration value="SMART_POST_ALLOWED_INDICIA"/>
+          <xs:enumeration value="SMART_POST_HUB_ID"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="ServiceSubOptionDetail">
+        <xs:annotation>
+          <xs:documentation>Supporting detail for applied options identified in a rate quote.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="FreightGuarantee" type="ns:FreightGuaranteeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the type of Freight Guarantee applied, if FREIGHT_GUARANTEE is applied to the rate quote.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SmartPostHubId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the smartPostHubId used during rate quote, if SMART_POST_HUB_ID is a variable option on the rate request.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SmartPostIndicia" type="ns:SmartPostIndiciaType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the indicia used during rate quote, if SMART_POST_ALLOWED_INDICIA is a variable option on the rate request.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="ServiceType">
+        <xs:annotation>
+          <xs:documentation>Identifies the FedEx service to use in shipping the package. See ServiceType for list of valid enumerated values.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="EUROPE_FIRST_INTERNATIONAL_PRIORITY"/>
+          <xs:enumeration value="FEDEX_1_DAY_FREIGHT"/>
+          <xs:enumeration value="FEDEX_2_DAY"/>
+          <xs:enumeration value="FEDEX_2_DAY_AM"/>
+          <xs:enumeration value="FEDEX_2_DAY_FREIGHT"/>
+          <xs:enumeration value="FEDEX_3_DAY_FREIGHT"/>
+          <xs:enumeration value="FEDEX_EXPRESS_SAVER"/>
+          <xs:enumeration value="FEDEX_FIRST_FREIGHT"/>
+          <xs:enumeration value="FEDEX_FREIGHT_ECONOMY"/>
+          <xs:enumeration value="FEDEX_FREIGHT_PRIORITY"/>
+          <xs:enumeration value="FEDEX_GROUND"/>
+          <xs:enumeration value="FIRST_OVERNIGHT"/>
+          <xs:enumeration value="GROUND_HOME_DELIVERY"/>
+          <xs:enumeration value="INTERNATIONAL_ECONOMY"/>
+          <xs:enumeration value="INTERNATIONAL_ECONOMY_FREIGHT"/>
+          <xs:enumeration value="INTERNATIONAL_FIRST"/>
+          <xs:enumeration value="INTERNATIONAL_PRIORITY"/>
+          <xs:enumeration value="INTERNATIONAL_PRIORITY_FREIGHT"/>
+          <xs:enumeration value="PRIORITY_OVERNIGHT"/>
+          <xs:enumeration value="SMART_POST"/>
+          <xs:enumeration value="STANDARD_OVERNIGHT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="ShipmentDryIceDetail">
+        <xs:annotation>
+          <xs:documentation>Shipment-level totals of dry ice data across all packages.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="PackageCount" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Total number of packages in the shipment that contain dry ice.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalWeight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Total shipment dry ice weight for all packages.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ShipmentLegRateDetail">
+        <xs:annotation>
+          <xs:documentation>Data for a single leg of a shipment's total/summary rates, as calculated per a specific rate type.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="LegDescription" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Human-readable text describing the shipment leg.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LegOrigin" type="ns:Address" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Origin for this leg.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LegDestination" type="ns:Address" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Destination for this leg.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RateType" type="ns:ReturnedRateType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Type used for this specific set of rate data.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RateScale" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates the rate scale used.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RateZone" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates the rate zone used (based on origin and destination).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PricingCode" type="ns:PricingCodeType" minOccurs="0"/>
+          <xs:element name="RatedWeightMethod" type="ns:RatedWeightMethod" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates which weight was used.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="MinimumChargeType" type="ns:MinimumChargeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>INTERNAL FEDEX USE ONLY.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CurrencyExchangeRate" type="ns:CurrencyExchangeRate" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies the currency exchange performed on financial amounts for this rate.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SpecialRatingApplied" type="ns:SpecialRatingAppliedType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Indicates which special rating cases applied to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DimDivisor" type="xs:nonNegativeInteger" minOccurs="0"/>
+          <xs:element name="DimDivisorType" type="ns:RateDimensionalDivisorType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the type of dim divisor that was applied.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FuelSurchargePercent" type="xs:decimal" minOccurs="0"/>
+          <xs:element name="TotalBillingWeight" type="ns:Weight" minOccurs="0"/>
+          <xs:element name="TotalDimWeight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Sum of dimensional weights for all packages.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalBaseCharge" type="ns:Money" minOccurs="0"/>
+          <xs:element name="TotalFreightDiscounts" type="ns:Money" minOccurs="0"/>
+          <xs:element name="TotalNetFreight" type="ns:Money" minOccurs="0"/>
+          <xs:element name="TotalSurcharges" type="ns:Money" minOccurs="0"/>
+          <xs:element name="TotalNetFedExCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This shipment's totalNetFreight + totalSurcharges (not including totalTaxes).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalTaxes" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Total of the transportation-based taxes.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalNetCharge" type="ns:Money" minOccurs="0"/>
+          <xs:element name="TotalRebates" type="ns:Money" minOccurs="0"/>
+          <xs:element name="TotalDutiesAndTaxes" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Total of all values under this shipment's dutiesAndTaxes; only provided if estimated duties and taxes were calculated for this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalNetChargeWithDutiesAndTaxes" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This shipment's totalNetCharge + totalDutiesAndTaxes; only provided if estimated duties and taxes were calculated for this shipment AND duties, taxes and transportation charges are all paid by the same sender's account.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FreightRateDetail" type="ns:FreightRateDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Rate data specific to FedEx Freight and FedEx National Freight services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FreightDiscounts" type="ns:RateDiscount" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All rate discounts that apply to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Rebates" type="ns:Rebate" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All rebates that apply to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Surcharges" type="ns:Surcharge" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All surcharges that apply to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Taxes" type="ns:Tax" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All transportation-based taxes applicable to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DutiesAndTaxes" type="ns:EdtCommodityTax" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All commodity-based duties and taxes applicable to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="VariableHandlingCharges" type="ns:VariableHandlingCharges" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The "order level" variable handling charges.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalVariableHandlingCharges" type="ns:VariableHandlingCharges" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The total of all variable handling charges at both shipment (order) and package level.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="ShipmentOnlyFieldsType">
+        <xs:annotation>
+          <xs:documentation>These values identify which package-level data values will be provided at the shipment-level.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="DIMENSIONS"/>
+          <xs:enumeration value="INSURED_VALUE"/>
+          <xs:enumeration value="WEIGHT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="ShipmentRateDetail">
+        <xs:annotation>
+          <xs:documentation>Data for a shipment's total/summary rates, as calculated per a specific rate type. The "total..." fields may differ from the sum of corresponding package data for Multiweight or Express MPS.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="RateType" type="ns:ReturnedRateType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Type used for this specific set of rate data.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RateScale" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates the rate scale used.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RateZone" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates the rate zone used (based on origin and destination).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PricingCode" type="ns:PricingCodeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates the type of pricing used for this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RatedWeightMethod" type="ns:RatedWeightMethod" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates which weight was used.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="MinimumChargeType" type="ns:MinimumChargeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>INTERNAL FEDEX USE ONLY.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CurrencyExchangeRate" type="ns:CurrencyExchangeRate" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies the currency exchange performed on financial amounts for this rate.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SpecialRatingApplied" type="ns:SpecialRatingAppliedType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Indicates which special rating cases applied to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DimDivisor" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The value used to calculate the weight based on the dimensions.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DimDivisorType" type="ns:RateDimensionalDivisorType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the type of dim divisor that was applied.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FuelSurchargePercent" type="xs:decimal" minOccurs="0"/>
+          <xs:element name="TotalBillingWeight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The weight used to calculate these rates.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalDimWeight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Sum of dimensional weights for all packages.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalBaseCharge" type="ns:Money" minOccurs="0"/>
+          <xs:element name="TotalFreightDiscounts" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The total discounts used in the rate calculation.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalNetFreight" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The freight charge minus discounts.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalSurcharges" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The total amount of all surcharges applied to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalNetFedExCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This shipment's totalNetFreight + totalSurcharges (not including totalTaxes).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalTaxes" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Total of the transportation-based taxes.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalNetCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The net charge after applying all discounts and surcharges.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalRebates" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The total sum of all rebates applied to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalDutiesAndTaxes" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Total of all values under this shipment's dutiesAndTaxes; only provided if estimated duties and taxes were calculated for this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalNetChargeWithDutiesAndTaxes" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This shipment's totalNetCharge + totalDutiesAndTaxes; only provided if estimated duties and taxes were calculated for this shipment AND duties, taxes and transportation charges are all paid by the same sender's account.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ShipmentLegRateDetails" type="ns:ShipmentLegRateDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Identifies the Rate Details per each leg in a Freight Shipment</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FreightRateDetail" type="ns:FreightRateDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Rate data specific to FedEx Freight and FedEx National Freight services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FreightDiscounts" type="ns:RateDiscount" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All rate discounts that apply to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Rebates" type="ns:Rebate" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All rebates that apply to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Surcharges" type="ns:Surcharge" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All surcharges that apply to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Taxes" type="ns:Tax" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All transportation-based taxes applicable to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DutiesAndTaxes" type="ns:EdtCommodityTax" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All commodity-based duties and taxes applicable to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="VariableHandlingCharges" type="ns:VariableHandlingCharges" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The "order level" variable handling charges.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalVariableHandlingCharges" type="ns:VariableHandlingCharges" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The total of all variable handling charges at both shipment (order) and package level.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="ShipmentSpecialServiceType">
+        <xs:annotation>
+          <xs:documentation>Identifies the collection of special service offered by FedEx.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BROKER_SELECT_OPTION"/>
+          <xs:enumeration value="CALL_BEFORE_DELIVERY"/>
+          <xs:enumeration value="COD"/>
+          <xs:enumeration value="CUSTOM_DELIVERY_WINDOW"/>
+          <xs:enumeration value="DANGEROUS_GOODS"/>
+          <xs:enumeration value="DO_NOT_BREAK_DOWN_PALLETS"/>
+          <xs:enumeration value="DO_NOT_STACK_PALLETS"/>
+          <xs:enumeration value="DRY_ICE"/>
+          <xs:enumeration value="EAST_COAST_SPECIAL"/>
+          <xs:enumeration value="ELECTRONIC_TRADE_DOCUMENTS"/>
+          <xs:enumeration value="EMAIL_NOTIFICATION"/>
+          <xs:enumeration value="EXTREME_LENGTH"/>
+          <xs:enumeration value="FOOD"/>
+          <xs:enumeration value="FREIGHT_GUARANTEE"/>
+          <xs:enumeration value="FUTURE_DAY_SHIPMENT"/>
+          <xs:enumeration value="HOLD_AT_LOCATION"/>
+          <xs:enumeration value="HOME_DELIVERY_PREMIUM"/>
+          <xs:enumeration value="INSIDE_DELIVERY"/>
+          <xs:enumeration value="INSIDE_PICKUP"/>
+          <xs:enumeration value="LIFTGATE_DELIVERY"/>
+          <xs:enumeration value="LIFTGATE_PICKUP"/>
+          <xs:enumeration value="LIMITED_ACCESS_DELIVERY"/>
+          <xs:enumeration value="LIMITED_ACCESS_PICKUP"/>
+          <xs:enumeration value="PENDING_SHIPMENT"/>
+          <xs:enumeration value="POISON"/>
+          <xs:enumeration value="PROTECTION_FROM_FREEZING"/>
+          <xs:enumeration value="RETURN_SHIPMENT"/>
+          <xs:enumeration value="SATURDAY_DELIVERY"/>
+          <xs:enumeration value="SATURDAY_PICKUP"/>
+          <xs:enumeration value="TOP_LOAD"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="ShipmentSpecialServicesRequested">
+        <xs:annotation>
+          <xs:documentation>These special services are available at the shipment level for some or all service types. If the shipper is requesting a special service which requires additional data (such as the COD amount), the shipment special service type must be present in the specialServiceTypes collection, and the supporting detail must be provided in the appropriate sub-object below.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="SpecialServiceTypes" type="ns:ShipmentSpecialServiceType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>The types of all special services requested for the enclosing shipment (or other shipment-level transaction).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CodDetail" type="ns:CodDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data required for a FedEx COD (Collect-On-Delivery) shipment. This element is required when SpecialServiceType.COD is present in the SpecialServiceTypes collection.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="HoldAtLocationDetail" type="ns:HoldAtLocationDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data required for a FedEx shipment that is to be held at the destination FedEx location for pickup by the recipient. This element is required when SpecialServiceType.HOLD_AT_LOCATION is present in the SpecialServiceTypes collection.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EMailNotificationDetail" type="ns:EMailNotificationDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data required for FedEx to provide email notification to the customer regarding the shipment. This element is required when SpecialServiceType.EMAIL_NOTIFICATION is present in the SpecialServiceTypes collection.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ReturnShipmentDetail" type="ns:ReturnShipmentDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The descriptive data required for FedEx Printed Return Label. This element is required when SpecialServiceType.PRINTED_RETURN_LABEL is present in the SpecialServiceTypes collection</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PendingShipmentDetail" type="ns:PendingShipmentDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This field should be populated for pending shipments (e.g. e-mail label) It is required by a PENDING_SHIPMENT special service type.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ShipmentDryIceDetail" type="ns:ShipmentDryIceDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The number of packages with dry ice and the total weight of the dry ice.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="HomeDeliveryPremiumDetail" type="ns:HomeDeliveryPremiumDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The descriptive data required for FedEx Home Delivery options. This element is required when SpecialServiceType.HOME_DELIVERY_PREMIUM is present in the SpecialServiceTypes collection</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FlatbedTrailerDetail" type="ns:FlatbedTrailerDetail" minOccurs="0"/>
+          <xs:element name="FreightGuaranteeDetail" type="ns:FreightGuaranteeDetail" minOccurs="0"/>
+          <xs:element name="EtdDetail" type="ns:EtdDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Electronic Trade document references.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomDeliveryWindowDetail" type="ns:CustomDeliveryWindowDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specification for date or range of dates on which delivery is to be attempted.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ShippingDocumentDispositionDetail">
+        <xs:annotation>
+          <xs:documentation>Each occurrence of this class specifies a particular way in which a kind of shipping document is to be produced and provided.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="DispositionType" type="ns:ShippingDocumentDispositionType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Values in this field specify how to create and return the document.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Grouping" type="ns:ShippingDocumentGroupingType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies how to organize all documents of this type.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EMailDetail" type="ns:ShippingDocumentEMailDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies how to e-mail document images.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PrintDetail" type="ns:ShippingDocumentPrintDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies how a queued document is to be printed.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="ShippingDocumentDispositionType">
+        <xs:annotation>
+          <xs:documentation>Specifies how to return a shipping document to the caller.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CONFIRMED"/>
+          <xs:enumeration value="DEFERRED_RETURNED"/>
+          <xs:enumeration value="DEFERRED_STORED"/>
+          <xs:enumeration value="EMAILED"/>
+          <xs:enumeration value="QUEUED"/>
+          <xs:enumeration value="RETURNED"/>
+          <xs:enumeration value="STORED"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="ShippingDocumentEMailDetail">
+        <xs:annotation>
+          <xs:documentation>Specifies how to e-mail shipping documents.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="EMailRecipients" type="ns:ShippingDocumentEMailRecipient" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Provides the roles and email addresses for e-mail recipients.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Grouping" type="ns:ShippingDocumentEMailGroupingType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the convention by which documents are to be grouped as e-mail attachments.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="ShippingDocumentEMailGroupingType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BY_RECIPIENT"/>
+          <xs:enumeration value="NONE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="ShippingDocumentEMailRecipient">
+        <xs:annotation>
+          <xs:documentation>Specifies an individual recipient of e-mailed shipping document(s).</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="RecipientType" type="ns:EMailNotificationRecipientType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the relationship of this recipient in the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Address" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Address to which the document is to be sent.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ShippingDocumentFormat">
+        <xs:annotation>
+          <xs:documentation>Specifies characteristics of a shipping document to be produced.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Dispositions" type="ns:ShippingDocumentDispositionDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies how to create, organize, and return the document.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TopOfPageOffset" type="ns:LinearMeasure" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies how far down the page to move the beginning of the image; allows for printing on letterhead and other pre-printed stock.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ImageType" type="ns:ShippingDocumentImageType" minOccurs="0"/>
+          <xs:element name="StockType" type="ns:ShippingDocumentStockType" minOccurs="0"/>
+          <xs:element name="ProvideInstructions" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>For those shipping document types which have both a "form" and "instructions" component (e.g. NAFTA Certificate of Origin and General Agency Agreement), this field indicates whether to provide the instructions.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Localization" type="ns:Localization" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Governs the language to be used for this individual document, independently from other content returned for the same shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="ShippingDocumentGroupingType">
+        <xs:annotation>
+          <xs:documentation>Specifies how to organize all shipping documents of the same type.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CONSOLIDATED_BY_DOCUMENT_TYPE"/>
+          <xs:enumeration value="INDIVIDUAL"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="ShippingDocumentImageType">
+        <xs:annotation>
+          <xs:documentation>Specifies the image format used for a shipping document.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="DPL"/>
+          <xs:enumeration value="EPL2"/>
+          <xs:enumeration value="PDF"/>
+          <xs:enumeration value="PNG"/>
+          <xs:enumeration value="ZPLII"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="ShippingDocumentPrintDetail">
+        <xs:annotation>
+          <xs:documentation>Specifies printing options for a shipping document.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="PrinterId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Provides environment-specific printer identification.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ShippingDocumentSpecification">
+        <xs:annotation>
+          <xs:documentation>Contains all data required for additional (non-label) shipping documents to be produced in conjunction with a specific shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="ShippingDocumentTypes" type="ns:RequestedShippingDocumentType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Indicates the types of shipping documents requested by the shipper.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CertificateOfOrigin" type="ns:CertificateOfOriginDetail" minOccurs="0"/>
+          <xs:element name="CommercialInvoiceDetail" type="ns:CommercialInvoiceDetail" minOccurs="0"/>
+          <xs:element name="CustomPackageDocumentDetail" type="ns:CustomDocumentDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies the production of each package-level custom document (the same specification is used for all packages).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomShipmentDocumentDetail" type="ns:CustomDocumentDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies the production of a shipment-level custom document.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="GeneralAgencyAgreementDetail" type="ns:GeneralAgencyAgreementDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Details pertaining to the GAA.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NaftaCertificateOfOriginDetail" type="ns:NaftaCertificateOfOriginDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Details pertaining to NAFTA COO.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Op900Detail" type="ns:Op900Detail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies the production of the OP-900 document for hazardous materials packages.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="ShippingDocumentStockType">
+        <xs:annotation>
+          <xs:documentation>Specifies the type of paper (stock) on which a document will be printed.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="OP_900_LG_B"/>
+          <xs:enumeration value="OP_900_LL_B"/>
+          <xs:enumeration value="PAPER_4X6"/>
+          <xs:enumeration value="PAPER_LETTER"/>
+          <xs:enumeration value="STOCK_4X6"/>
+          <xs:enumeration value="STOCK_4X6.75_LEADING_DOC_TAB"/>
+          <xs:enumeration value="STOCK_4X6.75_TRAILING_DOC_TAB"/>
+          <xs:enumeration value="STOCK_4X8"/>
+          <xs:enumeration value="STOCK_4X9_LEADING_DOC_TAB"/>
+          <xs:enumeration value="STOCK_4X9_TRAILING_DOC_TAB"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="SignatureOptionDetail">
+        <xs:annotation>
+          <xs:documentation>The descriptive data required for FedEx delivery signature services.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="OptionType" type="ns:SignatureOptionType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the delivery signature services option selected by the customer for this shipment. See OptionType for the list of valid values.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SignatureReleaseNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the delivery signature release authorization number.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>10</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="SignatureOptionType">
+        <xs:annotation>
+          <xs:documentation>Identifies the delivery signature services options offered by FedEx.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ADULT"/>
+          <xs:enumeration value="DIRECT"/>
+          <xs:enumeration value="INDIRECT"/>
+          <xs:enumeration value="NO_SIGNATURE_REQUIRED"/>
+          <xs:enumeration value="SERVICE_DEFAULT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="SmartPostAncillaryEndorsementType">
+        <xs:annotation>
+          <xs:documentation>These values are mutually exclusive; at most one of them can be attached to a SmartPost shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ADDRESS_CORRECTION"/>
+          <xs:enumeration value="CARRIER_LEAVE_IF_NO_RESPONSE"/>
+          <xs:enumeration value="CHANGE_SERVICE"/>
+          <xs:enumeration value="FORWARDING_SERVICE"/>
+          <xs:enumeration value="RETURN_SERVICE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="SmartPostIndiciaType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="MEDIA_MAIL"/>
+          <xs:enumeration value="PARCEL_RETURN"/>
+          <xs:enumeration value="PARCEL_SELECT"/>
+          <xs:enumeration value="PRESORTED_BOUND_PRINTED_MATTER"/>
+          <xs:enumeration value="PRESORTED_STANDARD"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="SmartPostShipmentDetail">
+        <xs:annotation>
+          <xs:documentation>Data required for shipments handled under the SMART_POST and GROUND_SMART_POST service types.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Indicia" type="ns:SmartPostIndiciaType" minOccurs="0"/>
+          <xs:element name="AncillaryEndorsement" type="ns:SmartPostAncillaryEndorsementType" minOccurs="0"/>
+          <xs:element name="HubId" type="xs:string" minOccurs="0"/>
+          <xs:element name="CustomerManifestId" type="xs:string" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="SpecialRatingAppliedType">
+        <xs:annotation>
+          <xs:documentation>Indicates which special rating cases applied to this shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="FIXED_FUEL_SURCHARGE"/>
+          <xs:enumeration value="IMPORT_PRICING"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Surcharge">
+        <xs:annotation>
+          <xs:documentation>Identifies each surcharge applied to the shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="SurchargeType" type="ns:SurchargeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The type of surcharge applied to the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Level" type="ns:SurchargeLevelType" minOccurs="0"/>
+          <xs:element name="Description" type="xs:string" minOccurs="0"/>
+          <xs:element name="Amount" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The amount of the surcharge applied to the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="SurchargeLevelType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="PACKAGE"/>
+          <xs:enumeration value="SHIPMENT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="SurchargeType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ADDITIONAL_HANDLING"/>
+          <xs:enumeration value="ANCILLARY_FEE"/>
+          <xs:enumeration value="APPOINTMENT_DELIVERY"/>
+          <xs:enumeration value="BROKER_SELECT_OPTION"/>
+          <xs:enumeration value="CANADIAN_DESTINATION"/>
+          <xs:enumeration value="CLEARANCE_ENTRY_FEE"/>
+          <xs:enumeration value="COD"/>
+          <xs:enumeration value="CUT_FLOWERS"/>
+          <xs:enumeration value="DANGEROUS_GOODS"/>
+          <xs:enumeration value="DELIVERY_AREA"/>
+          <xs:enumeration value="DELIVERY_CONFIRMATION"/>
+          <xs:enumeration value="DOCUMENTATION_FEE"/>
+          <xs:enumeration value="DRY_ICE"/>
+          <xs:enumeration value="EMAIL_LABEL"/>
+          <xs:enumeration value="EUROPE_FIRST"/>
+          <xs:enumeration value="EXCESS_VALUE"/>
+          <xs:enumeration value="EXHIBITION"/>
+          <xs:enumeration value="EXPORT"/>
+          <xs:enumeration value="EXTREME_LENGTH"/>
+          <xs:enumeration value="FEDEX_TAG"/>
+          <xs:enumeration value="FICE"/>
+          <xs:enumeration value="FLATBED"/>
+          <xs:enumeration value="FREIGHT_GUARANTEE"/>
+          <xs:enumeration value="FREIGHT_ON_VALUE"/>
+          <xs:enumeration value="FUEL"/>
+          <xs:enumeration value="HOLD_AT_LOCATION"/>
+          <xs:enumeration value="HOME_DELIVERY_APPOINTMENT"/>
+          <xs:enumeration value="HOME_DELIVERY_DATE_CERTAIN"/>
+          <xs:enumeration value="HOME_DELIVERY_EVENING"/>
+          <xs:enumeration value="INSIDE_DELIVERY"/>
+          <xs:enumeration value="INSIDE_PICKUP"/>
+          <xs:enumeration value="INSURED_VALUE"/>
+          <xs:enumeration value="INTERHAWAII"/>
+          <xs:enumeration value="LIFTGATE_DELIVERY"/>
+          <xs:enumeration value="LIFTGATE_PICKUP"/>
+          <xs:enumeration value="LIMITED_ACCESS_DELIVERY"/>
+          <xs:enumeration value="LIMITED_ACCESS_PICKUP"/>
+          <xs:enumeration value="METRO_DELIVERY"/>
+          <xs:enumeration value="METRO_PICKUP"/>
+          <xs:enumeration value="NON_MACHINABLE"/>
+          <xs:enumeration value="OFFSHORE"/>
+          <xs:enumeration value="ON_CALL_PICKUP"/>
+          <xs:enumeration value="OTHER"/>
+          <xs:enumeration value="OUT_OF_DELIVERY_AREA"/>
+          <xs:enumeration value="OUT_OF_PICKUP_AREA"/>
+          <xs:enumeration value="OVERSIZE"/>
+          <xs:enumeration value="OVER_DIMENSION"/>
+          <xs:enumeration value="PIECE_COUNT_VERIFICATION"/>
+          <xs:enumeration value="PRE_DELIVERY_NOTIFICATION"/>
+          <xs:enumeration value="PRIORITY_ALERT"/>
+          <xs:enumeration value="PROTECTION_FROM_FREEZING"/>
+          <xs:enumeration value="REGIONAL_MALL_DELIVERY"/>
+          <xs:enumeration value="REGIONAL_MALL_PICKUP"/>
+          <xs:enumeration value="RESIDENTIAL_DELIVERY"/>
+          <xs:enumeration value="RESIDENTIAL_PICKUP"/>
+          <xs:enumeration value="RETURN_LABEL"/>
+          <xs:enumeration value="SATURDAY_DELIVERY"/>
+          <xs:enumeration value="SATURDAY_PICKUP"/>
+          <xs:enumeration value="SIGNATURE_OPTION"/>
+          <xs:enumeration value="TARP"/>
+          <xs:enumeration value="THIRD_PARTY_CONSIGNEE"/>
+          <xs:enumeration value="TRANSMART_SERVICE_FEE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Tax">
+        <xs:annotation>
+          <xs:documentation>Identifies each tax applied to the shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="TaxType" type="ns:TaxType" minOccurs="0"/>
+          <xs:element name="Description" type="xs:string" minOccurs="0"/>
+          <xs:element name="Amount" type="ns:Money" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="TaxType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="EXPORT"/>
+          <xs:enumeration value="GST"/>
+          <xs:enumeration value="HST"/>
+          <xs:enumeration value="INTRACOUNTRY"/>
+          <xs:enumeration value="OTHER"/>
+          <xs:enumeration value="PST"/>
+          <xs:enumeration value="VAT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="TaxesOrMiscellaneousChargeType">
+        <xs:annotation>
+          <xs:documentation>Specifice the kind of tax or miscellaneous charge being reported on a Commercial Invoice.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="COMMISSIONS"/>
+          <xs:enumeration value="DISCOUNTS"/>
+          <xs:enumeration value="HANDLING_FEES"/>
+          <xs:enumeration value="OTHER"/>
+          <xs:enumeration value="ROYALTIES_AND_LICENSE_FEES"/>
+          <xs:enumeration value="TAXES"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="TaxpayerIdentification">
+        <xs:annotation>
+          <xs:documentation>The descriptive data for taxpayer identification information.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="TinType" type="ns:TinType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the category of the taxpayer identification number. See TinType for the list of values.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Number" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the taxpayer identification number.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>18</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Usage" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the usage of Tax Identification Number in Shipment processing</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="TermsOfSaleType">
+        <xs:annotation>
+          <xs:documentation>
+            Required for dutiable international express or ground shipment. This field is not applicable to an international PIB (document) or a non-document which does not require a commercial invoice express shipment.
+            CFR_OR_CPT (Cost and Freight/Carriage Paid TO)
+            CIF_OR_CIP (Cost Insurance and Freight/Carraige Insurance Paid)
+            DDP (Delivered Duty Paid)
+            DDU (Delivered Duty Unpaid)
+            EXW (Ex Works)
+            FOB_OR_FCA (Free On Board/Free Carrier)
+          </xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CFR_OR_CPT"/>
+          <xs:enumeration value="CIF_OR_CIP"/>
+          <xs:enumeration value="DDP"/>
+          <xs:enumeration value="DDU"/>
+          <xs:enumeration value="EXW"/>
+          <xs:enumeration value="FOB_OR_FCA"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="TinType">
+        <xs:annotation>
+          <xs:documentation>Identifies the category of the taxpayer identification number.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BUSINESS_NATIONAL"/>
+          <xs:enumeration value="BUSINESS_STATE"/>
+          <xs:enumeration value="PERSONAL_NATIONAL"/>
+          <xs:enumeration value="PERSONAL_STATE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="TrackingId">
+        <xs:sequence>
+          <xs:element name="TrackingIdType" type="ns:TrackingIdType" minOccurs="0"/>
+          <xs:element name="FormId" type="xs:string" minOccurs="0"/>
+          <xs:element name="TrackingNumber" type="xs:string" minOccurs="1"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="TrackingIdType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="EXPRESS"/>
+          <xs:enumeration value="FEDEX"/>
+          <xs:enumeration value="GROUND"/>
+          <xs:enumeration value="USPS"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="TransactionDetail">
+        <xs:annotation>
+          <xs:documentation>Descriptive data for this customer transaction. The TransactionDetail from the request is echoed back to the caller in the corresponding reply.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="CustomerTransactionId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Free form text to be echoed back in the reply. Used to match requests and replies.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Localization" type="ns:Localization" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Governs data payload language/translations (contrasted with ClientDetail.localization, which governs Notification.localizedMessage language selection).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="TransitTimeType">
+        <xs:annotation>
+          <xs:documentation>Time in transit from pickup to delivery.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="EIGHTEEN_DAYS"/>
+          <xs:enumeration value="EIGHT_DAYS"/>
+          <xs:enumeration value="ELEVEN_DAYS"/>
+          <xs:enumeration value="FIFTEEN_DAYS"/>
+          <xs:enumeration value="FIVE_DAYS"/>
+          <xs:enumeration value="FOURTEEN_DAYS"/>
+          <xs:enumeration value="FOUR_DAYS"/>
+          <xs:enumeration value="NINETEEN_DAYS"/>
+          <xs:enumeration value="NINE_DAYS"/>
+          <xs:enumeration value="ONE_DAY"/>
+          <xs:enumeration value="SEVENTEEN_DAYS"/>
+          <xs:enumeration value="SEVEN_DAYS"/>
+          <xs:enumeration value="SIXTEEN_DAYS"/>
+          <xs:enumeration value="SIX_DAYS"/>
+          <xs:enumeration value="TEN_DAYS"/>
+          <xs:enumeration value="THIRTEEN_DAYS"/>
+          <xs:enumeration value="THREE_DAYS"/>
+          <xs:enumeration value="TWELVE_DAYS"/>
+          <xs:enumeration value="TWENTY_DAYS"/>
+          <xs:enumeration value="TWO_DAYS"/>
+          <xs:enumeration value="UNKNOWN"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="UploadDocumentDetail">
+        <xs:sequence>
+          <xs:element name="LineNumber" type="xs:nonNegativeInteger" minOccurs="0"/>
+          <xs:element name="CustomerReference" type="xs:string" minOccurs="0"/>
+          <xs:element name="DocumentProducer" type="ns:UploadDocumentProducerType" minOccurs="0"/>
+          <xs:element name="DocumentType" type="ns:UploadDocumentType" minOccurs="0"/>
+          <xs:element name="FileName" type="xs:string" minOccurs="0"/>
+          <xs:element name="DocumentContent" type="xs:base64Binary" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="UploadDocumentIdProducer">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CUSTOMER"/>
+          <xs:enumeration value="FEDEX_CSHP"/>
+          <xs:enumeration value="FEDEX_GTM"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="UploadDocumentProducerType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CUSTOMER"/>
+          <xs:enumeration value="FEDEX_CLS"/>
+          <xs:enumeration value="FEDEX_GTM"/>
+          <xs:enumeration value="OTHER"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="UploadDocumentReferenceDetail">
+        <xs:sequence>
+          <xs:element name="LineNumber" type="xs:nonNegativeInteger" minOccurs="0"/>
+          <xs:element name="CustomerReference" type="xs:string" minOccurs="0"/>
+          <xs:element name="DocumentProducer" type="ns:UploadDocumentProducerType" minOccurs="0"/>
+          <xs:element name="DocumentType" type="ns:UploadDocumentType" minOccurs="0"/>
+          <xs:element name="DocumentId" type="xs:string" minOccurs="0"/>
+          <xs:element name="DocumentIdProducer" type="ns:UploadDocumentIdProducer" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="UploadDocumentType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CERTIFICATE_OF_ORIGIN"/>
+          <xs:enumeration value="COMMERCIAL_INVOICE"/>
+          <xs:enumeration value="ETD_LABEL"/>
+          <xs:enumeration value="NAFTA_CERTIFICATE_OF_ORIGIN"/>
+          <xs:enumeration value="OTHER"/>
+          <xs:enumeration value="PRO_FORMA_INVOICE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="VariableHandlingChargeDetail">
+        <xs:annotation>
+          <xs:documentation>This definition of variable handling charge detail is intended for use in Jan 2011 corp load.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="FixedValue" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Used with Variable handling charge type of FIXED_VALUE. Contains the amount to be added to the freight charge. Contains 2 explicit decimal positions with a total max length of 10 including the decimal.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PercentValue" type="xs:decimal" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Actual percentage (10 means 10%, which is a mutiplier of 0.1)</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RateElementBasis" type="ns:RateElementBasisType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Select the value from a set of rate data to which the percentage is applied.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RateTypeBasis" type="ns:RateTypeBasisType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Select the type of rate from which the element is to be selected.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="VariableHandlingCharges">
+        <xs:annotation>
+          <xs:documentation>The variable handling charges calculated based on the type variable handling charges requested.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="VariableHandlingCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The variable handling charge amount calculated based on the requested variable handling charge detail.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalCustomerCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The calculated varibale handling charge plus the net charge.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="Volume">
+        <xs:annotation>
+          <xs:documentation>Three-dimensional volume/cubic measurement.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Units" type="ns:VolumeUnits" minOccurs="0"/>
+          <xs:element name="Value" type="xs:decimal" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="VolumeUnits">
+        <xs:annotation>
+          <xs:documentation>Units of three-dimensional volume/cubic measure.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CUBIC_FT"/>
+          <xs:enumeration value="CUBIC_M"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Weight">
+        <xs:annotation>
+          <xs:documentation>The descriptive data for the heaviness of an object.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Units" type="ns:WeightUnits" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the unit of measure associated with a weight value.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Value" type="xs:decimal" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the weight value of a package/shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="WeightUnits">
+        <xs:annotation>
+          <xs:documentation>Identifies the unit of measure associated with a weight value. See WeightUnits for the list of valid enumerated values.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="KG"/>
+          <xs:enumeration value="LB"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="WebAuthenticationDetail">
+        <xs:annotation>
+          <xs:documentation>Used in authentication of the sender's identity.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="UserCredential" type="ns:WebAuthenticationCredential" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Credential used to authenticate a specific software application. This value is provided by FedEx after registration.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="WebAuthenticationCredential">
+        <xs:annotation>
+          <xs:documentation>Two part authentication string used for the sender's identity</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Key" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifying part of authentication credential. This value is provided by FedEx after registration</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Password" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Secret part of authentication key. This value is provided by FedEx after registration.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="VersionId">
+        <xs:annotation>
+          <xs:documentation>Identifies the version/level of a service operation expected by a caller (in each request) and performed by the callee (in each reply).</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="ServiceId" type="xs:string" fixed="crs" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies a system or sub-system which performs an operation.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Major" type="xs:int" fixed="10" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the service business level.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Intermediate" type="xs:int" fixed="0" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the service interface level.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Minor" type="xs:int" fixed="0" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the service code level.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+    </xs:schema>
+  </types>
+  <message name="RateRequest">
+    <part name="RateRequest" element="ns:RateRequest"/>
+  </message>
+  <message name="RateReply">
+    <part name="RateReply" element="ns:RateReply"/>
+  </message>
+  <portType name="RatePortType">
+    <operation name="getRates" parameterOrder="RateRequest">
+      <input message="ns:RateRequest"/>
+      <output message="ns:RateReply"/>
+    </operation>
+  </portType>
+  <binding name="RateServiceSoapBinding" type="ns:RatePortType">
+    <s1:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
+    <operation name="getRates">
+      <s1:operation soapAction="getRates" style="document"/>
+      <input>
+        <s1:body use="literal"/>
+      </input>
+      <output>
+        <s1:body use="literal"/>
+      </output>
+    </operation>
+  </binding>
+  <service name="RateService">
+    <port name="RateServicePort" binding="ns:RateServiceSoapBinding">
+      <s1:address location="https://wsbeta.fedex.com:443/web-services/rate"/>
+    </port>
+  </service>
+</definitions>
\ No newline at end of file
diff --git a/app/code/core/Mage/Usa/etc/wsdl/FedEx/ShipService_v10.wsdl b/app/code/core/Mage/Usa/etc/wsdl/FedEx/ShipService_v10.wsdl
new file mode 100644
index 0000000000000000000000000000000000000000..aca35b6b052799edba7fd18e3a470692e5c52961
--- /dev/null
+++ b/app/code/core/Mage/Usa/etc/wsdl/FedEx/ShipService_v10.wsdl
@@ -0,0 +1,5472 @@
+<definitions xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:ns="http://fedex.com/ws/ship/v9"
+             xmlns:s1="http://schemas.xmlsoap.org/wsdl/soap/"
+             targetNamespace="http://fedex.com/ws/ship/v9" name="ShipServiceDefinitions">
+  <types>
+    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://fedex.com/ws/ship/v9">
+      <xs:element name="CancelPendingShipmentReply" type="ns:CancelPendingShipmentReply"/>
+      <xs:element name="CancelPendingShipmentRequest" type="ns:CancelPendingShipmentRequest"/>
+      <xs:element name="CreatePendingShipmentReply" type="ns:CreatePendingShipmentReply"/>
+      <xs:element name="CreatePendingShipmentRequest" type="ns:CreatePendingShipmentRequest"/>
+      <xs:element name="DeleteShipmentRequest" type="ns:DeleteShipmentRequest"/>
+      <xs:element name="DeleteTagRequest" type="ns:DeleteTagRequest"/>
+      <xs:element name="ProcessShipmentReply" type="ns:ProcessShipmentReply"/>
+      <xs:element name="ProcessShipmentRequest" type="ns:ProcessShipmentRequest"/>
+      <xs:element name="ProcessTagReply" type="ns:ProcessTagReply"/>
+      <xs:element name="ProcessTagRequest" type="ns:ProcessTagRequest"/>
+      <xs:element name="ShipmentReply" type="ns:ShipmentReply"/>
+      <xs:element name="ValidateShipmentRequest" type="ns:ValidateShipmentRequest"/>
+      <xs:complexType name="AdditionalLabelsDetail">
+        <xs:annotation>
+          <xs:documentation>Specifies additional labels to be produced. All required labels for shipments will be produced without the need to request additional labels. These are only available as thermal labels.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Type" type="ns:AdditionalLabelsType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The type of additional labels to return.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Count" type="xs:nonNegativeInteger" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The number of this type label to return</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="AdditionalLabelsType">
+        <xs:annotation>
+          <xs:documentation>Identifies the type of additional labels.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BROKER"/>
+          <xs:enumeration value="CONSIGNEE"/>
+          <xs:enumeration value="CUSTOMS"/>
+          <xs:enumeration value="DESTINATION"/>
+          <xs:enumeration value="FREIGHT_REFERENCE"/>
+          <xs:enumeration value="MANIFEST"/>
+          <xs:enumeration value="ORIGIN"/>
+          <xs:enumeration value="RECIPIENT"/>
+          <xs:enumeration value="SHIPPER"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Address">
+        <xs:annotation>
+          <xs:documentation>Descriptive data for a physical location. May be used as an actual physical address (place to which one could go), or as a container of "address parts" which should be handled as a unit (such as a city-state-ZIP combination within the US).</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="StreetLines" type="xs:string" minOccurs="0" maxOccurs="2">
+            <xs:annotation>
+              <xs:documentation>Combination of number, street name, etc. At least one line is required for a valid physical address; empty lines should not be included.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="City" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Name of city, town, etc.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="StateOrProvinceCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifying abbreviation for US state, Canada province, etc. Format and presence of this field will vary, depending on country.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PostalCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identification of a region (usually small) for mail/package delivery. Format and presence of this field will vary, depending on country.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="UrbanizationCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Relevant only to addresses in Puerto Rico.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CountryCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The two-letter code used to identify a country.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Residential" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates whether this address residential (as opposed to commercial).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="AstraLabelElement">
+        <xs:sequence>
+          <xs:element name="Number" type="xs:int" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Position of Astra element</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Content" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Content corresponding to the Astra Element</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="B13AFilingOptionType">
+        <xs:annotation>
+          <xs:documentation>
+            Specifies which filing option is being exercised by the customer.
+            Required for non-document shipments originating in Canada destined for any country other than Canada, the United States, Puerto Rico or the U.S. Virgin Islands.
+          </xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="FILED_ELECTRONICALLY"/>
+          <xs:enumeration value="MANUALLY_ATTACHED"/>
+          <xs:enumeration value="NOT_REQUIRED"/>
+          <xs:enumeration value="SUMMARY_REPORTING"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="BarcodeSymbologyType">
+        <xs:annotation>
+          <xs:documentation>Identification of the type of barcode (symbology) used on FedEx documents and labels.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CODE128B"/>
+          <xs:enumeration value="CODE128C"/>
+          <xs:enumeration value="CODE39"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="BinaryBarcode">
+        <xs:annotation>
+          <xs:documentation>Each instance of this data type represents a barcode whose content must be represented as binary data (i.e. not ASCII text).</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Type" type="ns:BinaryBarcodeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The kind of barcode data in this instance.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Value" type="xs:base64Binary" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The data content of this instance.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="BinaryBarcodeType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="COMMON_2D"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="CancelPendingShipmentReply">
+        <xs:sequence>
+          <xs:element name="HighestSeverity" type="ns:NotificationSeverityType" minOccurs="1"/>
+          <xs:element name="Notifications" type="ns:Notification" minOccurs="1" maxOccurs="unbounded"/>
+          <xs:element name="TransactionDetail" type="ns:TransactionDetail" minOccurs="0"/>
+          <xs:element name="Version" type="ns:VersionId" minOccurs="1"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CancelPendingShipmentRequest">
+        <xs:annotation>
+          <xs:documentation>Descriptive data sent to FedEx by a customer in order to Cancel a Pending shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="WebAuthenticationDetail" type="ns:WebAuthenticationDetail" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data to be used in authentication of the sender's identity (and right to use FedEx web services).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ClientDetail" type="ns:ClientDetail" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data identifying the client submitting the transaction.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TransactionDetail" type="ns:TransactionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data for this customer transaction. The TransactionDetail from the request is echoed back to the caller in the corresponding reply.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Version" type="ns:VersionId" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the version/level of a service operation expected by a caller (in each request) and performed by the callee (in each reply).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TrackingId" type="ns:TrackingId" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="CarrierCodeType">
+        <xs:annotation>
+          <xs:documentation>Identification of a FedEx operating company (transportation).</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="FDXC"/>
+          <xs:enumeration value="FDXE"/>
+          <xs:enumeration value="FDXG"/>
+          <xs:enumeration value="FXCC"/>
+          <xs:enumeration value="FXFR"/>
+          <xs:enumeration value="FXSP"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="CertificateOfOriginDetail">
+        <xs:annotation>
+          <xs:documentation>The instructions indicating how to print the Certificate of Origin ( e.g. whether or not to include the instructions, image type, etc ...)</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="DocumentFormat" type="ns:ShippingDocumentFormat" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies characteristics of a shipping document to be produced.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomerImageUsages" type="ns:CustomerImageUsage" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies the usage and identification of customer supplied images to be used on this document.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="ClearanceBrokerageType">
+        <xs:annotation>
+          <xs:documentation>Specifies the type of brokerage to be applied to a shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BROKER_INCLUSIVE"/>
+          <xs:enumeration value="BROKER_INCLUSIVE_NON_RESIDENT_IMPORTER"/>
+          <xs:enumeration value="BROKER_SELECT"/>
+          <xs:enumeration value="BROKER_SELECT_NON_RESIDENT_IMPORTER"/>
+          <xs:enumeration value="BROKER_UNASSIGNED"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="ClientDetail">
+        <xs:annotation>
+          <xs:documentation>Descriptive data for the client submitting a transaction.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="AccountNumber" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The FedEx account number associated with this transaction.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="MeterNumber" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>This number is assigned by FedEx and identifies the unique device from which the request is originating</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="IntegratorId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Only used in transactions which require identification of the Fed Ex Office integrator.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Localization" type="ns:Localization" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The language to be used for human-readable Notification.localizedMessages in responses to the request containing this ClientDetail object. Different requests from the same client may contain different Localization data. (Contrast with TransactionDetail.localization, which governs data payload language/translation.)</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="CodAddTransportationChargesType">
+        <xs:annotation>
+          <xs:documentation>Identifies what freight charges should be added to the COD collect amount.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ADD_ACCOUNT_COD_SURCHARGE"/>
+          <xs:enumeration value="ADD_ACCOUNT_NET_CHARGE"/>
+          <xs:enumeration value="ADD_ACCOUNT_NET_FREIGHT"/>
+          <xs:enumeration value="ADD_ACCOUNT_TOTAL_CUSTOMER_CHARGE"/>
+          <xs:enumeration value="ADD_LIST_COD_SURCHARGE"/>
+          <xs:enumeration value="ADD_LIST_NET_CHARGE"/>
+          <xs:enumeration value="ADD_LIST_NET_FREIGHT"/>
+          <xs:enumeration value="ADD_LIST_TOTAL_CUSTOMER_CHARGE"/>
+          <xs:enumeration value="ADD_SUM_OF_ACCOUNT_NET_CHARGES"/>
+          <xs:enumeration value="ADD_SUM_OF_ACCOUNT_NET_FREIGHT"/>
+          <xs:enumeration value="ADD_SUM_OF_LIST_NET_CHARGES"/>
+          <xs:enumeration value="ADD_SUM_OF_LIST_NET_FREIGHT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="CodCollectionType">
+        <xs:annotation>
+          <xs:documentation>Identifies the type of funds FedEx should collect upon shipment delivery.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ANY"/>
+          <xs:enumeration value="CASH"/>
+          <xs:enumeration value="COMPANY_CHECK"/>
+          <xs:enumeration value="GUARANTEED_FUNDS"/>
+          <xs:enumeration value="PERSONAL_CHECK"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="CodDetail">
+        <xs:annotation>
+          <xs:documentation>Descriptive data required for a FedEx COD (Collect-On-Delivery) shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="CodCollectionAmount" type="ns:Money" minOccurs="0"/>
+          <xs:element name="AddTransportationCharges" type="ns:CodAddTransportationChargesType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies if freight charges are to be added to the COD amount. This element determines which freight charges should be added to the COD collect amount. See CodAddTransportationChargesType for a list of valid enumerated values.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CollectionType" type="ns:CodCollectionType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the type of funds FedEx should collect upon package delivery</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CodRecipient" type="ns:Party" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>For Express this is the descriptive data that is used for the recipient of the FedEx Letter containing the COD payment. For Ground this is the descriptive data for the party to receive the payment that prints the COD receipt.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ReferenceIndicator" type="ns:CodReturnReferenceIndicatorType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates which type of reference information to include on the COD return shipping label.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CodReturnPackageDetail">
+        <xs:sequence>
+          <xs:element name="CollectionAmount" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The COD amount (after any accumulations) that must be collected upon delivery of a package shipped using the COD special service.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Electronic" type="xs:boolean" minOccurs="0"/>
+          <xs:element name="Barcodes" type="ns:PackageBarcodes" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Contains the data which form the Astra and 2DCommon barcodes that print on the COD return label.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Label" type="ns:ShippingDocument" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The label image or printer commands to print the label.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="CodReturnReferenceIndicatorType">
+        <xs:annotation>
+          <xs:documentation>Indicates which type of reference information to include on the COD return shipping label.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="INVOICE"/>
+          <xs:enumeration value="PO"/>
+          <xs:enumeration value="REFERENCE"/>
+          <xs:enumeration value="TRACKING"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="CodReturnShipmentDetail">
+        <xs:sequence>
+          <xs:element name="CollectionAmount" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The COD amount (after any accumulations) that must be collected upon delivery of a package shipped using the COD special service.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Handling" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Currently not supported.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>TBD</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ServiceTypeDescription" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The description of the FedEx service type used for the COD return shipment. Currently not supported.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>70</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PackagingDescription" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The description of the packaging used for the COD return shipment.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>40</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SecuredDescription" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Currently not supported.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>TBD</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Remitter" type="ns:Party" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Currently not supported.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CodRecipient" type="ns:Party" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Currently not supported.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CodRoutingDetail" type="ns:RoutingDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>
+                The CodRoutingDetail element will contain the COD return tracking number and form id. In the case of a COD multiple piece shipment these will need to be inserted in the request for the last piece of the multiple piece shipment.
+                The service commitment is the only other element of the RoutingDetail that is used for a CodRoutingDetail.
+              </xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Barcodes" type="ns:PackageBarcodes" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Contains the data which form the Astra and 2DCommon barcodes that print on the COD return label.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Label" type="ns:ShippingDocument" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The label image or printer commands to print the label.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CommercialInvoice">
+        <xs:annotation>
+          <xs:documentation>CommercialInvoice element is required for electronic upload of CI data. It will serve to create/transmit an Electronic Commercial Invoice through the FedEx Systems. Customers are responsible for printing their own Commercial Invoice.If you would likeFedEx to generate a Commercial Invoice and transmit it to Customs. for clearance purposes, you need to specify that in the ShippingDocumentSpecification element. If you would like a copy of the Commercial Invoice that FedEx generated returned to you in reply it needs to be specified in the ETDDetail/RequestedDocumentCopies element. Commercial Invoice support consists of maximum of 99 commodity line items.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Comments" type="xs:string" minOccurs="0" maxOccurs="99">
+            <xs:annotation>
+              <xs:documentation>Any comments that need to be communicated about this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FreightCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Any freight charges that are associated with this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TaxesOrMiscellaneousCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Any taxes or miscellaneous charges(other than Freight charges or Insurance charges) that are associated with this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PackingCosts" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Any packing costs that are associated with this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="HandlingCosts" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Any handling costs that are associated with this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SpecialInstructions" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Free-form text.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DeclarationStatment" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Free-form text.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PaymentTerms" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Free-form text.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Purpose" type="ns:PurposeOfShipmentType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The reason for the shipment. Note: SOLD is not a valid purpose for a Proforma Invoice.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomerInvoiceNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Customer assigned Invoice number</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="OriginatorName" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Name of the International Expert that completed the Commercial Invoice different from Sender.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TermsOfSale" type="ns:TermsOfSaleType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Required for dutiable international Express or Ground shipment. This field is not applicable to an international PIB(document) or a non-document which does not require a Commercial Invoice</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CommercialInvoiceDetail">
+        <xs:annotation>
+          <xs:documentation>The instructions indicating how to print the Commercial Invoice( e.g. image type) Specifies characteristics of a shipping document to be produced.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Format" type="ns:ShippingDocumentFormat" minOccurs="0"/>
+          <xs:element name="CustomerImageUsages" type="ns:CustomerImageUsage" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies the usage and identification of a customer supplied image to be used on this document.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="Commodity">
+        <xs:annotation>
+          <xs:documentation>
+            For international multiple piece shipments, commodity information must be passed in the Master and on each child transaction.
+            If this shipment cotains more than four commodities line items, the four highest valued should be included in the first 4 occurances for this request.
+          </xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Name" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Name of this commodity.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NumberOfPieces" type="xs:nonNegativeInteger" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Total number of pieces of this commodity</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Description" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Complete and accurate description of this commodity.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>450</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CountryOfManufacture" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Country code where commodity contents were produced or manufactured in their final form.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>2</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="HarmonizedCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>
+                Unique alpha/numeric representing commodity item.
+                At least one occurrence is required for US Export shipments if the Customs Value is greater than $2500 or if a valid US Export license is required.
+              </xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>14</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Weight" type="ns:Weight" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Total weight of this commodity. 1 explicit decimal position. Max length 11 including decimal.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Quantity" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Number of units of a commodity in total number of pieces for this line item. Max length is 9</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="QuantityUnits" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Unit of measure used to express the quantity of this commodity line item.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>3</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AdditionalMeasures" type="ns:Measure" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Contains only additional quantitative information other than weight and quantity to calculate duties and taxes.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="UnitPrice" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Value of each unit in Quantity. Six explicit decimal positions, Max length 18 including decimal.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomsValue" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>
+                Total customs value for this line item.
+                It should equal the commodity unit quantity times commodity unit value.
+                Six explicit decimal positions, max length 18 including decimal.
+              </xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ExciseConditions" type="ns:EdtExciseCondition" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Defines additional characteristic of commodity used to calculate duties and taxes</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ExportLicenseNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Applicable to US export shipping only.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>12</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ExportLicenseExpirationDate" type="xs:date" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>
+                Date of expiration. Must be at least 1 day into future.
+                The date that the Commerce Export License expires. Export License commodities may not be exported from the U.S. on an expired license.
+                Applicable to US Export shipping only.
+                Required only if commodity is shipped on commerce export license, and Export License Number is supplied.
+              </xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CIMarksAndNumbers" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>
+                An identifying mark or number used on the packaging of a shipment to help customers identify a particular shipment.
+              </xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>15</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NaftaDetail" type="ns:NaftaCommodityDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>All data required for this commodity in NAFTA Certificate of Origin.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CompletedEtdDetail">
+        <xs:sequence>
+          <xs:element name="FolderId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The identifier for all clearance documents associated with this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="UploadDocumentReferenceDetails" type="ns:UploadDocumentReferenceDetail" minOccurs="0" maxOccurs="unbounded"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CompletedHoldAtLocationDetail">
+        <xs:sequence>
+          <xs:element name="HoldingLocation" type="ns:ContactAndAddress" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the branded location name, the hold at location phone number and the address of the location.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="HoldingLocationType" type="ns:FedExLocationType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the type of FedEx location.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CompletedPackageDetail">
+        <xs:sequence>
+          <xs:element name="SequenceNumber" type="xs:positiveInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The package sequence number of this package in a multiple piece shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TrackingIds" type="ns:TrackingId" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>The Tracking number and form id for this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="GroupNumber" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Used with request containing PACKAGE_GROUPS, to identify which group of identical packages was used to produce a reply item.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="OversizeClass" type="ns:OversizeClassType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Oversize class for this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PackageRating" type="ns:PackageRating" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>All package-level rating data for this package, which may include data for multiple rate types.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="GroundServiceCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Associated with package, due to interaction with per-package hazardous materials presence/absence.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Barcodes" type="ns:PackageBarcodes" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The data that is used to from the Astra and 2DCommon barcodes for the label..</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AstraHandlingText" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The textual description of the special service applied to the package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AstraLabelElements" type="ns:AstraLabelElement" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="Label" type="ns:ShippingDocument" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The label image or printer commands to print the label.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PackageDocuments" type="ns:ShippingDocument" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All package-level shipping documents (other than labels and barcodes). For use in loads after January, 2008.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CodReturnDetail" type="ns:CodReturnPackageDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Information about the COD return shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SignatureOption" type="ns:SignatureOptionType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Actual signature option applied, to allow for cases in which the original value conflicted with other service features in the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="HazardousCommodities" type="ns:ValidatedHazardousCommodityContent" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Documents the kinds and quantities of all hazardous commodities in the current package, using updated hazardous commodity description data.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CompletedShipmentDetail">
+        <xs:sequence>
+          <xs:element name="UsDomestic" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates whether or not this is a US Domestic shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CarrierCode" type="ns:CarrierCodeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates the carrier that will be used to deliver this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="MasterTrackingId" type="ns:TrackingId" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The master tracking number and form id of this multiple piece shipment. This information is to be provided for each subsequent of a multiple piece shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ServiceTypeDescription" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Description of the FedEx service used for this shipment. Currently not supported.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>70</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PackagingDescription" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Description of the packaging used for this shipment. Currently not supported.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>40</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RoutingDetail" type="ns:ShipmentRoutingDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Information about the routing, origin, destination and delivery of a shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AccessDetail" type="ns:PendingShipmentAccessDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Only used with pending shipments.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TagDetail" type="ns:CompletedTagDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Only used in the reply to tag requests.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SmartPostDetail" type="ns:CompletedSmartPostDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Provides reply information specific to SmartPost shipments.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ShipmentRating" type="ns:ShipmentRating" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>All shipment-level rating data for this shipment, which may include data for multiple rate types.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CodReturnDetail" type="ns:CodReturnShipmentDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Information about the COD return shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CompletedHoldAtLocationDetail" type="ns:CompletedHoldAtLocationDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Returns the default holding location information when HOLD_AT_LOCATION special service is requested and the client does not specify the hold location address.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="IneligibleForMoneyBackGuarantee" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates whether or not this shipment is eligible for a money back guarantee.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ExportComplianceStatement" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Returns any defaults or updates applied to RequestedShipment.exportDetail.exportComplianceStatement.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CompletedEtdDetail" type="ns:CompletedEtdDetail" minOccurs="0"/>
+          <xs:element name="ShipmentDocuments" type="ns:ShippingDocument" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All shipment-level shipping documents (other than labels and barcodes).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CompletedPackageDetails" type="ns:CompletedPackageDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Package level details about this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CompletedSmartPostDetail">
+        <xs:annotation>
+          <xs:documentation>Provides reply information specific to SmartPost shipments.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="PickUpCarrier" type="ns:CarrierCodeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the carrier that will pick up the SmartPost shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Machinable" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates whether the shipment is deemed to be machineable, based on dimensions, weight, and packaging.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CompletedTagDetail">
+        <xs:annotation>
+          <xs:documentation>Provides reply information specific to a tag request.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="ConfirmationNumber" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AccessTime" type="xs:duration" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>As of June 2007, returned only for FedEx Express services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CutoffTime" type="xs:time" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>As of June 2007, returned only for FedEx Express services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Location" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>As of June 2007, returned only for FedEx Express services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DeliveryCommitment" type="xs:dateTime" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>As of June 2007, returned only for FedEx Express services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DispatchDate" type="xs:date" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>FEDEX INTERNAL USE ONLY: for use by INET.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ConfigurableLabelReferenceEntry">
+        <xs:annotation>
+          <xs:documentation>Defines additional data to print in the Configurable portion of the label, this allows you to print the same type information on the label that can also be printed on the doc tab.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="ZoneNumber" type="xs:positiveInteger" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>1 of 12 possible zones to position data.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Header" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The identifiying text for the data in this zone.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DataField" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>A reference to a field in either the request or reply to print in this zone following the header.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LiteralValue" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>A literal value to print after the header in this zone.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="Contact">
+        <xs:annotation>
+          <xs:documentation>The descriptive data for a point-of-contact person.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="ContactId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Client provided identifier corresponding to this contact information.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PersonName" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the contact person's name.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Title" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the contact person's title.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CompanyName" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the company this contact is associated with.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PhoneNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the phone number associated with this contact.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PhoneExtension" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the phone extension associated with this contact.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PagerNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the pager number associated with this contact.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FaxNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the fax number associated with this contact.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EMailAddress" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the email address associated with this contact.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ContactAndAddress">
+        <xs:sequence>
+          <xs:element name="Contact" type="ns:Contact" minOccurs="1"/>
+          <xs:element name="Address" type="ns:Address" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ContentRecord">
+        <xs:annotation>
+          <xs:documentation>Content Record.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="PartNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Part Number.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ItemNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Item Number.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ReceivedQuantity" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Received Quantity.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Description" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Description.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CreatePendingShipmentReply">
+        <xs:annotation>
+          <xs:documentation>Reply to the Close Request transaction. The Close Reply bring back the ASCII data buffer which will be used to print the Close Manifest. The Manifest is essential at the time of pickup.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="HighestSeverity" type="ns:NotificationSeverityType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the highest severity encountered when executing the request; in order from high to low: FAILURE, ERROR, WARNING, NOTE, SUCCESS.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Notifications" type="ns:Notification" minOccurs="1" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>The descriptive data detailing the status of a sumbitted transaction.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TransactionDetail" type="ns:TransactionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data that governs data payload language/translations. The TransactionDetail from the request is echoed back to the caller in the corresponding reply.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Version" type="ns:VersionId" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the version/level of a service operation expected by a caller (in each request) and performed by the callee (in each reply).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CompletedShipmentDetail" type="ns:CompletedShipmentDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The reply payload. All of the returned information about this shipment/package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CreatePendingShipmentRequest">
+        <xs:annotation>
+          <xs:documentation>Create Pending Shipment Request</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="WebAuthenticationDetail" type="ns:WebAuthenticationDetail" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data to be used in authentication of the sender's identity (and right to use FedEx web services).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ClientDetail" type="ns:ClientDetail" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The descriptive data identifying the client submitting the transaction.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TransactionDetail" type="ns:TransactionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The descriptive data for this customer transaction. The TransactionDetail from the request is echoed back to the caller in the corresponding reply.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Version" type="ns:VersionId" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the version/level of a service operation expected by a caller (in each request) and performed by the callee (in each reply).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RequestedShipment" type="ns:RequestedShipment" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data about the shipment being sent by the requestor.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CurrencyExchangeRate">
+        <xs:annotation>
+          <xs:documentation>Currency exchange rate information.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="FromCurrency" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The currency code for the original (converted FROM) currency.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="IntoCurrency" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The currency code for the final (converted INTO) currency.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Rate" type="xs:decimal" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Multiplier used to convert fromCurrency units to intoCurrency units.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CustomDeliveryWindowDetail">
+        <xs:sequence>
+          <xs:element name="Type" type="ns:CustomDeliveryWindowType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates the type of custom delivery being requested.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RequestTime" type="xs:time" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Time by which delivery is requested.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RequestRange" type="ns:DateRange" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Range of dates for custom delivery request; only used if type is BETWEEN.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RequestDate" type="xs:date" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Date for custom delivery request; only used for types of ON, BETWEEN, or AFTER.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="CustomDeliveryWindowType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="AFTER"/>
+          <xs:enumeration value="BEFORE"/>
+          <xs:enumeration value="BETWEEN"/>
+          <xs:enumeration value="ON"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="CustomDocumentDetail">
+        <xs:annotation>
+          <xs:documentation>Data required to produce a custom-specified document, either at shipment or package level.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Format" type="ns:ShippingDocumentFormat" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Common information controlling document production.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LabelPrintingOrientation" type="ns:LabelPrintingOrientationType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Applicable only to documents produced on thermal printers with roll stock.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LabelRotation" type="ns:LabelRotationType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Applicable only to documents produced on thermal printers with roll stock.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SpecificationId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the formatting specification used to construct this custom document.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomDocumentIdentifier" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the individual document specified by the client.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DocTabContent" type="ns:DocTabContent" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>If provided, thermal documents will include specified doc tab content. If omitted, document will be produced without doc tab content.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CustomLabelBarcodeEntry">
+        <xs:annotation>
+          <xs:documentation>Constructed string, based on format and zero or more data fields, printed in specified barcode symbology.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Position" type="ns:CustomLabelPosition" minOccurs="1"/>
+          <xs:element name="Format" type="xs:string" minOccurs="0"/>
+          <xs:element name="DataFields" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="BarHeight" type="xs:int" minOccurs="0"/>
+          <xs:element name="ThinBarWidth" type="xs:int" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Width of thinnest bar/space element in the barcode.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BarcodeSymbology" type="ns:BarcodeSymbologyType" minOccurs="1"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CustomLabelBoxEntry">
+        <xs:annotation>
+          <xs:documentation>Solid (filled) rectangular area on label.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="TopLeftCorner" type="ns:CustomLabelPosition" minOccurs="1"/>
+          <xs:element name="BottomRightCorner" type="ns:CustomLabelPosition" minOccurs="1"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="CustomLabelCoordinateUnits">
+        <xs:annotation>
+          <xs:documentation>Valid values for CustomLabelCoordinateUnits</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="MILS"/>
+          <xs:enumeration value="PIXELS"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="CustomLabelDetail">
+        <xs:sequence>
+          <xs:element name="CoordinateUnits" type="ns:CustomLabelCoordinateUnits" minOccurs="0"/>
+          <xs:element name="TextEntries" type="ns:CustomLabelTextEntry" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="GraphicEntries" type="ns:CustomLabelGraphicEntry" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="BoxEntries" type="ns:CustomLabelBoxEntry" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="BarcodeEntries" type="ns:CustomLabelBarcodeEntry" minOccurs="0" maxOccurs="unbounded"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CustomLabelGraphicEntry">
+        <xs:annotation>
+          <xs:documentation>Image to be included from printer's memory, or from a local file for offline clients.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Position" type="ns:CustomLabelPosition" minOccurs="0"/>
+          <xs:element name="PrinterGraphicId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Printer-specific index of graphic image to be printed.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FileGraphicFullName" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Fully-qualified path and file name for graphic image to be printed.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CustomLabelPosition">
+        <xs:sequence>
+          <xs:element name="X" type="xs:nonNegativeInteger" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Horizontal position, relative to left edge of custom area.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Y" type="xs:nonNegativeInteger" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Vertical position, relative to top edge of custom area.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CustomLabelTextEntry">
+        <xs:annotation>
+          <xs:documentation>Constructed string, based on format and zero or more data fields, printed in specified printer font (for thermal labels) or generic font/size (for plain paper labels).</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Position" type="ns:CustomLabelPosition" minOccurs="1"/>
+          <xs:element name="Format" type="xs:string" minOccurs="0"/>
+          <xs:element name="DataFields" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="ThermalFontId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Printer-specific font name for use with thermal printer labels.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FontName" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Generic font name for use with plain paper labels.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FontSize" type="xs:positiveInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Generic font size for use with plain paper labels.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CustomerImageUsage">
+        <xs:sequence>
+          <xs:element name="Type" type="ns:CustomerImageUsageType" minOccurs="0"/>
+          <xs:element name="Id" type="ns:ImageId" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="CustomerImageUsageType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="LETTER_HEAD"/>
+          <xs:enumeration value="SIGNATURE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="CustomerReference">
+        <xs:annotation>
+          <xs:documentation>Reference information to be associated with this package.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="CustomerReferenceType" type="ns:CustomerReferenceType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The reference type to be associated with this reference data.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Value" type="xs:string" minOccurs="1"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="CustomerReferenceType">
+        <xs:annotation>
+          <xs:documentation>The types of references available for use.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BILL_OF_LADING"/>
+          <xs:enumeration value="CUSTOMER_REFERENCE"/>
+          <xs:enumeration value="DEPARTMENT_NUMBER"/>
+          <xs:enumeration value="ELECTRONIC_PRODUCT_CODE"/>
+          <xs:enumeration value="INTRACOUNTRY_REGULATORY_REFERENCE"/>
+          <xs:enumeration value="INVOICE_NUMBER"/>
+          <xs:enumeration value="P_O_NUMBER"/>
+          <xs:enumeration value="SHIPMENT_INTEGRITY"/>
+          <xs:enumeration value="STORE_NUMBER"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="CustomerSpecifiedLabelDetail">
+        <xs:annotation>
+          <xs:documentation>Allows customer-specified control of label content.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="DocTabContent" type="ns:DocTabContent" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>If omitted, no doc tab will be produced (i.e. default = former NONE type).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomContent" type="ns:CustomLabelDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Defines any custom content to print on the label.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ConfigurableReferenceEntries" type="ns:ConfigurableLabelReferenceEntry" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Defines additional data to print in the Configurable portion of the label, this allows you to print the same type information on the label that can also be printed on the doc tab.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="MaskedData" type="ns:LabelMaskableDataType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Controls which data/sections will be suppressed.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ScncOverride" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Customer-provided SCNC for use with label-data-only processing of FedEx Ground shipments.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TermsAndConditionsLocalization" type="ns:Localization" minOccurs="0"/>
+          <xs:element name="AdditionalLabels" type="ns:AdditionalLabelsDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Controls the number of additional copies of supplemental labels.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AirWaybillSuppressionCount" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This value reduces the default quantity of destination/consignee air waybill labels. A value of zero indicates no change to default. A minimum of one copy will always be produced.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="CustomsClearanceDetail">
+        <xs:sequence>
+          <xs:element name="Broker" type="ns:Party" minOccurs="0"/>
+          <xs:element name="ClearanceBrokerage" type="ns:ClearanceBrokerageType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Interacts both with properties of the shipment and contractual relationship with the shipper.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ImporterOfRecord" type="ns:Party" minOccurs="0"/>
+          <xs:element name="RecipientCustomsId" type="ns:RecipientCustomsId" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies how the recipient is identified for customs purposes; the requirements on this information vary with destination country.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DutiesPayment" type="ns:Payment" minOccurs="0"/>
+          <xs:element name="DocumentContent" type="ns:InternationalDocumentContentType" minOccurs="0"/>
+          <xs:element name="CustomsValue" type="ns:Money" minOccurs="0"/>
+          <xs:element name="FreightOnValue" type="ns:FreightOnValueType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies responsibilities with respect to loss, damage, etc.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="InsuranceCharges" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Documents amount paid to third party for coverage of shipment content.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PartiesToTransactionAreRelated" type="xs:boolean" minOccurs="0"/>
+          <xs:element name="CommercialInvoice" type="ns:CommercialInvoice" minOccurs="0"/>
+          <xs:element name="Commodities" type="ns:Commodity" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="ExportDetail" type="ns:ExportDetail" minOccurs="0"/>
+          <xs:element name="RegulatoryControls" type="ns:RegulatoryControlType" minOccurs="0" maxOccurs="unbounded"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="DangerousGoodsAccessibilityType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ACCESSIBLE"/>
+          <xs:enumeration value="INACCESSIBLE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="DangerousGoodsDetail">
+        <xs:annotation>
+          <xs:documentation>The descriptive data required for a FedEx shipment containing dangerous goods (hazardous materials).</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Accessibility" type="ns:DangerousGoodsAccessibilityType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies whether or not the products being shipped are required to be accessible during delivery.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CargoAircraftOnly" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Shipment is packaged/documented for movement ONLY on cargo aircraft.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Options" type="ns:HazardousCommodityOptionType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Indicates which kinds of hazardous content are in the current package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="HazardousCommodities" type="ns:HazardousCommodityContent" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Documents the kinds and quantities of all hazardous commodities in the current package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Packaging" type="ns:HazardousCommodityPackagingDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Description of the packaging of this commodity, suitable for use on OP-900 and OP-950 forms.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EmergencyContactNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Telephone number to use for contact in the event of an emergency.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Offeror" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Offeror's name or contract number, per DOT regulation.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="DateRange">
+        <xs:sequence>
+          <xs:element name="Begins" type="xs:date" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The beginning date in a date range.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Ends" type="xs:date" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The end date in a date range.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="DayOfWeekType">
+        <xs:annotation>
+          <xs:documentation>Valid values for DayofWeekType</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="FRI"/>
+          <xs:enumeration value="MON"/>
+          <xs:enumeration value="SAT"/>
+          <xs:enumeration value="SUN"/>
+          <xs:enumeration value="THU"/>
+          <xs:enumeration value="TUE"/>
+          <xs:enumeration value="WED"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="DeleteShipmentRequest">
+        <xs:annotation>
+          <xs:documentation>Descriptive data sent to FedEx by a customer in order to delete a package.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="WebAuthenticationDetail" type="ns:WebAuthenticationDetail" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data to be used in authentication of the sender's identity (and right to use FedEx web services).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ClientDetail" type="ns:ClientDetail" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data identifying the client submitting the transaction.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TransactionDetail" type="ns:TransactionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data for this customer transaction. The TransactionDetail from the request is echoed back to the caller in the corresponding reply.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Version" type="ns:VersionId" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the version/level of a service operation expected by a caller (in each request) and performed by the callee (in each reply).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ShipTimestamp" type="xs:dateTime" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The timestamp of the shipment request.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TrackingId" type="ns:TrackingId" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the FedEx tracking number of the package being cancelled.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DeletionControl" type="ns:DeletionControlType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Determines the type of deletion to be performed in relation to package level vs shipment level.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="DeleteTagRequest">
+        <xs:sequence>
+          <xs:element name="WebAuthenticationDetail" type="ns:WebAuthenticationDetail" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data to be used in authentication of the sender's identity (and right to use FedEx web services).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ClientDetail" type="ns:ClientDetail" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data identifying the client submitting the transaction.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TransactionDetail" type="ns:TransactionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data for this customer transaction. The TransactionDetail from the request is echoed back to the caller in the corresponding reply.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Version" type="ns:VersionId" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the version/level of a service operation expected by a caller (in each request) and performed by the callee (in each reply).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DispatchLocationId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Only used for tags which had FedEx Express services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DispatchDate" type="xs:date" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Only used for tags which had FedEx Express services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Payment" type="ns:Payment" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>If the original ProcessTagRequest specified third-party payment, then the delete request must contain the same pay type and payor account number for security purposes.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ConfirmationNumber" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Also known as Pickup Confirmation Number or Dispatch Number</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="DeletionControlType">
+        <xs:annotation>
+          <xs:documentation>Specifies the type of deletion to be performed on a shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="DELETE_ALL_PACKAGES"/>
+          <xs:enumeration value="DELETE_ONE_PACKAGE"/>
+          <xs:enumeration value="LEGACY"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="DestinationControlDetail">
+        <xs:annotation>
+          <xs:documentation>Data required to complete the Destionation Control Statement for US exports.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="StatementTypes" type="ns:DestinationControlStatementType" minOccurs="1" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>List of applicable Statment types.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DestinationCountries" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Comma-separated list of up to four country codes, required for DEPARTMENT_OF_STATE statement.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EndUser" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Name of end user, required for DEPARTMENT_OF_STATE statement.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="DestinationControlStatementType">
+        <xs:annotation>
+          <xs:documentation>Used to indicate whether the Destination Control Statement is of type Department of Commerce, Department of State or both.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="DEPARTMENT_OF_COMMERCE"/>
+          <xs:enumeration value="DEPARTMENT_OF_STATE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Dimensions">
+        <xs:annotation>
+          <xs:documentation>The dimensions of this package and the unit type used for the measurements.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Length" type="xs:nonNegativeInteger" minOccurs="1"/>
+          <xs:element name="Width" type="xs:nonNegativeInteger" minOccurs="1"/>
+          <xs:element name="Height" type="xs:nonNegativeInteger" minOccurs="1"/>
+          <xs:element name="Units" type="ns:LinearUnits" minOccurs="1"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="DocTabContent">
+        <xs:sequence>
+          <xs:element name="DocTabContentType" type="ns:DocTabContentType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The DocTabContentType options available.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Zone001" type="ns:DocTabContentZone001" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The DocTabContentType should be set to ZONE001 to specify additional Zone details.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Barcoded" type="ns:DocTabContentBarcoded" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The DocTabContentType should be set to BARCODED to specify additional BarCoded details.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="DocTabContentBarcoded">
+        <xs:sequence>
+          <xs:element name="Symbology" type="ns:BarcodeSymbologyType" minOccurs="0"/>
+          <xs:element name="Specification" type="ns:DocTabZoneSpecification" minOccurs="1"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="DocTabContentType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BARCODED"/>
+          <xs:enumeration value="MINIMUM"/>
+          <xs:enumeration value="STANDARD"/>
+          <xs:enumeration value="ZONE001"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="DocTabContentZone001">
+        <xs:sequence>
+          <xs:element name="DocTabZoneSpecifications" type="ns:DocTabZoneSpecification" minOccurs="1" maxOccurs="12"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="DocTabZoneJustificationType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="LEFT"/>
+          <xs:enumeration value="RIGHT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="DocTabZoneSpecification">
+        <xs:sequence>
+          <xs:element name="ZoneNumber" type="xs:positiveInteger" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Zone number can be between 1 and 12.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Header" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Header value on this zone.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DataField" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Reference path to the element in the request/reply whose value should be printed on this zone.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LiteralValue" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Free form-text to be printed in this zone.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Justification" type="ns:DocTabZoneJustificationType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Justification for the text printed on this zone.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="DropoffType">
+        <xs:annotation>
+          <xs:documentation>Identifies the method by which the package is to be tendered to FedEx. This element does not dispatch a courier for package pickup.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BUSINESS_SERVICE_CENTER"/>
+          <xs:enumeration value="DROP_BOX"/>
+          <xs:enumeration value="REGULAR_PICKUP"/>
+          <xs:enumeration value="REQUEST_COURIER"/>
+          <xs:enumeration value="STATION"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="EMailLabelDetail">
+        <xs:annotation>
+          <xs:documentation>Describes specific information about the email label shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="NotificationEMailAddress" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Notification email will be sent to this email address</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NotificationMessage" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Message to be sent in the notification email</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="EMailNotificationAggregationType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="PER_PACKAGE"/>
+          <xs:enumeration value="PER_SHIPMENT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="EMailNotificationDetail">
+        <xs:annotation>
+          <xs:documentation>Information describing email notifications that will be sent in relation to events that occur during package movement</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="AggregationType" type="ns:EMailNotificationAggregationType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies whether/how email notifications are grouped.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PersonalMessage" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>A message that will be included in the email notifications</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Recipients" type="ns:EMailNotificationRecipient" minOccurs="1" maxOccurs="6">
+            <xs:annotation>
+              <xs:documentation>Information describing the destination of the email, format of the email and events to be notified on</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="EMailNotificationFormatType">
+        <xs:annotation>
+          <xs:documentation>The format of the email</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="HTML"/>
+          <xs:enumeration value="TEXT"/>
+          <xs:enumeration value="WIRELESS"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="EMailNotificationRecipient">
+        <xs:annotation>
+          <xs:documentation>The descriptive data for a FedEx email notification recipient.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="EMailNotificationRecipientType" type="ns:EMailNotificationRecipientType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the relationship this email recipient has to the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EMailAddress" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The email address to send the notification to</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NotifyOnShipment" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Notify the email recipient when this shipment has been shipped.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NotifyOnException" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Notify the email recipient if this shipment encounters a problem while in route</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NotifyOnDelivery" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Notify the email recipient when this shipment has been delivered.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Format" type="ns:EMailNotificationFormatType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The format of the email notification.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Localization" type="ns:Localization" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The language/locale to be used in this email notification.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="EMailNotificationRecipientType">
+        <xs:annotation>
+          <xs:documentation>Identifies the set of valid email notification recipient types. For SHIPPER, RECIPIENT and BROKER the email address asssociated with their definitions will be used, any email address sent with the email notification for these three email notification recipient types will be ignored.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BROKER"/>
+          <xs:enumeration value="OTHER"/>
+          <xs:enumeration value="RECIPIENT"/>
+          <xs:enumeration value="SHIPPER"/>
+          <xs:enumeration value="THIRD_PARTY"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="EdtCommodityTax">
+        <xs:sequence>
+          <xs:element name="HarmonizedCode" type="xs:string" minOccurs="0"/>
+          <xs:element name="Taxes" type="ns:EdtTaxDetail" minOccurs="0" maxOccurs="unbounded"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="EdtExciseCondition">
+        <xs:sequence>
+          <xs:element name="Category" type="xs:string" minOccurs="0"/>
+          <xs:element name="Value" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Customer-declared value, with data type and legal values depending on excise condition, used in defining the taxable value of the item.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="EdtRequestType">
+        <xs:annotation>
+          <xs:documentation>Specifies the types of Estimated Duties and Taxes to be included in a rate quotation for an international shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ALL"/>
+          <xs:enumeration value="NONE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="EdtTaxDetail">
+        <xs:sequence>
+          <xs:element name="TaxType" type="ns:EdtTaxType" minOccurs="0"/>
+          <xs:element name="EffectiveDate" type="xs:date" minOccurs="0"/>
+          <xs:element name="Name" type="xs:string" minOccurs="0"/>
+          <xs:element name="TaxableValue" type="ns:Money" minOccurs="0"/>
+          <xs:element name="Description" type="xs:string" minOccurs="0"/>
+          <xs:element name="Formula" type="xs:string" minOccurs="0"/>
+          <xs:element name="Amount" type="ns:Money" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="EdtTaxType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ADDITIONAL_TAXES"/>
+          <xs:enumeration value="CONSULAR_INVOICE_FEE"/>
+          <xs:enumeration value="CUSTOMS_SURCHARGES"/>
+          <xs:enumeration value="DUTY"/>
+          <xs:enumeration value="EXCISE_TAX"/>
+          <xs:enumeration value="FOREIGN_EXCHANGE_TAX"/>
+          <xs:enumeration value="GENERAL_SALES_TAX"/>
+          <xs:enumeration value="IMPORT_LICENSE_FEE"/>
+          <xs:enumeration value="INTERNAL_ADDITIONAL_TAXES"/>
+          <xs:enumeration value="INTERNAL_SENSITIVE_PRODUCTS_TAX"/>
+          <xs:enumeration value="OTHER"/>
+          <xs:enumeration value="SENSITIVE_PRODUCTS_TAX"/>
+          <xs:enumeration value="STAMP_TAX"/>
+          <xs:enumeration value="STATISTICAL_TAX"/>
+          <xs:enumeration value="TRANSPORT_FACILITIES_TAX"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="ErrorLabelBehaviorType">
+        <xs:annotation>
+          <xs:documentation>
+            Specifies the client-requested response in the event of errors within shipment.
+            PACKAGE_ERROR_LABELS : Return per-package error label in addition to error Notifications.
+            STANDARD             : Return error Notifications only.
+          </xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="PACKAGE_ERROR_LABELS"/>
+          <xs:enumeration value="STANDARD"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="EtdDetail">
+        <xs:annotation>
+          <xs:documentation>Electronic Trade document references used with the ETD special service.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="RequestedDocumentCopies" type="ns:RequestedShippingDocumentType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Indicates the types of shipping documents produced for the shipper by FedEx (see ShippingDocumentSpecification) which should be copied back to the shipper in the shipment result data.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DocumentReferences" type="ns:UploadDocumentReferenceDetail" minOccurs="0" maxOccurs="unbounded"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ExportDetail">
+        <xs:annotation>
+          <xs:documentation>Country specific details of an International shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="B13AFilingOption" type="ns:B13AFilingOptionType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>
+                Specifies which filing option is being exercised by the customer.
+                Required for non-document shipments originating in Canada destined for any country other than Canada, the United States, Puerto Rico or the U.S. Virgin Islands.
+              </xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ExportComplianceStatement" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>General field for exporting-country-specific export data (e.g. B13A for CA, FTSR Exemption or AES Citation for US).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PermitNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This field is applicable only to Canada export non-document shipments of any value to any destination. No special characters allowed. </xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>10</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DestinationControlDetail" type="ns:DestinationControlDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Department of Commerce/Department of State information about this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ExpressFreightDetail">
+        <xs:annotation>
+          <xs:documentation>Details specific to an Express freight shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="PackingListEnclosed" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates whether or nor a packing list is enclosed.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ShippersLoadAndCount" type="xs:positiveInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>
+                Total shipment pieces.
+                e.g. 3 boxes and 3 pallets of 100 pieces each = Shippers Load and Count of 303.
+                Applicable to International Priority Freight and International Economy Freight.
+                Values must be in the range of 1 - 99999
+              </xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BookingConfirmationNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Required for International Freight shipping. Values must be 8- 12 characters in length.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>12</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="FedExLocationType">
+        <xs:annotation>
+          <xs:documentation>Identifies a kind of FedEx facility.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="FEDEX_EXPRESS_STATION"/>
+          <xs:enumeration value="FEDEX_GROUND_TERMINAL"/>
+          <xs:enumeration value="FEDEX_OFFICE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="FreightAccountPaymentType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="COLLECT"/>
+          <xs:enumeration value="PREPAID"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="FreightAddressLabelDetail">
+        <xs:annotation>
+          <xs:documentation>Data required to produce the Freight handling-unit-level address labels. Note that the number of UNIQUE labels (the N as in 1 of N, 2 of N, etc.) is determined by total handling units.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Format" type="ns:ShippingDocumentFormat" minOccurs="0"/>
+          <xs:element name="Copies" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates the number of copies to be produced for each unique label.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DocTabContent" type="ns:DocTabContent" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>If omitted, no doc tab will be produced (i.e. default = former NONE type).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="FreightBaseCharge">
+        <xs:annotation>
+          <xs:documentation>Individual charge which contributes to the total base charge for the shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="FreightClass" type="ns:FreightClassType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Freight class for this line item.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RatedAsClass" type="ns:FreightClassType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Effective freight class used for rating this line item.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NmfcCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>NMFC Code for commodity.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Description" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Customer-provided description for this commodity or class line.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Weight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Weight for this commodity or class line.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ChargeRate" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Rate or factor applied to this line item.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ChargeBasis" type="ns:FreightChargeBasisType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the manner in which the chargeRate for this line item was applied.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ExtendedAmount" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The net or extended charge for this line item.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="FreightChargeBasisType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CWT"/>
+          <xs:enumeration value="FLAT"/>
+          <xs:enumeration value="MINIMUM"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="FreightClassType">
+        <xs:annotation>
+          <xs:documentation>These values represent the industry-standard freight classes used for FedEx Freight and FedEx National Freight shipment description. (Note: The alphabetic prefixes are required to distinguish these values from decimal numbers on some client platforms.)</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CLASS_050"/>
+          <xs:enumeration value="CLASS_055"/>
+          <xs:enumeration value="CLASS_060"/>
+          <xs:enumeration value="CLASS_065"/>
+          <xs:enumeration value="CLASS_070"/>
+          <xs:enumeration value="CLASS_077_5"/>
+          <xs:enumeration value="CLASS_085"/>
+          <xs:enumeration value="CLASS_092_5"/>
+          <xs:enumeration value="CLASS_100"/>
+          <xs:enumeration value="CLASS_110"/>
+          <xs:enumeration value="CLASS_125"/>
+          <xs:enumeration value="CLASS_150"/>
+          <xs:enumeration value="CLASS_175"/>
+          <xs:enumeration value="CLASS_200"/>
+          <xs:enumeration value="CLASS_250"/>
+          <xs:enumeration value="CLASS_300"/>
+          <xs:enumeration value="CLASS_400"/>
+          <xs:enumeration value="CLASS_500"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="FreightCollectTermsType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="SECTION_7_SIGNED"/>
+          <xs:enumeration value="STANDARD"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="FreightOnValueType">
+        <xs:annotation>
+          <xs:documentation>Identifies responsibilities with respect to loss, damage, etc.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CARRIER_RISK"/>
+          <xs:enumeration value="OWN_RISK"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="FreightRateDetail">
+        <xs:annotation>
+          <xs:documentation>Rate data specific to FedEx Freight or FedEx National Freight services.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="QuoteNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>A unique identifier for a specific rate quotation.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BaseCharges" type="ns:FreightBaseCharge" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Freight charges which accumulate to the total base charge for the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Notations" type="ns:FreightRateNotation" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Human-readable descriptions of additional information on this shipment rating.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="FreightRateNotation">
+        <xs:annotation>
+          <xs:documentation>Additional non-monetary data returned with Freight rates.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Code" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Unique identifier for notation.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Description" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Human-readable explanation of notation.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="FreightShipmentDetail">
+        <xs:annotation>
+          <xs:documentation>Data applicable to shipments using FEDEX_FREIGHT and FEDEX_NATIONAL_FREIGHT services.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="FedExFreightAccountNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Account number used with FEDEX_FREIGHT service.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FedExFreightBillingContactAndAddress" type="ns:ContactAndAddress" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Used for validating FedEx Freight account number and (optionally) identifying third party payment on the bill of lading.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PrintedReferences" type="ns:PrintedReference" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Identification values to be printed during creation of a Freight bill of lading.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Role" type="ns:FreightShipmentRoleType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates the role of the party submitting the transaction.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PaymentType" type="ns:FreightAccountPaymentType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Designates which of the requester's tariffs will be used for rating.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CollectTermsType" type="ns:FreightCollectTermsType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Designates the terms of the "collect" payment for a Freight Shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DeclaredValuePerUnit" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the declared value for the shipment</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DeclaredValueUnits" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the declared value units corresponding to the above defined declared value</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LiabilityCoverageDetail" type="ns:LiabilityCoverageDetail" minOccurs="0"/>
+          <xs:element name="Coupons" type="xs:string" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Identifiers for promotional discounts offered to customers.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalHandlingUnits" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Total number of individual handling units in the entire shipment (for unit pricing).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ClientDiscountPercent" type="xs:decimal" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Estimated discount rate provided by client for unsecured rate quote.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PalletWeight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Total weight of pallets used in shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ShipmentDimensions" type="ns:Dimensions" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Overall shipment dimensions.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Comment" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Description for the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SpecialServicePayments" type="ns:FreightSpecialServicePayment" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies which party will pay surcharges for any special services which support split billing.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="HazardousMaterialsEmergencyContactNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Must be populated if any line items contain hazardous materials.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LineItems" type="ns:FreightShipmentLineItem" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Details of the commodities in the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="FreightShipmentLineItem">
+        <xs:annotation>
+          <xs:documentation>Description of an individual commodity or class of content in a shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="FreightClass" type="ns:FreightClassType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Freight class for this line item.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ClassProvidedByCustomer" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>FEDEX INTERNAL USE ONLY: for FedEx system that estimate freight class from customer-provided dimensions and weight.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="HandlingUnits" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Number of individual handling units to which this line applies. (NOTE: Total of line-item-level handling units may not balance to shipment-level total handling units.)</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Packaging" type="ns:PhysicalPackagingType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specification of handling-unit packaging for this commodity or class line.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Pieces" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Number of pieces for this commodity or class line.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NmfcCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>NMFC Code for commodity.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="HazardousMaterials" type="ns:HazardousCommodityOptionType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates the kind of hazardous material content in this line item.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BillOfLadingNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>For printed reference per line item.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PurchaseOrderNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>For printed reference per line item.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Description" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Customer-provided description for this commodity or class line.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Weight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Weight for this commodity or class line.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Dimensions" type="ns:Dimensions" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>FED EX INTERNAL USE ONLY - Individual line item dimensions.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Volume" type="ns:Volume" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Volume (cubic measure) for this commodity or class line.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="FreightShipmentRoleType">
+        <xs:annotation>
+          <xs:documentation>Indicates the role of the party submitting the transaction.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CONSIGNEE"/>
+          <xs:enumeration value="SHIPPER"/>
+          <xs:enumeration value="THIRD_PARTY"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="FreightSpecialServicePayment">
+        <xs:annotation>
+          <xs:documentation>Specifies which party will be responsible for payment of any surcharges for Freight special services for which split billing is allowed.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="SpecialService" type="ns:ShipmentSpecialServiceType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the special service.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PaymentType" type="ns:FreightAccountPaymentType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates who will pay for the special service.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="GeneralAgencyAgreementDetail">
+        <xs:annotation>
+          <xs:documentation>Data required to produce a General Agency Agreement document. Remaining content (business data) to be defined once requirements have been completed.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Format" type="ns:ShippingDocumentFormat" minOccurs="1"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="HazardousCommodityContent">
+        <xs:annotation>
+          <xs:documentation>Documents the kind and quantity of an individual hazardous commodity in a package.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Description" type="ns:HazardousCommodityDescription" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies and describes an individual hazardous commodity.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Quantity" type="ns:HazardousCommodityQuantityDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies the amount of the commodity in alternate units.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Options" type="ns:HazardousCommodityOptionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Customer-provided specifications for handling individual commodities.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="HazardousCommodityDescription">
+        <xs:annotation>
+          <xs:documentation>Identifies and describes an individual hazardous commodity. For 201001 load, this is based on data from the FedEx Ground Hazardous Materials Shipping Guide.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Id" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Regulatory identifier for a commodity (e.g. "UN ID" value).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PackingGroup" type="ns:HazardousCommodityPackingGroupType" minOccurs="0"/>
+          <xs:element name="ProperShippingName" type="xs:string" minOccurs="0"/>
+          <xs:element name="TechnicalName" type="xs:string" minOccurs="0"/>
+          <xs:element name="HazardClass" type="xs:string" minOccurs="0"/>
+          <xs:element name="SubsidiaryClasses" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="LabelText" type="xs:string" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="HazardousCommodityLabelTextOptionType">
+        <xs:annotation>
+          <xs:documentation>Specifies how the commodity is to be labeled.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="APPEND"/>
+          <xs:enumeration value="OVERRIDE"/>
+          <xs:enumeration value="STANDARD"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="HazardousCommodityOptionDetail">
+        <xs:annotation>
+          <xs:documentation>Customer-provided specifications for handling individual commodities.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="LabelTextOption" type="ns:HazardousCommodityLabelTextOptionType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies how the customer wishes the label text to be handled for this commodity in this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomerSuppliedLabelText" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Text used in labeling the commodity under control of the labelTextOption field.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="HazardousCommodityOptionType">
+        <xs:annotation>
+          <xs:documentation>Indicates which kind of hazardous content (as defined by DOT) is being reported.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="HAZARDOUS_MATERIALS"/>
+          <xs:enumeration value="LITHIUM_BATTERY_EXCEPTION"/>
+          <xs:enumeration value="ORM_D"/>
+          <xs:enumeration value="REPORTABLE_QUANTITIES"/>
+          <xs:enumeration value="SMALL_QUANTITY_EXCEPTION"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="HazardousCommodityPackagingDetail">
+        <xs:annotation>
+          <xs:documentation>Identifies number and type of packaging units for hazardous commodities.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Count" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Number of units of the type below.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Units" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Units in which the hazardous commodity is packaged.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="HazardousCommodityPackingGroupType">
+        <xs:annotation>
+          <xs:documentation>Identifies DOT packing group for a hazardous commodity.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="I"/>
+          <xs:enumeration value="II"/>
+          <xs:enumeration value="III"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="HazardousCommodityQuantityDetail">
+        <xs:annotation>
+          <xs:documentation>Identifies amount and units for quantity of hazardous commodities.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Amount" type="xs:decimal" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Number of units of the type below.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Units" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Units by which the hazardous commodity is measured.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="HoldAtLocationDetail">
+        <xs:annotation>
+          <xs:documentation>Descriptive data required for a FedEx shipment that is to be held at the destination FedEx location for pickup by the recipient.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="PhoneNumber" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Contact phone number for recipient of shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LocationContactAndAddress" type="ns:ContactAndAddress" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Contact and address of FedEx facility at which shipment is to be held.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LocationType" type="ns:FedExLocationType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Type of facility at which package/shipment is to be held.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="HomeDeliveryPremiumDetail">
+        <xs:annotation>
+          <xs:documentation>The descriptive data required by FedEx for home delivery services.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="HomeDeliveryPremiumType" type="ns:HomeDeliveryPremiumType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The type of Home Delivery Premium service being requested.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Date" type="xs:date" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Required for Date Certain Home Delivery.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PhoneNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Required for Date Certain and Appointment Home Delivery.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>15</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="HomeDeliveryPremiumType">
+        <xs:annotation>
+          <xs:documentation>The type of Home Delivery Premium service being requested.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="APPOINTMENT"/>
+          <xs:enumeration value="DATE_CERTAIN"/>
+          <xs:enumeration value="EVENING"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="ImageId">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="IMAGE_1"/>
+          <xs:enumeration value="IMAGE_2"/>
+          <xs:enumeration value="IMAGE_3"/>
+          <xs:enumeration value="IMAGE_4"/>
+          <xs:enumeration value="IMAGE_5"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="InternationalDocumentContentType">
+        <xs:annotation>
+          <xs:documentation>The type of International shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="DERIVED"/>
+          <xs:enumeration value="DOCUMENTS_ONLY"/>
+          <xs:enumeration value="NON_DOCUMENTS"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="LabelFormatType">
+        <xs:annotation>
+          <xs:documentation>Specifies the type of label to be returned.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="COMMON2D"/>
+          <xs:enumeration value="FEDEX_FREIGHT_STRAIGHT_BILL_OF_LADING"/>
+          <xs:enumeration value="LABEL_DATA_ONLY"/>
+          <xs:enumeration value="VICS_BILL_OF_LADING"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="LabelMaskableDataType">
+        <xs:annotation>
+          <xs:documentation>Names for data elements / areas which may be suppressed from printing on labels.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CUSTOMS_VALUE"/>
+          <xs:enumeration value="DUTIES_AND_TAXES_PAYOR_ACCOUNT_NUMBER"/>
+          <xs:enumeration value="SHIPPER_ACCOUNT_NUMBER"/>
+          <xs:enumeration value="TERMS_AND_CONDITIONS"/>
+          <xs:enumeration value="TRANSPORTATION_CHARGES_PAYOR_ACCOUNT_NUMBER"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="LabelPrintingOrientationType">
+        <xs:annotation>
+          <xs:documentation>This indicates if the top or bottom of the label comes out of the printer first.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BOTTOM_EDGE_OF_TEXT_FIRST"/>
+          <xs:enumeration value="TOP_EDGE_OF_TEXT_FIRST"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="LabelRotationType">
+        <xs:annotation>
+          <xs:documentation>Relative to normal orientation for the printer.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="LEFT"/>
+          <xs:enumeration value="NONE"/>
+          <xs:enumeration value="RIGHT"/>
+          <xs:enumeration value="UPSIDE_DOWN"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="LabelSpecification">
+        <xs:annotation>
+          <xs:documentation>Description of shipping label to be returned in the reply</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Dispositions" type="ns:ShippingDocumentDispositionDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies how to create, organize, and return the document.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LabelFormatType" type="ns:LabelFormatType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Specify type of label to be returned</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ImageType" type="ns:ShippingDocumentImageType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies the image format used for a shipping document.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LabelStockType" type="ns:LabelStockType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>For thermal printer lables this indicates the size of the label and the location of the doc tab if present.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LabelPrintingOrientation" type="ns:LabelPrintingOrientationType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This indicates if the top or bottom of the label comes out of the printer first.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PrintedLabelOrigin" type="ns:ContactAndAddress" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>If present, this contact and address information will replace the return address information on the label.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomerSpecifiedDetail" type="ns:CustomerSpecifiedLabelDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Allows customer-specified control of label content.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="LabelStockType">
+        <xs:annotation>
+          <xs:documentation>For thermal printer labels this indicates the size of the label and the location of the doc tab if present.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="PAPER_4X6"/>
+          <xs:enumeration value="PAPER_4X8"/>
+          <xs:enumeration value="PAPER_4X9"/>
+          <xs:enumeration value="PAPER_7X4.75"/>
+          <xs:enumeration value="PAPER_8.5X11_BOTTOM_HALF_LABEL"/>
+          <xs:enumeration value="PAPER_8.5X11_TOP_HALF_LABEL"/>
+          <xs:enumeration value="PAPER_LETTER"/>
+          <xs:enumeration value="STOCK_4X6"/>
+          <xs:enumeration value="STOCK_4X6.75_LEADING_DOC_TAB"/>
+          <xs:enumeration value="STOCK_4X6.75_TRAILING_DOC_TAB"/>
+          <xs:enumeration value="STOCK_4X8"/>
+          <xs:enumeration value="STOCK_4X9_LEADING_DOC_TAB"/>
+          <xs:enumeration value="STOCK_4X9_TRAILING_DOC_TAB"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="LiabilityCoverageDetail">
+        <xs:sequence>
+          <xs:element name="CoverageType" type="ns:LiabilityCoverageType" minOccurs="0"/>
+          <xs:element name="CoverageAmount" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the Liability Coverage Amount. For Jan 2010 this value represents coverage amount per pound</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="LiabilityCoverageType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="NEW"/>
+          <xs:enumeration value="USED_OR_RECONDITIONED"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="LinearMeasure">
+        <xs:annotation>
+          <xs:documentation>Represents a one-dimensional measurement in small units (e.g. suitable for measuring a package or document), contrasted with Distance, which represents a large one-dimensional measurement (e.g. distance between cities).</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Value" type="xs:decimal" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The numerical quantity of this measurement.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Units" type="ns:LinearUnits" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The units for this measurement.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="LinearUnits">
+        <xs:annotation>
+          <xs:documentation>CM = centimeters, IN = inches</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CM"/>
+          <xs:enumeration value="IN"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Localization">
+        <xs:annotation>
+          <xs:documentation>Identifies the representation of human-readable text.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="LanguageCode" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Two-letter code for language (e.g. EN, FR, etc.)</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LocaleCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Two-letter code for the region (e.g. us, ca, etc..).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="Measure">
+        <xs:sequence>
+          <xs:element name="Quantity" type="xs:decimal" minOccurs="0"/>
+          <xs:element name="Units" type="xs:string" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="MinimumChargeType">
+        <xs:annotation>
+          <xs:documentation>Identifies which type minimum charge was applied.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CUSTOMER"/>
+          <xs:enumeration value="CUSTOMER_FREIGHT_WEIGHT"/>
+          <xs:enumeration value="EARNED_DISCOUNT"/>
+          <xs:enumeration value="MIXED"/>
+          <xs:enumeration value="RATE_SCALE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Money">
+        <xs:annotation>
+          <xs:documentation>The descriptive data for the medium of exchange for FedEx services.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Currency" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the currency of the monetary amount.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>3</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Amount" type="xs:decimal" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the monetary amount.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="NaftaCertificateOfOriginDetail">
+        <xs:annotation>
+          <xs:documentation>Data required to produce a Certificate of Origin document. Remaining content (business data) to be defined once requirements have been completed.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Format" type="ns:ShippingDocumentFormat" minOccurs="0"/>
+          <xs:element name="BlanketPeriod" type="ns:DateRange" minOccurs="0"/>
+          <xs:element name="ImporterSpecification" type="ns:NaftaImporterSpecificationType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates which Party (if any) from the shipment is to be used as the source of importer data on the NAFTA COO form.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SignatureContact" type="ns:Contact" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Contact information for "Authorized Signature" area of form.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ProducerSpecification" type="ns:NaftaProducerSpecificationType" minOccurs="0"/>
+          <xs:element name="Producers" type="ns:NaftaProducer" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="CustomerImageUsages" type="ns:CustomerImageUsage" minOccurs="0" maxOccurs="unbounded"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="NaftaCommodityDetail">
+        <xs:annotation>
+          <xs:documentation>This element is currently not supported and is for the future use.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="PreferenceCriterion" type="ns:NaftaPreferenceCriterionCode" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Defined by NAFTA regulations.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ProducerDetermination" type="ns:NaftaProducerDeterminationCode" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Defined by NAFTA regulations.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ProducerId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identification of which producer is associated with this commodity (if multiple producers are used in a single shipment).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NetCostMethod" type="ns:NaftaNetCostMethodCode" minOccurs="0"/>
+          <xs:element name="NetCostDateRange" type="ns:DateRange" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Date range over which RVC net cost was calculated.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="NaftaImporterSpecificationType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="IMPORTER_OF_RECORD"/>
+          <xs:enumeration value="RECIPIENT"/>
+          <xs:enumeration value="UNKNOWN"/>
+          <xs:enumeration value="VARIOUS"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="NaftaNetCostMethodCode">
+        <xs:annotation>
+          <xs:documentation>Net cost method used.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="NC"/>
+          <xs:enumeration value="NO"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="NaftaPreferenceCriterionCode">
+        <xs:annotation>
+          <xs:documentation>See instructions for NAFTA Certificate of Origin for code definitions.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="A"/>
+          <xs:enumeration value="B"/>
+          <xs:enumeration value="C"/>
+          <xs:enumeration value="D"/>
+          <xs:enumeration value="E"/>
+          <xs:enumeration value="F"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="NaftaProducer">
+        <xs:annotation>
+          <xs:documentation>This element is currently not supported and is for the future use.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Id" type="xs:string" minOccurs="0"/>
+          <xs:element name="Producer" type="ns:Party" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="NaftaProducerDeterminationCode">
+        <xs:annotation>
+          <xs:documentation>See instructions for NAFTA Certificate of Origin for code definitions.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="NO_1"/>
+          <xs:enumeration value="NO_2"/>
+          <xs:enumeration value="NO_3"/>
+          <xs:enumeration value="YES"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="NaftaProducerSpecificationType">
+        <xs:annotation>
+          <xs:documentation>This element is currently not supported and is for the future use.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="AVAILABLE_UPON_REQUEST"/>
+          <xs:enumeration value="MULTIPLE_SPECIFIED"/>
+          <xs:enumeration value="SAME"/>
+          <xs:enumeration value="SINGLE_SPECIFIED"/>
+          <xs:enumeration value="UNKNOWN"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Notification">
+        <xs:annotation>
+          <xs:documentation>The descriptive data regarding the result of the submitted transaction.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Severity" type="ns:NotificationSeverityType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The severity of this notification. This can indicate success or failure or some other information about the request. The values that can be returned are SUCCESS - Your transaction succeeded with no other applicable information. NOTE - Additional information that may be of interest to you about your transaction. WARNING - Additional information that you need to know about your transaction that you may need to take action on. ERROR - Information about an error that occurred while processing your transaction. FAILURE - FedEx was unable to process your transaction at this time due to a system failure. Please try again later</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Source" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Indicates the source of this notification. Combined with the Code it uniquely identifies this notification</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Code" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>A code that represents this notification. Combined with the Source it uniquely identifies this notification.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Message" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Human-readable text that explains this notification.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LocalizedMessage" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The translated message. The language and locale specified in the ClientDetail. Localization are used to determine the representation. Currently only supported in a TrackReply.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="MessageParameters" type="ns:NotificationParameter" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>A collection of name/value pairs that provide specific data to help the client determine the nature of an error (or warning, etc.) witout having to parse the message string.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="NotificationParameter">
+        <xs:sequence>
+          <xs:element name="Id" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the type of data contained in Value (e.g. SERVICE_TYPE, PACKAGE_SEQUENCE, etc..).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Value" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The value of the parameter (e.g. PRIORITY_OVERNIGHT, 2, etc..).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="NotificationSeverityType">
+        <xs:annotation>
+          <xs:documentation>Identifies the set of severity values for a Notification.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ERROR"/>
+          <xs:enumeration value="FAILURE"/>
+          <xs:enumeration value="NOTE"/>
+          <xs:enumeration value="SUCCESS"/>
+          <xs:enumeration value="WARNING"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Op900Detail">
+        <xs:annotation>
+          <xs:documentation>The instructions indicating how to print the OP-900 form for hazardous materials packages.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Format" type="ns:ShippingDocumentFormat" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies characteristics of a shipping document to be produced.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Reference" type="ns:CustomerReferenceType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies which reference type (from the package's customer references) is to be used as the source for the reference on this OP-900.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomerImageUsages" type="ns:CustomerImageUsage" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies the usage and identification of customer supplied images to be used on this document.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SignatureName" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Data field to be used when a name is to be printed in the document instead of (or in addition to) a signature image.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="OversizeClassType">
+        <xs:annotation>
+          <xs:documentation>The oversize class types.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="OVERSIZE_1"/>
+          <xs:enumeration value="OVERSIZE_2"/>
+          <xs:enumeration value="OVERSIZE_3"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="PackageBarcodes">
+        <xs:annotation>
+          <xs:documentation>Each instance of this data type represents the set of barcodes (of all types) which are associated with a specific package.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="BinaryBarcodes" type="ns:BinaryBarcode" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Binary-style barcodes for this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="StringBarcodes" type="ns:StringBarcode" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>String-style barcodes for this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="PackageRateDetail">
+        <xs:annotation>
+          <xs:documentation>Data for a package's rates, as calculated per a specific rate type.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="RateType" type="ns:ReturnedRateType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Type used for this specific set of rate data.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RatedWeightMethod" type="ns:RatedWeightMethod" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates which weight was used.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="MinimumChargeType" type="ns:MinimumChargeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>INTERNAL FEDEX USE ONLY.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BillingWeight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The weight that was used to calculate the rate.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DimWeight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The dimensional weight of this package (if greater than actual).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="OversizeWeight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The oversize weight of this package (if the package is oversize).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="BaseCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The transportation charge only (prior to any discounts applied) for this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalFreightDiscounts" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The sum of all discounts on this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NetFreight" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This package's baseCharge - totalFreightDiscounts.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalSurcharges" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The sum of all surcharges on this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NetFedExCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This package's netFreight + totalSurcharges (not including totalTaxes).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalTaxes" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The sum of all taxes on this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NetCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This package's netFreight + totalSurcharges + totalTaxes.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalRebates" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The total sum of all rebates applied to this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FreightDiscounts" type="ns:RateDiscount" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All rate discounts that apply to this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Rebates" type="ns:Rebate" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All rebates that apply to this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Surcharges" type="ns:Surcharge" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All surcharges that apply to this package (either because of characteristics of the package itself, or because it is carrying per-shipment surcharges for the shipment of which it is a part).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Taxes" type="ns:Tax" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All taxes applicable (or distributed to) this package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="VariableHandlingCharges" type="ns:VariableHandlingCharges" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The variable handling charges calculated based on the type variable handling charges requested.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="PackageRating">
+        <xs:annotation>
+          <xs:documentation>This class groups together for a single package all package-level rate data (across all rate types) as part of the response to a shipping request, which groups shipment-level data together and groups package-level data by package.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="ActualRateType" type="ns:ReturnedRateType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This rate type identifies which entry in the following array is considered as presenting the "actual" rates for the package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EffectiveNetDiscount" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The "list" net charge minus "actual" net charge.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PackageRateDetails" type="ns:PackageRateDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Each element of this field provides package-level rate data for a specific rate type.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="PackageSpecialServiceType">
+        <xs:annotation>
+          <xs:documentation>Identifies the collection of special service offered by FedEx. BROKER_SELECT_OPTION should be used for Ground shipments only.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="APPOINTMENT_DELIVERY"/>
+          <xs:enumeration value="COD"/>
+          <xs:enumeration value="DANGEROUS_GOODS"/>
+          <xs:enumeration value="DRY_ICE"/>
+          <xs:enumeration value="NON_STANDARD_CONTAINER"/>
+          <xs:enumeration value="PRIORITY_ALERT"/>
+          <xs:enumeration value="SIGNATURE_OPTION"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="PackageSpecialServicesRequested">
+        <xs:annotation>
+          <xs:documentation>These special services are available at the package level for some or all service types. If the shipper is requesting a special service which requires additional data, the package special service type must be present in the specialServiceTypes collection, and the supporting detail must be provided in the appropriate sub-object below.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="SpecialServiceTypes" type="ns:PackageSpecialServiceType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>The types of all special services requested for the enclosing shipment or package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CodDetail" type="ns:CodDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>For use with FedEx Ground services only; COD must be present in shipment's special services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DangerousGoodsDetail" type="ns:DangerousGoodsDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data required for a FedEx shipment containing dangerous materials. This element is required when SpecialServiceType.DANGEROUS_GOODS or HAZARDOUS_MATERIAL is present in the SpecialServiceTypes collection.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DryIceWeight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data required for a FedEx shipment containing dry ice. This element is required when SpecialServiceType.DRY_ICE is present in the SpecialServiceTypes collection.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SignatureOptionDetail" type="ns:SignatureOptionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The descriptive data required for FedEx signature services. This element is required when SpecialServiceType.SIGNATURE_OPTION is present in the SpecialServiceTypes collection.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PriorityAlertDetail" type="ns:PriorityAlertDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The descriptive data required for FedEx Priority Alert service. This element is required when SpecialServiceType.PRIORITY_ALERT is present in the SpecialServiceTypes collection.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="PackagingType">
+        <xs:annotation>
+          <xs:documentation>Identifies the collection of available FedEx or customer packaging options.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="FEDEX_10KG_BOX"/>
+          <xs:enumeration value="FEDEX_25KG_BOX"/>
+          <xs:enumeration value="FEDEX_BOX"/>
+          <xs:enumeration value="FEDEX_ENVELOPE"/>
+          <xs:enumeration value="FEDEX_PAK"/>
+          <xs:enumeration value="FEDEX_TUBE"/>
+          <xs:enumeration value="YOUR_PACKAGING"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Party">
+        <xs:annotation>
+          <xs:documentation>The descriptive data for a person or company entitiy doing business with FedEx.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="AccountNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the FedEx account number assigned to the customer.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>12</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Tins" type="ns:TaxpayerIdentification" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="Contact" type="ns:Contact" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data identifying the point-of-contact person.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Address" type="ns:Address" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The descriptive data for a physical location.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="Payment">
+        <xs:annotation>
+          <xs:documentation>The descriptive data for the monetary compensation given to FedEx for services rendered to the customer.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="PaymentType" type="ns:PaymentType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the method of payment for a service. See PaymentType for list of valid enumerated values.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Payor" type="ns:Payor" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data identifying the party responsible for payment for a service.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="PaymentType">
+        <xs:annotation>
+          <xs:documentation>Identifies the method of payment for a service.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="COLLECT"/>
+          <xs:enumeration value="RECIPIENT"/>
+          <xs:enumeration value="SENDER"/>
+          <xs:enumeration value="THIRD_PARTY"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Payor">
+        <xs:annotation>
+          <xs:documentation>The descriptive data identifying the party responsible for payment for a service.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="AccountNumber" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the FedEx account number assigned to the payor.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>12</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CountryCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the country of the payor.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>2</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="PendingShipmentAccessDetail">
+        <xs:annotation>
+          <xs:documentation>This information describes how and when a pending shipment may be accessed for completion.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="EmailLabelUrl" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Only for pending shipment type of "EMAIL"</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="UserId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Only for pending shipment type of "EMAIL"</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Password" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Only for pending shipment type of "EMAIL"</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ExpirationTimestamp" type="xs:dateTime" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This element is currently not supported and is for the future use.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="PendingShipmentDetail">
+        <xs:annotation>
+          <xs:documentation>This information describes the kind of pending shipment being requested.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Type" type="ns:PendingShipmentType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the type of FedEx pending shipment</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ExpirationDate" type="xs:date" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Date after which the pending shipment will no longer be available for completion.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EmailLabelDetail" type="ns:EMailLabelDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Only used with type of EMAIL.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="PendingShipmentType">
+        <xs:annotation>
+          <xs:documentation>Identifies the type of service for a pending shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="EMAIL"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="PhysicalPackagingType">
+        <xs:annotation>
+          <xs:documentation>This enumeration rationalizes the former FedEx Express international "admissibility package" types (based on ANSI X.12) and the FedEx Freight packaging types. The values represented are those common to both carriers.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BAG"/>
+          <xs:enumeration value="BARREL"/>
+          <xs:enumeration value="BASKET"/>
+          <xs:enumeration value="BOX"/>
+          <xs:enumeration value="BUCKET"/>
+          <xs:enumeration value="BUNDLE"/>
+          <xs:enumeration value="CARTON"/>
+          <xs:enumeration value="CASE"/>
+          <xs:enumeration value="CONTAINER"/>
+          <xs:enumeration value="CRATE"/>
+          <xs:enumeration value="CYLINDER"/>
+          <xs:enumeration value="DRUM"/>
+          <xs:enumeration value="ENVELOPE"/>
+          <xs:enumeration value="HAMPER"/>
+          <xs:enumeration value="OTHER"/>
+          <xs:enumeration value="PAIL"/>
+          <xs:enumeration value="PALLET"/>
+          <xs:enumeration value="PIECE"/>
+          <xs:enumeration value="REEL"/>
+          <xs:enumeration value="ROLL"/>
+          <xs:enumeration value="SKID"/>
+          <xs:enumeration value="TANK"/>
+          <xs:enumeration value="TUBE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="PickupDetail">
+        <xs:annotation>
+          <xs:documentation>This class describes the pickup characteristics of a shipment (e.g. for use in a tag request).</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="ReadyDateTime" type="xs:dateTime" minOccurs="0"/>
+          <xs:element name="LatestPickupDateTime" type="xs:dateTime" minOccurs="0"/>
+          <xs:element name="CourierInstructions" type="xs:string" minOccurs="0"/>
+          <xs:element name="RequestType" type="ns:PickupRequestType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the type of Pickup request</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RequestSource" type="ns:PickupRequestSourceType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the type of source for Pickup request</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="PickupRequestSourceType">
+        <xs:annotation>
+          <xs:documentation>Identifies the type of source for pickup request service.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="AUTOMATION"/>
+          <xs:enumeration value="CUSTOMER_SERVICE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="PickupRequestType">
+        <xs:annotation>
+          <xs:documentation>Identifies the type of pickup request service.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="FUTURE_DAY"/>
+          <xs:enumeration value="SAME_DAY"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="PricingCodeType">
+        <xs:annotation>
+          <xs:documentation>Identifies the type of pricing used for this shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ACTUAL"/>
+          <xs:enumeration value="ALTERNATE"/>
+          <xs:enumeration value="BASE"/>
+          <xs:enumeration value="HUNDREDWEIGHT"/>
+          <xs:enumeration value="HUNDREDWEIGHT_ALTERNATE"/>
+          <xs:enumeration value="INTERNATIONAL_DISTRIBUTION"/>
+          <xs:enumeration value="INTERNATIONAL_ECONOMY_SERVICE"/>
+          <xs:enumeration value="LTL_FREIGHT"/>
+          <xs:enumeration value="PACKAGE"/>
+          <xs:enumeration value="SHIPMENT"/>
+          <xs:enumeration value="SHIPMENT_FIVE_POUND_OPTIONAL"/>
+          <xs:enumeration value="SHIPMENT_OPTIONAL"/>
+          <xs:enumeration value="SPECIAL"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="PrintedReference">
+        <xs:annotation>
+          <xs:documentation>Represents a reference identifier printed on Freight bills of lading</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Type" type="ns:PrintedReferenceType" minOccurs="0"/>
+          <xs:element name="Value" type="xs:string" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="PrintedReferenceType">
+        <xs:annotation>
+          <xs:documentation>Identifies a particular reference identifier printed on a Freight bill of lading.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CONSIGNEE_ID_NUMBER"/>
+          <xs:enumeration value="SHIPPER_ID_NUMBER"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="PriorityAlertDetail">
+        <xs:sequence>
+          <xs:element name="Content" type="xs:string" minOccurs="1" maxOccurs="unbounded"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ProcessShipmentReply">
+        <xs:sequence>
+          <xs:element name="HighestSeverity" type="ns:NotificationSeverityType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>This indicates the highest level of severity of all the notifications returned in this reply</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Notifications" type="ns:Notification" minOccurs="1" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>The descriptive data regarding the results of the submitted transaction.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TransactionDetail" type="ns:TransactionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data for this customer transaction. The TransactionDetail from the request is echoed back to the caller in the corresponding reply.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Version" type="ns:VersionId" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the version/level of a service operation expected by a caller (in each request) and performed by the callee (in each reply).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CompletedShipmentDetail" type="ns:CompletedShipmentDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The reply payload. All of the returned information about this shipment/package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ErrorLabels" type="ns:ShippingDocument" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Empty unless error label behavior is PACKAGE_ERROR_LABELS and one or more errors occured during transaction processing.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ProcessShipmentRequest">
+        <xs:annotation>
+          <xs:documentation>Descriptive data sent to FedEx by a customer in order to ship a package.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="WebAuthenticationDetail" type="ns:WebAuthenticationDetail" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data to be used in authentication of the sender's identity (and right to use FedEx web services).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ClientDetail" type="ns:ClientDetail" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data identifying the client submitting the transaction.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TransactionDetail" type="ns:TransactionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data for this customer transaction. The TransactionDetail from the request is echoed back to the caller in the corresponding reply.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Version" type="ns:VersionId" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the version/level of a service operation expected by a caller (in each request) and performed by the callee (in each reply).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RequestedShipment" type="ns:RequestedShipment" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data about the shipment being sent by the requestor.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ProcessTagReply">
+        <xs:sequence>
+          <xs:element name="HighestSeverity" type="ns:NotificationSeverityType" minOccurs="1"/>
+          <xs:element name="Notifications" type="ns:Notification" minOccurs="1" maxOccurs="unbounded"/>
+          <xs:element name="TransactionDetail" type="ns:TransactionDetail" minOccurs="0"/>
+          <xs:element name="Version" type="ns:VersionId" minOccurs="1"/>
+          <xs:element name="CompletedShipmentDetail" type="ns:CompletedShipmentDetail" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ProcessTagRequest">
+        <xs:annotation>
+          <xs:documentation>Descriptive data sent to FedEx by a customer in order to ship a package.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="WebAuthenticationDetail" type="ns:WebAuthenticationDetail" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data to be used in authentication of the sender's identity (and right to use FedEx web services).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ClientDetail" type="ns:ClientDetail" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data identifying the client submitting the transaction.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TransactionDetail" type="ns:TransactionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data for this customer transaction. The TransactionDetail from the request is echoed back to the caller in the corresponding reply.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Version" type="ns:VersionId" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the version/level of a service operation expected by a caller (in each request) and performed by the callee (in each reply).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RequestedShipment" type="ns:RequestedShipment" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data about the shipment being sent by the requestor.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="PurposeOfShipmentType">
+        <xs:annotation>
+          <xs:documentation>Test for the Commercial Invoice. Note that Sold is not a valid Purpose for a Proforma Invoice.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="GIFT"/>
+          <xs:enumeration value="NOT_SOLD"/>
+          <xs:enumeration value="PERSONAL_EFFECTS"/>
+          <xs:enumeration value="REPAIR_AND_RETURN"/>
+          <xs:enumeration value="SAMPLE"/>
+          <xs:enumeration value="SOLD"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="RateDimensionalDivisorType">
+        <xs:annotation>
+          <xs:documentation>Indicates the reason that a dim divisor value was chose.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="COUNTRY"/>
+          <xs:enumeration value="CUSTOMER"/>
+          <xs:enumeration value="OTHER"/>
+          <xs:enumeration value="PRODUCT"/>
+          <xs:enumeration value="WAIVED"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="RateDiscount">
+        <xs:annotation>
+          <xs:documentation>Identifies a discount applied to the shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="RateDiscountType" type="ns:RateDiscountType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the type of discount applied to the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Description" type="xs:string" minOccurs="0"/>
+          <xs:element name="Amount" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The amount of the discount applied to the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Percent" type="xs:decimal" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The percentage of the discount applied to the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="RateDiscountType">
+        <xs:annotation>
+          <xs:documentation>The type of the discount.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BONUS"/>
+          <xs:enumeration value="COUPON"/>
+          <xs:enumeration value="EARNED"/>
+          <xs:enumeration value="INCENTIVE"/>
+          <xs:enumeration value="OTHER"/>
+          <xs:enumeration value="VOLUME"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="RateRequestType">
+        <xs:annotation>
+          <xs:documentation>Identifies the type(s) of rates to be returned in the reply.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ACCOUNT"/>
+          <xs:enumeration value="LIST"/>
+          <xs:enumeration value="PREFERRED"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="RatedWeightMethod">
+        <xs:annotation>
+          <xs:documentation>The weight method used to calculate the rate.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ACTUAL"/>
+          <xs:enumeration value="AVERAGE_PACKAGE_WEIGHT_MINIMUM"/>
+          <xs:enumeration value="BALLOON"/>
+          <xs:enumeration value="DIM"/>
+          <xs:enumeration value="FREIGHT_MINIMUM"/>
+          <xs:enumeration value="MIXED"/>
+          <xs:enumeration value="OVERSIZE"/>
+          <xs:enumeration value="OVERSIZE_1"/>
+          <xs:enumeration value="OVERSIZE_2"/>
+          <xs:enumeration value="OVERSIZE_3"/>
+          <xs:enumeration value="PACKAGING_MINIMUM"/>
+          <xs:enumeration value="WEIGHT_BREAK"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Rebate">
+        <xs:sequence>
+          <xs:element name="RebateType" type="ns:RebateType" minOccurs="0"/>
+          <xs:element name="Description" type="xs:string" minOccurs="0"/>
+          <xs:element name="Amount" type="ns:Money" minOccurs="0"/>
+          <xs:element name="Percent" type="xs:decimal" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="RebateType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BONUS"/>
+          <xs:enumeration value="EARNED"/>
+          <xs:enumeration value="OTHER"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="RecipientCustomsId">
+        <xs:annotation>
+          <xs:documentation>Specifies how the recipient is identified for customs purposes; the requirements on this information vary with destination country.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Type" type="ns:RecipientCustomsIdType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies the kind of identification being used.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Value" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Contains the actual ID value, of the type specified above.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="RecipientCustomsIdType">
+        <xs:annotation>
+          <xs:documentation>Type of Brazilian taxpayer identifier provided in Recipient/TaxPayerIdentification/Number. For shipments bound for Brazil this overrides the value in Recipient/TaxPayerIdentification/TinType</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="COMPANY"/>
+          <xs:enumeration value="INDIVIDUAL"/>
+          <xs:enumeration value="PASSPORT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="RegulatoryControlType">
+        <xs:annotation>
+          <xs:documentation>FOOD_OR_PERISHABLE is required by FDA/BTA; must be true for food/perishable items coming to US or PR from non-US/non-PR origin</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="EU_CIRCULATION"/>
+          <xs:enumeration value="FOOD_OR_PERISHABLE"/>
+          <xs:enumeration value="NAFTA"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="RequestedPackageDetailType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="INDIVIDUAL_PACKAGES"/>
+          <xs:enumeration value="PACKAGE_GROUPS"/>
+          <xs:enumeration value="PACKAGE_SUMMARY"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="RequestedPackageLineItem">
+        <xs:annotation>
+          <xs:documentation>This class rationalizes RequestedPackage and RequestedPackageSummary from previous interfaces. The way in which it is uses within a RequestedShipment depends on the RequestedPackageDetailType value specified for that shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="SequenceNumber" type="xs:positiveInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Used only with INDIVIDUAL_PACKAGE, as a unique identifier of each requested package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="GroupNumber" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Used only with PACKAGE_GROUPS, as a unique identifier of each group of identical packages.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="GroupPackageCount" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Used only with PACKAGE_GROUPS, as a count of packages within a group of identical packages.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="VariableHandlingChargeDetail" type="ns:VariableHandlingChargeDetail" minOccurs="0"/>
+          <xs:element name="InsuredValue" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Only used for INDIVIDUAL_PACKAGES and PACKAGE_GROUPS. Ignored for PACKAGE_SUMMARY, in which case totalInsuredValue and packageCount on the shipment will be used to determine this value.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Weight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Only used for INDIVIDUAL_PACKAGES and PACKAGE_GROUPS. Ignored for PACKAGE_SUMMARY, in which case totalweight and packageCount on the shipment will be used to determine this value.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Dimensions" type="ns:Dimensions" minOccurs="0"/>
+          <xs:element name="PhysicalPackaging" type="ns:PhysicalPackagingType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Provides additional detail on how the customer has physically packaged this item. As of June 2009, required for packages moving under international and SmartPost services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ItemDescription" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Human-readable text describing the package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomerReferences" type="ns:CustomerReference" minOccurs="0" maxOccurs="3"/>
+          <xs:element name="SpecialServicesRequested" type="ns:PackageSpecialServicesRequested" minOccurs="0"/>
+          <xs:element name="ContentRecords" type="ns:ContentRecord" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Only used for INDIVIDUAL_PACKAGES and PACKAGE_GROUPS.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="RequestedShipment">
+        <xs:annotation>
+          <xs:documentation>The descriptive data for the shipment being tendered to FedEx.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="ShipTimestamp" type="xs:dateTime" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the date and time the package is tendered to FedEx. Both the date and time portions of the string are expected to be used. The date should not be a past date or a date more than 10 days in the future. The time is the local time of the shipment based on the shipper's time zone. The date component must be in the format: YYYY-MM-DD (e.g. 2006-06-26). The time component must be in the format: HH:MM:SS using a 24 hour clock (e.g. 11:00 a.m. is 11:00:00, whereas 5:00 p.m. is 17:00:00). The date and time parts are separated by the letter T (e.g. 2006-06-26T17:00:00). There is also a UTC offset component indicating the number of hours/mainutes from UTC (e.g 2006-06-26T17:00:00-0400 is defined form June 26, 2006 5:00 pm Eastern Time).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DropoffType" type="ns:DropoffType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the method by which the package is to be tendered to FedEx. This element does not dispatch a courier for package pickup. See DropoffType for list of valid enumerated values.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ServiceType" type="ns:ServiceType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the FedEx service to use in shipping the package. See ServiceType for list of valid enumerated values.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PackagingType" type="ns:PackagingType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the packaging used by the requestor for the package. See PackagingType for list of valid enumerated values.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalWeight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the total weight of the shipment being conveyed to FedEx.This is only applicable to International shipments and should only be used on the first package of a mutiple piece shipment.This value contains 1 explicit decimal position</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalInsuredValue" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Total insured amount.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalDimensions" type="ns:Dimensions" minOccurs="0"/>
+          <xs:element name="Shipper" type="ns:Party" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data identifying the party responsible for shipping the package. Shipper and Origin should have the same address.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Recipient" type="ns:Party" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data identifying the party receiving the package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RecipientLocationNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>A unique identifier for a recipient location</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>10</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Origin" type="ns:ContactAndAddress" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Physical starting address for the shipment, if different from shipper's address.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ShippingChargesPayment" type="ns:Payment" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data indicating the method and means of payment to FedEx for providing shipping services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SpecialServicesRequested" type="ns:ShipmentSpecialServicesRequested" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data regarding special services requested by the shipper for this shipment. If the shipper is requesting a special service which requires additional data (e.g. COD), the special service type must be present in the specialServiceTypes collection, and the supporting detail must be provided in the appropriate sub-object. For example, to request COD, "COD" must be included in the SpecialServiceTypes collection and the CodDetail object must contain the required data.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ExpressFreightDetail" type="ns:ExpressFreightDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Details specific to an Express freight shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FreightShipmentDetail" type="ns:FreightShipmentDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Data applicable to shipments using FEDEX_FREIGHT and FEDEX_NATIONAL_FREIGHT services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DeliveryInstructions" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Used with Ground Home Delivery and Freight.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="VariableHandlingChargeDetail" type="ns:VariableHandlingChargeDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Details about how to calculate variable handling charges at the shipment level.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomsClearanceDetail" type="ns:CustomsClearanceDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Customs clearance data, used for both international and intra-country shipping.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PickupDetail" type="ns:PickupDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>For use in "process tag" transaction.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SmartPostDetail" type="ns:SmartPostShipmentDetail" minOccurs="0"/>
+          <xs:element name="BlockInsightVisibility" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>If true, only the shipper/payor will have visibility of this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ErrorLabelBehavior" type="ns:ErrorLabelBehaviorType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies the client-requested response in the event of errors within shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LabelSpecification" type="ns:LabelSpecification" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Details about the image format and printer type the label is to returned in.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ShippingDocumentSpecification" type="ns:ShippingDocumentSpecification" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Contains data used to create additional (non-label) shipping documents.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RateRequestTypes" type="ns:RateRequestType" minOccurs="1" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies whether and what kind of rates the customer wishes to have quoted on this shipment. The reply will also be constrained by other data on the shipment and customer.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomerSelectedActualRateType" type="ns:ReturnedRateType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies the type of rate the customer wishes to have used as the actual rate type.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EdtRequestType" type="ns:EdtRequestType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies whether the customer wishes to have Estimated Duties and Taxes provided with the rate quotation on this shipment. Only applies with shipments moving under international services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="MasterTrackingId" type="ns:TrackingId" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Only used with multiple-transaction shipments.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CodReturnTrackingId" type="ns:TrackingId" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Only used with multi-piece COD shipments sent in multiple transactions. Required on last transaction only.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PackageCount" type="xs:nonNegativeInteger" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The total number of packages in the entire shipment (even when the shipment spans multiple transactions.)</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PackageDetail" type="ns:RequestedPackageDetailType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies whether packages are described individually, in groups, or summarized in a single description for total-piece-total-weight. This field controls which fields of the RequestedPackageLineItem will be used, and how many occurrences are expected.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RequestedPackageLineItems" type="ns:RequestedPackageLineItem" minOccurs="0" maxOccurs="999">
+            <xs:annotation>
+              <xs:documentation>One or more package-attribute descriptions, each of which describes an individual package, a group of identical packages, or (for the total-piece-total-weight case) common characteristics all packages in the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="RequestedShippingDocumentType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CERTIFICATE_OF_ORIGIN"/>
+          <xs:enumeration value="COMMERCIAL_INVOICE"/>
+          <xs:enumeration value="CUSTOMER_SPECIFIED_LABELS"/>
+          <xs:enumeration value="CUSTOM_PACKAGE_DOCUMENT"/>
+          <xs:enumeration value="CUSTOM_SHIPMENT_DOCUMENT"/>
+          <xs:enumeration value="FREIGHT_ADDRESS_LABEL"/>
+          <xs:enumeration value="GENERAL_AGENCY_AGREEMENT"/>
+          <xs:enumeration value="LABEL"/>
+          <xs:enumeration value="NAFTA_CERTIFICATE_OF_ORIGIN"/>
+          <xs:enumeration value="OP_900"/>
+          <xs:enumeration value="PRO_FORMA_INVOICE"/>
+          <xs:enumeration value="RETURN_INSTRUCTIONS"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="ReturnEMailAllowedSpecialServiceType">
+        <xs:annotation>
+          <xs:documentation>These values are used to control the availability of certain special services at the time when a customer uses the e-mail label link to create a return shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="SATURDAY_DELIVERY"/>
+          <xs:enumeration value="SATURDAY_PICKUP"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="ReturnEMailDetail">
+        <xs:annotation>
+          <xs:documentation>Return Email Details</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="MerchantPhoneNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Phone number of the merchant</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AllowedSpecialServices" type="ns:ReturnEMailAllowedSpecialServiceType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Identifies the allowed (merchant-authorized) special services which may be selected when the subsequent shipment is created. Only services represented in EMailLabelAllowedSpecialServiceType will be controlled by this list.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ReturnShipmentDetail">
+        <xs:annotation>
+          <xs:documentation>Information relating to a return shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="ReturnType" type="ns:ReturnType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The type of return shipment that is being requested.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Rma" type="ns:Rma" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Return Merchant Authorization</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ReturnEMailDetail" type="ns:ReturnEMailDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Describes specific information about the email label for return shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="ReturnType">
+        <xs:annotation>
+          <xs:documentation>The type of return shipment that is being requested.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="FEDEX_TAG"/>
+          <xs:enumeration value="PENDING"/>
+          <xs:enumeration value="PRINT_RETURN_LABEL"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="ReturnedRateType">
+        <xs:annotation>
+          <xs:documentation>The "PAYOR..." rates are expressed in the currency identified in the payor's rate table(s). The "RATED..." rates are expressed in the currency of the origin country. Former "...COUNTER..." values have become "...RETAIL..." values, except for PAYOR_COUNTER and RATED_COUNTER, which have been removed.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="INCENTIVE"/>
+          <xs:enumeration value="PAYOR_ACCOUNT_PACKAGE"/>
+          <xs:enumeration value="PAYOR_ACCOUNT_SHIPMENT"/>
+          <xs:enumeration value="PAYOR_LIST_PACKAGE"/>
+          <xs:enumeration value="PAYOR_LIST_SHIPMENT"/>
+          <xs:enumeration value="RATED_ACCOUNT_PACKAGE"/>
+          <xs:enumeration value="RATED_ACCOUNT_SHIPMENT"/>
+          <xs:enumeration value="RATED_LIST_PACKAGE"/>
+          <xs:enumeration value="RATED_LIST_SHIPMENT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="ReturnedShippingDocumentType">
+        <xs:annotation>
+          <xs:documentation>Shipping document type.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="AUXILIARY_LABEL"/>
+          <xs:enumeration value="CERTIFICATE_OF_ORIGIN"/>
+          <xs:enumeration value="COD_RETURN_2_D_BARCODE"/>
+          <xs:enumeration value="COD_RETURN_LABEL"/>
+          <xs:enumeration value="COMMERCIAL_INVOICE"/>
+          <xs:enumeration value="CUSTOM_PACKAGE_DOCUMENT"/>
+          <xs:enumeration value="CUSTOM_SHIPMENT_DOCUMENT"/>
+          <xs:enumeration value="ETD_LABEL"/>
+          <xs:enumeration value="FREIGHT_ADDRESS_LABEL"/>
+          <xs:enumeration value="GENERAL_AGENCY_AGREEMENT"/>
+          <xs:enumeration value="GROUND_BARCODE"/>
+          <xs:enumeration value="NAFTA_CERTIFICATE_OF_ORIGIN"/>
+          <xs:enumeration value="OP_900"/>
+          <xs:enumeration value="OUTBOUND_2_D_BARCODE"/>
+          <xs:enumeration value="OUTBOUND_LABEL"/>
+          <xs:enumeration value="PRO_FORMA_INVOICE"/>
+          <xs:enumeration value="RECIPIENT_ADDRESS_BARCODE"/>
+          <xs:enumeration value="RECIPIENT_POSTAL_BARCODE"/>
+          <xs:enumeration value="RETURN_INSTRUCTIONS"/>
+          <xs:enumeration value="TERMS_AND_CONDITIONS"/>
+          <xs:enumeration value="USPS_BARCODE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Rma">
+        <xs:annotation>
+          <xs:documentation>Return Merchant Authorization</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Number" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The RMA number.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>20</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Reason" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The reason for the return.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>60</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="RoutingAstraDetail">
+        <xs:annotation>
+          <xs:documentation>The tracking number information and the data to form the Astra barcode for the label.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="TrackingId" type="ns:TrackingId" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The tracking number information for the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Barcode" type="ns:StringBarcode" minOccurs="0"/>
+          <xs:element name="AstraHandlingText" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The textual description of the special service applied to the package.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AstraLabelElements" type="ns:AstraLabelElement" minOccurs="0" maxOccurs="unbounded"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="RoutingDetail">
+        <xs:annotation>
+          <xs:documentation>Information about the routing, origin, destination and delivery of a shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="ShipmentRoutingDetail" type="ns:ShipmentRoutingDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The routing information detail for this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AstraDetails" type="ns:RoutingAstraDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>The tracking number information and the data to form the Astra barcode for the label.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="ServiceType">
+        <xs:annotation>
+          <xs:documentation>Identifies the collection of available FedEx service options.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="EUROPE_FIRST_INTERNATIONAL_PRIORITY"/>
+          <xs:enumeration value="FEDEX_1_DAY_FREIGHT"/>
+          <xs:enumeration value="FEDEX_2_DAY"/>
+          <xs:enumeration value="FEDEX_2_DAY_FREIGHT"/>
+          <xs:enumeration value="FEDEX_3_DAY_FREIGHT"/>
+          <xs:enumeration value="FEDEX_EXPRESS_SAVER"/>
+          <xs:enumeration value="FEDEX_GROUND"/>
+          <xs:enumeration value="FIRST_OVERNIGHT"/>
+          <xs:enumeration value="GROUND_HOME_DELIVERY"/>
+          <xs:enumeration value="INTERNATIONAL_ECONOMY"/>
+          <xs:enumeration value="INTERNATIONAL_ECONOMY_FREIGHT"/>
+          <xs:enumeration value="INTERNATIONAL_FIRST"/>
+          <xs:enumeration value="INTERNATIONAL_GROUND"/>
+          <xs:enumeration value="INTERNATIONAL_PRIORITY"/>
+          <xs:enumeration value="INTERNATIONAL_PRIORITY_FREIGHT"/>
+          <xs:enumeration value="PRIORITY_OVERNIGHT"/>
+          <xs:enumeration value="SMART_POST"/>
+          <xs:enumeration value="STANDARD_OVERNIGHT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="ShipmentDryIceDetail">
+        <xs:annotation>
+          <xs:documentation>Shipment-level totals of dry ice data across all packages.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="PackageCount" type="xs:nonNegativeInteger" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Total number of packages in the shipment that contain dry ice.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalWeight" type="ns:Weight" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Total shipment dry ice weight for all packages.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ShipmentRateDetail">
+        <xs:annotation>
+          <xs:documentation>Data for a shipment's total/summary rates, as calculated per a specific rate type. The "total..." fields may differ from the sum of corresponding package data for Multiweight or Express MPS.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="RateType" type="ns:ReturnedRateType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Type used for this specific set of rate data.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RateScale" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates the rate scale used.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RateZone" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates the rate zone used (based on origin and destination).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PricingCode" type="ns:PricingCodeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the type of pricing used for this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RatedWeightMethod" type="ns:RatedWeightMethod" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Indicates which weight was used.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="MinimumChargeType" type="ns:MinimumChargeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>INTERNAL FEDEX USE ONLY.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CurrencyExchangeRate" type="ns:CurrencyExchangeRate" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies the currency exchange performed on financial amounts for this rate.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SpecialRatingApplied" type="ns:SpecialRatingAppliedType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Indicates which special rating cases applied to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DimDivisor" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The value used to calculate the weight based on the dimensions.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DimDivisorType" type="ns:RateDimensionalDivisorType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the type of dim divisor that was applied.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FuelSurchargePercent" type="xs:decimal" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies a fuel surcharge percentage.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalBillingWeight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The weight used to calculate these rates.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalDimWeight" type="ns:Weight" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Sum of dimensional weights for all packages.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalBaseCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The total freight charge that was calculated for this package before surcharges, discounts and taxes.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalFreightDiscounts" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The total discounts used in the rate calculation.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalNetFreight" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The freight charge minus discounts.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalSurcharges" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The total amount of all surcharges applied to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalNetFedExCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This shipment's totalNetFreight + totalSurcharges (not including totalTaxes).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalTaxes" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Total of the transportation-based taxes.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalNetCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The net charge after applying all discounts and surcharges.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalRebates" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The total sum of all rebates applied to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalDutiesAndTaxes" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Total of all values under this shipment's dutiesAndTaxes; only provided if estimated duties and taxes were calculated for this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalNetChargeWithDutiesAndTaxes" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This shipment's totalNetCharge + totalDutiesAndTaxes; only provided if estimated duties and taxes were calculated for this shipment AND duties, taxes and transportation charges are all paid by the same sender's account.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FreightRateDetail" type="ns:FreightRateDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Rate data specific to FedEx Freight and FedEx National Freight services.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FreightDiscounts" type="ns:RateDiscount" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All rate discounts that apply to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Rebates" type="ns:Rebate" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All rebates that apply to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Surcharges" type="ns:Surcharge" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All surcharges that apply to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Taxes" type="ns:Tax" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All transportation-based taxes applicable to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DutiesAndTaxes" type="ns:EdtCommodityTax" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>All commodity-based duties and taxes applicable to this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="VariableHandlingCharges" type="ns:VariableHandlingCharges" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The "order level" variable handling charges.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalVariableHandlingCharges" type="ns:VariableHandlingCharges" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The total of all variable handling charges at both shipment (order) and package level.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ShipmentRating">
+        <xs:annotation>
+          <xs:documentation>This class groups together all shipment-level rate data (across all rate types) as part of the response to a shipping request, which groups shipment-level data together and groups package-level data by package.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="ActualRateType" type="ns:ReturnedRateType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This rate type identifies which entry in the following array is considered as presenting the "actual" rates for the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EffectiveNetDiscount" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The "list" total net charge minus "actual" total net charge.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ShipmentRateDetails" type="ns:ShipmentRateDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Each element of this field provides shipment-level rate totals for a specific rate type.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ShipmentReply">
+        <xs:sequence>
+          <xs:element name="HighestSeverity" type="ns:NotificationSeverityType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>This indicates the highest level of severity of all the notifications returned in this reply</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Notifications" type="ns:Notification" minOccurs="1" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>The descriptive data regarding the results of the submitted transaction.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TransactionDetail" type="ns:TransactionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data for this customer transaction. The TransactionDetail from the request is echoed back to the caller in the corresponding reply.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Version" type="ns:VersionId" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the version/level of a service operation expected by a caller (in each request) and performed by the callee (in each reply).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ShipmentRoutingDetail">
+        <xs:annotation>
+          <xs:documentation>Information about the routing, origin, destination and delivery of a shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="UrsaPrefixCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The prefix portion of the URSA (Universal Routing and Sort Aid) code.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>2</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="UrsaSuffixCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The suffix portion of the URSA code.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>5</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="OriginLocationId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The identifier of the origin location of the shipment. Express only.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>5</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="OriginServiceArea" type="xs:string" minOccurs="0"/>
+          <xs:element name="DestinationLocationId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The identifier of the destination location of the shipment. Express only.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>5</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DestinationServiceArea" type="xs:string" minOccurs="0"/>
+          <xs:element name="DestinationLocationStateOrProvinceCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This is the state of the destination location ID, and is not necessarily the same as the postal state.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DeliveryDate" type="xs:date" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Expected/estimated date of delivery.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="DeliveryDay" type="ns:DayOfWeekType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Expected/estimated day of week of delivery.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CommitDate" type="xs:date" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Committed date of delivery.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CommitDay" type="ns:DayOfWeekType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Committed day of week of delivery.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TransitTime" type="ns:TransitTimeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Standard transit time per origin, destination, and service.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="MaximumTransitTime" type="ns:TransitTimeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Maximum expected transit time</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AstraPlannedServiceLevel" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Text describing planned delivery.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AstraDescription" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Currently not supported.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>TBD</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PostalCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The postal code of the destination of the shipment.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>16</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="StateOrProvinceCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The state or province code of the destination of the shipment.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>14</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CountryCode" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The country code of the destination of the shipment.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>2</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="AirportId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The identifier for the airport of the destination of the shipment.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>4</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="ShipmentSpecialServiceType">
+        <xs:annotation>
+          <xs:documentation>Identifies the collection of special service offered by FedEx. BROKER_SELECT_OPTION should be used for Express shipments only.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BROKER_SELECT_OPTION"/>
+          <xs:enumeration value="CALL_BEFORE_DELIVERY"/>
+          <xs:enumeration value="COD"/>
+          <xs:enumeration value="CUSTOM_DELIVERY_WINDOW"/>
+          <xs:enumeration value="DANGEROUS_GOODS"/>
+          <xs:enumeration value="DO_NOT_BREAK_DOWN_PALLETS"/>
+          <xs:enumeration value="DO_NOT_STACK_PALLETS"/>
+          <xs:enumeration value="DRY_ICE"/>
+          <xs:enumeration value="EAST_COAST_SPECIAL"/>
+          <xs:enumeration value="ELECTRONIC_TRADE_DOCUMENTS"/>
+          <xs:enumeration value="EMAIL_NOTIFICATION"/>
+          <xs:enumeration value="EXTREME_LENGTH"/>
+          <xs:enumeration value="FOOD"/>
+          <xs:enumeration value="FREIGHT_GUARANTEE"/>
+          <xs:enumeration value="FUTURE_DAY_SHIPMENT"/>
+          <xs:enumeration value="HOLD_AT_LOCATION"/>
+          <xs:enumeration value="HOME_DELIVERY_PREMIUM"/>
+          <xs:enumeration value="INSIDE_DELIVERY"/>
+          <xs:enumeration value="INSIDE_PICKUP"/>
+          <xs:enumeration value="LIFTGATE_DELIVERY"/>
+          <xs:enumeration value="LIFTGATE_PICKUP"/>
+          <xs:enumeration value="LIMITED_ACCESS_DELIVERY"/>
+          <xs:enumeration value="LIMITED_ACCESS_PICKUP"/>
+          <xs:enumeration value="PENDING_SHIPMENT"/>
+          <xs:enumeration value="POISON"/>
+          <xs:enumeration value="PROTECTION_FROM_FREEZING"/>
+          <xs:enumeration value="RETURN_SHIPMENT"/>
+          <xs:enumeration value="SATURDAY_DELIVERY"/>
+          <xs:enumeration value="SATURDAY_PICKUP"/>
+          <xs:enumeration value="TOP_LOAD"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="ShipmentSpecialServicesRequested">
+        <xs:annotation>
+          <xs:documentation>These special services are available at the shipment level for some or all service types. If the shipper is requesting a special service which requires additional data (such as the COD amount), the shipment special service type must be present in the specialServiceTypes collection, and the supporting detail must be provided in the appropriate sub-object below.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="SpecialServiceTypes" type="ns:ShipmentSpecialServiceType" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>The types of all special services requested for the enclosing shipment (or other shipment-level transaction).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CodDetail" type="ns:CodDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data required for a FedEx COD (Collect-On-Delivery) shipment. This element is required when SpecialServiceType.COD is present in the SpecialServiceTypes collection.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="HoldAtLocationDetail" type="ns:HoldAtLocationDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data required for a FedEx shipment that is to be held at the destination FedEx location for pickup by the recipient. This element is required when SpecialServiceType.HOLD_AT_LOCATION is present in the SpecialServiceTypes collection.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EMailNotificationDetail" type="ns:EMailNotificationDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data required for FedEx to provide email notification to the customer regarding the shipment. This element is required when SpecialServiceType.EMAIL_NOTIFICATION is present in the SpecialServiceTypes collection.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ReturnShipmentDetail" type="ns:ReturnShipmentDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The descriptive data required for FedEx Printed Return Label. This element is required when SpecialServiceType.PRINTED_RETURN_LABEL is present in the SpecialServiceTypes collection</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PendingShipmentDetail" type="ns:PendingShipmentDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This field should be populated for pending shipments (e.g. e-mail label) It is required by a PENDING_SHIPMENT special service type.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ShipmentDryIceDetail" type="ns:ShipmentDryIceDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Number of packages in this shipment which contain dry ice and the total weight of the dry ice for this shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="HomeDeliveryPremiumDetail" type="ns:HomeDeliveryPremiumDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The descriptive data required for FedEx Home Delivery options. This element is required when SpecialServiceType.HOME_DELIVERY_PREMIUM is present in the SpecialServiceTypes collection</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EtdDetail" type="ns:EtdDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Electronic Trade document references.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomDeliveryWindowDetail" type="ns:CustomDeliveryWindowDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specification for date or range of dates on which delivery is to be attempted.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ShippingDocument">
+        <xs:annotation>
+          <xs:documentation>All package-level shipping documents (other than labels and barcodes).</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Type" type="ns:ReturnedShippingDocumentType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Shipping Document Type</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Grouping" type="ns:ShippingDocumentGroupingType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies how this document image/file is organized.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ShippingDocumentDisposition" type="ns:ShippingDocumentDispositionType" minOccurs="0"/>
+          <xs:element name="AccessReference" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The name under which a STORED or DEFERRED document is written.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Resolution" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies the image resolution in DPI (dots per inch).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CopiesToPrint" type="xs:nonNegativeInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Can be zero for documents whose disposition implies that no content is included.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Parts" type="ns:ShippingDocumentPart" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>One or more document parts which make up a single logical document, such as multiple pages of a single form.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ShippingDocumentDispositionDetail">
+        <xs:annotation>
+          <xs:documentation>Each occurrence of this class specifies a particular way in which a kind of shipping document is to be produced and provided.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="DispositionType" type="ns:ShippingDocumentDispositionType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Values in this field specify how to create and return the document.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Grouping" type="ns:ShippingDocumentGroupingType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies how to organize all documents of this type.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="EMailDetail" type="ns:ShippingDocumentEMailDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies how to e-mail document images.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PrintDetail" type="ns:ShippingDocumentPrintDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies how a queued document is to be printed.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="ShippingDocumentDispositionType">
+        <xs:annotation>
+          <xs:documentation>Specifies how to return a shipping document to the caller.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CONFIRMED"/>
+          <xs:enumeration value="DEFERRED_RETURNED"/>
+          <xs:enumeration value="DEFERRED_STORED"/>
+          <xs:enumeration value="EMAILED"/>
+          <xs:enumeration value="QUEUED"/>
+          <xs:enumeration value="RETURNED"/>
+          <xs:enumeration value="STORED"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="ShippingDocumentEMailDetail">
+        <xs:annotation>
+          <xs:documentation>Specifies how to e-mail shipping documents.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="EMailRecipients" type="ns:ShippingDocumentEMailRecipient" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Provides the roles and email addresses for e-mail recipients.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Grouping" type="ns:ShippingDocumentEMailGroupingType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the convention by which documents are to be grouped as e-mail attachments.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="ShippingDocumentEMailGroupingType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BY_RECIPIENT"/>
+          <xs:enumeration value="NONE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="ShippingDocumentEMailRecipient">
+        <xs:annotation>
+          <xs:documentation>Specifies an individual recipient of e-mailed shipping document(s).</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="RecipientType" type="ns:EMailNotificationRecipientType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the relationship of this recipient in the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Address" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Address to which the document is to be sent.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ShippingDocumentFormat">
+        <xs:annotation>
+          <xs:documentation>Specifies characteristics of a shipping document to be produced.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Dispositions" type="ns:ShippingDocumentDispositionDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies how to create, organize, and return the document.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TopOfPageOffset" type="ns:LinearMeasure" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies how far down the page to move the beginning of the image; allows for printing on letterhead and other pre-printed stock.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ImageType" type="ns:ShippingDocumentImageType" minOccurs="0"/>
+          <xs:element name="StockType" type="ns:ShippingDocumentStockType" minOccurs="0"/>
+          <xs:element name="ProvideInstructions" type="xs:boolean" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>For those shipping document types which have both a "form" and "instructions" component (e.g. NAFTA Certificate of Origin and General Agency Agreement), this field indicates whether to provide the instructions.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Localization" type="ns:Localization" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Governs the language to be used for this individual document, independently from other content returned for the same shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomDocumentIdentifier" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the individual document specified by the client.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="ShippingDocumentGroupingType">
+        <xs:annotation>
+          <xs:documentation>Specifies how to organize all shipping documents of the same type.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CONSOLIDATED_BY_DOCUMENT_TYPE"/>
+          <xs:enumeration value="INDIVIDUAL"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="ShippingDocumentImageType">
+        <xs:annotation>
+          <xs:documentation>Specifies the image format used for a shipping document.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="DOC"/>
+          <xs:enumeration value="DPL"/>
+          <xs:enumeration value="EPL2"/>
+          <xs:enumeration value="PDF"/>
+          <xs:enumeration value="PNG"/>
+          <xs:enumeration value="RTF"/>
+          <xs:enumeration value="TEXT"/>
+          <xs:enumeration value="ZPLII"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="ShippingDocumentPart">
+        <xs:annotation>
+          <xs:documentation>A single part of a shipping document, such as one page of a multiple-page document whose format requires a separate image per page.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="DocumentPartSequenceNumber" type="xs:positiveInteger" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The one-origin position of this part within a document.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Image" type="xs:base64Binary" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Graphic or printer commands for this image within a document.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ShippingDocumentPrintDetail">
+        <xs:annotation>
+          <xs:documentation>Specifies printing options for a shipping document.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="PrinterId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Provides environment-specific printer identification.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ShippingDocumentSpecification">
+        <xs:annotation>
+          <xs:documentation>Contains all data required for additional (non-label) shipping documents to be produced in conjunction with a specific shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="ShippingDocumentTypes" type="ns:RequestedShippingDocumentType" minOccurs="1" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Indicates the types of shipping documents requested by the shipper.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CertificateOfOrigin" type="ns:CertificateOfOriginDetail" minOccurs="0"/>
+          <xs:element name="CommercialInvoiceDetail" type="ns:CommercialInvoiceDetail" minOccurs="0"/>
+          <xs:element name="CustomPackageDocumentDetail" type="ns:CustomDocumentDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies the production of each package-level custom document (the same specification is used for all packages).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="CustomShipmentDocumentDetail" type="ns:CustomDocumentDetail" minOccurs="0" maxOccurs="unbounded">
+            <xs:annotation>
+              <xs:documentation>Specifies the production of a shipment-level custom document.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="GeneralAgencyAgreementDetail" type="ns:GeneralAgencyAgreementDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>This element is currently not supported and is for the future use. (Details pertaining to the GAA.)</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="NaftaCertificateOfOriginDetail" type="ns:NaftaCertificateOfOriginDetail" minOccurs="0"/>
+          <xs:element name="Op900Detail" type="ns:Op900Detail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies the production of the OP-900 document for hazardous materials packages.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FreightAddressLabelDetail" type="ns:FreightAddressLabelDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies the production of the OP-900 document for hazardous materials.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="ShippingDocumentStockType">
+        <xs:annotation>
+          <xs:documentation>Specifies the type of paper (stock) on which a document will be printed.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="OP_900_LG_B"/>
+          <xs:enumeration value="OP_900_LL_B"/>
+          <xs:enumeration value="OP_950"/>
+          <xs:enumeration value="PAPER_4X6"/>
+          <xs:enumeration value="PAPER_LETTER"/>
+          <xs:enumeration value="STOCK_4X6"/>
+          <xs:enumeration value="STOCK_4X6.75_LEADING_DOC_TAB"/>
+          <xs:enumeration value="STOCK_4X6.75_TRAILING_DOC_TAB"/>
+          <xs:enumeration value="STOCK_4X8"/>
+          <xs:enumeration value="STOCK_4X9_LEADING_DOC_TAB"/>
+          <xs:enumeration value="STOCK_4X9_TRAILING_DOC_TAB"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="SignatureOptionDetail">
+        <xs:annotation>
+          <xs:documentation>The descriptive data required for FedEx delivery signature services.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="OptionType" type="ns:SignatureOptionType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the delivery signature services option selected by the customer for this shipment. See OptionType for the list of valid values.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="SignatureReleaseNumber" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the delivery signature release authorization number.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>10</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="SignatureOptionType">
+        <xs:annotation>
+          <xs:documentation>Identifies the delivery signature services options offered by FedEx.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ADULT"/>
+          <xs:enumeration value="DIRECT"/>
+          <xs:enumeration value="INDIRECT"/>
+          <xs:enumeration value="NO_SIGNATURE_REQUIRED"/>
+          <xs:enumeration value="SERVICE_DEFAULT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="SmartPostAncillaryEndorsementType">
+        <xs:annotation>
+          <xs:documentation>These values are mutually exclusive; at most one of them can be attached to a SmartPost shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ADDRESS_CORRECTION"/>
+          <xs:enumeration value="CARRIER_LEAVE_IF_NO_RESPONSE"/>
+          <xs:enumeration value="CHANGE_SERVICE"/>
+          <xs:enumeration value="FORWARDING_SERVICE"/>
+          <xs:enumeration value="RETURN_SERVICE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="SmartPostIndiciaType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="MEDIA_MAIL"/>
+          <xs:enumeration value="PARCEL_RETURN"/>
+          <xs:enumeration value="PARCEL_SELECT"/>
+          <xs:enumeration value="PRESORTED_BOUND_PRINTED_MATTER"/>
+          <xs:enumeration value="PRESORTED_STANDARD"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="SmartPostShipmentDetail">
+        <xs:annotation>
+          <xs:documentation>Data required for shipments handled under the SMART_POST and GROUND_SMART_POST service types.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Indicia" type="ns:SmartPostIndiciaType" minOccurs="0"/>
+          <xs:element name="AncillaryEndorsement" type="ns:SmartPostAncillaryEndorsementType" minOccurs="0"/>
+          <xs:element name="HubId" type="xs:string" minOccurs="0"/>
+          <xs:element name="CustomerManifestId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>
+                The CustomerManifestId is used to group Smart Post packages onto a manifest for each trailer that is being prepared. If you do not have multiple trailers this field can be omitted. If you have multiple trailers, you
+                must assign the same Manifest Id to each SmartPost package as determined by its trailer.  In other words, all packages on a trailer must have the same Customer Manifest Id. The manifest Id must be unique to your account number for a minimum of 6 months
+                and cannot exceed 8 characters in length. We recommend you use the day of year + the trailer id (this could simply be a sequential number for that trailer). So if you had 3 trailers that you started loading on Feb 10
+                the 3 manifest ids would be 041001, 041002, 041003 (in this case we used leading zeros on the trailer numbers).
+              </xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="SpecialRatingAppliedType">
+        <xs:annotation>
+          <xs:documentation>Special circumstance rating used for this shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="FIXED_FUEL_SURCHARGE"/>
+          <xs:enumeration value="IMPORT_PRICING"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="StringBarcode">
+        <xs:annotation>
+          <xs:documentation>Each instance of this data type represents a barcode whose content must be represented as ASCII text (i.e. not binary data).</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Type" type="ns:StringBarcodeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The kind of barcode data in this instance.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Value" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The data content of this instance.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="StringBarcodeType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ADDRESS"/>
+          <xs:enumeration value="ASTRA"/>
+          <xs:enumeration value="FDX_1D"/>
+          <xs:enumeration value="GROUND"/>
+          <xs:enumeration value="POSTAL"/>
+          <xs:enumeration value="USPS"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Surcharge">
+        <xs:annotation>
+          <xs:documentation>Identifies each surcharge applied to the shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="SurchargeType" type="ns:SurchargeType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The type of surcharge applied to the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Level" type="ns:SurchargeLevelType" minOccurs="0"/>
+          <xs:element name="Description" type="xs:string" minOccurs="0"/>
+          <xs:element name="Amount" type="ns:Money" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The amount of the surcharge applied to the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="SurchargeLevelType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="PACKAGE"/>
+          <xs:enumeration value="SHIPMENT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="SurchargeType">
+        <xs:annotation>
+          <xs:documentation>The type of the surcharge.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="ADDITIONAL_HANDLING"/>
+          <xs:enumeration value="ANCILLARY_FEE"/>
+          <xs:enumeration value="APPOINTMENT_DELIVERY"/>
+          <xs:enumeration value="BROKER_SELECT_OPTION"/>
+          <xs:enumeration value="CANADIAN_DESTINATION"/>
+          <xs:enumeration value="CLEARANCE_ENTRY_FEE"/>
+          <xs:enumeration value="COD"/>
+          <xs:enumeration value="CUT_FLOWERS"/>
+          <xs:enumeration value="DANGEROUS_GOODS"/>
+          <xs:enumeration value="DELIVERY_AREA"/>
+          <xs:enumeration value="DELIVERY_CONFIRMATION"/>
+          <xs:enumeration value="DOCUMENTATION_FEE"/>
+          <xs:enumeration value="DRY_ICE"/>
+          <xs:enumeration value="EMAIL_LABEL"/>
+          <xs:enumeration value="EUROPE_FIRST"/>
+          <xs:enumeration value="EXCESS_VALUE"/>
+          <xs:enumeration value="EXHIBITION"/>
+          <xs:enumeration value="EXPORT"/>
+          <xs:enumeration value="EXTREME_LENGTH"/>
+          <xs:enumeration value="FEDEX_TAG"/>
+          <xs:enumeration value="FICE"/>
+          <xs:enumeration value="FLATBED"/>
+          <xs:enumeration value="FREIGHT_GUARANTEE"/>
+          <xs:enumeration value="FREIGHT_ON_VALUE"/>
+          <xs:enumeration value="FUEL"/>
+          <xs:enumeration value="HOLD_AT_LOCATION"/>
+          <xs:enumeration value="HOME_DELIVERY_APPOINTMENT"/>
+          <xs:enumeration value="HOME_DELIVERY_DATE_CERTAIN"/>
+          <xs:enumeration value="HOME_DELIVERY_EVENING"/>
+          <xs:enumeration value="INSIDE_DELIVERY"/>
+          <xs:enumeration value="INSIDE_PICKUP"/>
+          <xs:enumeration value="INSURED_VALUE"/>
+          <xs:enumeration value="INTERHAWAII"/>
+          <xs:enumeration value="LIFTGATE_DELIVERY"/>
+          <xs:enumeration value="LIFTGATE_PICKUP"/>
+          <xs:enumeration value="LIMITED_ACCESS_DELIVERY"/>
+          <xs:enumeration value="LIMITED_ACCESS_PICKUP"/>
+          <xs:enumeration value="METRO_DELIVERY"/>
+          <xs:enumeration value="METRO_PICKUP"/>
+          <xs:enumeration value="NON_MACHINABLE"/>
+          <xs:enumeration value="OFFSHORE"/>
+          <xs:enumeration value="ON_CALL_PICKUP"/>
+          <xs:enumeration value="OTHER"/>
+          <xs:enumeration value="OUT_OF_DELIVERY_AREA"/>
+          <xs:enumeration value="OUT_OF_PICKUP_AREA"/>
+          <xs:enumeration value="OVERSIZE"/>
+          <xs:enumeration value="OVER_DIMENSION"/>
+          <xs:enumeration value="PIECE_COUNT_VERIFICATION"/>
+          <xs:enumeration value="PRE_DELIVERY_NOTIFICATION"/>
+          <xs:enumeration value="PRIORITY_ALERT"/>
+          <xs:enumeration value="PROTECTION_FROM_FREEZING"/>
+          <xs:enumeration value="REGIONAL_MALL_DELIVERY"/>
+          <xs:enumeration value="REGIONAL_MALL_PICKUP"/>
+          <xs:enumeration value="RESIDENTIAL_DELIVERY"/>
+          <xs:enumeration value="RESIDENTIAL_PICKUP"/>
+          <xs:enumeration value="RETURN_LABEL"/>
+          <xs:enumeration value="SATURDAY_DELIVERY"/>
+          <xs:enumeration value="SATURDAY_PICKUP"/>
+          <xs:enumeration value="SIGNATURE_OPTION"/>
+          <xs:enumeration value="TARP"/>
+          <xs:enumeration value="THIRD_PARTY_CONSIGNEE"/>
+          <xs:enumeration value="TRANSMART_SERVICE_FEE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Tax">
+        <xs:annotation>
+          <xs:documentation>Identifies each tax applied to the shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="TaxType" type="ns:TaxType" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The type of tax applied to the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Description" type="xs:string" minOccurs="0"/>
+          <xs:element name="Amount" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The amount of the tax applied to the shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="TaxType">
+        <xs:annotation>
+          <xs:documentation>The type of the tax.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="EXPORT"/>
+          <xs:enumeration value="GST"/>
+          <xs:enumeration value="HST"/>
+          <xs:enumeration value="INTRACOUNTRY"/>
+          <xs:enumeration value="OTHER"/>
+          <xs:enumeration value="PST"/>
+          <xs:enumeration value="VAT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="TaxpayerIdentification">
+        <xs:annotation>
+          <xs:documentation>The descriptive data for taxpayer identification information.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="TinType" type="ns:TinType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the category of the taxpayer identification number. See TinType for the list of values.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Number" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the taxpayer identification number.</xs:documentation>
+              <xs:appinfo>
+                <xs:MaxLength>15</xs:MaxLength>
+              </xs:appinfo>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Usage" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies the usage of Tax Identification Number in Shipment processing</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="TermsOfSaleType">
+        <xs:annotation>
+          <xs:documentation>
+            Required for dutiable international express or ground shipment. This field is not applicable to an international PIB (document) or a non-document which does not require a commercial invoice express shipment.
+            CFR_OR_CPT (Cost and Freight/Carriage Paid TO)
+            CIF_OR_CIP (Cost Insurance and Freight/Carraige Insurance Paid)
+            DDP (Delivered Duty Paid)
+            DDU (Delivered Duty Unpaid)
+            EXW (Ex Works)
+            FOB_OR_FCA (Free On Board/Free Carrier)
+          </xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CFR_OR_CPT"/>
+          <xs:enumeration value="CIF_OR_CIP"/>
+          <xs:enumeration value="DDP"/>
+          <xs:enumeration value="DDU"/>
+          <xs:enumeration value="EXW"/>
+          <xs:enumeration value="FOB_OR_FCA"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="TinType">
+        <xs:annotation>
+          <xs:documentation>Identifies the category of the taxpayer identification number.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="BUSINESS_NATIONAL"/>
+          <xs:enumeration value="BUSINESS_STATE"/>
+          <xs:enumeration value="PERSONAL_NATIONAL"/>
+          <xs:enumeration value="PERSONAL_STATE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="TrackingId">
+        <xs:sequence>
+          <xs:element name="TrackingIdType" type="ns:TrackingIdType" minOccurs="0"/>
+          <xs:element name="FormId" type="xs:string" minOccurs="0"/>
+          <xs:element name="UspsApplicationId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>For use with SmartPost tracking IDs only</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TrackingNumber" type="xs:string" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="TrackingIdType">
+        <xs:annotation>
+          <xs:documentation>TrackingIdType</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="EXPRESS"/>
+          <xs:enumeration value="FREIGHT"/>
+          <xs:enumeration value="GROUND"/>
+          <xs:enumeration value="USPS"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="TransactionDetail">
+        <xs:annotation>
+          <xs:documentation>Descriptive data for this customer transaction. The TransactionDetail from the request is echoed back to the caller in the corresponding reply.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="CustomerTransactionId" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Free form text to be echoed back in the reply. Used to match requests and replies.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Localization" type="ns:Localization" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Governs data payload language/translations (contrasted with ClientDetail.localization, which governs Notification.localizedMessage language selection).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="TransitTimeType">
+        <xs:annotation>
+          <xs:documentation>Identifies the set of valid shipment transit time values.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="EIGHTEEN_DAYS"/>
+          <xs:enumeration value="EIGHT_DAYS"/>
+          <xs:enumeration value="ELEVEN_DAYS"/>
+          <xs:enumeration value="FIFTEEN_DAYS"/>
+          <xs:enumeration value="FIVE_DAYS"/>
+          <xs:enumeration value="FOURTEEN_DAYS"/>
+          <xs:enumeration value="FOUR_DAYS"/>
+          <xs:enumeration value="NINETEEN_DAYS"/>
+          <xs:enumeration value="NINE_DAYS"/>
+          <xs:enumeration value="ONE_DAY"/>
+          <xs:enumeration value="SEVENTEEN_DAYS"/>
+          <xs:enumeration value="SEVEN_DAYS"/>
+          <xs:enumeration value="SIXTEEN_DAYS"/>
+          <xs:enumeration value="SIX_DAYS"/>
+          <xs:enumeration value="TEN_DAYS"/>
+          <xs:enumeration value="THIRTEEN_DAYS"/>
+          <xs:enumeration value="THREE_DAYS"/>
+          <xs:enumeration value="TWELVE_DAYS"/>
+          <xs:enumeration value="TWENTY_DAYS"/>
+          <xs:enumeration value="TWO_DAYS"/>
+          <xs:enumeration value="UNKNOWN"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="UploadDocumentIdProducer">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CUSTOMER"/>
+          <xs:enumeration value="FEDEX_CSHP"/>
+          <xs:enumeration value="FEDEX_GTM"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:simpleType name="UploadDocumentProducerType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CUSTOMER"/>
+          <xs:enumeration value="FEDEX_CLS"/>
+          <xs:enumeration value="FEDEX_GTM"/>
+          <xs:enumeration value="OTHER"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="UploadDocumentReferenceDetail">
+        <xs:sequence>
+          <xs:element name="LineNumber" type="xs:nonNegativeInteger" minOccurs="0"/>
+          <xs:element name="CustomerReference" type="xs:string" minOccurs="0"/>
+          <xs:element name="DocumentProducer" type="ns:UploadDocumentProducerType" minOccurs="0"/>
+          <xs:element name="DocumentType" type="ns:UploadDocumentType" minOccurs="0"/>
+          <xs:element name="DocumentId" type="xs:string" minOccurs="0"/>
+          <xs:element name="DocumentIdProducer" type="ns:UploadDocumentIdProducer" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="UploadDocumentType">
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CERTIFICATE_OF_ORIGIN"/>
+          <xs:enumeration value="COMMERCIAL_INVOICE"/>
+          <xs:enumeration value="ETD_LABEL"/>
+          <xs:enumeration value="NAFTA_CERTIFICATE_OF_ORIGIN"/>
+          <xs:enumeration value="OTHER"/>
+          <xs:enumeration value="PRO_FORMA_INVOICE"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="ValidateShipmentRequest">
+        <xs:annotation>
+          <xs:documentation>Descriptive data sent to FedEx by a customer in order to validate a shipment.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="WebAuthenticationDetail" type="ns:WebAuthenticationDetail" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data to be used in authentication of the sender's identity (and right to use FedEx web services).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="ClientDetail" type="ns:ClientDetail" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data identifying the client submitting the transaction.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TransactionDetail" type="ns:TransactionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Descriptive data for this customer transaction. The TransactionDetail from the request is echoed back to the caller in the corresponding reply.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Version" type="ns:VersionId" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the version/level of a service operation expected by a caller (in each request) and performed by the callee (in each reply).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="RequestedShipment" type="ns:RequestedShipment" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Descriptive data about the shipment being sent by the requestor.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ValidatedHazardousCommodityContent">
+        <xs:annotation>
+          <xs:documentation>Documents the kind and quantity of an individual hazardous commodity in a package.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Description" type="ns:ValidatedHazardousCommodityDescription" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Identifies and describes an individual hazardous commodity.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Quantity" type="ns:HazardousCommodityQuantityDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Specifies the amount of the commodity in alternate units.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Options" type="ns:HazardousCommodityOptionDetail" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Customer-provided specifications for handling individual commodities.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="ValidatedHazardousCommodityDescription">
+        <xs:annotation>
+          <xs:documentation>Identifies and describes an individual hazardous commodity. For 201001 load, this is based on data from the FedEx Ground Hazardous Materials Shipping Guide.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Id" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Regulatory identifier for a commodity (e.g. "UN ID" value).</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PackingGroup" type="ns:HazardousCommodityPackingGroupType" minOccurs="0"/>
+          <xs:element name="ProperShippingName" type="xs:string" minOccurs="0"/>
+          <xs:element name="ProperShippingNameAndDescription" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Fully-expanded descriptive text for a hazardous commodity.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TechnicalName" type="xs:string" minOccurs="0"/>
+          <xs:element name="HazardClass" type="xs:string" minOccurs="0"/>
+          <xs:element name="SubsidiaryClasses" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
+          <xs:element name="Symbols" type="xs:string" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Coded indications for special requirements or constraints.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="LabelText" type="xs:string" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="VariableHandlingChargeDetail">
+        <xs:annotation>
+          <xs:documentation>Details about how to calculate variable handling charges at the shipment level.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="VariableHandlingChargeType" type="ns:VariableHandlingChargeType" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>The type of handling charge to be calculated and returned in the reply.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="FixedValue" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>
+                Used with Variable handling charge type of FIXED_VALUE.
+                Contains the amount to be added to the freight charge.
+                Contains 2 explicit decimal positions with a total max length of 10 including the decimal.
+              </xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="PercentValue" type="xs:decimal" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>Actual percentage (10 means 10%, which is a mutiplier of 0.1)</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="VariableHandlingChargeType">
+        <xs:annotation>
+          <xs:documentation>The type of handling charge to be calculated and returned in the reply.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="FIXED_AMOUNT"/>
+          <xs:enumeration value="PERCENTAGE_OF_NET_CHARGE"/>
+          <xs:enumeration value="PERCENTAGE_OF_NET_CHARGE_EXCLUDING_TAXES"/>
+          <xs:enumeration value="PERCENTAGE_OF_NET_FREIGHT"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="VariableHandlingCharges">
+        <xs:annotation>
+          <xs:documentation>The variable handling charges calculated based on the type variable handling charges requested.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="VariableHandlingCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The variable handling charge amount calculated based on the requested variable handling charge detail.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="TotalCustomerCharge" type="ns:Money" minOccurs="0">
+            <xs:annotation>
+              <xs:documentation>The calculated varibale handling charge plus the net charge.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="Volume">
+        <xs:annotation>
+          <xs:documentation>Three-dimensional volume/cubic measurement.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Units" type="ns:VolumeUnits" minOccurs="0"/>
+          <xs:element name="Value" type="xs:decimal" minOccurs="0"/>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="VolumeUnits">
+        <xs:annotation>
+          <xs:documentation>Units of three-dimensional volume/cubic measure.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="CUBIC_FT"/>
+          <xs:enumeration value="CUBIC_M"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="Weight">
+        <xs:annotation>
+          <xs:documentation>The descriptive data for the heaviness of an object.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Units" type="ns:WeightUnits" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the unit of measure associated with a weight value.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Value" type="xs:decimal" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the weight value of a package/shipment.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:simpleType name="WeightUnits">
+        <xs:annotation>
+          <xs:documentation>Identifies the unit of measure associated with a weight value. See the list of enumerated types for valid values.</xs:documentation>
+        </xs:annotation>
+        <xs:restriction base="xs:string">
+          <xs:enumeration value="KG"/>
+          <xs:enumeration value="LB"/>
+        </xs:restriction>
+      </xs:simpleType>
+      <xs:complexType name="WebAuthenticationDetail">
+        <xs:annotation>
+          <xs:documentation>Used in authentication of the sender's identity.</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="UserCredential" type="ns:WebAuthenticationCredential" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Credential used to authenticate a specific software application. This value is provided by FedEx after registration.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="WebAuthenticationCredential">
+        <xs:annotation>
+          <xs:documentation>Two part authentication string used for the sender's identity</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="Key" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifying part of authentication credential. This value is provided by FedEx after registration</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Password" type="xs:string" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Secret part of authentication key. This value is provided by FedEx after registration.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+      <xs:complexType name="VersionId">
+        <xs:annotation>
+          <xs:documentation>Identifies the version/level of a service operation expected by a caller (in each request) and performed by the callee (in each reply).</xs:documentation>
+        </xs:annotation>
+        <xs:sequence>
+          <xs:element name="ServiceId" type="xs:string" fixed="ship" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies a system or sub-system which performs an operation.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Major" type="xs:int" fixed="10" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the service business level.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Intermediate" type="xs:int" fixed="0" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the service interface level.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+          <xs:element name="Minor" type="xs:int" fixed="0" minOccurs="1">
+            <xs:annotation>
+              <xs:documentation>Identifies the service code level.</xs:documentation>
+            </xs:annotation>
+          </xs:element>
+        </xs:sequence>
+      </xs:complexType>
+    </xs:schema>
+  </types>
+  <message name="ProcessShipmentReply">
+    <part name="ProcessShipmentReply" element="ns:ProcessShipmentReply"/>
+  </message>
+  <message name="DeleteTagRequest">
+    <part name="DeleteTagRequest" element="ns:DeleteTagRequest"/>
+  </message>
+  <message name="ProcessShipmentRequest">
+    <part name="ProcessShipmentRequest" element="ns:ProcessShipmentRequest"/>
+  </message>
+  <message name="CreatePendingShipmentRequest">
+    <part name="CreatePendingShipmentRequest" element="ns:CreatePendingShipmentRequest"/>
+  </message>
+  <message name="ProcessTagRequest">
+    <part name="ProcessTagRequest" element="ns:ProcessTagRequest"/>
+  </message>
+  <message name="CancelPendingShipmentReply">
+    <part name="CancelPendingShipmentReply" element="ns:CancelPendingShipmentReply"/>
+  </message>
+  <message name="CancelPendingShipmentRequest">
+    <part name="CancelPendingShipmentRequest" element="ns:CancelPendingShipmentRequest"/>
+  </message>
+  <message name="DeleteShipmentRequest">
+    <part name="DeleteShipmentRequest" element="ns:DeleteShipmentRequest"/>
+  </message>
+  <message name="ShipmentReply">
+    <part name="ShipmentReply" element="ns:ShipmentReply"/>
+  </message>
+  <message name="ProcessTagReply">
+    <part name="ProcessTagReply" element="ns:ProcessTagReply"/>
+  </message>
+  <message name="ValidateShipmentRequest">
+    <part name="ValidateShipmentRequest" element="ns:ValidateShipmentRequest"/>
+  </message>
+  <message name="CreatePendingShipmentReply">
+    <part name="CreatePendingShipmentReply" element="ns:CreatePendingShipmentReply"/>
+  </message>
+  <portType name="ShipPortType">
+    <operation name="processTag" parameterOrder="ProcessTagRequest">
+      <input message="ns:ProcessTagRequest"/>
+      <output message="ns:ProcessTagReply"/>
+    </operation>
+    <operation name="createPendingShipment" parameterOrder="CreatePendingShipmentRequest">
+      <input message="ns:CreatePendingShipmentRequest"/>
+      <output message="ns:CreatePendingShipmentReply"/>
+    </operation>
+    <operation name="cancelPendingShipment" parameterOrder="CancelPendingShipmentRequest">
+      <input message="ns:CancelPendingShipmentRequest"/>
+      <output message="ns:CancelPendingShipmentReply"/>
+    </operation>
+    <operation name="processShipment" parameterOrder="ProcessShipmentRequest">
+      <input message="ns:ProcessShipmentRequest"/>
+      <output message="ns:ProcessShipmentReply"/>
+    </operation>
+    <operation name="deleteTag" parameterOrder="DeleteTagRequest">
+      <input message="ns:DeleteTagRequest"/>
+      <output message="ns:ShipmentReply"/>
+    </operation>
+    <operation name="validateShipment" parameterOrder="ValidateShipmentRequest">
+      <input message="ns:ValidateShipmentRequest"/>
+      <output message="ns:ShipmentReply"/>
+    </operation>
+    <operation name="deleteShipment" parameterOrder="DeleteShipmentRequest">
+      <input message="ns:DeleteShipmentRequest"/>
+      <output message="ns:ShipmentReply"/>
+    </operation>
+  </portType>
+  <binding name="ShipServiceSoapBinding" type="ns:ShipPortType">
+    <s1:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
+    <operation name="processTag">
+      <s1:operation soapAction="processTag" style="document"/>
+      <input>
+        <s1:body use="literal"/>
+      </input>
+      <output>
+        <s1:body use="literal"/>
+      </output>
+    </operation>
+    <operation name="createPendingShipment">
+      <s1:operation soapAction="createPendingShipment" style="document"/>
+      <input>
+        <s1:body use="literal"/>
+      </input>
+      <output>
+        <s1:body use="literal"/>
+      </output>
+    </operation>
+    <operation name="cancelPendingShipment">
+      <s1:operation soapAction="cancelPendingShipment" style="document"/>
+      <input>
+        <s1:body use="literal"/>
+      </input>
+      <output>
+        <s1:body use="literal"/>
+      </output>
+    </operation>
+    <operation name="processShipment">
+      <s1:operation soapAction="processShipment" style="document"/>
+      <input>
+        <s1:body use="literal"/>
+      </input>
+      <output>
+        <s1:body use="literal"/>
+      </output>
+    </operation>
+    <operation name="deleteTag">
+      <s1:operation soapAction="deleteTag" style="document"/>
+      <input>
+        <s1:body use="literal"/>
+      </input>
+      <output>
+        <s1:body use="literal"/>
+      </output>
+    </operation>
+    <operation name="validateShipment">
+      <s1:operation soapAction="validateShipment" style="document"/>
+      <input>
+        <s1:body use="literal"/>
+      </input>
+      <output>
+        <s1:body use="literal"/>
+      </output>
+    </operation>
+    <operation name="deleteShipment">
+      <s1:operation soapAction="deleteShipment" style="document"/>
+      <input>
+        <s1:body use="literal"/>
+      </input>
+      <output>
+        <s1:body use="literal"/>
+      </output>
+    </operation>
+  </binding>
+  <service name="ShipService">
+    <port name="ShipServicePort" binding="ns:ShipServiceSoapBinding">
+      <s1:address location="https://wsbeta.fedex.com:443/web-services/ship"/>
+    </port>
+  </service>
+</definitions>
diff --git a/app/code/core/Mage/Weee/etc/config.xml b/app/code/core/Mage/Weee/etc/config.xml
index 29be61b6ef4dc0e9323416b5e4d6c28112ebf1f5..72592d77d4e85adc81e2f2a98ab2e705523000a2 100644
--- a/app/code/core/Mage/Weee/etc/config.xml
+++ b/app/code/core/Mage/Weee/etc/config.xml
@@ -95,8 +95,8 @@
                 <totals>
                     <weee>
                         <class>Mage_Weee_Model_Total_Invoice_Weee</class>
-                        <after>subtotal,tax</after>
-                        <before>grand_total</before>
+                        <after>subtotal</after>
+                        <before>tax,discount,grand_total</before>
                     </weee>
                 </totals>
             </order_invoice>
@@ -104,8 +104,8 @@
                 <totals>
                     <weee>
                         <class>Mage_Weee_Model_Total_Creditmemo_Weee</class>
-                        <after>subtotal,tax</after>
-                        <before>grand_total</before>
+                        <after>subtotal</after>
+                        <before>tax,discount,grand_total</before>
                     </weee>
                 </totals>
             </order_creditmemo>
diff --git a/app/code/core/Mage/Weee/view/frontend/layout.xml b/app/code/core/Mage/Weee/view/frontend/layout.xml
index f2421dbe3d2be68ec8d6346a86346a16d859af76..367a1a8cbc8a998ed2531efd9cacd3aebb76bdfe 100644
--- a/app/code/core/Mage/Weee/view/frontend/layout.xml
+++ b/app/code/core/Mage/Weee/view/frontend/layout.xml
@@ -27,27 +27,9 @@
 
 -->
 <layout version="0.1.0">
-    <checkout_cart_index>
+    <default>
         <reference name="head">
             <action method="addJs"><file>Mage_Weee::tax_toggle.js</file></action>
         </reference>
-    </checkout_cart_index>
-
-    <checkout_onepage_index>
-        <reference name="head">
-            <action method="addJs"><file>Mage_Weee::tax_toggle.js</file></action>
-        </reference>
-    </checkout_onepage_index>
-    
-    <checkout_multishipping>
-        <reference name="head">
-            <action method="addJs"><file>Mage_Weee::tax_toggle.js</file></action>
-        </reference>
-    </checkout_multishipping>
-
-    <customer_logged_in>
-        <reference name="head">
-            <action method="addJs"><file>Mage_Weee::tax_toggle.js</file></action>
-        </reference>
-    </customer_logged_in>
+    </default>
 </layout>
diff --git a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Chooser.php b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Chooser.php
index 7a07bdaa1d69f51eea3a44c9035d11a40c6211ca..232f695b8201c933c68902fac84647474e19a78f 100644
--- a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Chooser.php
+++ b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Chooser.php
@@ -182,21 +182,21 @@ class Mage_Widget_Block_Adminhtml_Widget_Chooser extends Mage_Adminhtml_Block_Te
             <div id="' . $chooserId . 'advice-container" class="hidden"></div>
             <script type="text/javascript">//<![CDATA[
                 (function() {
-                    var fun_'. $chooserId .' = function() {
+                    var instantiateChooser = function() {
                         window.' . $chooserId . ' = new WysiwygWidget.chooser(
                             "' . $chooserId . '",
                             "' . $this->getSourceUrl() . '",
                             ' . $configJson . '
                         );
-                    };
+                        if ($("' . $chooserId . 'value")) {
+                            $("' . $chooserId . 'value").advaiceContainer = "' . $chooserId . 'advice-container";
+                        }
+                    }
+
                     if (document.loaded) { //allow load over ajax
-                        $("'.$chooserId.'value").advaiceContainer = "'.$chooserId.'advice-container";
-                        fun_'. $chooserId .'.call();
+                        instantiateChooser();
                     } else {
-                        document.observe("dom:loaded", function () {
-                            $("'.$chooserId.'value").advaiceContainer = "'.$chooserId.'advice-container";
-                            fun_'. $chooserId .'.call();
-                        });
+                        document.observe("dom:loaded", instantiateChooser);
                     }
                 })();
             //]]></script>
diff --git a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Block.php b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Block.php
deleted file mode 100644
index d51e456c01fed15eedd7e4efc595c4e969c6c60b..0000000000000000000000000000000000000000
--- a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Block.php
+++ /dev/null
@@ -1,254 +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    Mage
- * @package     Mage_Widget
- * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
- * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
- */
-
-/**
- * Widget Instance block reference chooser
- *
- * @category    Mage
- * @package     Mage_Widget
- * @author      Magento Core Team <core@magentocommerce.com>
- */
-class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_Block
-    extends Mage_Adminhtml_Block_Widget
-{
-    protected $_layoutHandlesXml = null;
-
-    protected $_layoutHandleUpdates = array();
-
-    protected $_layoutHandleUpdatesXml = null;
-
-    protected $_layoutHandle = array();
-
-    protected $_blocks = array();
-
-    protected $_allowedBlocks = array();
-
-    /**
-     * Setter
-     *
-     * @param array $allowedBlocks
-     * @return Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_Block
-     */
-    public function setAllowedBlocks($allowedBlocks)
-    {
-        $this->_allowedBlocks = $allowedBlocks;
-        return $this;
-    }
-
-    /**
-     * Add allowed block
-     *
-     * @param string $block
-     * @return Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_Block
-     */
-    public function addAllowedBlock($block)
-    {
-        $this->_allowedBlocks[] = $block;
-        return $this;
-    }
-
-    /**
-     * Getter
-     *
-     * @return array
-     */
-    public function getAllowedBlocks()
-    {
-        return $this->_allowedBlocks;
-    }
-
-    /**
-     * Setter
-     * If string given exlopde to array by ',' delimiter
-     *
-     * @param string|array $layoutHandle
-     * @return Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_Block
-     */
-    public function setLayoutHandle($layoutHandle)
-    {
-        if (is_string($layoutHandle)) {
-            $layoutHandle = explode(',', $layoutHandle);
-        }
-        $this->_layoutHandle = array_merge(array('default'), (array)$layoutHandle);
-        return $this;
-    }
-
-    /**
-     * Getter
-     *
-     * @return array
-     */
-    public function getLayoutHandle()
-    {
-        return $this->_layoutHandle;
-    }
-
-    /**
-     * Getter
-     *
-     * @return string
-     */
-    public function getArea()
-    {
-        if (!$this->_getData('area')) {
-            return Mage_Core_Model_Design_Package::DEFAULT_AREA;
-        }
-        return $this->_getData('area');
-    }
-
-    /**
-     * Getter
-     *
-     * @return string
-     */
-    public function getPackage()
-    {
-        if (!$this->_getData('package')) {
-            return Mage_Core_Model_Design_Package::DEFAULT_PACKAGE;
-        }
-        return $this->_getData('package');
-    }
-
-    /**
-     * Getter
-     *
-     * @return string
-     */
-    public function getTheme()
-    {
-        if (!$this->_getData('theme')) {
-            return Mage_Core_Model_Design_Package::DEFAULT_THEME;
-        }
-        return $this->_getData('theme');
-    }
-
-    /**
-     * Prepare html output
-     *
-     * @return string
-     */
-    protected function _toHtml()
-    {
-        $selectBlock = $this->getLayout()->createBlock('Mage_Core_Block_Html_Select')
-            ->setName('block')
-            ->setClass('required-entry select')
-            ->setExtraParams('onchange="WidgetInstance.loadSelectBoxByType(\'block_template\','
-                .' this.up(\'div.group_container\'), this.value)"')
-            ->setOptions($this->getBlocks())
-            ->setValue($this->getSelected());
-        return parent::_toHtml().$selectBlock->toHtml();
-    }
-
-    /**
-     * Retrieve blocks array
-     *
-     * @return array
-     */
-    public function getBlocks()
-    {
-        if (empty($this->_blocks)) {
-            /* @var $update Mage_Core_Model_Layout_Update */
-            $update = Mage::getModel('Mage_Core_Model_Layout')->getUpdate();
-            /* @var $layoutHandles Mage_Core_Model_Layout_Element */
-            $this->_layoutHandlesXml = $update->getFileLayoutUpdatesXml(
-                $this->getArea(),
-                $this->getPackage(),
-                $this->getTheme());
-            $this->_collectLayoutHandles();
-            $this->_collectBlocks();
-            array_unshift($this->_blocks, array(
-                'value' => '',
-                'label' => Mage::helper('Mage_Widget_Helper_Data')->__('-- Please Select --')
-            ));
-        }
-        return $this->_blocks;
-    }
-
-    /**
-     * Merging layout handles and create xml of merged layout handles
-     *
-     */
-    protected function _collectLayoutHandles()
-    {
-        foreach ($this->getLayoutHandle() as $handle) {
-            $this->_mergeLayoutHandles($handle);
-        }
-        $updatesStr = '<'.'?xml version="1.0"?'.'><layout>'.implode('', $this->_layoutHandleUpdates).'</layout>';
-        $this->_layoutHandleUpdatesXml = simplexml_load_string($updatesStr, 'Varien_Simplexml_Element');
-    }
-
-    /**
-     * Adding layout handle that specified in node 'update' to general layout handles
-     *
-     * @param string $handle
-     */
-    public function _mergeLayoutHandles($handle)
-    {
-        foreach ($this->_layoutHandlesXml->{$handle} as $updateXml) {
-            foreach ($updateXml->children() as $child) {
-                if (strtolower($child->getName()) == 'update' && isset($child['handle'])) {
-                    $this->_mergeLayoutHandles((string)$child['handle']);
-                }
-            }
-            $this->_layoutHandleUpdates[] = $updateXml->asNiceXml();
-        }
-    }
-
-
-    /**
-     * Filter and collect blocks into array
-     */
-    protected function _collectBlocks()
-    {
-        if ($blocks = $this->_layoutHandleUpdatesXml->xpath('//block/label/..')) {
-            /* @var $block Mage_Core_Model_Layout_Element */
-            foreach ($blocks as $block) {
-                if ((string)$block->getAttribute('name') && $this->_filterBlock($block)) {
-                    $helper = Mage::helper(Mage_Core_Model_Layout::findTranslationModuleName($block));
-                    $this->_blocks[(string)$block->getAttribute('name')] = $helper->__((string)$block->label);
-                }
-            }
-        }
-        asort($this->_blocks, SORT_STRING);
-    }
-
-    /**
-     * Check whether given block match allowed block types
-     *
-     * @param Mage_Core_Model_Layout_Element $block
-     * @return boolean
-     */
-    protected function _filterBlock($block)
-    {
-        if (!$this->getAllowedBlocks()) {
-            return true;
-        }
-        if (in_array((string)$block->getAttribute('name'), $this->getAllowedBlocks())) {
-            return true;
-        }
-        return false;
-    }
-}
diff --git a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Container.php b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Container.php
new file mode 100644
index 0000000000000000000000000000000000000000..d533330764497aa1dcc290f22cf03f7d9473a60f
--- /dev/null
+++ b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Container.php
@@ -0,0 +1,78 @@
+<?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_Widget
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * A chooser for container for widget instances
+ */
+class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_Container extends Mage_Core_Block_Html_Select
+{
+    /**
+     * Assign attributes for the HTML select element
+     */
+    protected function _construct()
+    {
+        $this->setName('block');
+        $this->setClass('required-entry select');
+        $this->setExtraParams('onchange="WidgetInstance.loadSelectBoxByType(\'block_template\','
+            . ' this.up(\'div.group_container\'), this.value)"');
+    }
+
+    /**
+     * Add necessary options
+     *
+     * @return Mage_Core_Block_Abstract
+     */
+    protected function _beforeToHtml()
+    {
+        if (!$this->getOptions()) {
+            $layoutUpdateParams = array(
+                'area'    => $this->getArea(),
+                'package' => $this->getPackage(),
+                'theme'   => $this->getTheme(),
+            );
+            /** @var $layoutUpdate Mage_Core_Model_Layout_Update */
+            $layoutUpdate = Mage::getModel('Mage_Core_Model_Layout_Update', $layoutUpdateParams);
+            $layoutUpdate->addPageHandles(array($this->getLayoutHandle()));
+            $layoutUpdate->load();
+
+            $containers = $layoutUpdate->getContainers();
+            if ($this->getAllowedContainers()) {
+                foreach (array_keys($containers) as $containerName) {
+                    if (!in_array($containerName, $this->getAllowedContainers())) {
+                        unset($containers[$containerName]);
+                    }
+                }
+            }
+            asort($containers, SORT_STRING);
+
+            $this->addOption('', Mage::helper('Mage_Widget_Helper_Data')->__('-- Please Select --'));
+            foreach ($containers as $containerName => $containerLabel) {
+                $this->addOption($containerName, $containerLabel);
+            }
+        }
+        return parent::_beforeToHtml();
+    }
+}
diff --git a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Layout.php b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Layout.php
index d28fe5d92d2d0d44d6360d33be51150b9bd0ceb1..87773718d1c21c4272e2303bdb147931871e5491 100644
--- a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Layout.php
+++ b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Layout.php
@@ -26,168 +26,61 @@
 
 /**
  * Widget Instance layouts chooser
- *
- * @category    Mage
- * @package     Mage_Widget
- * @author      Magento Core Team <core@magentocommerce.com>
  */
-class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_Layout
-    extends Mage_Adminhtml_Block_Widget
+class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_Layout extends Mage_Core_Block_Html_Select
 {
-    protected $_layoutHandles = array();
-
     /**
-     * layout handles wildcar patterns
+     * Add necessary options
      *
-     * @var array
+     * @return Mage_Core_Block_Abstract
      */
-    protected $_layoutHandlePatterns = array(
-        '^default$',
-        '^catalog_category_*',
-        '^catalog_product_*',
-        '^PRODUCT_*'
-    );
-
-    /**
-     * Constructor
-     */
-    protected function _construct()
+    protected function _beforeToHtml()
     {
-        parent::_construct();
-    }
-
-    /**
-     * Add not allowed layout handle pattern
-     *
-     * @param string $pattern
-     * @return Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_Layout
-     */
-    public function addLayoutHandlePattern($pattern)
-    {
-        $this->_layoutHandlePatterns[] = $pattern;
-        return $this;
-    }
-
-    /**
-     * Getter
-     *
-     * @return array
-     */
-    public function getLayoutHandlePatterns()
-    {
-        return $this->_layoutHandlePatterns;
-    }
-
-    /**
-     * Getter
-     *
-     * @return string
-     */
-    public function getArea()
-    {
-        if (!$this->_getData('area')) {
-            return Mage_Core_Model_Design_Package::DEFAULT_AREA;
-        }
-        return $this->_getData('area');
-    }
-
-    /**
-     * Getter
-     *
-     * @return string
-     */
-    public function getPackage()
-    {
-        if (!$this->_getData('package')) {
-            return Mage_Core_Model_Design_Package::DEFAULT_PACKAGE;
-        }
-        return $this->_getData('package');
-    }
-
-    /**
-     * Getter
-     *
-     * @return string
-     */
-    public function getTheme()
-    {
-        if (!$this->_getData('theme')) {
-            return Mage_Core_Model_Design_Package::DEFAULT_THEME;
-        }
-        return $this->_getData('theme');
-    }
-
-    /**
-     * Prepare html output
-     *
-     * @return string
-     */
-    protected function _toHtml()
-    {
-        $selectBlock = $this->getLayout()->createBlock('Mage_Core_Block_Html_Select')
-            ->setName($this->getSelectName())
-            ->setId('layout_handle')
-            ->setClass('required-entry select')
-            ->setExtraParams("onchange=\"WidgetInstance.loadSelectBoxByType(\'block_reference\', " .
-                            "this.up(\'div.pages\'), this.value)\"")
-            ->setOptions($this->getLayoutHandles(
-                $this->getArea(),
-                $this->getPackage(),
-                $this->getTheme()));
-        return parent::_toHtml().$selectBlock->toHtml();
-    }
-
-    /**
-     * Retrieve layout handles
-     *
-     * @param string $area
-     * @param string $package
-     * @param string $theme
-     * @return array
-     */
-    public function getLayoutHandles($area, $package, $theme)
-    {
-        if (empty($this->_layoutHandles)) {
-            /* @var $update Mage_Core_Model_Layout_Update */
-            $update = Mage::getModel('Mage_Core_Model_Layout')->getUpdate();
-            $this->_layoutHandles[''] = Mage::helper('Mage_Widget_Helper_Data')->__('-- Please Select --');
-            $this->_collectLayoutHandles($update->getFileLayoutUpdatesXml($area, $package, $theme));
+        if (!$this->getOptions()) {
+            $this->addOption('', Mage::helper('Mage_Widget_Helper_Data')->__('-- Please Select --'));
+            $layoutUpdateParams = array(
+                'area'    => $this->getArea(),
+                'package' => $this->getPackage(),
+                'theme'   => $this->getTheme(),
+            );
+            $pageTypes = array();
+            $pageTypesAll = $this->_getLayoutUpdate($layoutUpdateParams)->getPageTypesHierarchy();
+            foreach ($pageTypesAll as $pageTypeName => $pageTypeInfo) {
+                $layoutUpdate = $this->_getLayoutUpdate($layoutUpdateParams);
+                $layoutUpdate->addPageHandles(array($pageTypeName));
+                $layoutUpdate->load();
+                if (!$layoutUpdate->getContainers()) {
+                    continue;
+                }
+                $pageTypes[$pageTypeName] = $pageTypeInfo;
+            }
+            $this->_addPageTypeOptions($pageTypes);
         }
-        return $this->_layoutHandles;
+        return parent::_beforeToHtml();
     }
 
     /**
-     * Filter and collect layout handles into array
+     * Retrieve new layout update model instance
      *
-     * @param Mage_Core_Model_Layout_Element $layoutHandles
+     * @param array $arguments
+     * @return Mage_Core_Model_Layout_Update
      */
-    protected function _collectLayoutHandles($layoutHandles)
+    protected function _getLayoutUpdate(array $arguments)
     {
-        if ($layoutHandlesArr = $layoutHandles->xpath('/*/*/label/..')) {
-            foreach ($layoutHandlesArr as $node) {
-                if ($this->_filterLayoutHandle($node->getName())) {
-                    $helper = Mage::helper(Mage_Core_Model_Layout::findTranslationModuleName($node));
-                    $this->_layoutHandles[$node->getName()] = $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(
-                        $helper->__((string)$node->label)
-                    );
-                }
-            }
-            asort($this->_layoutHandles, SORT_STRING);
-        }
+        return Mage::getModel('Mage_Core_Model_Layout_Update', $arguments);
     }
 
     /**
-     * Check if given layout handle allowed (do not match not allowed patterns)
+     * Add page types information to the options
      *
-     * @param string $layoutHandle
-     * @return boolean
+     * @param array $pageTypes
+     * @param int $level
      */
-    protected function _filterLayoutHandle($layoutHandle)
+    protected function _addPageTypeOptions(array $pageTypes, $level = 0)
     {
-        $wildCard = '/('.implode(')|(', $this->getLayoutHandlePatterns()).')/';
-        if (preg_match($wildCard, $layoutHandle)) {
-            return false;
+        foreach ($pageTypes as $pageTypeName => $pageTypeInfo) {
+            $this->addOption($pageTypeName, str_repeat('. ', $level) . $pageTypeInfo['label']);
+            $this->_addPageTypeOptions($pageTypeInfo['children'], $level + 1);
         }
-        return true;
     }
 }
diff --git a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Template.php b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Template.php
index ee6ed0b3730b68443bd0c286fc54c7dcae3d0e8e..c393d3f9752815e6f3e5a4d99002f6cf6c0345c8 100644
--- a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Template.php
+++ b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/Template.php
@@ -42,7 +42,7 @@ class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_Template
     protected function _toHtml()
     {
         if (!$this->getWidgetTemplates()) {
-            $html = '<p class="nm"><small>' . Mage::helper('Mage_Widget_Helper_Data')->__('Please Select Block Reference First') . '</small></p>';
+            $html = '<p class="nm"><small>' . Mage::helper('Mage_Widget_Helper_Data')->__('Please Select Container First') . '</small></p>';
         } elseif (count($this->getWidgetTemplates()) == 1) {
             $widgetTemplate = current($this->getWidgetTemplates());
             $html = '<input type="hidden" name="template" value="' . $widgetTemplate['value'] . '" />';
diff --git a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main.php b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main.php
index 23cbd24608a1dd475fba69a9caf924e9f98df71f..9ab5222efc8a97b642354f52da372e807b0b9878 100644
--- a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main.php
+++ b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main.php
@@ -153,6 +153,7 @@ class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Main
                 'title'     => Mage::helper('Mage_Widget_Helper_Data')->__('Assign to Store Views'),
                 'required'  => true,
                 'values'    => Mage::getSingleton('Mage_Adminhtml_Model_System_Store')->getStoreValuesForForm(false, true),
+                'after_element_html' => Mage::getBlockSingleton('Mage_Adminhtml_Block_Store_Switcher')->getHintHtml()
             ));
         }
 
@@ -162,7 +163,7 @@ class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Main
             'title' => Mage::helper('Mage_Widget_Helper_Data')->__('Sort Order'),
             'class' => '',
             'required' => false,
-            'note' => Mage::helper('Mage_Widget_Helper_Data')->__('Sort Order of widget instances in the same block reference')
+            'note' => Mage::helper('Mage_Widget_Helper_Data')->__('Sort Order of widget instances in the same container')
         ));
 
         /* @var $layoutBlock Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Main_Layout */
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 5776a2b03b78b65a448b450eb8aa1275f3cb7070..09be5feb35691ec27ce51817f8b0141590d9caf5 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
@@ -207,7 +207,7 @@ class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Main_Layout
             'label' => 'Categories',
             'code' => 'categories',
             'name' => 'anchor_categories',
-            'layout_handle' => 'default,catalog_category_layered',
+            'layout_handle' => Mage_Widget_Model_Widget_Instance::ANCHOR_CATEGORY_LAYOUT_HANDLE,
             'is_anchor_only' => 1,
             'product_type_id' => ''
         );
@@ -215,7 +215,7 @@ class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Main_Layout
             'label' => 'Categories',
             'code' => 'categories',
             'name' => 'notanchor_categories',
-            'layout_handle' => 'default,catalog_category_default',
+            'layout_handle' => Mage_Widget_Model_Widget_Instance::NOTANCHOR_CATEGORY_LAYOUT_HANDLE,
             'is_anchor_only' => 0,
             'product_type_id' => ''
         );
@@ -223,7 +223,7 @@ class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Main_Layout
             'label' => 'Products',
             'code' => 'products',
             'name' => 'all_products',
-            'layout_handle' => 'default,catalog_product_view',
+            'layout_handle' => Mage_Widget_Model_Widget_Instance::PRODUCT_LAYOUT_HANDLE,
             'is_anchor_only' => '',
             'product_type_id' => ''
         );
@@ -232,7 +232,8 @@ class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Main_Layout
                 'label' => 'Products',
                 'code' => 'products',
                 'name' => $typeId . '_products',
-                'layout_handle' => 'default,catalog_product_view,PRODUCT_TYPE_'.$typeId,
+                'layout_handle'
+                    => str_replace('{{TYPE}}', $typeId, Mage_Widget_Model_Widget_Instance::PRODUCT_TYPE_LAYOUT_HANDLE),
                 'is_anchor_only' => '',
                 'product_type_id' => $typeId
             );
@@ -247,13 +248,18 @@ class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Main_Layout
      */
     public function getLayoutsChooser()
     {
-        $layouts = $this->getLayout()
+        $chooserBlock = $this->getLayout()
             ->createBlock('Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_Layout')
-            ->setSelectName('widget_instance[{{id}}][pages][layout_handle]')
+            ->setName('widget_instance[{{id}}][pages][layout_handle]')
+            ->setId('layout_handle')
+            ->setClass('required-entry select')
+            ->setExtraParams("onchange=\"WidgetInstance.loadSelectBoxByType(\'block_reference\', "
+                . "this.up(\'div.pages\'), this.value)\"")
             ->setArea($this->getWidgetInstance()->getArea())
             ->setPackage($this->getWidgetInstance()->getPackage())
-            ->setTheme($this->getWidgetInstance()->getTheme());
-        return $layouts->toHtml();
+            ->setTheme($this->getWidgetInstance()->getTheme())
+        ;
+        return $chooserBlock->toHtml();
     }
 
     /**
diff --git a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Settings.php b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Settings.php
index c6cf1d79313f8c47a637a112d941c53fc4c6a201..3c6f2ecec1c6854a25703045cfca572593856025 100644
--- a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Settings.php
+++ b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Settings.php
@@ -111,8 +111,8 @@ class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Settings
 
         $this->_addElementTypes($fieldset);
 
-        $fieldset->addField('instance_type', 'select', array(
-            'name'  => 'instance_type',
+        $fieldset->addField('type', 'select', array(
+            'name'  => 'type',
             'label' => Mage::helper('Mage_Widget_Helper_Data')->__('Type'),
             'title' => Mage::helper('Mage_Widget_Helper_Data')->__('Type'),
             'class' => '',
@@ -130,7 +130,7 @@ class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Settings
             ->createBlock('Mage_Adminhtml_Block_Widget_Button')
             ->setData(array(
                 'label'     => Mage::helper('Mage_Widget_Helper_Data')->__('Continue'),
-                'onclick'   => "setSettings('" . $this->getContinueUrl() . "', 'instance_type', 'package_theme')",
+                'onclick'   => "setSettings('" . $this->getContinueUrl() . "', 'type', 'package_theme')",
                 'class'     => 'save'
             ));
         $fieldset->addField('continue_button', 'note', array(
@@ -151,7 +151,7 @@ class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Settings
     {
         return $this->getUrl('*/*/*', array(
             '_current' => true,
-            'instance_type' => '{{instance_type}}',
+            'type' => '{{type}}',
             'package_theme' => '{{package_theme}}'
         ));
     }
diff --git a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Options.php b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Options.php
index b24e4e03e848da16fff51531d8f8c4a42b117a77..a654e08795cbd87242e7f220fe06bc15ce31930f 100644
--- a/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Options.php
+++ b/app/code/core/Mage/Widget/Block/Adminhtml/Widget/Options.php
@@ -179,7 +179,7 @@ class Mage_Widget_Block_Adminhtml_Widget_Options extends Mage_Adminhtml_Block_Wi
             $fieldType = 'hidden';
         }
         // just an element renderer
-        elseif ($fieldType && class_exists($fieldType)) {
+        elseif ($fieldType && $this->_isClassName($fieldType)) {
             $fieldRenderer = $this->getLayout()->createBlock($fieldType);
             $fieldType = $this->_defaultElementType;
         }
@@ -202,7 +202,7 @@ class Mage_Widget_Block_Adminhtml_Widget_Options extends Mage_Adminhtml_Block_Wi
         }
 
         // dependencies from other fields
-        $dependenceBlock = $this->getChild('form_after');
+        $dependenceBlock = $this->getChildBlock('form_after');
         $dependenceBlock->addFieldMap($field->getId(), $fieldName);
         if ($parameter->getDepends()) {
             foreach ($parameter->getDepends() as $from => $row) {
@@ -213,4 +213,15 @@ class Mage_Widget_Block_Adminhtml_Widget_Options extends Mage_Adminhtml_Block_Wi
 
         return $field;
     }
+
+    /**
+     * Checks whether $fieldType is a class name of custom renderer, and not just a type of input element
+     *
+     * @param string $fieldType
+     * @return bool
+     */
+    protected function _isClassName($fieldType)
+    {
+        return preg_match('/[A-Z]/', $fieldType) > 0;
+    }
 }
diff --git a/app/code/core/Mage/Widget/Model/Widget/Instance.php b/app/code/core/Mage/Widget/Model/Widget/Instance.php
index 2ae670d969a35327590b5fc19d2c3cb354a0ce20..464cf6a7ac0209ae2b9f15088bf79278033e3db5 100644
--- a/app/code/core/Mage/Widget/Model/Widget/Instance.php
+++ b/app/code/core/Mage/Widget/Model/Widget/Instance.php
@@ -47,11 +47,11 @@ class Mage_Widget_Model_Widget_Instance extends Mage_Core_Model_Abstract
 
     const DEFAULT_LAYOUT_HANDLE            = 'default';
     const PRODUCT_LAYOUT_HANDLE            = 'catalog_product_view';
-    const SINGLE_PRODUCT_LAYOUT_HANLDE     = 'PRODUCT_{{ID}}';
-    const PRODUCT_TYPE_LAYOUT_HANDLE       = 'PRODUCT_TYPE_{{TYPE}}';
-    const ANCHOR_CATEGORY_LAYOUT_HANDLE    = 'catalog_category_layered';
-    const NOTANCHOR_CATEGORY_LAYOUT_HANDLE = 'catalog_category_default';
-    const SINGLE_CATEGORY_LAYOUT_HANDLE    = 'CATEGORY_{{ID}}';
+    const SINGLE_PRODUCT_LAYOUT_HANLDE     = 'catalog_product_view_id_{{ID}}';
+    const PRODUCT_TYPE_LAYOUT_HANDLE       = 'catalog_product_view_type_{{TYPE}}';
+    const ANCHOR_CATEGORY_LAYOUT_HANDLE    = 'catalog_category_view_type_layered';
+    const NOTANCHOR_CATEGORY_LAYOUT_HANDLE = 'catalog_category_view_type_default';
+    const SINGLE_CATEGORY_LAYOUT_HANDLE    = 'catalog_category_view_{{ID}}';
 
     const XML_NODE_RELATED_CACHE = 'global/widget/related_cache_types';
 
@@ -64,6 +64,13 @@ class Mage_Widget_Model_Widget_Instance extends Mage_Core_Model_Abstract
      */
     protected $_widgetConfigXml = null;
 
+    /**
+     * Prefix of model events names
+     *
+     * @var string
+     */
+    protected $_eventPrefix = 'widget_widget_instance';
+
     /**
      * Internal Constructor
      */
@@ -101,7 +108,6 @@ class Mage_Widget_Model_Widget_Instance extends Mage_Core_Model_Abstract
         $pageGroups = $this->getData('page_groups');
         if ($pageGroups) {
             foreach ($pageGroups as $pageGroup) {
-                $tmpPageGroup = array();
                 if (isset($pageGroup[$pageGroup['page_group']])) {
                     $pageGroupData = $pageGroup[$pageGroup['page_group']];
                     if ($pageGroupData['page_id']) {
@@ -183,7 +189,6 @@ class Mage_Widget_Model_Widget_Instance extends Mage_Core_Model_Abstract
     public function setType($type)
     {
         $this->setData('instance_type', $type);
-        $this->_prepareType();
         return $this;
     }
 
@@ -195,23 +200,9 @@ class Mage_Widget_Model_Widget_Instance extends Mage_Core_Model_Abstract
      */
     public function getType()
     {
-        $this->_prepareType();
         return $this->_getData('instance_type');
     }
 
-    /**
-     * Replace '-' to '/', if was passed from request(GET request)
-     *
-     * @return Mage_Widget_Model_Widget_Instance
-     */
-    protected function _prepareType()
-    {
-        if (strpos($this->_getData('instance_type'), '-') >= 0) {
-            $this->setData('instance_type', str_replace('-', '/', $this->_getData('instance_type')));
-        }
-        return $this;
-    }
-
     /**
      * Setter
      * Prepare widget package theme
@@ -287,6 +278,9 @@ class Mage_Widget_Model_Widget_Instance extends Mage_Core_Model_Abstract
             list($package, $theme) = explode('/', $this->getPackageTheme());
             $this->setData('package', $package);
             $this->setData('theme', $theme);
+        } else {
+            $this->setData('package', Mage_Core_Model_Design_Package::DEFAULT_PACKAGE);
+            $this->setData('theme', Mage_Core_Model_Design_Package::DEFAULT_THEME);
         }
         return $this;
     }
@@ -399,39 +393,39 @@ class Mage_Widget_Model_Widget_Instance extends Mage_Core_Model_Abstract
     }
 
     /**
-     * Retrieve blocks that widget support
+     * Get list of containers that widget is limited to be in
      *
      * @return array
      */
-    public function getWidgetSupportedBlocks()
+    public function getWidgetSupportedContainers()
     {
-        $blocks = array();
-        if ($this->getWidgetConfig() && ($supportedBlocks = $this->getWidgetConfig()->supported_blocks)) {
-            foreach ($supportedBlocks->children() as $block) {
-                $blocks[] = (string)$block->block_name;
+        $containers = array();
+        if ($this->getWidgetConfig() && ($configNodes = $this->getWidgetConfig()->supported_containers)) {
+            foreach ($configNodes->children() as $node) {
+                $containers[] = (string)$node->container_name;
             }
         }
-        return $blocks;
+        return $containers;
     }
 
     /**
-     * Retrieve widget templates that supported by given block reference
+     * Retrieve widget templates that supported by specified container name
      *
-     * @param string $blockReference
+     * @param string $containerName
      * @return array
      */
-    public function getWidgetSupportedTemplatesByBlock($blockReference)
+    public function getWidgetSupportedTemplatesByContainer($containerName)
     {
         $templates = array();
         $widgetTemplates = $this->getWidgetTemplates();
         if ($this->getWidgetConfig()) {
-            if (!($supportedBlocks = $this->getWidgetConfig()->supported_blocks)) {
+            if (!($configNodes = $this->getWidgetConfig()->supported_containers)) {
                 return $widgetTemplates;
             }
-            foreach ($supportedBlocks->children() as $block) {
-                if ((string)$block->block_name == $blockReference) {
-                    if ($block->template && $block->template->children()) {
-                        foreach ($block->template->children() as $template) {
+            foreach ($configNodes->children() as $node) {
+                if ((string)$node->container_name == $containerName) {
+                    if ($node->template && $node->template->children()) {
+                        foreach ($node->template->children() as $template) {
                             if (isset($widgetTemplates[(string)$template])) {
                                 $templates[] = $widgetTemplates[(string)$template];
                             }
@@ -450,16 +444,17 @@ class Mage_Widget_Model_Widget_Instance extends Mage_Core_Model_Abstract
     /**
      * Generate layout update xml
      *
-     * @param string $blockReference
-     * @param string $position
+     * @param string $container
+     * @param string $templatePath
      * @return string
      */
-    public function generateLayoutUpdateXml($blockReference, $templatePath = '')
+    public function generateLayoutUpdateXml($container, $templatePath = '')
     {
         $templateFilename = Mage::getSingleton('Mage_Core_Model_Design_Package')->getTemplateFilename($templatePath, array(
             '_area'    => $this->getArea(),
             '_package' => $this->getPackage(),
-            '_theme'   => $this->getTheme()
+            '_theme'   => $this->getTheme(),
+            '_module'  => Mage_Core_Block_Abstract::extractModuleName($this->getType()),
         ));
         if (!$this->getId() && !$this->isCompleteToCreate()
             || ($templatePath && !is_readable($templateFilename)))
@@ -467,7 +462,7 @@ class Mage_Widget_Model_Widget_Instance extends Mage_Core_Model_Abstract
             return '';
         }
         $parameters = $this->getWidgetParameters();
-        $xml = '<reference name="' . $blockReference . '">';
+        $xml = '<reference name="' . $container . '">';
         $template = '';
         if (isset($parameters['template'])) {
             unset($parameters['template']);
diff --git a/app/code/core/Mage/Widget/controllers/Adminhtml/Widget/InstanceController.php b/app/code/core/Mage/Widget/controllers/Adminhtml/Widget/InstanceController.php
index b1aea553f47afd64d91ea0679474e0b1027fc372..b8c97a371e67a1ed916a2038f45c3b83914f3cb1 100644
--- a/app/code/core/Mage/Widget/controllers/Adminhtml/Widget/InstanceController.php
+++ b/app/code/core/Mage/Widget/controllers/Adminhtml/Widget/InstanceController.php
@@ -72,8 +72,12 @@ class Mage_Widget_Adminhtml_Widget_InstanceController extends Mage_Adminhtml_Con
         $widgetInstance = Mage::getModel('Mage_Widget_Model_Widget_Instance');
 
         $instanceId = $this->getRequest()->getParam('instance_id', null);
-        $type = $this->getRequest()->getParam('instance_type', null);
+        $type = $this->getRequest()->getParam('type', null);
         $packageTheme = $this->getRequest()->getParam('package_theme', null);
+        if ($packageTheme) {
+            $packageTheme = str_replace('-', '/', $packageTheme);
+        }
+
         if ($instanceId) {
             $widgetInstance->load($instanceId);
             if (!$widgetInstance->getId()) {
@@ -266,13 +270,13 @@ class Mage_Widget_Adminhtml_Widget_InstanceController extends Mage_Adminhtml_Con
         $layout = $this->getRequest()->getParam('layout');
         $selected = $this->getRequest()->getParam('selected', null);
         $blocksChooser = $this->getLayout()
-            ->createBlock('Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_Block')
+            ->createBlock('Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_Container')
+            ->setValue($selected)
             ->setArea($widgetInstance->getArea())
             ->setPackage($widgetInstance->getPackage())
             ->setTheme($widgetInstance->getTheme())
             ->setLayoutHandle($layout)
-            ->setSelected($selected)
-            ->setAllowedBlocks($widgetInstance->getWidgetSupportedBlocks());
+            ->setAllowedContainers($widgetInstance->getWidgetSupportedContainers());
         $this->setBody($blocksChooser->toHtml());
     }
 
@@ -289,7 +293,7 @@ class Mage_Widget_Adminhtml_Widget_InstanceController extends Mage_Adminhtml_Con
         $templateChooser = $this->getLayout()
             ->createBlock('Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_Template')
             ->setSelected($selected)
-            ->setWidgetTemplates($widgetInstance->getWidgetSupportedTemplatesByBlock($block));
+            ->setWidgetTemplates($widgetInstance->getWidgetSupportedTemplatesByContainer($block));
         $this->setBody($templateChooser->toHtml());
     }
 
diff --git a/app/code/core/Mage/Widget/etc/translater.xml b/app/code/core/Mage/Widget/etc/jstranslator.xml
similarity index 97%
rename from app/code/core/Mage/Widget/etc/translater.xml
rename to app/code/core/Mage/Widget/etc/jstranslator.xml
index ca1dc019f9788cc70b38462b969f22a1d55885bc..b698c7575495ed114be5f913cc12eba9eb9d3454 100644
--- a/app/code/core/Mage/Widget/etc/translater.xml
+++ b/app/code/core/Mage/Widget/etc/jstranslator.xml
@@ -25,10 +25,10 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 -->
-<translater>
+<jstranslator>
     <!-- widget.js -->
     <widget-ui-insert translate="message" module="Mage_Widget">
         <message>Insert Widget...</message>
     </widget-ui-insert>
     <!-- end widget.js -->
-</translater>
+</jstranslator>
diff --git a/app/code/core/Mage/Widget/sql/widget_setup/install-1.6.0.0.php b/app/code/core/Mage/Widget/sql/widget_setup/install-1.6.0.0.php
index 82a4ab8859afec346791727e09468890817df8a8..9eab6df8ab00e80c572ed3568f10c9b73d230121 100644
--- a/app/code/core/Mage/Widget/sql/widget_setup/install-1.6.0.0.php
+++ b/app/code/core/Mage/Widget/sql/widget_setup/install-1.6.0.0.php
@@ -162,7 +162,7 @@ $table = $installer->getConnection()
     ->addColumn('layout_handle', Varien_Db_Ddl_Table::TYPE_TEXT, 255, array(
         ), 'Layout Handle')
     ->addColumn('block_reference', Varien_Db_Ddl_Table::TYPE_TEXT, 255, array(
-        ), 'Block Reference')
+        ), 'Container')
     ->addColumn('page_for', Varien_Db_Ddl_Table::TYPE_TEXT, 25, array(
         ), 'For instance entities')
     ->addColumn('entities', Varien_Db_Ddl_Table::TYPE_TEXT, '64k', array(
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 93c2f29eda3fdc903cd9855d2280e680e7f14f84..4b9a34d4db965b048cfc90423e8b78cd4e67d184 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
@@ -56,7 +56,7 @@ var pageGroupTemplate = '<div class="options-box page_group_container" id="page_
             '<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')->__('Block Reference')) ?> <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>'+
@@ -109,7 +109,7 @@ var pageGroupTemplate = '<div class="options-box page_group_container" id="page_
         '<col />'+
         '<thead>'+
             '<tr>'+
-                '<th><label><?php echo $this->helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('Block Reference')) ?> <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>'+
@@ -143,7 +143,7 @@ var pageGroupTemplate = '<div class="options-box page_group_container" id="page_
         '<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')->__('Block Reference')) ?> <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>'+
@@ -198,6 +198,7 @@ var WidgetInstance = {
             if (data.group) {
                 pageGroup = $(data.group+'_'+data.id);
                 additional = {};
+                additional.selectedLayoutHandle = data.layout_handle;
                 additional.selectedBlock = data.block;
                 additional.selectedTemplate = data.template;
                 additional.position = data.position;
@@ -293,6 +294,8 @@ var WidgetInstance = {
             layoutHandle = '';
             if (layoutHandleField = container.down('input.layout_handle_pattern')) {
                 layoutHandle = layoutHandleField.value;
+            } else if (additional.selectedLayoutHandle) {
+                layoutHandle = additional.selectedLayoutHandle;
             }
             this.loadSelectBoxByType('block_reference', container, layoutHandle, additional);
         }
diff --git a/app/code/core/Mage/Widget/view/adminhtml/instance/js.phtml b/app/code/core/Mage/Widget/view/adminhtml/instance/js.phtml
index 642d258720f69621a8878281371ec8e3efd73cb8..9e3fd1c22b38e00b30316e29d9d4d823bc2b5161 100644
--- a/app/code/core/Mage/Widget/view/adminhtml/instance/js.phtml
+++ b/app/code/core/Mage/Widget/view/adminhtml/instance/js.phtml
@@ -29,20 +29,15 @@
 function setSettings(urlTemplate, typeElement, packageThemeElement) {
     templateSyntax = /(^|.|\r|\n)({{(\w+)}})/;
     var template = new Template(urlTemplate, templateSyntax);
-    typeElement = $F(typeElement).replace(/\//g, "-");
-    packageThemeElement = $F(packageThemeElement).split(/\//g);
-    if(typeof packageThemeElement[0] == 'undefined' || typeof packageThemeElement[1] == 'undefined') {
-        alert('<?php echo Mage::helper('Mage_Core_Helper_Data')->jsQuoteEscape(Mage::helper('Mage_Widget_Helper_Data')->__('Undefined Design Package or Theme.')); ?>');
-        return false;
-    }
+    typeElement = $F(typeElement);
+    packageThemeElement = $F(packageThemeElement).replace(/\//g, "-");
     setLocation(template.evaluate({
         'type':    typeElement,
-        'package': packageThemeElement[0],
-        'theme':   packageThemeElement[1]
+        'package_theme': packageThemeElement
     }));
 }
 function saveAndContinueEdit(){
-    editForm.submit($('edit_form').action+'back/edit/');
+    editForm.submit($('edit_form').action + 'back/edit/');
 }
 //]]>
 </script>
diff --git a/app/code/core/Mage/Widget/view/adminhtml/layout.xml b/app/code/core/Mage/Widget/view/adminhtml/layout.xml
index ad67cc27b4cebccac82197bcccba0af89afbaa35..d5f01268bd20266f3d91a7cfc82285fb885568ad 100644
--- a/app/code/core/Mage/Widget/view/adminhtml/layout.xml
+++ b/app/code/core/Mage/Widget/view/adminhtml/layout.xml
@@ -28,11 +28,11 @@
 
 <layout>
     <adminhtml_widget_index>
-        <block name="wysiwyg_widget" type="Mage_Widget_Block_Adminhtml_Widget" output="toHtml" />
+        <block name="wysiwyg_widget" type="Mage_Widget_Block_Adminhtml_Widget" output="1" />
     </adminhtml_widget_index>
 
     <adminhtml_widget_loadoptions>
-        <block name="wysiwyg_widget.options" type="Mage_Widget_Block_Adminhtml_Widget_Options" output="toHtml" />
+        <block name="wysiwyg_widget.options" type="Mage_Widget_Block_Adminhtml_Widget_Options" output="1" />
     </adminhtml_widget_loadoptions>
 
     <adminhtml_widget_instance_index>
@@ -47,7 +47,7 @@
             <action method="addJs"><file>mage/adminhtml/wysiwyg/widget.js</file></action>
             <action method="addJs"><file>prototype/window.js</file></action>
             <action method="addCss"><file>prototype/windows/themes/default.css</file></action>
-            <action method="addCss"><file>prototype/windows/themes/magento.css</file></action>
+            <action method="addCss"><file>Mage_Core::prototype/magento.css</file></action>
         </reference>
         <reference name="content">
             <block type="Mage_Widget_Block_Adminhtml_Widget_Instance_Edit" name="widget_instance_edit" />
diff --git a/app/code/core/Mage/Wishlist/Block/Abstract.php b/app/code/core/Mage/Wishlist/Block/Abstract.php
index b9d07e19b9bdd04fa8fbd61139875578de9255e5..dfeacc4a962f18af6db0b6eed587bf1e1fafc7d7 100644
--- a/app/code/core/Mage/Wishlist/Block/Abstract.php
+++ b/app/code/core/Mage/Wishlist/Block/Abstract.php
@@ -117,6 +117,16 @@ abstract class Mage_Wishlist_Block_Abstract extends Mage_Catalog_Block_Product_A
         return $this;
     }
 
+    /**
+     * Create wishlist item collection
+     *
+     * @return Mage_Wishlist_Model_Resource_Item_Collection
+     */
+    protected function _createWishlistItemCollection()
+    {
+        return $this->_getWishlist()->getItemCollection();
+    }
+
     /**
      * Retrieve Wishlist Product Items collection
      *
@@ -125,14 +135,23 @@ abstract class Mage_Wishlist_Block_Abstract extends Mage_Catalog_Block_Product_A
     public function getWishlistItems()
     {
         if (is_null($this->_collection)) {
-            $this->_collection = $this->_getWishlist()
-                ->getItemCollection();
+            $this->_collection = $this->_createWishlistItemCollection();
             $this->_prepareCollection($this->_collection);
         }
 
         return $this->_collection;
     }
 
+    /**
+     * Retrieve wishlist instance
+     *
+     * @return Mage_Wishlist_Model_Wishlist
+     */
+    public function getWishlistInstance()
+    {
+        return $this->_getWishlist();
+    }
+
     /**
      * Retrieve URL for Removing item from wishlist
      *
diff --git a/app/code/core/Mage/Wishlist/Block/Customer/Sharing.php b/app/code/core/Mage/Wishlist/Block/Customer/Sharing.php
index 879f281414979892442421aa3ee909b8c2539b69..6633a00ec03555cafa160f2a4e5ed44951a2e7be 100644
--- a/app/code/core/Mage/Wishlist/Block/Customer/Sharing.php
+++ b/app/code/core/Mage/Wishlist/Block/Customer/Sharing.php
@@ -84,4 +84,14 @@ class Mage_Wishlist_Block_Customer_Sharing extends Mage_Core_Block_Template
             return $this->escapeHtml($this->_enteredData[$key]);
         }
     }
+
+    /**
+     * Retrieve back button url
+     *
+     * @return string
+     */
+    public function getBackUrl()
+    {
+        return $this->getUrl('*/*/index');
+    }
 }
diff --git a/app/code/core/Mage/Wishlist/Block/Customer/Sidebar.php b/app/code/core/Mage/Wishlist/Block/Customer/Sidebar.php
index be59aa097d27b4053b80ad3dc13bd0f62c9c7c35..e40a8b23579a5052e3a0197486a8ed34b0de4bb7 100644
--- a/app/code/core/Mage/Wishlist/Block/Customer/Sidebar.php
+++ b/app/code/core/Mage/Wishlist/Block/Customer/Sidebar.php
@@ -34,6 +34,16 @@
  */
 class Mage_Wishlist_Block_Customer_Sidebar extends Mage_Wishlist_Block_Abstract
 {
+    /**
+     * Retrieve block title
+     *
+     * @return string
+     */
+    public function getTitle()
+    {
+        return $this->__('My Wishlist <small>(%d)</small>', $this->getItemCount());
+    }
+
     /**
      * Add sidebar conditions to collection
      *
@@ -57,7 +67,7 @@ class Mage_Wishlist_Block_Customer_Sidebar extends Mage_Wishlist_Block_Abstract
      */
     protected function _toHtml()
     {
-        if (($this->getCustomWishlist() && $this->getItemCount()) || $this->hasWishlistItems()) {
+        if ($this->getItemCount()) {
             return parent::_toHtml();
         }
 
@@ -67,6 +77,7 @@ class Mage_Wishlist_Block_Customer_Sidebar extends Mage_Wishlist_Block_Abstract
     /**
      * Can Display wishlist
      *
+     * @deprecated after 1.6.2.0
      * @return bool
      */
     public function getCanDisplayWishlist()
@@ -75,19 +86,19 @@ class Mage_Wishlist_Block_Customer_Sidebar extends Mage_Wishlist_Block_Abstract
     }
 
     /**
-     * Retrieve Wishlist model
+     * Retrieve Wishlist Product Items collection
      *
-     * @return Mage_Wishlist_Model_Wishlist
+     * @return Mage_Wishlist_Model_Resource_Item_Collection
      */
-    protected function _getWishlist()
+    public function getWishlistItems()
     {
-
-        if (!$this->getCustomWishlist() || !is_null($this->_wishlist)) {
-            return parent::_getWishlist();
+        if (is_null($this->_collection)) {
+            $this->_collection = clone $this->_createWishlistItemCollection();
+            $this->_collection->clear();
+            $this->_prepareCollection($this->_collection);
         }
 
-        $this->_wishlist = $this->getCustomWishlist();
-        return $this->_wishlist;
+        return $this->_collection;
     }
 
     /**
@@ -97,10 +108,16 @@ class Mage_Wishlist_Block_Customer_Sidebar extends Mage_Wishlist_Block_Abstract
      */
     public function getItemCount()
     {
-        if ($this->getCustomWishlist()) {
-            return $this->getCustomWishlist()->getItemsCount();
-        }
+        return $this->_getHelper()->getItemCount();
+    }
 
-        return $this->getWishlistItemsCount();
+    /**
+     * Check whether user has items in his wishlist
+     *
+     * @return bool
+     */
+    public function hasWishlistItems()
+    {
+        return $this->getItemCount() > 0;
     }
 }
diff --git a/app/code/core/Mage/Wishlist/Block/Customer/Wishlist.php b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist.php
index 7d86e26d1f965598a985f408c978a6e86510f6d8..c6e593975fee37f66e92a4d84fb4ede64edac542 100644
--- a/app/code/core/Mage/Wishlist/Block/Customer/Wishlist.php
+++ b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist.php
@@ -35,19 +35,10 @@
 class Mage_Wishlist_Block_Customer_Wishlist extends Mage_Wishlist_Block_Abstract
 {
     /*
-     * List of product type configuration to render options list
+     * List of product options rendering configurations by product type
      */
     protected $_optionsCfg = array();
 
-    /*
-     * Constructor of block - adds default renderer for product configuration
-     */
-    public function _construct()
-    {
-        parent::_construct();
-        $this->addOptionsRenderCfg('default','Mage_Catalog_Helper_Product_Configuration','options_list.phtml');
-    }
-
     /**
      * Add wishlist conditions to collection
      *
@@ -81,15 +72,13 @@ class Mage_Wishlist_Block_Customer_Wishlist extends Mage_Wishlist_Block_Abstract
      */
     public function getBackUrl()
     {
-        if ($this->getRefererUrl()) {
-            return $this->getRefererUrl();
-        }
         return $this->getUrl('customer/account/');
     }
 
     /**
      * Sets all options render configurations
      *
+     * @deprecated after 1.6.2.0
      * @param null|array $optionCfg
      * @return Mage_Wishlist_Block_Customer_Wishlist
      */
@@ -102,6 +91,7 @@ class Mage_Wishlist_Block_Customer_Wishlist extends Mage_Wishlist_Block_Abstract
     /**
      * Returns all options render configurations
      *
+     * @deprecated after 1.6.2.0
      * @return array
      */
     public function getOptionsRenderCfgs()
@@ -111,8 +101,8 @@ class Mage_Wishlist_Block_Customer_Wishlist extends Mage_Wishlist_Block_Abstract
 
     /*
      * Adds config for rendering product type options
-     * If template is null - later default will be used
      *
+     * @deprecated after 1.6.2.0
      * @param string $productType
      * @param string $helperName
      * @param null|string $template
@@ -127,6 +117,7 @@ class Mage_Wishlist_Block_Customer_Wishlist extends Mage_Wishlist_Block_Abstract
     /**
      * Returns html for showing item options
      *
+     * @deprecated after 1.6.2.0
      * @param string $productType
      * @return array|null
      */
@@ -144,6 +135,7 @@ class Mage_Wishlist_Block_Customer_Wishlist extends Mage_Wishlist_Block_Abstract
     /**
      * Returns html for showing item options
      *
+     * @deprecated after 1.6.2.0
      * @param Mage_Wishlist_Model_Item $item
      * @return string
      */
@@ -159,7 +151,7 @@ class Mage_Wishlist_Block_Customer_Wishlist extends Mage_Wishlist_Block_Abstract
             Mage::throwException($this->__("Helper for wishlist options rendering doesn't implement required interface."));
         }
 
-        $block = $this->getChild('item_options');
+        $block = $this->getChildBlock('item_options');
         if (!$block) {
             return '';
         }
@@ -179,24 +171,10 @@ class Mage_Wishlist_Block_Customer_Wishlist extends Mage_Wishlist_Block_Abstract
             ->toHtml();
     }
 
-    /**
-     * Returns default description to show in textarea field
-     *
-     * @param Mage_Wishlist_Model_Item $item
-     * @return string
-     */
-    public function getCommentValue(Mage_Wishlist_Model_Item $item)
-    {
-        if ($this->hasDescription($item)) {
-            return  $this->getEscapedDescription($item);
-        }
-
-        return Mage::helper('Mage_Wishlist_Helper_Data')->defaultCommentString();
-    }
-
     /**
      * Returns qty to show visually to user
      *
+     * @deprecated after 1.6.2.0
      * @param Mage_Wishlist_Model_Item $item
      * @return float
      */
diff --git a/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Button.php b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Button.php
new file mode 100644
index 0000000000000000000000000000000000000000..8df83d266adce6f3ba8afd1d9dc8ac9111c90935
--- /dev/null
+++ b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Button.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_Wishlist
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Wishlist block customer item cart column
+ *
+ * @category    Mage
+ * @package     Mage_Wishlist
+ * @author      Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_Wishlist_Block_Customer_Wishlist_Button extends Mage_Core_Block_Template
+{
+    /**
+     * Retrieve current wishlist
+     *
+     * @return Mage_Wishlist_Model_Wishlist
+     */
+    public function getWishlist()
+    {
+        return Mage::helper('Mage_Wishlist_Helper_Data')->getWishlist();
+    }
+}
diff --git a/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column.php b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column.php
new file mode 100644
index 0000000000000000000000000000000000000000..7770d2d698c2bad538700d3bf484d86a5b499293
--- /dev/null
+++ b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column.php
@@ -0,0 +1,83 @@
+<?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_Wishlist
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Wishlist block customer item column
+ *
+ * @category    Mage
+ * @package     Mage_Wishlist
+ * @author      Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_Wishlist_Block_Customer_Wishlist_Item_Column extends Mage_Wishlist_Block_Abstract
+{
+    /**
+     * Checks whether column should be shown in table
+     *
+     * @return bool
+     */
+    public function isEnabled()
+    {
+        return true;
+    }
+
+    /**
+     * Retrieve block html
+     *
+     * @return string
+     */
+    protected function _toHtml()
+    {
+        if ($this->isEnabled()) {
+            if (!$this->getLayout()) {
+                return '';
+            }
+            foreach ($this->getLayout()->getChildBlocks($this->getNameInLayout()) as $child) {
+                if ($child) {
+                    $child->setItem($this->getItem());
+                }
+            }
+            return parent::_toHtml();
+        }
+        return '';
+    }
+
+    /**
+     * Retrieve column related javascript code
+     *
+     * @return string
+     */
+    public function getJs()
+    {
+        if (!$this->getLayout()) {
+            return '';
+        }
+        $js = '';
+        foreach ($this->getLayout()->getChildBlocks($this->getNameInLayout()) as $block) {
+            $js .= $block->getJs();
+        }
+        return $js;
+    }
+}
diff --git a/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column/Cart.php b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column/Cart.php
new file mode 100644
index 0000000000000000000000000000000000000000..f7d8cdc7de4029e26b74c50fd9952a6f7c87a1a9
--- /dev/null
+++ b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column/Cart.php
@@ -0,0 +1,74 @@
+<?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_Wishlist
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Wishlist block customer item cart column
+ *
+ * @category    Mage
+ * @package     Mage_Wishlist
+ * @author      Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_Wishlist_Block_Customer_Wishlist_Item_Column_Cart extends Mage_Wishlist_Block_Customer_Wishlist_Item_Column
+{
+    /**
+     * Returns qty to show visually to user
+     *
+     * @param Mage_Wishlist_Model_Item $item
+     * @return float
+     */
+    public function getAddToCartQty(Mage_Wishlist_Model_Item $item)
+    {
+        $qty = $item->getQty();
+        return $qty ? $qty : 1;
+    }
+
+    /**
+     * Retrieve column related javascript code
+     *
+     * @return string
+     */
+    public function getJs()
+    {
+        $js = "
+            function addWItemToCart(itemId) {
+                var url = '" . $this->getItemAddToCartUrl('%item%') . "';
+                url = url.gsub('%item%', itemId);
+                var form = $('wishlist-view-form');
+                if (form) {
+                    var input = form['qty[' + itemId + ']'];
+                    if (input) {
+                        var separator = (url.indexOf('?') >= 0) ? '&' : '?';
+                        url += separator + input.name + '=' + encodeURIComponent(input.value);
+                    }
+                }
+                setLocation(url);
+            }
+        ";
+
+        $js .= parent::getJs();
+        return $js;
+    }
+}
diff --git a/app/code/core/Mage/Adminhtml/Helper/Rss.php b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column/Comment.php
similarity index 55%
rename from app/code/core/Mage/Adminhtml/Helper/Rss.php
rename to app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column/Comment.php
index 572ce277439228dfd34c6a569f41832f9465c624..7da7edd0f15c861e5842b5a13e643e5bc57a7d43 100644
--- a/app/code/core/Mage/Adminhtml/Helper/Rss.php
+++ b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column/Comment.php
@@ -19,32 +19,36 @@
  * needs please refer to http://www.magentocommerce.com for more information.
  *
  * @category    Mage
- * @package     Mage_Adminhtml
+ * @package     Mage_Wishlist
  * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
 /**
- * Default rss helper
+ * Wishlist block customer item cart column
  *
+ * @category    Mage
+ * @package     Mage_Wishlist
  * @author      Magento Core Team <core@magentocommerce.com>
  */
-class Mage_Adminhtml_Helper_Rss extends Mage_Core_Helper_Abstract
+class Mage_Wishlist_Block_Customer_Wishlist_Item_Column_Comment
+    extends Mage_Wishlist_Block_Customer_Wishlist_Item_Column
 {
-    public function authAdmin($path)
+    /**
+     * Retrieve column javascript code
+     *
+     * @return string
+     */
+    public function getJs()
     {
-        $session = Mage::getSingleton('Mage_Rss_Model_Session');
-        if ($session->isAdminLoggedIn()) {
-            return;
-        }
-        list($username, $password) = Mage::helper('Mage_Core_Helper_Http')->authValidate();
-        $adminSession = Mage::getModel('Mage_Admin_Model_Session');
-        $user = $adminSession->login($username, $password);
-        //$user = Mage::getModel('Mage_Admin_Model_User')->login($username, $password);
-        if($user && $user->getId() && $user->getIsActive() == '1' && $adminSession->isAllowed($path)){
-            $session->setAdmin($user);
-        } else {
-            Mage::helper('Mage_Core_Helper_Http')->authFailed();
+        return parent::getJs() . "
+        function focusComment(obj) {
+            if( obj.value == '" . $this->helper('Mage_Wishlist_Helper_Data')->defaultCommentString() . "' ) {
+                obj.value = '';
+            } else if( obj.value == '' ) {
+                obj.value = '" . $this->helper('Mage_Wishlist_Helper_Data')->defaultCommentString() . "';
+            }
         }
+        ";
     }
 }
diff --git a/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column/Image.php b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column/Image.php
new file mode 100644
index 0000000000000000000000000000000000000000..1804c269d20fa71b54a49b614dee588ac1927967
--- /dev/null
+++ b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column/Image.php
@@ -0,0 +1,36 @@
+<?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_Wishlist
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Wishlist block customer item cart column
+ *
+ * @category    Mage
+ * @package     Mage_Wishlist
+ * @author      Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_Wishlist_Block_Customer_Wishlist_Item_Column_Image extends Mage_Wishlist_Block_Customer_Wishlist_Item_Column
+{
+}
diff --git a/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column/Remove.php b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column/Remove.php
new file mode 100644
index 0000000000000000000000000000000000000000..25dd0b517a8d539cb2b0723b57b17728ec433ba1
--- /dev/null
+++ b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Column/Remove.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.
+ *
+ * @category    Mage
+ * @package     Mage_Wishlist
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Delete item column in customer wishlist table
+ *
+ * @category    Mage
+ * @package     Mage_Wishlist
+ * @author      Magento Core Team <core@magentocommerce.com>
+ */
+class Mage_Wishlist_Block_Customer_Wishlist_Item_Column_Remove extends Mage_Wishlist_Block_Customer_Wishlist_Item_Column
+{
+    /**
+     * Retrieve block javascript
+     *
+     * @return string
+     */
+    public function getJs()
+    {
+        return parent::getJs() . "
+        function confirmRemoveWishlistItem() {
+            return confirm('" . $this->__('Are you sure you want to remove this product from your wishlist?') . "');
+        }
+        ";
+    }
+}
diff --git a/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Options.php b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Options.php
index 358ef1c01b0d7a2ebf365572b1c3a875d6ae2f71..dcb8f64ac8a0503d869351df14d8215c42b966a5 100644
--- a/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Options.php
+++ b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Item/Options.php
@@ -33,4 +33,85 @@
  */
 class Mage_Wishlist_Block_Customer_Wishlist_Item_Options extends Mage_Wishlist_Block_Abstract
 {
+    /*
+     * List of product options rendering configurations by product type
+     *
+     * @var array
+     */
+    protected $_optionsCfg = array('default' => array(
+        'helper' => 'Mage_Catalog_Helper_Product_Configuration',
+        'template' => 'Mage_Wishlist::options_list.phtml'
+    ));
+
+    /**
+     * Initialize block
+     */
+    public function __construct()
+    {
+        parent::__construct();
+        Mage::dispatchEvent('product_option_renderer_init', array('block' => $this));
+    }
+
+    /*
+     * Adds config for rendering product type options
+     *
+     * @param string $productType
+     * @param string $helperName
+     * @param null|string $template
+     * @return Mage_Wishlist_Block_Customer_Wishlist_Item_Options
+     */
+    public function addOptionsRenderCfg($productType, $helperName, $template = null)
+    {
+        $this->_optionsCfg[$productType] = array('helper' => $helperName, 'template' => $template);
+        return $this;
+    }
+
+    /**
+     * Get item options renderer config
+     *
+     * @param string $productType
+     * @return array|null
+     */
+    public function getOptionsRenderCfg($productType)
+    {
+        if (isset($this->_optionsCfg[$productType])) {
+            return $this->_optionsCfg[$productType];
+        } elseif (isset($this->_optionsCfg['default'])) {
+            return $this->_optionsCfg['default'];
+        } else {
+            return null;
+        }
+    }
+
+    /**
+     * Render block html
+     *
+     * @return string
+     */
+    protected function _toHtml()
+    {
+        $cfg = $this->getOptionsRenderCfg($this->getItem()->getProduct()->getTypeId());
+        if (!$cfg) {
+            return '';
+        }
+
+        $helper = Mage::helper($cfg['helper']);
+        if (!($helper instanceof Mage_Catalog_Helper_Product_Configuration_Interface)) {
+            Mage::throwException($this->__("Helper for wishlist options rendering doesn't implement required interface."));
+        }
+
+        if ($cfg['template']) {
+            $template = $cfg['template'];
+        } else {
+            $cfgDefault = $this->getOptionsRenderCfg('default');
+            if (!$cfgDefault) {
+                return '';
+            }
+            $template = $cfgDefault['template'];
+        }
+
+        $this->setTemplate($template)
+            ->setOptionList($helper->getOptions($this->getItem()));
+        return parent::_toHtml();
+    }
 }
diff --git a/lib/Varien/Db/Statement/Sqlsrv.php b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Items.php
similarity index 52%
rename from lib/Varien/Db/Statement/Sqlsrv.php
rename to app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Items.php
index 3cdf0b06ed75f774ef684750331e840fb83a9717..8bed464b148273d072a17c6f172dd07f2617cd6e 100644
--- a/lib/Varien/Db/Statement/Sqlsrv.php
+++ b/app/code/core/Mage/Wishlist/Block/Customer/Wishlist/Items.php
@@ -18,46 +18,34 @@
  * 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     Varien_Db
+ * @category    Mage
+ * @package     Mage_Wishlist
  * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
 /**
- * Sqlsrv driver DB Statement
+ * Wishlist block customer items
  *
- * @category    Varien
- * @package     Varien_Db
+ * @category    Mage
+ * @package     Mage_Wishlist
  * @author      Magento Core Team <core@magentocommerce.com>
  */
-class Varien_Db_Statement_Sqlsrv extends Zend_Db_Statement_Sqlsrv
+class Mage_Wishlist_Block_Customer_Wishlist_Items extends Mage_Core_Block_Template
 {
     /**
-     * Fetches a row from the result set.
+     * Retreive table column object list
      *
-     * @param  int $style  OPTIONAL Fetch mode for this fetch operation.
-     * @param  int $cursor OPTIONAL Absolute, relative, or other.
-     * @param  int $offset OPTIONAL Number for absolute or relative cursors.
-     * @return mixed Array, object, or scalar depending on fetch mode.
-     * @throws Zend_Db_Statement_Exception
+     * @return array
      */
-    public function fetch($style = null, $cursor = null, $offset = null)
+    public function getColumns()
     {
-        try {
-            $result = parent::fetch($style, $cursor, $offset);
-        } catch (Zend_Db_Statement_Sqlsrv_Exception $e) {
-            if ($e->getCode() == -22) {
-                return false;
+        $columns = array();
+        foreach ($this->getLayout()->getChildBlocks($this->getNameInLayout()) as $child) {
+            if ($child->isEnabled()){
+                $columns[] = $child;
             }
-            throw $e;
-        }
-
-        if ($result === null) {
-            return false;
         }
-
-        return $result;
+        return $columns;
     }
 }
diff --git a/app/code/core/Mage/Wishlist/Block/Links.php b/app/code/core/Mage/Wishlist/Block/Links.php
index bd78b4663b6c31fbc2e0c857c3890811a8ffc6cb..cee33fdc495cb877ed43fc3a228100791efb4dd9 100644
--- a/app/code/core/Mage/Wishlist/Block/Links.php
+++ b/app/code/core/Mage/Wishlist/Block/Links.php
@@ -41,31 +41,57 @@ class Mage_Wishlist_Block_Links extends Mage_Page_Block_Template_Links_Block
     protected $_position = 30;
 
     /**
-     * Set link title, label and url
+     * @return string
      */
-    public function __construct()
+    protected function _toHtml()
     {
-        parent::__construct();
-        $this->initLinkProperties();
+        if ($this->helper('Mage_Wishlist_Helper_Data')->isAllow()) {
+            $text = $this->_createLabel($this->_getItemCount());
+            $this->_label = $text;
+            $this->_title = $text;
+            $this->_url = $this->getUrl('wishlist');
+            return parent::_toHtml();
+        }
+        return '';
     }
 
     /**
      * Define label, title and url for wishlist link
+     *
+     * @deprecated after 1.6.2.0
      */
     public function initLinkProperties()
     {
-        if ($this->helper('Mage_Wishlist_Helper_Data')->isAllow()) {
-            $count = $this->getItemCount() ? $this->getItemCount() : $this->helper('Mage_Wishlist_Helper_Data')->getItemCount();
-            if ($count > 1) {
-                $text = $this->__('My Wishlist (%d items)', $count);
-            } else if ($count == 1) {
-                $text = $this->__('My Wishlist (%d item)', $count);
-            } else {
-                $text = $this->__('My Wishlist');
-            }
-            $this->_label = $text;
-            $this->_title = $text;
-            $this->_url = $this->getUrl('wishlist');
+        $text = $this->_createLabel($this->_getItemCount());
+        $this->_label = $text;
+        $this->_title = $text;
+        $this->_url = $this->getUrl('wishlist');
+    }
+
+    /**
+     * Count items in wishlist
+     *
+     * @return int
+     */
+    protected function _getItemCount()
+    {
+        return $this->helper('Mage_Wishlist_Helper_Data')->getItemCount();
+    }
+
+    /**
+     * Create button label based on wishlist item quantity
+     *
+     * @param int $count
+     * @return string
+     */
+    protected function _createLabel($count)
+    {
+        if ($count > 1) {
+            return $this->__('My Wishlist (%d items)', $count);
+        } else if ($count == 1) {
+            return $this->__('My Wishlist (%d item)', $count);
+        } else {
+            return $this->__('My Wishlist');
         }
     }
 }
diff --git a/app/code/core/Mage/Wishlist/Controller/Abstract.php b/app/code/core/Mage/Wishlist/Controller/Abstract.php
index 7d7484b26b619441103702dca166a7ac38bdc207..255d03fd57c6daf30d1df26954dd8aeac71a8018 100644
--- a/app/code/core/Mage/Wishlist/Controller/Abstract.php
+++ b/app/code/core/Mage/Wishlist/Controller/Abstract.php
@@ -49,9 +49,11 @@ abstract class Mage_Wishlist_Controller_Abstract extends Mage_Core_Controller_Fr
     protected function _processLocalizedQty($qty)
     {
         if (!$this->_localFilter) {
-            $this->_localFilter = new Zend_Filter_LocalizedToNormalized(array('locale' => Mage::app()->getLocale()->getLocaleCode()));
+            $this->_localFilter = new Zend_Filter_LocalizedToNormalized(
+                array('locale' => Mage::app()->getLocale()->getLocaleCode())
+            );
         }
-        $qty = $this->_localFilter->filter($qty);
+        $qty = $this->_localFilter->filter((float)$qty);
         if ($qty < 0) {
             $qty = null;
         }
@@ -91,6 +93,7 @@ abstract class Mage_Wishlist_Controller_Abstract extends Mage_Core_Controller_Fr
         foreach ($collection as $item) {
             /** @var Mage_Wishlist_Model_Item */
             try {
+                $disableAddToCart = $item->getProduct()->getDisableAddToCart();
                 $item->unsProduct();
 
                 // Set qty
@@ -100,7 +103,7 @@ abstract class Mage_Wishlist_Controller_Abstract extends Mage_Core_Controller_Fr
                         $item->setQty($qty);
                     }
                 }
-
+                $item->getProduct()->setDisableAddToCart($disableAddToCart);
                 // Add to cart
                 if ($item->addToCart($cart, $isOwner)) {
                     $addedItems[] = $item->getProduct();
@@ -121,7 +124,7 @@ abstract class Mage_Wishlist_Controller_Abstract extends Mage_Core_Controller_Fr
         }
 
         if ($isOwner) {
-            $indexUrl = Mage::helper('Mage_Wishlist_Helper_Data')->getListUrl();
+            $indexUrl = Mage::helper('Mage_Wishlist_Helper_Data')->getListUrl($wishlist->getId());
         } else {
             $indexUrl = Mage::getUrl('wishlist/shared', array('code' => $wishlist->getSharingCode()));
         }
diff --git a/app/code/core/Mage/Wishlist/Helper/Data.php b/app/code/core/Mage/Wishlist/Helper/Data.php
index 9242ed0bf36a83716d19d92a7ad12b557e26b947..a5d7bb2efeb5905772d006596a0a7043b7a35a7d 100644
--- a/app/code/core/Mage/Wishlist/Helper/Data.php
+++ b/app/code/core/Mage/Wishlist/Helper/Data.php
@@ -44,6 +44,13 @@ class Mage_Wishlist_Helper_Data extends Mage_Core_Helper_Abstract
      */
     const XML_PATH_CATALOGINVENTORY_SHOW_OUT_OF_STOCK = 'cataloginventory/options/show_out_of_stock';
 
+    /**
+     * Currently logged in customer
+     *
+     * @var Mage_Customer_Model_Customer
+     */
+    protected $_currentCustomer = null;
+
     /**
      * Customer Wishlist instance
      *
@@ -92,7 +99,30 @@ class Mage_Wishlist_Helper_Data extends Mage_Core_Helper_Abstract
      */
     protected function _getCurrentCustomer()
     {
-        return $this->_getCustomerSession()->getCustomer();
+        return $this->getCustomer();
+    }
+
+    /**
+     * Set current customer
+     *
+     * @param Mage_Customer_Model_Customer $customer
+     */
+    public function setCustomer(Mage_Customer_Model_Customer $customer)
+    {
+        $this->_currentCustomer = $customer;
+    }
+
+    /**
+     * Retrieve current customer
+     *
+     * @return Mage_Customer_Model_Customer|null
+     */
+    public function getCustomer()
+    {
+        if (!$this->_currentCustomer && $this->_getCustomerSession()->isLoggedIn()) {
+            $this->_currentCustomer = $this->_getCustomerSession()->getCustomer();
+        }
+        return $this->_currentCustomer;
     }
 
     /**
@@ -111,8 +141,8 @@ class Mage_Wishlist_Helper_Data extends Mage_Core_Helper_Abstract
             }
             else {
                 $this->_wishlist = Mage::getModel('Mage_Wishlist_Model_Wishlist');
-                if ($this->_getCustomerSession()->isLoggedIn()) {
-                    $this->_wishlist->loadByCustomer($this->_getCustomerSession()->getCustomer());
+                if ($this->getCustomer()) {
+                    $this->_wishlist->loadByCustomer($this->getCustomer());
                 }
             }
         }
@@ -142,6 +172,16 @@ class Mage_Wishlist_Helper_Data extends Mage_Core_Helper_Abstract
         return $this->_getCustomerSession()->getWishlistItemCount();
     }
 
+    /**
+     * Create wishlist item collection
+     *
+     * @return Mage_Wishlist_Model_Resource_Item_Collection
+     */
+    protected function _createWishlistItemCollection()
+    {
+        return $this->getWishlist()->getItemCollection();
+    }
+
     /**
      * Retrieve wishlist items collection
      *
@@ -150,8 +190,7 @@ class Mage_Wishlist_Helper_Data extends Mage_Core_Helper_Abstract
     public function getWishlistItemCollection()
     {
         if (is_null($this->_wishlistItemCollection)) {
-            $this->_wishlistItemCollection = $this->getWishlist()
-                ->getItemCollection();
+            $this->_wishlistItemCollection = $this->_createWishlistItemCollection();
         }
         return $this->_wishlistItemCollection;
     }
@@ -220,6 +259,18 @@ class Mage_Wishlist_Helper_Data extends Mage_Core_Helper_Abstract
         return $this->getAddUrlWithParams($item);
     }
 
+    /**
+     * Retrieve url for adding product to wishlist
+     *
+     * @param int $itemId
+     *
+     * @return  string
+     */
+    public function getMoveFromCartUrl($itemId)
+    {
+        return $this->_getUrl('wishlist/index/fromcart', array('item' => $itemId));
+    }
+
     /**
      * Retrieve url for updating product in wishlist
      *
@@ -238,8 +289,7 @@ class Mage_Wishlist_Helper_Data extends Mage_Core_Helper_Abstract
         }
 
         if ($itemId) {
-            $params['id'] = $itemId;
-            return $this->_getUrlStore($item)->getUrl('wishlist/index/updateItemOptions', $params);
+            return $this->_getUrl('wishlist/index/updateItemOptions', array('id' => $itemId));
         }
 
         return false;
@@ -321,11 +371,16 @@ class Mage_Wishlist_Helper_Data extends Mage_Core_Helper_Abstract
     /**
      * Retrieve customer wishlist url
      *
+     * @param int $wishlistId
      * @return string
      */
-    public function getListUrl()
+    public function getListUrl($wishlistId = null)
     {
-        return $this->_getUrl('wishlist');
+        $params = array();
+        if ($wishlistId) {
+            $params['wishlist_id'] = $wishlistId;
+        }
+        return $this->_getUrl('wishlist', $params);
     }
 
     /**
@@ -348,34 +403,44 @@ class Mage_Wishlist_Helper_Data extends Mage_Core_Helper_Abstract
      */
     public function isAllowInCart()
     {
-        return $this->isAllow() && $this->_isCustomerLogIn();
+        return $this->isAllow() && $this->getCustomer();
     }
 
     /**
      * Retrieve customer name
      *
-     * @return string
+     * @return string|null
      */
     public function getCustomerName()
     {
-        return $this->_getCurrentCustomer()->getName();
+        $customer = $this->_getCurrentCustomer();
+        if ($customer) {
+            return $customer->getName();
+        }
     }
 
     /**
      * Retrieve RSS URL
      *
+     * @param $wishlistId
      * @return string
      */
-    public function getRssUrl()
+    public function getRssUrl($wishlistId = null)
     {
         $customer = $this->_getCurrentCustomer();
-        $key = $customer->getId().','.$customer->getEmail();
+        if ($customer) {
+            $key = $customer->getId() . ',' . $customer->getEmail();
+            $params = array(
+                'data' => Mage::helper('Mage_Core_Helper_Data')->urlEncode($key),
+                '_secure' => false,
+            );
+        }
+        if ($wishlistId) {
+            $params['wishlist_id'] = $wishlistId;
+        }
         return $this->_getUrl(
             'rss/index/wishlist',
-            array(
-                'data' => Mage::helper('Mage_Core_Helper_Data')->urlEncode($key),
-                '_secure' => false
-            )
+            $params
         );
     }
 
@@ -399,6 +464,16 @@ class Mage_Wishlist_Helper_Data extends Mage_Core_Helper_Abstract
         return $this->__('Please, enter your comments...');
     }
 
+    /**
+     * Retrieve default empty comment message
+     *
+     * @return string
+     */
+    public function getDefaultWishlistName()
+    {
+        return $this->__('Wishlist');
+    }
+
     /**
      * Calculate count of wishlist items and put value to customer session.
      * Method called after wishlist modifications and trigger 'wishlist_items_renewed' event.
@@ -410,7 +485,7 @@ class Mage_Wishlist_Helper_Data extends Mage_Core_Helper_Abstract
     {
         $session = $this->_getCustomerSession();
         $count = 0;
-        if ($this->_isCustomerLogIn()) {
+        if ($this->getCustomer()) {
             $collection = $this->getWishlistItemCollection()->setInStockFilter(true);
             if (Mage::getStoreConfig(self::XML_PATH_WISHLIST_LINK_USE_QTY)) {
                 $count = $collection->getItemsQty();
@@ -426,4 +501,14 @@ class Mage_Wishlist_Helper_Data extends Mage_Core_Helper_Abstract
         Mage::dispatchEvent('wishlist_items_renewed');
         return $this;
     }
+
+    /**
+     * Should display item quantities in my wishlist link
+     *
+     * @return bool
+     */
+    public function isDisplayQty()
+    {
+        return Mage::getStoreConfig(self::XML_PATH_WISHLIST_LINK_USE_QTY);
+    }
 }
diff --git a/app/code/core/Mage/Wishlist/Model/Resource/Item/Collection.php b/app/code/core/Mage/Wishlist/Model/Resource/Item/Collection.php
index 00df05275b4e65ed3209e444e6e41c54dfded66c..c41021e4a7111541917f49a3d1dacf7bee0f4f3d 100755
--- a/app/code/core/Mage/Wishlist/Model/Resource/Item/Collection.php
+++ b/app/code/core/Mage/Wishlist/Model/Resource/Item/Collection.php
@@ -52,7 +52,7 @@ class Mage_Wishlist_Model_Resource_Item_Collection extends Mage_Core_Model_Resou
      * If product out of stock, its item will be removed after load
      *
      * @var bool
-     */
+      */
     protected $_productInStock = false;
 
     /**
@@ -173,6 +173,11 @@ class Mage_Wishlist_Model_Resource_Item_Collection extends Mage_Core_Model_Resou
         foreach ($storeIds as $id) {
             $productCollection->addStoreFilter($id);
         }
+
+        if ($this->_productVisible) {
+            $productCollection->setVisibility(Mage::getSingleton('Mage_Catalog_Model_Product_Visibility')->getVisibleInSiteIds());
+        }
+
         $productCollection->addPriceData()
             ->addTaxPercents()
             ->addIdFilter($this->_productIds)
@@ -180,11 +185,6 @@ class Mage_Wishlist_Model_Resource_Item_Collection extends Mage_Core_Model_Resou
             ->addOptionsToResult()
             ->addUrlRewrite();
 
-        if ($this->_productVisible) {
-            $productCollection->setVisibility(
-                Mage::getSingleton('Mage_Catalog_Model_Product_Visibility')->getVisibleInSiteIds()
-            );
-        }
         if ($this->_productSalable) {
             $productCollection = Mage::helper('Mage_Adminhtml_Helper_Sales')->applySalableProductTypesFilter($productCollection);
         }
@@ -198,7 +198,7 @@ class Mage_Wishlist_Model_Resource_Item_Collection extends Mage_Core_Model_Resou
         foreach ($this as $item) {
             $product = $productCollection->getItemById($item->getProductId());
             if ($product) {
-                if ($checkInStock && !$product->isSalable()) {
+                if ($checkInStock && !$product->isInStock()) {
                     $this->removeItemByKey($item->getId());
                 } else {
                     $product->setCustomOptions(array());
@@ -229,6 +229,24 @@ class Mage_Wishlist_Model_Resource_Item_Collection extends Mage_Core_Model_Resou
         return $this;
     }
 
+    /**
+     * Add filtration by customer id
+     *
+     * @param int $customerId
+     * @return Mage_Wishlist_Model_Resource_Item_Collection
+     */
+    public function addCustomerIdFilter($customerId)
+    {
+        $this->getSelect()
+            ->join(
+                array('wishlist' => $this->getTable('wishlist')),
+                'main_table.wishlist_id = wishlist.wishlist_id',
+                array()
+            )
+            ->where('wishlist.customer_id = ?', $customerId);
+        return $this;
+    }
+
     /**
      * Add filter by shared stores
      *
diff --git a/app/code/core/Mage/Wishlist/Model/Resource/Wishlist.php b/app/code/core/Mage/Wishlist/Model/Resource/Wishlist.php
index 2c00d53f48deb06de822e9e6fe98edf8d07ade46..d0cb3d895b2c197c8a20fba85f552820d2bac2aa 100755
--- a/app/code/core/Mage/Wishlist/Model/Resource/Wishlist.php
+++ b/app/code/core/Mage/Wishlist/Model/Resource/Wishlist.php
@@ -56,6 +56,24 @@ class Mage_Wishlist_Model_Resource_Wishlist extends Mage_Core_Model_Resource_Db_
         $this->_init('wishlist', 'wishlist_id');
     }
 
+    /**
+     * Prepare wishlist load select query
+     *
+     * @param string $field
+     * @param mixed $value
+     * @param mixed $object
+     * @return Zend_Db_Select
+     */
+    protected function _getLoadSelect($field, $value, $object)
+    {
+        $select = parent::_getLoadSelect($field, $value, $object);
+        if ($field == $this->_customerIdFieldName) {
+            $select->order('wishlist_id ' . Zend_Db_Select::SQL_ASC)
+                ->limit(1);
+        }
+        return $select;
+    }
+
     /**
      * Getter for customer ID field name
      *
diff --git a/app/code/core/Mage/Wishlist/Model/Resource/Wishlist/Collection.php b/app/code/core/Mage/Wishlist/Model/Resource/Wishlist/Collection.php
index f480a66362974fc35458080cda6cb95eef09966d..be5510874c52334ece188dd9a5d055f258fe953c 100755
--- a/app/code/core/Mage/Wishlist/Model/Resource/Wishlist/Collection.php
+++ b/app/code/core/Mage/Wishlist/Model/Resource/Wishlist/Collection.php
@@ -42,4 +42,39 @@ class Mage_Wishlist_Model_Resource_Wishlist_Collection extends Mage_Core_Model_R
     {
         $this->_init('Mage_Wishlist_Model_Wishlist', 'Mage_Wishlist_Model_Resource_Wishlist');
     }
+
+    /**
+     * Filter collection by customer
+     *
+     * @param Mage_Customer_Model_Customer $customer
+     * @return Mage_Wishlist_Model_Resource_Wishlist_Collection
+     */
+    public function filterByCustomer(Mage_Customer_Model_Customer $customer)
+    {
+        return $this->filterByCustomerId($customer->getId());
+    }
+
+    /**
+     * Filter collection by customer id
+     *
+     * @param int $customerId
+     * @return Mage_Wishlist_Model_Resource_Wishlist_Collection
+     */
+    public function filterByCustomerId($customerId)
+    {
+        $this->addFieldToFilter('customer_id', $customerId);
+        return $this;
+    }
+
+    /**
+     * Filter collection by customer ids
+     *
+     * @param array $customerIds
+     * @return Mage_Wishlist_Model_Resource_Wishlist_Collection
+     */
+    public function filterByCustomerIds(array $customerIds)
+    {
+        $this->addFieldToFilter('customer_id', array('in' => $customerIds));
+        return $this;
+    }
 }
diff --git a/app/code/core/Mage/Wishlist/Model/Wishlist.php b/app/code/core/Mage/Wishlist/Model/Wishlist.php
index 001674e7659f62185d5a568068460b9ba72cee1b..6258d85dd7db6d569e8ac152f79f15243480679a 100644
--- a/app/code/core/Mage/Wishlist/Model/Wishlist.php
+++ b/app/code/core/Mage/Wishlist/Model/Wishlist.php
@@ -43,6 +43,12 @@
  */
 class Mage_Wishlist_Model_Wishlist extends Mage_Core_Model_Abstract
 {
+    /**
+     * Prefix of model events names
+     *
+     * @var string
+     */
+    protected $_eventPrefix = 'wishlist';
     /**
      * Wishlist item collection
      *
@@ -97,6 +103,31 @@ class Mage_Wishlist_Model_Wishlist extends Mage_Core_Model_Abstract
         return $this;
     }
 
+    /**
+     * Retrieve wishlist name
+     *
+     * @return string
+     */
+    public function getName()
+    {
+        $name = $this->_getData('name');
+        if (!strlen($name)) {
+            return Mage::helper('Mage_Wishlist_Helper_Data')->getDefaultWishlistName();
+        }
+        return $name;
+    }
+
+    /**
+     * Set random sharing code
+     *
+     * @return Mage_Wishlist_Model_Wishlist
+     */
+    public function generateSharingCode()
+    {
+        $this->setSharingCode($this->_getSharingRandomCode());
+        return $this;
+    }
+
     /**
      * Load by sharing code
      *
@@ -180,6 +211,9 @@ class Mage_Wishlist_Model_Wishlist extends Mage_Core_Model_Abstract
                 ->setProduct($product)
                 ->setQty($qty)
                 ->save();
+            if ($item->getId()) {
+                $this->getItemCollection()->addItem($item);
+            }
         } else {
             $qty = $forciblySetQty ? $qty : $item->getQty() + $qty;
             $item->setQty($qty)
@@ -339,7 +373,7 @@ class Mage_Wishlist_Model_Wishlist extends Mage_Core_Model_Abstract
     /**
      * Retrieve customer id
      *
-     * @return Mage_Wishlist_Model_Wishlist
+     * @return int
      */
     public function getCustomerId()
     {
@@ -471,7 +505,7 @@ class Mage_Wishlist_Model_Wishlist extends Mage_Core_Model_Abstract
      *
      * For more options see Mage_Catalog_Helper_Product->addParamsToBuyRequest()
      *
-     * @param int $itemId
+     * @param int|Mage_Wishlist_Model_Item $itemId
      * @param Varien_Object $buyRequest
      * @param null|array|Varien_Object $params
      * @return Mage_Wishlist_Model_Wishlist
@@ -480,7 +514,12 @@ class Mage_Wishlist_Model_Wishlist extends Mage_Core_Model_Abstract
      */
     public function updateItem($itemId, $buyRequest, $params = null)
     {
-        $item = $this->getItem((int)$itemId);
+        $item = null;
+        if ($itemId instanceof Mage_Wishlist_Model_Item) {
+            $item = $itemId;
+        } else {
+            $item = $this->getItem((int)$itemId);
+        }
         if (!$item) {
             Mage::throwException(Mage::helper('Mage_Wishlist_Helper_Data')->__('Cannot specify wishlist item.'));
         }
@@ -531,4 +570,15 @@ class Mage_Wishlist_Model_Wishlist extends Mage_Core_Model_Abstract
         }
         return $this;
     }
+
+    /**
+     * Save wishlist.
+     *
+     * @return Mage_Wishlist_Model_Wishlist
+     */
+    public function save()
+    {
+        $this->_hasDataChanges = true;
+        return parent::save();
+    }
 }
diff --git a/app/code/core/Mage/Wishlist/controllers/IndexController.php b/app/code/core/Mage/Wishlist/controllers/IndexController.php
index 5d7218c306e2aec3e84637e5fe6ada447b6fb140..221cc900c8ee2ea5249ac760e38720f829103e88 100644
--- a/app/code/core/Mage/Wishlist/controllers/IndexController.php
+++ b/app/code/core/Mage/Wishlist/controllers/IndexController.php
@@ -54,7 +54,7 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
 
         if (!$this->_skipAuthentication && !Mage::getSingleton('Mage_Customer_Model_Session')->authenticate($this)) {
             $this->setFlag('', 'no-dispatch', true);
-            if(!Mage::getSingleton('Mage_Customer_Model_Session')->getBeforeWishlistUrl()) {
+            if (!Mage::getSingleton('Mage_Customer_Model_Session')->getBeforeWishlistUrl()) {
                 Mage::getSingleton('Mage_Customer_Model_Session')->setBeforeWishlistUrl($this->_getRefererUrl());
             }
             Mage::getSingleton('Mage_Customer_Model_Session')->setBeforeWishlistRequest($this->getRequest()->getParams());
@@ -78,10 +78,10 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
 
     /**
      * Retrieve wishlist object
-     *
+     * @param int $wishlistId
      * @return Mage_Wishlist_Model_Wishlist|bool
      */
-    protected function _getWishlist()
+    protected function _getWishlist($wishlistId = null)
     {
         $wishlist = Mage::registry('wishlist');
         if ($wishlist) {
@@ -89,14 +89,32 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
         }
 
         try {
-            $wishlist = Mage::getModel('Mage_Wishlist_Model_Wishlist')
-                ->loadByCustomer(Mage::getSingleton('Mage_Customer_Model_Session')->getCustomer(), true);
+            if (!$wishlistId) {
+                $wishlistId = $this->getRequest()->getParam('wishlist_id');
+            }
+            $customerId = Mage::getSingleton('Mage_Customer_Model_Session')->getCustomerId();
+            /* @var Mage_Wishlist_Model_Wishlist $wishlist */
+            $wishlist = Mage::getModel('Mage_Wishlist_Model_Wishlist');
+            if ($wishlistId) {
+                $wishlist->load($wishlistId);
+            } else {
+                $wishlist->loadByCustomer($customerId, true);
+            }
+
+            if (!$wishlist->getId() || $wishlist->getCustomerId() != $customerId) {
+                $wishlist = null;
+                Mage::throwException(
+                    Mage::helper('Mage_Wishlist_Helper_Data')->__("Requested wishlist doesn't exist")
+                );
+            }
+
             Mage::register('wishlist', $wishlist);
         } catch (Mage_Core_Exception $e) {
             Mage::getSingleton('Mage_Wishlist_Model_Session')->addError($e->getMessage());
+            return false;
         } catch (Exception $e) {
             Mage::getSingleton('Mage_Wishlist_Model_Session')->addException($e,
-                Mage::helper('Mage_Wishlist_Helper_Data')->__('Cannot create wishlist.')
+                Mage::helper('Mage_Wishlist_Helper_Data')->__('Wishlist could not be created.')
             );
             return false;
         }
@@ -109,10 +127,11 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
      */
     public function indexAction()
     {
-        $this->_getWishlist();
+        if (!$this->_getWishlist()) {
+            return $this->norouteAction();
+        }
         $this->loadLayout();
 
-
         $session = Mage::getSingleton('Mage_Customer_Model_Session');
         $block   = $this->getLayout()->getBlock('customer.wishlist');
         $referer = $session->getAddActionReferer(true);
@@ -136,13 +155,13 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
      */
     public function addAction()
     {
-        $session = Mage::getSingleton('Mage_Customer_Model_Session');
         $wishlist = $this->_getWishlist();
         if (!$wishlist) {
-            $this->_redirect('*/');
-            return;
+            return $this->norouteAction();
         }
 
+        $session = Mage::getSingleton('Mage_Customer_Model_Session');
+
         $productId = (int) $this->getRequest()->getParam('product');
         if (!$productId) {
             $this->_redirect('*/');
@@ -201,9 +220,10 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
         }
         catch (Exception $e) {
             $session->addError($this->__('An error occurred while adding item to wishlist.'));
+            Mage::logException($e);
         }
 
-        $this->_redirect('*');
+        $this->_redirect('*', array('wishlist_id' => $wishlist->getId()));
     }
 
     /**
@@ -212,13 +232,16 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
     public function configureAction()
     {
         $id = (int) $this->getRequest()->getParam('id');
-        $wishlist = $this->_getWishlist();
-        /* @var $item Mage_Wishlist_Model_Item */
-        $item = $wishlist->getItem($id);
-
         try {
-            if (!$item) {
-                throw new Exception($this->__('Cannot load wishlist item'));
+            /* @var $item Mage_Wishlist_Model_Item */
+            $item = Mage::getModel('Mage_Wishlist_Model_Item');
+            $item->loadWithOptions($id);
+            if (!$item->getId()) {
+                Mage::throwException($this->__('Cannot load wishlist item'));
+            }
+            $wishlist = $this->_getWishlist($item->getWishlistId());
+            if (!$wishlist) {
+                return $this->norouteAction();
             }
 
             Mage::register('wishlist_item', $item);
@@ -226,7 +249,6 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
             $params = new Varien_Object();
             $params->setCategoryId(false);
             $params->setConfigureMode(true);
-
             $buyRequest = $item->getBuyRequest();
             if (!$buyRequest->getQty() && $item->getQty()) {
                 $buyRequest->setQty($item->getQty());
@@ -236,7 +258,6 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
                 Mage::helper('Mage_Wishlist_Helper_Data')->calculate();
             }
             $params->setBuyRequest($buyRequest);
-
             Mage::helper('Mage_Catalog_Helper_Product_View')->prepareAndRender($item->getProductId(), $this, $params);
         } catch (Mage_Core_Exception $e) {
             Mage::getSingleton('Mage_Customer_Model_Session')->addError($e->getMessage());
@@ -256,12 +277,6 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
     public function updateItemOptionsAction()
     {
         $session = Mage::getSingleton('Mage_Customer_Model_Session');
-        $wishlist = $this->_getWishlist();
-        if (!$wishlist) {
-            $this->_redirect('*/');
-            return;
-        }
-
         $productId = (int) $this->getRequest()->getParam('product');
         if (!$productId) {
             $this->_redirect('*/');
@@ -277,6 +292,15 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
 
         try {
             $id = (int) $this->getRequest()->getParam('id');
+            /* @var Mage_Wishlist_Model_Item */
+            $item = Mage::getModel('Mage_Wishlist_Model_Item');
+            $item->load($id);
+            $wishlist = $this->_getWishlist($item->getWishlistId());
+            if (!$wishlist) {
+                $this->_redirect('*/');
+                return;
+            }
+
             $buyRequest = new Varien_Object($this->getRequest()->getParams());
 
             $wishlist->updateItem($id, $buyRequest)
@@ -297,7 +321,7 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
             $session->addError($this->__('An error occurred while updating wishlist.'));
             Mage::logException($e);
         }
-        $this->_redirect('*/*');
+        $this->_redirect('*/*', array('wishlist_id' => $wishlist->getId()));
     }
 
     /**
@@ -308,9 +332,13 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
         if (!$this->_validateFormKey()) {
             return $this->_redirect('*/*/');
         }
+        $wishlist = $this->_getWishlist();
+        if (!$wishlist) {
+            return $this->norouteAction();
+        }
+
         $post = $this->getRequest()->getPost();
         if($post && isset($post['description']) && is_array($post['description'])) {
-            $wishlist = $this->_getWishlist();
             $updatedItems = 0;
 
             foreach ($post['description'] as $itemId => $description) {
@@ -373,11 +401,11 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
             }
 
             if (isset($post['save_and_share'])) {
-                $this->_redirect('*/*/share');
+                $this->_redirect('*/*/share', array('wishlist_id' => $wishlist->getId()));
                 return;
             }
         }
-        $this->_redirect('*');
+        $this->_redirect('*', array('wishlist_id' => $wishlist->getId()));
     }
 
     /**
@@ -385,25 +413,26 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
      */
     public function removeAction()
     {
-        $wishlist = $this->_getWishlist();
         $id = (int) $this->getRequest()->getParam('item');
         $item = Mage::getModel('Mage_Wishlist_Model_Item')->load($id);
-
-        if($item->getWishlistId() == $wishlist->getId()) {
-            try {
-                $item->delete();
-                $wishlist->save();
-            }
-            catch (Mage_Core_Exception $e) {
-                Mage::getSingleton('Mage_Customer_Model_Session')->addError(
-                    $this->__('An error occurred while deleting the item from wishlist: %s', $e->getMessage())
-                );
-            }
-            catch(Exception $e) {
-                Mage::getSingleton('Mage_Customer_Model_Session')->addError(
-                    $this->__('An error occurred while deleting the item from wishlist.')
-                );
-            }
+        if (!$item->getId()) {
+            return $this->norouteAction();
+        }
+        $wishlist = $this->_getWishlist($item->getWishlistId());
+        if (!$wishlist) {
+            return $this->norouteAction();
+        }
+        try {
+            $item->delete();
+            $wishlist->save();
+        } catch (Mage_Core_Exception $e) {
+            Mage::getSingleton('Mage_Customer_Model_Session')->addError(
+                $this->__('An error occurred while deleting the item from wishlist: %s', $e->getMessage())
+            );
+        } catch(Exception $e) {
+            Mage::getSingleton('Mage_Customer_Model_Session')->addError(
+                $this->__('An error occurred while deleting the item from wishlist.')
+            );
         }
 
         Mage::helper('Mage_Wishlist_Helper_Data')->calculate();
@@ -416,21 +445,18 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
      *
      * If Product has required options - item removed from wishlist and redirect
      * to product view page with message about needed defined required options
-     *
      */
     public function cartAction()
     {
-        $wishlist   = $this->_getWishlist();
-        if (!$wishlist) {
-            return $this->_redirect('*/*');
-        }
-
         $itemId = (int) $this->getRequest()->getParam('item');
 
         /* @var $item Mage_Wishlist_Model_Item */
         $item = Mage::getModel('Mage_Wishlist_Model_Item')->load($itemId);
-
-        if (!$item->getId() || $item->getWishlistId() != $wishlist->getId()) {
+        if (!$item->getId()) {
+            return $this->_redirect('*/*');
+        }
+        $wishlist = $this->_getWishlist($item->getWishlistId());
+        if (!$wishlist) {
             return $this->_redirect('*/*');
         }
 
@@ -496,20 +522,81 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
         return $this->_redirectUrl($redirectUrl);
     }
 
+    /**
+     * Add cart item to wishlist and remove from cart
+     */
+    public function fromcartAction()
+    {
+        $wishlist = $this->_getWishlist();
+        if (!$wishlist) {
+            return $this->norouteAction();
+        }
+        $itemId = (int) $this->getRequest()->getParam('item');
+
+        /* @var Mage_Checkout_Model_Cart $cart */
+        $cart = Mage::getSingleton('Mage_Checkout_Model_Cart');
+        $session = Mage::getSingleton('Mage_Checkout_Model_Session');
+
+        try{
+            $item = $cart->getQuote()->getItemById($itemId);
+            if (!$item) {
+                Mage::throwException(
+                    Mage::helper('Mage_Wishlist_Helper_Data')->__("Requested cart item doesn't exist")
+                );
+            }
+
+            $productId  = $item->getProductId();
+            $buyRequest = $item->getBuyRequest();
+
+            $wishlist->addNewItem($productId, $buyRequest);
+
+            $productIds[] = $productId;
+            $cart->getQuote()->removeItem($itemId);
+            $cart->save();
+            Mage::helper('Mage_Wishlist_Helper_Data')->calculate();
+            $productName = Mage::helper('Mage_Core_Helper_Data')->escapeHtml($item->getProduct()->getName());
+            $wishlistName = Mage::helper('Mage_Core_Helper_Data')->escapeHtml($wishlist->getName());
+            $session->addSuccess(
+                Mage::helper('Mage_Wishlist_Helper_Data')->__("%s has been moved to wishlist %s", $productName, $wishlistName)
+            );
+            $wishlist->save();
+        } catch (Mage_Core_Exception $e) {
+            $session->addError($e->getMessage());
+        } catch (Exception $e) {
+            $session->addException($e, Mage::helper('Mage_Wishlist_Helper_Data')->__('Cannot move item to wishlist'));
+        }
+
+        return $this->_redirectUrl(Mage::helper('Mage_Checkout_Helper_Cart')->getCartUrl());
+    }
+
+    /**
+     * Prepare wishlist for share
+     */
     public function shareAction()
     {
+        $this->_getWishlist();
         $this->loadLayout();
         $this->_initLayoutMessages('Mage_Customer_Model_Session');
         $this->_initLayoutMessages('Mage_Wishlist_Model_Session');
         $this->renderLayout();
     }
 
+    /**
+     * Share wishlist
+     *
+     * @return Mage_Core_Controller_Varien_Action|void
+     */
     public function sendAction()
     {
         if (!$this->_validateFormKey()) {
             return $this->_redirect('*/*/');
         }
 
+        $wishlist = $this->_getWishlist();
+        if (!$wishlist) {
+            return $this->norouteAction();
+        }
+
         $emails  = explode(',', $this->getRequest()->getPost('emails'));
         $message = nl2br(htmlspecialchars((string) $this->getRequest()->getPost('message')));
         $error   = false;
@@ -539,11 +626,13 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
 
         try {
             $customer = Mage::getSingleton('Mage_Customer_Model_Session')->getCustomer();
-            $wishlist = $this->_getWishlist();
 
             /*if share rss added rss feed to email template*/
             if ($this->getRequest()->getParam('rss_url')) {
-                $rss_url = $this->getLayout()->createBlock('Mage_Wishlist_Block_Share_Email_Rss')->toHtml();
+                $rss_url = $this->getLayout()
+                    ->createBlock('Mage_Wishlist_Block_Share_Email_Rss')
+                    ->setWishlistId($wishlist->getId())
+                    ->toHtml();
                 $message .=$rss_url;
             }
             $wishlistBlock = $this->getLayout()->createBlock('Mage_Wishlist_Block_Share_Email_Items')->toHtml();
@@ -579,7 +668,7 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
             Mage::getSingleton('Mage_Customer_Model_Session')->addSuccess(
                 $this->__('Your Wishlist has been shared.')
             );
-            $this->_redirect('*/*');
+            $this->_redirect('*/*', array('wishlist_id' => $wishlist->getId()));
         }
         catch (Exception $e) {
             $translate->setTranslateInline(true);
@@ -592,28 +681,45 @@ class Mage_Wishlist_IndexController extends Mage_Wishlist_Controller_Abstract
 
     /**
      * Custom options download action
-     *
      * @return void
      */
     public function downloadCustomOptionAction()
     {
+        $option = Mage::getModel('Mage_Wishlist_Model_Item_Option')->load($this->getRequest()->getParam('id'));
+
+        if (!$option->getId()) {
+            return $this->_forward('noRoute');
+        }
+
+        $optionId = null;
+        if (strpos($option->getCode(), Mage_Catalog_Model_Product_Type_Abstract::OPTION_PREFIX) === 0) {
+            $optionId = str_replace(Mage_Catalog_Model_Product_Type_Abstract::OPTION_PREFIX, '', $option->getCode());
+            if ((int)$optionId != $optionId) {
+                return $this->_forward('noRoute');
+            }
+        }
+        $productOption = Mage::getModel('Mage_Catalog_Model_Product_Option')->load($optionId);
+
+        if (!$productOption
+            || !$productOption->getId()
+            || $productOption->getProductId() != $option->getProductId()
+            || $productOption->getType() != 'file'
+        ) {
+            return $this->_forward('noRoute');
+        }
+
         try {
-            $optionId = $this->getRequest()->getParam('id');
-            $option   = Mage::getModel('Mage_Wishlist_Model_Item_Option')->load($optionId);
-            $hasError = false;
-
-            if ($option->getId() && $option->getCode() !== 'info_buyRequest') {
-                $info      = unserialize($option->getValue());
-                $filePath  = Mage::getBaseDir() . $info['quote_path'];
-                $secretKey = $this->getRequest()->getParam('key');
-
-                if ($secretKey == $info['secret_key']) {
-                    $this->_prepareDownloadResponse($info['title'], array(
-                        'value' => $filePath,
-                        'type'  => 'filename'
-                    ));
-                }
+            $info      = unserialize($option->getValue());
+            $filePath  = Mage::getBaseDir() . $info['quote_path'];
+            $secretKey = $this->getRequest()->getParam('key');
+
+            if ($secretKey == $info['secret_key']) {
+                $this->_prepareDownloadResponse($info['title'], array(
+                    'value' => $filePath,
+                    'type'  => 'filename'
+                ));
             }
+
         } catch(Exception $e) {
             $this->_forward('noRoute');
         }
diff --git a/app/code/core/Mage/Wishlist/controllers/SharedController.php b/app/code/core/Mage/Wishlist/controllers/SharedController.php
index edc10be7f2767c1b19d7a005fd630ec1b25c2288..d26a3688e3e8d46d245904291ab0e363e37a4b48 100644
--- a/app/code/core/Mage/Wishlist/controllers/SharedController.php
+++ b/app/code/core/Mage/Wishlist/controllers/SharedController.php
@@ -66,7 +66,7 @@ class Mage_Wishlist_SharedController extends Mage_Wishlist_Controller_Abstract
         $customerId = Mage::getSingleton('Mage_Customer_Model_Session')->getCustomerId();
 
         if ($wishlist && $wishlist->getCustomerId() && $wishlist->getCustomerId() == $customerId) {
-            $this->_redirectUrl(Mage::helper('Mage_Wishlist_Helper_Data')->getListUrl());
+            $this->_redirectUrl(Mage::helper('Mage_Wishlist_Helper_Data')->getListUrl($wishlist->getId()));
             return;
         }
 
diff --git a/app/code/core/Mage/Wishlist/view/email/share_notification.html b/app/code/core/Mage/Wishlist/view/email/share_notification.html
index 7bb07f2b74a1f5accb514f87797ab2f84918f49e..8ea9ecf54ad4775a3d8f9898c44fb21c7f77aa51 100644
--- a/app/code/core/Mage/Wishlist/view/email/share_notification.html
+++ b/app/code/core/Mage/Wishlist/view/email/share_notification.html
@@ -1,7 +1,8 @@
 <!--@subject Take a look at {{var customer.name}}'s wishlist @-->
 <!--@vars
 {"store url=\"\"":"Store Url",
-"skin url=\"images/logo_email.gif\" _area='frontend'":"Email Logo Image",
+"var logo_url":"Email Logo Image Url",
+"var logo_alt":"Email Logo Image Alt",
 "var message":"Wishlist Message",
 "var items":"Wishlist Items"}
 @-->
@@ -18,7 +19,7 @@ body,td { color:#2f2f2f; font:11px/1.35em Verdana, Arial, Helvetica, sans-serif;
             <table bgcolor="FFFFFF" cellspacing="0" cellpadding="10" border="0" width="650" style="border:1px solid #E0E0E0;">
                 <tr>
                     <td valign="top">
-                        <a href="{{store url=""}}" style="color:#1E7EC8;"><img src="{{skin url="images/logo_email.gif" _area='frontend'}}" alt="{{var store.getFrontendName()}}" border="0"/></a>
+                        <a href="{{store url=""}}" style="color:#1E7EC8;"><img src="{{var logo_url}}" alt="{{var logo_alt}}" border="0"/></a>
                     </td>
                 </tr>
                 <!-- [ middle starts here] -->
diff --git a/app/code/core/Mage/Wishlist/view/frontend/button/share.phtml b/app/code/core/Mage/Wishlist/view/frontend/button/share.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..65f0667bb8fe05ce441b999be65a4e7f5a2ae3a7
--- /dev/null
+++ b/app/code/core/Mage/Wishlist/view/frontend/button/share.phtml
@@ -0,0 +1,30 @@
+<?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     base_default
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+
+<?php if($this->getWishlist()->getItemsCount()): ?>
+    <button type="submit" name="save_and_share" title="<?php echo $this->__('Share Wishlist') ?>" class="button btn-share"><span><span><?php echo $this->__('Share Wishlist') ?></span></span></button>
+<?php endif;?>
diff --git a/app/code/core/Mage/Wishlist/view/frontend/button/tocart.phtml b/app/code/core/Mage/Wishlist/view/frontend/button/tocart.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..70922fad212c5a62c7cbb51af1773845e196ccf4
--- /dev/null
+++ b/app/code/core/Mage/Wishlist/view/frontend/button/tocart.phtml
@@ -0,0 +1,30 @@
+<?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     base_default
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+
+<?php if($this->getWishlist()->getItemsCount() && $this->getWishlist()->isSalable()): ?>
+    <button type="button" title="<?php echo $this->__('Add All to Cart') ?>" onclick="addAllWItemsToCart()" class="button btn-add"><span><span><?php echo $this->__('Add All to Cart') ?></span></span></button>
+<?php endif;?>
diff --git a/app/code/core/Mage/Wishlist/view/frontend/button/update.phtml b/app/code/core/Mage/Wishlist/view/frontend/button/update.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..8fa47d07b08e8e9d4845f6c931d68ccc6d6ce030
--- /dev/null
+++ b/app/code/core/Mage/Wishlist/view/frontend/button/update.phtml
@@ -0,0 +1,30 @@
+<?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     base_default
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+
+<?php if($this->getWishlist()->getItemsCount()): ?>
+    <button type="submit" name="do" title="<?php echo $this->__('Update Wishlist') ?>" class="button btn-update"><span><span><?php echo $this->__('Update Wishlist') ?></span></span></button>
+<?php endif;?>
diff --git a/app/code/core/Mage/Wishlist/view/frontend/email/rss.phtml b/app/code/core/Mage/Wishlist/view/frontend/email/rss.phtml
index 4e634735bfdb45461c90aa3e1695ffeaf2f6580d..1e31eaa2a7b3291bb10113e8e804a9117d39ba5c 100644
--- a/app/code/core/Mage/Wishlist/view/frontend/email/rss.phtml
+++ b/app/code/core/Mage/Wishlist/view/frontend/email/rss.phtml
@@ -27,5 +27,5 @@
 <p style="font-size:12px; line-height:16px; margin:0 0 16px;">
     <?php echo $this->__("RSS link to %s's wishlist",$this->helper('Mage_Wishlist_Helper_Data')->getCustomerName()) ?>
     <br />
-    <a href="<?php echo $this->helper('Mage_Wishlist_Helper_Data')->getRssUrl(); ?>"><?php echo $this->helper('Mage_Wishlist_Helper_Data')->getRssUrl(); ?></a>
+    <a href="<?php echo $this->helper('Mage_Wishlist_Helper_Data')->getRssUrl($this->getWishlistId()); ?>"><?php echo $this->helper('Mage_Wishlist_Helper_Data')->getRssUrl($this->getWishlistId()); ?></a>
 </p>
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
new file mode 100644
index 0000000000000000000000000000000000000000..84c266a3f704c4a933c1ead951911811876f8bf8
--- /dev/null
+++ b/app/code/core/Mage/Wishlist/view/frontend/item/column/cart.phtml
@@ -0,0 +1,54 @@
+<?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     base_default
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+
+/* @var $this Mage_Wishlist_Block_Customer_Wishlist_Item_Column_Cart */
+/* @var Mage_Wishlist_Model_Item $item */
+$item = $this->getItem();
+$product = $item->getProduct();
+?>
+<div class="cart-cell">
+<?php echo $this->getPriceHtml($product);?>
+<div class="add-to-cart-alt">
+<?php if ($item->canHaveQty() && $item->getProduct()->isVisibleInSiteVisibility()): ?>
+    <input type="text" class="input-text qty validate-not-negative-number" 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') ?>" onclick="addWItemToCart(<?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>
+    <?php else: ?>
+        <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 endforeach;?>
+<?php if ($product->isVisibleInSiteVisibility()): ?>
+    <p><a class="link-edit" href="<?php echo $this->getItemConfigureUrl($item) ?>"><?php echo $this->__('Edit') ?></a></p>
+<?php endif ?>
+</div>
diff --git a/app/code/core/Mage/Wishlist/view/frontend/item/column/image.phtml b/app/code/core/Mage/Wishlist/view/frontend/item/column/image.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..eeec95bc6fdf97c46030994c2e1045eddbaa62a1
--- /dev/null
+++ b/app/code/core/Mage/Wishlist/view/frontend/item/column/image.phtml
@@ -0,0 +1,33 @@
+<?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     base_default
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+
+/* @var Mage_Wishlist_Model_Item $item */
+$item = $this->getItem();
+$product = $item->getProduct();
+?>
+<a class="product-image" href="<?php echo $this->getProductUrl($item) ?>" title="<?php echo $this->escapeHtml($product->getName()) ?>">
+    <img src="<?php echo $this->helper('Mage_Catalog_Helper_Image')->init($product, 'small_image')->resize(113, 113); ?>" width="113" height="113" alt="<?php echo $this->escapeHtml($product->getName()) ?>" />
+</a>
diff --git a/app/code/core/Mage/Wishlist/view/frontend/item/column/info.phtml b/app/code/core/Mage/Wishlist/view/frontend/item/column/info.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..43fe669c93e278f1b1e045da535272749e9cfa71
--- /dev/null
+++ b/app/code/core/Mage/Wishlist/view/frontend/item/column/info.phtml
@@ -0,0 +1,41 @@
+<?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     base_default
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+
+/* @var Mage_Wishlist_Model_Item $item */
+$item = $this->getItem();
+$product = $item->getProduct();
+?>
+<h3 class="product-name"><a href="<?php echo $this->getProductUrl($item) ?>" title="<?php echo $this->escapeHtml($product->getName()) ?>"><?php echo $this->escapeHtml($product->getName()) ?></a></h3>
+<div class="description std"><div class="inner"><?php echo $this->escapeHtml($this->stripTags($product->getShortDescription()));?></div></div>
+<textarea name="description[<?php echo $item->getWishlistItemId() ?>]" rows="3" cols="5" onfocus="focusComment(this)" onblur="focusComment(this)" title="<?php echo $this->__('Comment') ?>"><?php echo ($this->escapeHtml($item->getDescription())) ?></textarea>
+<?php $children = $this->getChildNames(); ?>
+<?php if ($children): ?>
+    <div class="item-manage">
+    <?php foreach($children as $childName):?>
+        <?php echo $this->getLayout()->renderElement($childName, false);?>
+    <?php endforeach;?>
+    </div>
+<?php endif; ?>
diff --git a/app/code/core/Mage/Wishlist/view/frontend/item/column/remove.phtml b/app/code/core/Mage/Wishlist/view/frontend/item/column/remove.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..15ea90eff9bfc8cbce1e4a620c7466e56e138846
--- /dev/null
+++ b/app/code/core/Mage/Wishlist/view/frontend/item/column/remove.phtml
@@ -0,0 +1,29 @@
+<?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     base_default
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+
+?>
+<a href="<?php echo $this->getItemRemoveUrl($this->getItem()); ?>" onclick="return confirmRemoveWishlistItem();" title="<?php echo $this->__('Remove Item') ?>"
+    class="btn-remove btn-remove2"><?php echo $this->__('Remove item');?></a>
diff --git a/app/code/core/Mage/Wishlist/view/frontend/item/configure/addto.phtml b/app/code/core/Mage/Wishlist/view/frontend/item/configure/addto.phtml
index e6315249195a4d625e490e96837276717d7c1365..df8b18dbc2df910e2b584a6de094ce37bbdad1f9 100644
--- a/app/code/core/Mage/Wishlist/view/frontend/item/configure/addto.phtml
+++ b/app/code/core/Mage/Wishlist/view/frontend/item/configure/addto.phtml
@@ -29,7 +29,7 @@
 <?php $_wishlistSubmitUrl = $this->helper('Mage_Wishlist_Helper_Data')->getUpdateUrl($_wishlistItem); ?>
 <ul class="add-to-links">
 <?php if ($this->helper('Mage_Wishlist_Helper_Data')->isAllow()) : ?>
-    <li><a href="<?php echo $_wishlistSubmitUrl ?>" onclick="productAddToCartForm.submitLight(this, '<?php echo $_wishlistSubmitUrl ?>'); return false;" class="link-wishlist"><?php echo $this->__('Update Wishlist') ?></a></li>
+    <li><a href="<?php echo $_wishlistSubmitUrl ?>" onclick="productAddToCartForm.submitLight(this, this.href); return false;" class="link-compare"><?php echo $this->__('Update Wishlist') ?></a></li>
 <?php endif; ?>
 <?php $_product = $this->getProduct(); ?>
 <?php $_compareUrl = $this->helper('Mage_Catalog_Helper_Product_Compare')->getAddUrl($_product); ?>
diff --git a/app/code/core/Mage/Wishlist/view/frontend/item/list.phtml b/app/code/core/Mage/Wishlist/view/frontend/item/list.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..bbe3d6ab977681a6d4cac105a0a7cc16b94b8ad2
--- /dev/null
+++ b/app/code/core/Mage/Wishlist/view/frontend/item/list.phtml
@@ -0,0 +1,63 @@
+<?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     base_default
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+?>
+<?php
+    $columns = $this->getColumns();
+?>
+<table class="data-table" id="wishlist-table">
+    <thead>
+        <tr>
+            <?php foreach ($columns as $column): ?>
+                <th><?php echo $column->getTitle();?></th>
+            <?php endforeach; ?>
+        </tr>
+    </thead>
+    <tbody>
+        <?php if (count($this->getItems())): ?>
+            <?php foreach ($this->getItems() as $item): ?>
+                <tr id="item_<?php echo $item->getId();?>">
+                    <?php foreach ($columns as $column): ?>
+                        <td><?php $column->setItem($item); echo $column->toHtml($item);?></td>
+                    <?php endforeach; ?>
+                </tr>
+            <?php endforeach ?>
+        <?php else: ?>
+            <td colspan="<?php echo count($columns);?>" class="wishlist-empty"><?php echo $this->__('This Wishlist has no Items');?></td>
+        <?php endif; ?>
+    </tbody>
+</table>
+<?php foreach ($columns as $column): ?>
+    <?php echo $column->getAdditionalHtml();?>
+<?php endforeach; ?>
+<script type="text/javascript">
+//<![CDATA[
+    decorateTable('wishlist-table');
+
+<?php foreach ($columns as $column): ?>
+    <?php echo $column->getJs();?>
+<?php endforeach; ?>
+//]]>
+</script>
diff --git a/app/code/core/Mage/Wishlist/view/frontend/layout.xml b/app/code/core/Mage/Wishlist/view/frontend/layout.xml
index 989c927c202fc9b232fe883c9da1583ad20977fd..c5df589f60b1317fd7f7b7c8911f125c5daca0f4 100644
--- a/app/code/core/Mage/Wishlist/view/frontend/layout.xml
+++ b/app/code/core/Mage/Wishlist/view/frontend/layout.xml
@@ -71,13 +71,35 @@ Customer account home dashboard layout
 Wishlist pages
 -->
 
-    <wishlist_index_index translate="label">
+    <wishlist_index_index translate="label" type="page" parent="customer_account_index">
         <label>Customer My Account My Wishlist</label>
         <!-- Mage_Wishlist -->
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
             <block type="Mage_Wishlist_Block_Customer_Wishlist" name="customer.wishlist" template="view.phtml">
-                <block type="Mage_Wishlist_Block_Customer_Wishlist_Item_Options" name="customer.wishlist.item.options" as="item_options"/>
+                <action method="setTitle" translate="title">
+                    <title>My Wishlist</title>
+                </action>
+                <block type="Mage_Wishlist_Block_Customer_Wishlist_Items" name="customer.wishlist.items" as="items" template="item/list.phtml">
+                    <block type="Mage_Wishlist_Block_Customer_Wishlist_Item_Column_Image" name="customer.wishlist.item.image" template="item/column/image.phtml"></block>
+                    <block type="Mage_Wishlist_Block_Customer_Wishlist_Item_Column_Comment" name="customer.wishlist.item.info" template="item/column/info.phtml">
+                        <action method="setTitle" translate="title">
+                            <title>Product Details and Comment</title>
+                        </action>
+                    </block>
+                    <block type="Mage_Wishlist_Block_Customer_Wishlist_Item_Column_Cart" name="customer.wishlist.item.cart" template="item/column/cart.phtml">
+                        <action method="setTitle" translate="title">
+                            <title>Add to Cart</title>
+                        </action>
+                        <block type="Mage_Wishlist_Block_Customer_Wishlist_Item_Options" name="customer.wishlist.item.options"/>
+                    </block>
+                    <block type="Mage_Wishlist_Block_Customer_Wishlist_Item_Column_Remove" name="customer.wishlist.item.remove" template="item/column/remove.phtml"></block>
+                </block>
+                <container name="customer.wishlist.buttons" as="control_buttons" label="Wishlist Control Buttons">
+                    <block type="Mage_Wishlist_Block_Customer_Wishlist_Button" name="customer.wishlist.button.share" template="button/share.phtml"></block>
+                    <block type="Mage_Wishlist_Block_Customer_Wishlist_Button" name="customer.wishlist.button.toCart" template="button/tocart.phtml"></block>
+                    <block type="Mage_Wishlist_Block_Customer_Wishlist_Button" name="customer.wishlist.button.update" template="button/update.phtml"></block>
+                </container>
             </block>
         </reference>
         <reference name="right">
@@ -85,7 +107,7 @@ Wishlist pages
         </reference>
     </wishlist_index_index>
 
-    <wishlist_index_share translate="label">
+    <wishlist_index_share translate="label" type="page" parent="wishlist_index_index">
         <label>Customer My Account Wishlist Sharing Form</label>
         <!-- Mage_Wishlist -->
         <update handle="customer_account"/>
@@ -97,7 +119,7 @@ Wishlist pages
         </reference>
     </wishlist_index_share>
 
-    <wishlist_index_configure translate="label">
+    <wishlist_index_configure translate="label" type="page" parent="wishlist_index_index">
         <label>Configure Wishlist Item</label>
         <update handle="catalog_product_view"/>
         <reference name="product.info">
@@ -109,7 +131,7 @@ Wishlist pages
         </reference>
     </wishlist_index_configure>
 
-    <wishlist_shared_index translate="label">
+    <wishlist_shared_index translate="label" type="page" parent="wishlist_index_share">
         <label>Customer Shared Wishlist View</label>
         <!-- Mage_Wishlist -->
         <reference name="content">
diff --git a/app/code/core/Mage/Wishlist/view/frontend/shared.phtml b/app/code/core/Mage/Wishlist/view/frontend/shared.phtml
index 1cd048bd1bd24f9a09db273f0c4b9ad0a58d3157..7c504c844596a9b77dca3e42b062ce9e179a0946 100644
--- a/app/code/core/Mage/Wishlist/view/frontend/shared.phtml
+++ b/app/code/core/Mage/Wishlist/view/frontend/shared.phtml
@@ -64,7 +64,7 @@
                             <button type="button" title="<?php echo $this->__('Add to Cart') ?>" onclick="setLocation('<?php echo $this->getSharedItemAddToCartUrl($item) ?>')" class="button btn-cart"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
                         <?php endif ?>
                     <?php endif; ?>
-                        <p><a href="#" onclick="setLocation('<?php echo $this->getAddToWishlistUrl($item) ?>'); return false;" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></p>
+                        <p><a href="<?php echo $this->getAddToWishlistUrl($item) ?>" onclick="setLocation(this.href); return false;" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></p>
                     </td>
                 </tr>
             <?php endforeach ?>
diff --git a/app/code/core/Mage/Wishlist/view/frontend/sharing.phtml b/app/code/core/Mage/Wishlist/view/frontend/sharing.phtml
index 333de2010b82b4ac7b813bfcae0aadd4c39ad96f..683d954918b937eb9c8715af4079c8e7b20ce448 100644
--- a/app/code/core/Mage/Wishlist/view/frontend/sharing.phtml
+++ b/app/code/core/Mage/Wishlist/view/frontend/sharing.phtml
@@ -57,7 +57,7 @@
     </div>
     <div class="buttons-set form-buttons">
         <p class="required"><?php echo $this->__('* Required Fields') ?></p>
-        <p class="back-link"><a href="<?php echo $this->getUrl('*/')?>"><small>&laquo; </small><?php echo $this->__('Back')?></a></p>
+        <p class="back-link"><a href="<?php echo $this->getBackUrl(); ?>"><small>&laquo; </small><?php echo $this->__('Back')?></a></p>
         <button type="submit" title="<?php echo $this->__('Share Wishlist') ?>" class="button"><span><span><?php echo $this->__('Share Wishlist') ?></span></span></button>
     </div>
 </form>
diff --git a/app/code/core/Mage/Wishlist/view/frontend/sidebar.phtml b/app/code/core/Mage/Wishlist/view/frontend/sidebar.phtml
index e2f3f6b32ebdaec69c32cc688cfd9a0dbfb8cb9e..44431a93f3e9c81d774c3ea80513da1ba69efc24 100644
--- a/app/code/core/Mage/Wishlist/view/frontend/sidebar.phtml
+++ b/app/code/core/Mage/Wishlist/view/frontend/sidebar.phtml
@@ -28,7 +28,7 @@
 <?php if ($this->helper('Mage_Wishlist_Helper_Data')->isAllow()) : ?>
 <div class="block block-wishlist">
     <div class="block-title">
-        <strong><span><?php echo $this->__('My Wishlist <small>(%d)</small>', $this->getItemCount()) ?></span></strong>
+        <strong><span><?php echo $this->getTitle(); ?></span></strong>
     </div>
     <div class="block-content">
     <p class="block-subtitle"><?php echo $this->__('Last Added Items') ?></p>
diff --git a/app/code/core/Mage/Wishlist/view/frontend/view.phtml b/app/code/core/Mage/Wishlist/view/frontend/view.phtml
index 4c89ddbb4aad3db3ec4031c66d00bb6ec6fde745..cbaf698822ac267f53f2c1567ac96175a2d3b85a 100644
--- a/app/code/core/Mage/Wishlist/view/frontend/view.phtml
+++ b/app/code/core/Mage/Wishlist/view/frontend/view.phtml
@@ -26,130 +26,51 @@
 /* @var $this Mage_Wishlist_Block_Customer_Wishlist */
 ?>
 <?php if ($this->helper('Mage_Wishlist_Helper_Data')->isAllow()) : ?>
-<div class="my-wishlist">
-    <div class="page-title title-buttons">
-        <?php if ($this->helper('Mage_Wishlist_Helper_Data')->isRssAllow() && $this->hasWishlistItems()): ?>
-            <a href="<?php echo $this->helper('Mage_Wishlist_Helper_Data')->getRssUrl(); ?>" class="link-rss"><?php echo $this->__('RSS Feed') ?></a>
-        <?php endif; ?>
-        <h1><?php echo $this->__('My Wishlist') ?></h1>
-    </div>
-    <?php echo $this->getMessagesBlock()->getGroupedHtml() ?>
-    <?php if ($this->hasWishlistItems()): ?>
-    <form id="wishlist-view-form" action="<?php echo $this->getUrl('*/*/update') ?>" method="post">
-        <fieldset>
-            <?php echo $this->getBlockHtml('formkey')?>
-            <table class="data-table" id="wishlist-table">
-            <col width="1" />
-            <col />
-            <col width="1" />
-            <col width="1" />
-            <col width="1" />
-                <thead>
-                    <tr>
-                        <th><?php echo $this->__('Product') ?></th>
-                        <th><?php echo $this->__('Comment') ?></th>
-                        <th class="a-center"><span class="nobr"><?php echo $this->__('Added On') ?></span></th>
-                        <th class="a-center"><span class="nobr"><?php echo $this->__('Add to Cart') ?></span></th>
-                        <th>&nbsp;</th>
-                    </tr>
-                </thead>
-                <tbody>
-                <?php foreach ($this->getWishlistItems() as $item): ?>
-                    <?php
-                        $product = $item->getProduct();
-                        $isVisibleProduct = $product->isVisibleInSiteVisibility();
-                    ?>
-                    <tr>
-                        <td>
-                            <a class="product-image" href="<?php echo $this->getProductUrl($item) ?>" title="<?php echo $this->escapeHtml($product->getName()) ?>"><img src="<?php echo $this->getImageUrl($product); ?>" width="<?php echo $this->getImageSize()?>" height="<?php echo $this->getImageSize()?>" alt="<?php echo $this->escapeHtml($item->getName()) ?>" /></a>
-                            <h2 class="product-name"><a href="<?php echo $this->getProductUrl($item) ?>"><?php echo $this->escapeHtml($product->getName()) ?></a></h2>
-                            <?php echo $this->getPriceHtml($product) ?>
-                            <?php echo $this->getDetailsHtml($item) ?>
-                        </td>
-                        <td>
-                            <textarea name="description[<?php echo $item->getWishlistItemId() ?>]" rows="3" cols="5" onfocus="focusComment(this)" onblur="focusComment(this)" title="<?php echo $this->__('Comment') ?>"><?php echo $this->getCommentValue($item); ?></textarea>
-                        </td>
-                        <td>
-                            <span class="nobr"><?php echo $this->getFormatedDate($item->getAddedAt()) ?></span>
-                        </td>
-                        <td class="a-center">
-                        <?php if ($item->canHaveQty() && $isVisibleProduct): ?>
-                            <p><input type="text" class="input-text qty" name="qty[<?php echo $item->getId() ?>]" value="<?php echo $this->getAddToCartQty($item) * 1 ?>" /></p>
-                        <?php endif; ?>
-                        <?php if ($product->isSaleable()): ?>
-                            <?php if ($isVisibleProduct): ?>
-                            <button type="button" title="<?php echo $this->__('Add to Cart') ?>" onclick="addWItemToCart(<?php echo $item->getId(); ?>)" class="button btn-cart"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
-                            <?php endif ?>
-                        <?php else: ?>
-                            <p class="availability out-of-stock"><span><?php echo $this->__('Out of stock') ?></span></p>
-                        <?php endif; ?>
-                            <?php if ($isVisibleProduct): ?>
-                            <p><a href="<?php echo $this->getItemConfigureUrl($item) ?>"><?php echo $this->__('Edit') ?></a></p>
-                            <?php endif ?>
-                        </td>
-                        <td>
-                            <a href="<?php echo $this->getItemRemoveUrl($item) ?>" title="<?php echo $this->__('Remove Item') ?>" onclick="return confirmRemoveWishlistItem();" class="btn-remove btn-remove2"><?php echo $this->__('Remove item')?></a>
-                        </td>
-                    </tr>
-                <?php endforeach ?>
-                </tbody>
-            </table>
-            <script type="text/javascript">decorateTable('wishlist-table')</script>
-            <div class="buttons-set buttons-set2">
-                <button type="submit" onclick="this.name='save_and_share'" title="<?php echo $this->__('Share Wishlist') ?>" class="button btn-share"><span><span><?php echo $this->__('Share Wishlist') ?></span></span></button>
-                <?php if($this->isSaleable()):?>
-                    <button type="button" title="<?php echo $this->__('Add All to Cart') ?>" onclick="addAllWItemsToCart()" class="button btn-add"><span><span><?php echo $this->__('Add All to Cart') ?></span></span></button>
-                <?php endif;?>
-                <button type="submit" title="<?php echo $this->__('Update Wishlist') ?>" onclick="this.name='do'" class="button btn-update"><span><span><?php echo $this->__('Update Wishlist') ?></span></span></button>
-            </div>
-        </fieldset>
-    </form>
-    <?php else: ?>
-        <p><?php echo $this->__('You have no items in your wishlist.') ?></p>
-    <?php endif ?>
-    <script type="text/javascript">
-    //<![CDATA[
-    function confirmRemoveWishlistItem() {
-        return confirm('<?php echo $this->__('Are you sure you want to remove this product from your wishlist?') ?>');
-    }
+    <div class="my-wishlist">
+        <div class="page-title title-buttons">
+            <?php if ($this->helper('Mage_Wishlist_Helper_Data')->isRssAllow() && $this->hasWishlistItems()): ?>
+                <a href="<?php echo $this->helper('Mage_Wishlist_Helper_Data')->getRssUrl($this->getWishlistInstance()->getId()); ?>" class="link-rss"><?php echo $this->__('RSS Feed') ?></a>
+            <?php endif; ?>
+            <h1><?php echo $this->getTitle(); ?></h1>
+        </div>
+        <?php echo $this->getMessagesBlock()->getGroupedHtml() ?>
 
-    function focusComment(obj) {
-        if( obj.value == '<?php echo $this->helper('Mage_Wishlist_Helper_Data')->defaultCommentString() ?>' ) {
-            obj.value = '';
-        } else if( obj.value == '' ) {
-            obj.value = '<?php echo $this->helper('Mage_Wishlist_Helper_Data')->defaultCommentString() ?>';
-        }
-    }
+        <form id="wishlist-view-form" action="<?php echo $this->getUrl('*/*/update', array('wishlist_id' => $this->getWishlistInstance()->getId())) ?>" method="post">
+            <?php echo $this->getChildHtml('top'); ?>
+            <fieldset>
+                <?php if ($this->hasWishlistItems()): ?>
+                        <?php echo $this->getBlockHtml('formkey');?>
+                        <?php $this->getChildBlock('items')->setItems($this->getWishlistItems()); ?>
+                        <?php echo $this->getChildHtml('items');?>
+                        <script type="text/javascript">decorateTable('wishlist-table')</script>
+                <?php else: ?>
+                    <p class="wishlist-empty"><?php echo $this->__('You have no items in your wishlist.') ?></p>
+                <?php endif ?>
+                <div class="buttons-set buttons-set2">
+                    <?php echo $this->getChildHtml('control_buttons');?>
+                </div>
+            </fieldset>
+        </form>
 
-    function addWItemToCart(itemId) {
-        var url = '<?php echo $this->getItemAddToCartUrl('%item%') ?>';
-        url = url.gsub('%item%', itemId);
-        var form = $('wishlist-view-form');
-        if (form) {
-            var input = form['qty[' + itemId + ']'];
-            if (input) {
-                var separator = (url.indexOf('?') >= 0) ? '&' : '?';
-                url += separator + input.name + '=' + encodeURIComponent(input.value);
-            }
+        <script type="text/javascript">
+        //<![CDATA[
+        var wishlistForm = new Validation($('wishlist-view-form'));
+        function addAllWItemsToCart() {
+            var url = '<?php echo $this->getUrl('*/*/allcart', array('wishlist_id' => $this->getWishlistInstance()->getId())) ?>';
+            var separator = (url.indexOf('?') >= 0) ? '&' : '?';
+            $$('#wishlist-view-form .qty').each(
+                function (input, index) {
+                    url += separator + input.name + '=' + encodeURIComponent(input.value);
+                    separator = '&';
+                }
+            );
+            setLocation(url);
         }
-        setLocation(url);
-    }
-
-    function addAllWItemsToCart() {
-        var url = '<?php echo $this->getUrl('*/*/allcart') ?>';
-        var separator = (url.indexOf('?') >= 0) ? '&' : '?';
-        $$('#wishlist-view-form .qty').each(
-            function (input, index) {
-                url += separator + input.name + '=' + encodeURIComponent(input.value);
-                separator = '&';
-            }
-        );
-        setLocation(url);
-    }
-    //]]>
-    </script>
-</div>
-<div class="buttons-set">
-    <p class="back-link"><a href="<?php echo $this->escapeUrl($this->getBackUrl()) ?>"><small>&laquo; </small><?php echo $this->__('Back') ?></a></p>
-</div>
+        //]]>
+        </script>
+    </div>
+    <?php echo $this->getChildHtml('bottom'); ?>
+    <div class="buttons-set">
+        <p class="back-link"><a href="<?php echo $this->escapeUrl($this->getBackUrl()) ?>"><small>&laquo; </small><?php echo $this->__('Back') ?></a></p>
+    </div>
 <?php endif ?>
diff --git a/app/code/core/Mage/XmlConnect/Block/Cart/Crosssell.php b/app/code/core/Mage/XmlConnect/Block/Cart/Crosssell.php
index 0ede156381ef9d1553f149cfad481fdc24dfcd09..884bd8130bee686266af604bb4ce4f956ddae8e4 100644
--- a/app/code/core/Mage/XmlConnect/Block/Cart/Crosssell.php
+++ b/app/code/core/Mage/XmlConnect/Block/Cart/Crosssell.php
@@ -83,8 +83,8 @@ class Mage_XmlConnect_Block_Cart_Crosssell extends Mage_Checkout_Block_Cart_Cros
                 $itemXmlObj->addChild('is_salable', (int)$product->isSalable());
             }
 
-            if ($this->getChild('product_price')) {
-                $this->getChild('product_price')->setProduct($product)->setProductXmlObj($itemXmlObj)
+            if ($this->getChildBlock('product_price')) {
+                $this->getChildBlock('product_price')->setProduct($product)->setProductXmlObj($itemXmlObj)
                     ->collectProductPrices();
             }
 
diff --git a/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mecl/Details.php b/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mecl/Details.php
index b2be761c90f16cda3f2e071c7e2ed5435cf588db..247f889263df7930100d19742ec405ac6e46d86a 100644
--- a/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mecl/Details.php
+++ b/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mecl/Details.php
@@ -46,7 +46,7 @@ class Mage_XmlConnect_Block_Cart_Paypal_Mecl_Details extends Mage_Paypal_Block_E
             $this->getItemXml($_item, $itemsXmlObj);
         }
 
-        $reviewXmlObj->appendChild($this->getChild('totals')->setReturnObjectFlag(true)->_toHtml());
+        $reviewXmlObj->appendChild($this->getChildBlock('totals')->setReturnObjectFlag(true)->_toHtml());
 
         return $reviewXmlObj;
     }
diff --git a/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mecl/Review.php b/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mecl/Review.php
index 8075daa127e98658697ab0b4917c57b03cf39b87..df14588b39cdf41d3d5a6e3a4a61a6cf87d80012 100644
--- a/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mecl/Review.php
+++ b/app/code/core/Mage/XmlConnect/Block/Cart/Paypal/Mecl/Review.php
@@ -87,7 +87,7 @@ class Mage_XmlConnect_Block_Cart_Paypal_Mecl_Review extends Mage_Paypal_Block_Ex
                 'payer_email'   => $this->__('Payer Email: %s', $this->getBillingAddress()->getEmail())
         ));
 
-        $this->getChild('details')->addDetailsToXmlObj($reviewXmlObj);
+        $this->getChildBlock('details')->addDetailsToXmlObj($reviewXmlObj);
 
         return $reviewXmlObj->asNiceXml();
     }
diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Category.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Category.php
index 3f40326ae907c7bd7211dc6be52cd93eea7268a2..e775ddd2388f06dbf37363a5d6e6ade72dd4b2ef 100644
--- a/app/code/core/Mage/XmlConnect/Block/Catalog/Category.php
+++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Category.php
@@ -52,7 +52,7 @@ class Mage_XmlConnect_Block_Catalog_Category extends Mage_XmlConnect_Block_Catal
         $categoryModel  = Mage::getModel('Mage_Catalog_Model_Category')->load($categoryId);
         if ($categoryModel->getId()) {
             $hasMoreProductItems = 0;
-            $productListBlock = $this->getChild('product_list');
+            $productListBlock = $this->getChildBlock('product_list');
             if ($productListBlock && $categoryModel->getLevel() > 1) {
                 $layer = Mage::getSingleton('Mage_Catalog_Model_Layer');
                 $productsXmlObj = $productListBlock->setCategory($categoryModel)->setLayer($layer)
@@ -60,7 +60,7 @@ class Mage_XmlConnect_Block_Catalog_Category extends Mage_XmlConnect_Block_Catal
                 $hasMoreProductItems = (int)$productListBlock->getHasProductItems();
             }
 
-            $infoBlock = $this->getChild('category_info');
+            $infoBlock = $this->getChildBlock('category_info');
             if ($infoBlock) {
                 $categoryInfoXmlObj = $infoBlock->setCategory($categoryModel)->getCategoryInfoXmlObject();
                 $categoryInfoXmlObj->addChild('has_more_items', $hasMoreProductItems);
diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product.php
index b403c22197d2eb686728a77547329c49bcdf2444..025eb773f8a690ab4ac78b6065914fa88751a318 100644
--- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product.php
+++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product.php
@@ -98,13 +98,13 @@ class Mage_XmlConnect_Block_Catalog_Product extends Mage_XmlConnect_Block_Catalo
             $item->addChild('rating_summary', round((int)$product->getRatingSummary()->getRatingSummary() / 10));
             $item->addChild('reviews_count', $product->getRatingSummary()->getReviewsCount());
 
-            if ($this->getChild('product_price')) {
-                $this->getChild('product_price')->setProduct($product)->setProductXmlObj($item)
+            if ($this->getChildBlock('product_price')) {
+                $this->getChildBlock('product_price')->setProduct($product)->setProductXmlObj($item)
                     ->collectProductPrices();
             }
 
-            if ($this->getChild('additional_info')) {
-                $this->getChild('additional_info')->addAdditionalData($product, $item);
+            if ($this->getChildBlock('additional_info')) {
+                $this->getChildBlock('additional_info')->addAdditionalData($product, $item);
             }
         }
 
@@ -145,14 +145,14 @@ class Mage_XmlConnect_Block_Catalog_Product extends Mage_XmlConnect_Block_Catalo
             $this->setProduct($product);
             $productXmlObj = $this->productToXmlObject($product, 'product');
 
-            $relatedProductsBlock = $this->getChild('related_products');
+            $relatedProductsBlock = $this->getChildBlock('related_products');
             if ($relatedProductsBlock) {
                 $relatedXmlObj = $relatedProductsBlock->getRelatedProductsXmlObj();
                 $productXmlObj->appendChild($relatedXmlObj);
             }
         }
 
-        $productOptions = $this->getChild('xmlconnect.catalog.product.options')
+        $productOptions = $this->getChildBlock('xmlconnect.catalog.product.options')
             ->getProductOptionsXmlObject($product);
         if ($productOptions instanceof Mage_XmlConnect_Model_Simplexml_Element) {
             $productXmlObj->appendChild($productOptions);
diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Related.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Related.php
index b7f1c281999935815446f6f32cace4ea0e0dbe85..d3b34f5266a4083f7e4a75b4d143d599aa7886e1 100644
--- a/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Related.php
+++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Product/Related.php
@@ -85,8 +85,8 @@ class Mage_XmlConnect_Block_Catalog_Product_Related extends Mage_XmlConnect_Bloc
                 continue;
             }
 
-            if ($this->getParentBlock()->getChild('product_price')) {
-                $this->getParentBlock()->getChild('product_price')->setProduct($product)
+            if ($this->getParentBlock()->getChildBlock('product_price')) {
+                $this->getParentBlock()->getChildBlock('product_price')->setProduct($product)
                     ->setProductXmlObj($productXmlObj)->collectProductPrices();
             }
             $relatedXmlObj->appendChild($productXmlObj);
diff --git a/app/code/core/Mage/XmlConnect/Block/Catalog/Search.php b/app/code/core/Mage/XmlConnect/Block/Catalog/Search.php
index a4f621da9b993957e9ae537972b8a2aeab05cc2b..f638e08f4bd8327f98ca427f6288391b2314fec8 100644
--- a/app/code/core/Mage/XmlConnect/Block/Catalog/Search.php
+++ b/app/code/core/Mage/XmlConnect/Block/Catalog/Search.php
@@ -62,7 +62,7 @@ class Mage_XmlConnect_Block_Catalog_Search extends Mage_XmlConnect_Block_Catalog
         /**
          * Products
          */
-        $productListBlock = $this->getChild('product_list');
+        $productListBlock = $this->getChildBlock('product_list');
         if ($productListBlock) {
             $layer = Mage::getSingleton('Mage_CatalogSearch_Model_Layer');
             $productsXmlObj = $productListBlock->setLayer($layer)
diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Address/Billing.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Address/Billing.php
index a69a8cf485890dcebc7c21be72874b2ee4c2577d..95bc3245e9669e00ab5bf17c1449bba109292839 100644
--- a/app/code/core/Mage/XmlConnect/Block/Checkout/Address/Billing.php
+++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Address/Billing.php
@@ -53,7 +53,7 @@ class Mage_XmlConnect_Block_Checkout_Address_Billing extends Mage_Checkout_Block
             if ($addressId == $address->getId()) {
                 $item->addAttribute('selected', 1);
             }
-            $this->getChild('address_list')->prepareAddressData($address, $item);
+            $this->getChildBlock('address_list')->prepareAddressData($address, $item);
             $item->addChild(
                 'address_line', $billingXmlObj->escapeXml($address->format('oneline'))
             );
diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Address/Shipping.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Address/Shipping.php
index f6b9d66968a2885df9c99568628e84b8bd46bba6..cdb63892ba44c7e0dec4be2f014f5cbbfedf52a9 100644
--- a/app/code/core/Mage/XmlConnect/Block/Checkout/Address/Shipping.php
+++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Address/Shipping.php
@@ -53,7 +53,7 @@ class Mage_XmlConnect_Block_Checkout_Address_Shipping extends Mage_Checkout_Bloc
             if ($addressId == $address->getId()) {
                 $item->addAttribute('selected', 1);
             }
-            $this->getChild('address_list')->prepareAddressData($address, $item);
+            $this->getChildBlock('address_list')->prepareAddressData($address, $item);
             $item->addChild('address_line', $shippingXmlObj->escapeXml($address->format('oneline')));
         }
 
diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/List.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/List.php
index 710b094276a1b2dca37d4ef8d7f232d60cf0c29f..957cbe354e8f79d87c9b59738f377ac10419afd5 100644
--- a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/List.php
+++ b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/List.php
@@ -214,35 +214,24 @@ class Mage_XmlConnect_Block_Checkout_Payment_Method_List extends Mage_Payment_Bl
             $sortedAvailableMethodCodes[] = $method->getCode();
         }
 
-        /**
-         * Get blocks for layout to check available renderers
-         */
-        $methodBlocks = $this->getChild();
-
         /**
          * Collect directly supported by xmlconnect methods
          */
-        if (!empty($methodBlocks) && is_array($methodBlocks)) {
-            foreach ($methodBlocks as $block) {
-                if (!$block) {
-                    continue;
-                }
-
-                $method = $block->getMethod();
-                if (!$this->_canUseMethod($method) || in_array($method->getCode(), $usedCodes)) {
-                    continue;
-                }
-                $this->_assignMethod($method);
-                $usedCodes[] = $method->getCode();
-                $usedMethods[$method->getCode()] = array('renderer' => $block, 'method' => $method);
+        foreach ($this->getLayout()->getChildBlocks($this->getNameInLayout()) as $block) {
+            $method = $block->getMethod();
+            if (!$this->_canUseMethod($method) || in_array($method->getCode(), $usedCodes)) {
+                continue;
             }
+            $this->_assignMethod($method);
+            $usedCodes[] = $method->getCode();
+            $usedMethods[$method->getCode()] = array('renderer' => $block, 'method' => $method);
         }
 
         /**
          * Collect all "Credit Card" / "CheckMo" / "Purchaseorder" method compatible methods
          */
         foreach ($methodArray as $methodName => $methodModelClassName) {
-            $methodRenderer = $this->getChild($methodName);
+            $methodRenderer = $this->getChildBlock($methodName);
             if (!empty($methodRenderer)) {
                 foreach ($sortedAvailableMethodCodes as $methodCode) {
                     /**
diff --git a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Abstract.php b/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Abstract.php
deleted file mode 100755
index 67ebc568fb3cd8a8d9e4658d43f144ea4e8f46d5..0000000000000000000000000000000000000000
--- a/app/code/core/Mage/XmlConnect/Block/Checkout/Payment/Method/Pbridge/Abstract.php
+++ /dev/null
@@ -1,90 +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    Mage
- * @package     Mage_XmlConnect
- * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
- * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
- */
-
-/**
- * Abstract Pbridge Payment method xml renderer
- *
- * @category    Mage
- * @package     Mage_XmlConnect
- * @author      Magento Core Team <core@magentocommerce.com>
- */
-abstract class Mage_XmlConnect_Block_Checkout_Payment_Method_Pbridge_Abstract
-    extends Enterprise_Pbridge_Block_Payment_Form_Abstract
-{
-    /**
-     * Retrieve payment method model
-     *
-     * @return Mage_Payment_Model_Method_Abstract
-     */
-    public function getMethod()
-    {
-        $method = $this->getData('method');
-        if (!$method) {
-            $method = Mage::getModel('Enterprise_Pbridge_Model_Payment_Method_' . $this->_model);
-            $this->setData('method', $method);
-        }
-        return $method;
-    }
-
-    /**
-     * Return redirect url for Payment Bridge application
-     *
-     * @return string
-     */
-    public function getRedirectUrl()
-    {
-        return $this->getUrl('xmlconnect/pbridge/result', array('_current' => true, '_secure' => true));
-    }
-
-    /**
-     * Add payment method through Pbridge iframe XML object
-     *
-     * @param Mage_XmlConnect_Model_Simplexml_Element $paymentItemXmlObj
-     * @return Mage_XmlConnect_Model_Simplexml_Element
-     */
-    public function addPaymentFormToXmlObj(Mage_XmlConnect_Model_Simplexml_Element $paymentItemXmlObj)
-    {
-        $paymentItemXmlObj->addAttribute('is_pbridge', 1);
-        $paymentItemXmlObj->addChild('pb_iframe', $paymentItemXmlObj->xmlentities($this->createIframe()));
-        return $paymentItemXmlObj;
-    }
-
-    /**
-     * Create html page with iframe for devices
-     *
-     * @return string html
-     */
-    protected function createIframe()
-    {
-        $code = $this->getMethodCode();
-        $body = <<<EOT
-<div id="payment_form_{$code}" style="margin:0 auto; max-width:500px;">
-    {$this->getIframeBlock()->toHtml()}
-</div>
-EOT;
-        return $this->helper('Mage_XmlConnect_Helper_Data')->htmlize($body);
-    }
-}
diff --git a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Details.php b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Details.php
index f70676209888092ab90eb3456fe5322ff14dc948..6b0c70c09d0347e0482f1f7e3d70fe85200e688f 100755
--- a/app/code/core/Mage/XmlConnect/Block/Customer/Order/Details.php
+++ b/app/code/core/Mage/XmlConnect/Block/Customer/Order/Details.php
@@ -127,7 +127,7 @@ class Mage_XmlConnect_Block_Customer_Order_Details extends Mage_Payment_Block_In
             $currentBlockName = 'xmlconnect.checkout.payment.method.info.' . $methodCode;
             $this->getLayout()->addBlock($currentBlockRenderer, $currentBlockName);
             $this->setChild($methodCode, $currentBlockName);
-            $renderer = $this->getChild($methodCode)->setInfo($order->getPayment());
+            $renderer = $this->getChildBlock($methodCode)->setInfo($order->getPayment());
             $renderer->addPaymentInfoToXmlObj($paymentNode);
         } else {
             $paymentNode->addAttribute('type', $methodCode);
diff --git a/app/code/core/Mage/XmlConnect/Block/Wishlist.php b/app/code/core/Mage/XmlConnect/Block/Wishlist.php
index f293f14413e416d2eb55d7c3d195316a9bc16758..0ea3347aa29cda428dcca9c6263f5285a6d8006d 100644
--- a/app/code/core/Mage/XmlConnect/Block/Wishlist.php
+++ b/app/code/core/Mage/XmlConnect/Block/Wishlist.php
@@ -96,8 +96,8 @@ class Mage_XmlConnect_Block_Wishlist extends Mage_Wishlist_Block_Customer_Wishli
                 $addedDate = $wishlistXmlObj->escapeXml($this->getFormatedDate($item->getAddedAt()));
                 $itemXmlObj->addChild('added_date', $addedDate);
 
-                if ($this->getChild('product_price')) {
-                    $this->getChild('product_price')->setProduct($item->getProduct())->setProductXmlObj($itemXmlObj)
+                if ($this->getChildBlock('product_price')) {
+                    $this->getChildBlock('product_price')->setProduct($item->getProduct())->setProductXmlObj($itemXmlObj)
                         ->collectProductPrices();
                 }
 
diff --git a/app/code/core/Mage/XmlConnect/Helper/Theme.php b/app/code/core/Mage/XmlConnect/Helper/Theme.php
index 61cf16e9276d329cdd5d365bae5323de73f35ffe..e0a3bbe7950707c185120da651d8ba9fa9a951f9 100644
--- a/app/code/core/Mage/XmlConnect/Helper/Theme.php
+++ b/app/code/core/Mage/XmlConnect/Helper/Theme.php
@@ -382,7 +382,7 @@ EOT;
         $result = false;
         $ioFile = new Varien_Io_File();
         $ioFile->cd($this->getMediaThemePath());
-        $themeFile = $themeId . '.xml';
+        $themeFile = basename($themeId . '.xml');
         if ($ioFile->fileExists($themeFile)) {
             $result = $ioFile->rm($themeFile);
         }
diff --git a/app/code/core/Mage/XmlConnect/controllers/Adminhtml/MobileController.php b/app/code/core/Mage/XmlConnect/controllers/Adminhtml/MobileController.php
index eac013491f187d335521305c353c16dddade1ef7..d538a8e7febfdee9d0148593bde040d559eeac7a 100644
--- a/app/code/core/Mage/XmlConnect/controllers/Adminhtml/MobileController.php
+++ b/app/code/core/Mage/XmlConnect/controllers/Adminhtml/MobileController.php
@@ -1165,9 +1165,8 @@ class Mage_XmlConnect_Adminhtml_MobileController extends Mage_Adminhtml_Controll
                         break;
                 }
                 if ($temporaryObject->getExecTime()) {
-                    $message->setExecTime(
-                        Mage::getSingleton('Mage_Core_Model_Date')->gmtDate(null, $temporaryObject->getExecTime())
-                    );
+                    $execTime = Mage::getSingleton('Mage_Core_Model_Date')->gmtDate(null, $temporaryObject->getExecTime());
+                    $message->setExecTime($execTime ? $execTime : Mage::getSingleton('Mage_Core_Model_Date')->gmtDate());
                 } else {
                     $message->setExecTime(new Zend_Db_Expr('NULL'));
                 }
diff --git a/app/code/core/Mage/XmlConnect/controllers/Paypal/MeclController.php b/app/code/core/Mage/XmlConnect/controllers/Paypal/MeclController.php
index e10fdeac172a37d4d7750b8a41100712f7ed41c5..3cbda0d73cf9ef83222cd4790829071beee6bfe8 100644
--- a/app/code/core/Mage/XmlConnect/controllers/Paypal/MeclController.php
+++ b/app/code/core/Mage/XmlConnect/controllers/Paypal/MeclController.php
@@ -180,8 +180,8 @@ class Mage_XmlConnect_Paypal_MeclController extends Mage_XmlConnect_Controller_A
                 $detailsBlock->setPaypalMessages($messageArray);
             }
 
-            $detailsBlock->setQuote($this->_getQuote())->getChild('details')->setQuote($this->_getQuote())
-                ->getChild('totals')->setQuote($this->_getQuote());
+            $detailsBlock->setQuote($this->_getQuote())->getChildBlock('details')->setQuote($this->_getQuote())
+                ->getChildBlock('totals')->setQuote($this->_getQuote());
             $this->renderLayout();
             return;
         } catch (Mage_Core_Exception $e) {
diff --git a/app/code/core/Mage/XmlConnect/view/adminhtml/layout.xml b/app/code/core/Mage/XmlConnect/view/adminhtml/layout.xml
index a40ee8c3ec5696f7d4c60582acc6f4d594c90cfb..684656ffb26ece246cf17dbc2e8e190ee77df8a4 100644
--- a/app/code/core/Mage/XmlConnect/view/adminhtml/layout.xml
+++ b/app/code/core/Mage/XmlConnect/view/adminhtml/layout.xml
@@ -80,7 +80,7 @@
             <action method="addJs"><file>mage/adminhtml/browser.js</file></action>
             <action method="addJs"><file>prototype/window.js</file></action>
             <action method="addCss"><file>prototype/windows/themes/default.css</file></action>
-            <action method="addCss"><file>prototype/windows/themes/magento.css</file></action>
+            <action method="addCss"><file>Mage_Core::prototype/magento.css</file></action>
         </reference>
         <reference name="content">
             <block type="Mage_XmlConnect_Block_Adminhtml_Template_Edit" name="template_edit"/>
@@ -145,7 +145,7 @@
 
     <adminhtml_mobile_submissionhistorygrid>
         <remove name="root"/>
-        <block type="Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Submission_History" name="submission_history_grid" output="toHtml"/>
+        <block type="Mage_XmlConnect_Block_Adminhtml_Mobile_Edit_Tab_Submission_History" name="submission_history_grid" output="1"/>
     </adminhtml_mobile_submissionhistorygrid>
 
     <adminhtml_mobile_submission>
@@ -167,71 +167,71 @@
     </adminhtml_mobile_submission>
 
     <adminhtml_mobile_grid>
-        <block type="Mage_XmlConnect_Block_Adminhtml_Mobile_Grid" name="mobile_grid" output="toHtml"/>
+        <block type="Mage_XmlConnect_Block_Adminhtml_Mobile_Grid" name="mobile_grid" output="1"/>
     </adminhtml_mobile_grid>
 
     <adminhtml_mobile_history_grid>
-        <block type="Mage_XmlConnect_Block_Adminhtml_History_Grid" name="history_grid" output="toHtml"/>
+        <block type="Mage_XmlConnect_Block_Adminhtml_History_Grid" name="history_grid" output="1"/>
     </adminhtml_mobile_history_grid>
 
     <adminhtml_mobile_template_preview>
-        <block type="Mage_Core_Block_Template" name="root" output="toHtml" template="Mage_XmlConnect::template/preview.phtml">
+        <block type="Mage_Core_Block_Template" name="root" output="1" template="Mage_XmlConnect::template/preview.phtml">
             <block type="Mage_XmlConnect_Block_Adminhtml_Template_Preview" name="content" as="content"></block>
         </block>
     </adminhtml_mobile_template_preview>
 
     <adminhtml_mobile_previewhome>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_XmlConnect_Block_Adminhtml_Mobile_Preview_Content" name="preview_home_content">
                 <action method="setTemplate"><templateType>home</templateType></action>
                 <block type="Mage_XmlConnect_Block_Adminhtml_Mobile_Preview_Tabitems" name="preview_tab_items" as="tab_items">
                     <action method="setActiveTab"><tab>home</tab></action>
                 </block>
             </block>
-        </block>
+        </container>
     </adminhtml_mobile_previewhome>
 
     <adminhtml_mobile_previewhomehor>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_XmlConnect_Block_Adminhtml_Mobile_Preview_Content" name="preview_home_hor_content">
                 <action method="setTemplate"><templateType>home_hor</templateType></action>
                 <block type="Mage_XmlConnect_Block_Adminhtml_Mobile_Preview_Tabitems" name="preview_tab_items" as="tab_items">
                     <action method="setActiveTab"><tab>home</tab></action>
                 </block>
             </block>
-        </block>
+        </container>
     </adminhtml_mobile_previewhomehor>
 
     <adminhtml_mobile_previewcataloghor>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_XmlConnect_Block_Adminhtml_Mobile_Preview_Content" name="preview_catalog_hor_content">
                 <action method="setTemplate"><templateType>catalog_hor</templateType></action>
                 <block type="Mage_XmlConnect_Block_Adminhtml_Mobile_Preview_Tabitems" name="preview_tab_items" as="tab_items">
                     <action method="setActiveTab"><tab>shop</tab></action>
                 </block>
             </block>
-        </block>
+        </container>
     </adminhtml_mobile_previewcataloghor>
 
     <adminhtml_mobile_previewcatalog>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_XmlConnect_Block_Adminhtml_Mobile_Preview_Content" name="preview_catalog_content">
                 <action method="setTemplate"><templateType>catalog</templateType></action>
                 <block type="Mage_XmlConnect_Block_Adminhtml_Mobile_Preview_Tabitems" name="preview_tab_items" as="tab_items">
                     <action method="setActiveTab"><tab>shop</tab></action>
                 </block>
             </block>
-        </block>
+        </container>
     </adminhtml_mobile_previewcatalog>
 
     <adminhtml_mobile_previewproductinfo>
-        <block type="Mage_Core_Block_Text_List" name="root" output="toHtml">
+        <container name="root" label="Root" output="1">
             <block type="Mage_XmlConnect_Block_Adminhtml_Mobile_Preview_Content" name="preview_productinfo_content">
                 <action method="setTemplate"><templateType>productinfo</templateType></action>
                 <block type="Mage_XmlConnect_Block_Adminhtml_Mobile_Preview_Tabitems" name="preview_tab_items" as="tab_items">
                     <action method="setActiveTab"><tab>shop</tab></action>
                 </block>
             </block>
-        </block>
+        </container>
     </adminhtml_mobile_previewproductinfo>
 </layout>
diff --git a/app/code/core/Mage/XmlConnect/view/frontend/layout.xml b/app/code/core/Mage/XmlConnect/view/frontend/layout.xml
index 9b7b01284409e712cf1a509b549fce10343d24c7..97168a729026e07700136bf570e93c43431399f8 100644
--- a/app/code/core/Mage/XmlConnect/view/frontend/layout.xml
+++ b/app/code/core/Mage/XmlConnect/view/frontend/layout.xml
@@ -30,19 +30,22 @@
     </default>
 
     <!-- Home -->
-    <xmlconnect_index_index>
-        <block type="Mage_XmlConnect_Block_Home" name="xmlconnect.home" output="toHtml"/>
+    <xmlconnect_index_index translate="label">
+        <label>XML Connect</label>
+        <block type="Mage_XmlConnect_Block_Home" name="xmlconnect.home" output="1"/>
     </xmlconnect_index_index>
 
     <!-- Catalog -->
 
-    <xmlconnect_catalog_filters>
-        <block type="Mage_XmlConnect_Block_Catalog_Filters" name="xmlconnect.catalog.filters" output="toHtml"/>
+    <xmlconnect_catalog_filters translate="label" parent="xmlconnect_catalog_category">
+        <label>XML Connect Catalog Filters</label>
+        <block type="Mage_XmlConnect_Block_Catalog_Filters" name="xmlconnect.catalog.filters" output="1"/>
     </xmlconnect_catalog_filters>
 
     <!-- Category -->
-    <xmlconnect_catalog_category>
-        <block type="Mage_XmlConnect_Block_Catalog_Category" name="xmlconnect.catalog.category" output="toHtml">
+    <xmlconnect_catalog_category translate="label" parent="xmlconnect_index_index">
+        <label>XML Connect Catalog Category</label>
+        <block type="Mage_XmlConnect_Block_Catalog_Category" name="xmlconnect.catalog.category" output="1">
             <block type="Mage_XmlConnect_Block_Catalog_Product_List" name="xmlconnect.catalog.product.list" as="product_list" output="">
                 <block type="Mage_XmlConnect_Block_Catalog_Product_Price" name="xmlconnect.catalog.product.price" as="product_price" output="">
                     <action method="addRenderer"><type>bundle</type><renderer>Mage_XmlConnect_Block_Catalog_Product_Price_Bundle</renderer></action>
@@ -56,8 +59,9 @@
 
     <!-- Product -->
 
-    <xmlconnect_catalog_product>
-        <block type="Mage_XmlConnect_Block_Catalog_Product" name="xmlconnect.catalog.product" output="toHtml">
+    <xmlconnect_catalog_product translate="label" parent="xmlconnect_catalog_category">
+        <label>XML Connect Catalog Product</label>
+        <block type="Mage_XmlConnect_Block_Catalog_Product" name="xmlconnect.catalog.product" output="1">
             <block type="Mage_XmlConnect_Block_Catalog_Product_Related" name="xmlconnect.product.related" as="related_products" output=""/>
 
             <block type="Mage_XmlConnect_Block_Catalog_Product_Price" name="xmlconnect.catalog.product.price" as="product_price" output="">
@@ -78,8 +82,9 @@
         </block>
     </xmlconnect_catalog_product>
 
-    <xmlconnect_catalog_productoptions>
-        <block type="Mage_XmlConnect_Block_Catalog_Product_Options" name="xmlconnect.catalog.product.options" output="toHtml">
+    <xmlconnect_catalog_productoptions translate="label" parent="xmlconnect_catalog_product">
+        <label>XML Connect Catalog Product Options</label>
+        <block type="Mage_XmlConnect_Block_Catalog_Product_Options" name="xmlconnect.catalog.product.options" output="1">
             <action method="addRenderer"><type>simple</type><renderer>Mage_XmlConnect_Block_Catalog_Product_Options_Simple</renderer></action>
             <action method="addRenderer"><type>virtual</type><renderer>Mage_XmlConnect_Block_Catalog_Product_Options_Virtual</renderer></action>
             <action method="addRenderer"><type>configurable</type><renderer>Mage_XmlConnect_Block_Catalog_Product_Options_Configurable</renderer></action>
@@ -89,22 +94,26 @@
         </block>
     </xmlconnect_catalog_productoptions>
 
-    <xmlconnect_catalog_productgallery>
-        <block type="Mage_XmlConnect_Block_Catalog_Product_Gallery" name="xmlconnect.catalog.product.gallery" output="toHtml"/>
+    <xmlconnect_catalog_productgallery translate="label" parent="xmlconnect_catalog_product">
+        <label>XML Connect Catalog Product Gallery</label>
+        <block type="Mage_XmlConnect_Block_Catalog_Product_Gallery" name="xmlconnect.catalog.product.gallery" output="1"/>
     </xmlconnect_catalog_productgallery>
 
-    <xmlconnect_catalog_productreview>
-        <block type="Mage_XmlConnect_Block_Catalog_Product_Review" name="xmlconnect.catalog.product.review" output="toHtml"/>
+    <xmlconnect_catalog_productreview translate="label" parent="xmlconnect_catalog_product">
+        <label>XML Connect Catalog Product Review</label>
+        <block type="Mage_XmlConnect_Block_Catalog_Product_Review" name="xmlconnect.catalog.product.review" output="1"/>
     </xmlconnect_catalog_productreview>
 
-    <xmlconnect_catalog_productreviews>
-        <block type="Mage_XmlConnect_Block_Catalog_Product_Review_List" name="xmlconnect.catalog.product.reviews" output="toHtml"/>
+    <xmlconnect_catalog_productreviews translate="label" parent="xmlconnect_catalog_product">
+        <label>XML Connect Catalog Product Review List</label>
+        <block type="Mage_XmlConnect_Block_Catalog_Product_Review_List" name="xmlconnect.catalog.product.reviews" output="1"/>
     </xmlconnect_catalog_productreviews>
 
     <!-- Search -->
 
-    <xmlconnect_catalog_search>
-        <block type="Mage_XmlConnect_Block_Catalog_Search" name="xmlconnect.catalog.search" output="toHtml">
+    <xmlconnect_catalog_search translate="label" parent="xmlconnect_catalog_category">
+        <label>XML Connect Catalog Search</label>
+        <block type="Mage_XmlConnect_Block_Catalog_Search" name="xmlconnect.catalog.search" output="1">
             <block type="Mage_XmlConnect_Block_Catalog_Product_List" name="xmlconnect.catalog.product.list" as="product_list" output="">
                 <block type="Mage_XmlConnect_Block_Catalog_Product_Price" name="xmlconnect.catalog.product.price" as="product_price" output="">
                     <action method="addRenderer"><type>bundle</type><renderer>Mage_XmlConnect_Block_Catalog_Product_Price_Bundle</renderer></action>
@@ -114,13 +123,15 @@
         </block>
     </xmlconnect_catalog_search>
 
-     <xmlconnect_catalog_searchsuggest>
-        <block type="Mage_XmlConnect_Block_Catalog_Search_Suggest" name="xmlconnect.catalog.search.suggest" output="toHtml"/>
+    <xmlconnect_catalog_searchsuggest translate="label" parent="xmlconnect_catalog_search">
+         <label>XML Connect Catalog Search Suggest</label>
+        <block type="Mage_XmlConnect_Block_Catalog_Search_Suggest" name="xmlconnect.catalog.search.suggest" output="1"/>
     </xmlconnect_catalog_searchsuggest>
 
     <!-- Shopping Cart -->
-    <xmlconnect_cart_index>
-        <block type="Mage_XmlConnect_Block_Cart" name="xmlconnect.cart" output="toHtml">
+    <xmlconnect_cart_index translate="label" parent="xmlconnect_index_index">
+        <label>XML Connect Cart</label>
+        <block type="Mage_XmlConnect_Block_Cart" name="xmlconnect.cart" output="1">
             <action method="addItemRender"><type>simple</type><block>Mage_Checkout_Block_Cart_Item_Renderer</block><template>cart/item/default.phtml</template></action>
             <action method="addItemRender"><type>configurable</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Configurable</block><template>cart/item/default.phtml</template></action>
             <action method="addItemRender"><type>grouped</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Grouped</block><template>cart/item/default.phtml</template></action>
@@ -130,20 +141,23 @@
         </block>
     </xmlconnect_cart_index>
 
-    <xmlconnect_cart_info>
-        <block type="Mage_XmlConnect_Block_Cart_Info" name="xmlconnect.cart.info" as="cart_info" output="toHtml">
+    <xmlconnect_cart_info translate="label" parent="xmlconnect_cart_index">
+        <label>XML Connect Cart Info</label>
+        <block type="Mage_XmlConnect_Block_Cart_Info" name="xmlconnect.cart.info" as="cart_info" output="1">
             <block type="Mage_XmlConnect_Block_Cart_Totals" name="xmlconnect.cart.totals" as="totals"/>
         </block>
     </xmlconnect_cart_info>
 
     <!-- Customer -->
 
-    <xmlconnect_customer_form>
-        <block type="Mage_XmlConnect_Block_Customer_Form" name="xmlconnect.customer.form" output="toHtml"/>
+    <xmlconnect_customer_form translate="label" parent="xmlconnect_index_index">
+        <label>XML Connect Customer Form</label>
+        <block type="Mage_XmlConnect_Block_Customer_Form" name="xmlconnect.customer.form" output="1"/>
     </xmlconnect_customer_form>
 
-    <xmlconnect_wishlist_index>
-        <block type="Mage_XmlConnect_Block_Wishlist" name="xmlconnect.wishlist" output="toHtml">
+    <xmlconnect_wishlist_index translate="label" parent="xmlconnect_index_index">
+        <label>XML Connect Wishlist</label>
+        <block type="Mage_XmlConnect_Block_Wishlist" name="xmlconnect.wishlist" output="1">
             <block type="Mage_XmlConnect_Block_Catalog_Product_Price" name="xmlconnect.catalog.product.price" as="product_price" output="">
                 <action method="addRenderer"><type>bundle</type><renderer>Mage_XmlConnect_Block_Catalog_Product_Price_Bundle</renderer></action>
                 <action method="addRenderer"><type>giftcard</type><renderer>Mage_XmlConnect_Block_Catalog_Product_Price_Giftcard</renderer></action>
@@ -151,20 +165,24 @@
         </block>
     </xmlconnect_wishlist_index>
 
-    <xmlconnect_customer_address>
-        <block type="Mage_XmlConnect_Block_Customer_Address_List" name="xmlconnect.customer.address.list" output="toHtml"/>
+    <xmlconnect_customer_address translate="label" parent="xmlconnect_customer_form">
+        <label>XML Connect Customer Address</label>
+        <block type="Mage_XmlConnect_Block_Customer_Address_List" name="xmlconnect.customer.address.list" output="1"/>
     </xmlconnect_customer_address>
 
-    <xmlconnect_customer_addressform>
-        <block type="Mage_XmlConnect_Block_Customer_Address_Form" name="xmlconnect.customer.address.form" output="toHtml"/>
+    <xmlconnect_customer_addressform translate="label" parent="xmlconnect_customer_address">
+        <label>XML Connect Customer Address Form</label>
+        <block type="Mage_XmlConnect_Block_Customer_Address_Form" name="xmlconnect.customer.address.form" output="1"/>
     </xmlconnect_customer_addressform>
 
-    <xmlconnect_customer_orderlist>
-        <block type="Mage_XmlConnect_Block_Customer_Order_List" name="xmlconnect.customer.order.list" output="toHtml"/>
+    <xmlconnect_customer_orderlist translate="label" parent="xmlconnect_customer_form">
+        <label>XML Connect Customer Order List</label>
+        <block type="Mage_XmlConnect_Block_Customer_Order_List" name="xmlconnect.customer.order.list" output="1"/>
     </xmlconnect_customer_orderlist>
 
-    <xmlconnect_customer_orderdetails>
-        <block type="Mage_XmlConnect_Block_Customer_Order_Details" name="xmlconnect.customer.order.details" output="toHtml">
+    <xmlconnect_customer_orderdetails translate="label" parent="xmlconnect_customer_orderlist">
+        <label>XML Connect Customer Order Details</label>
+        <block type="Mage_XmlConnect_Block_Customer_Order_Details" name="xmlconnect.customer.order.details" output="1">
             <block type="Mage_XmlConnect_Block_Customer_Order_Items" name="xmlconnect.customer.order.items" as="order_items" output="">
                 <action method="addItemRender"><type>default</type><block>Mage_XmlConnect_Block_Customer_Order_Item_Renderer_Default</block><template></template></action>
                 <action method="addItemRender"><type>grouped</type><block>Mage_XmlConnect_Block_Customer_Order_Item_Renderer_Grouped</block><template></template></action>
@@ -179,58 +197,68 @@
         </block>
     </xmlconnect_customer_orderdetails>
 
-    <xmlconnect_customer_storecredit>
-        <block type="Mage_XmlConnect_Block_Customer_Storecredit" name="xmlconnect.customer.storecredit" output="toHtml"/>
+    <xmlconnect_customer_storecredit translate="label" parent="xmlconnect_customer_form">
+        <label>XML Connect Customer Store Credit</label>
+        <block type="Mage_XmlConnect_Block_Customer_Storecredit" name="xmlconnect.customer.storecredit" output="1"/>
     </xmlconnect_customer_storecredit>
 
-    <xmlconnect_customer_giftcardcheck>
-        <block type="Mage_XmlConnect_Block_Customer_GiftcardCheck" name="xmlconnect.customer.giftcardCheck" output="toHtml"/>
+    <xmlconnect_customer_giftcardcheck translate="label" parent="xmlconnect_customer_form">
+        <label>XML Connect Customer Gift Card Check</label>
+        <block type="Mage_XmlConnect_Block_Customer_GiftcardCheck" name="xmlconnect.customer.giftcardCheck" output="1"/>
     </xmlconnect_customer_giftcardcheck>
 
     <!-- Configuration -->
 
-    <xmlconnect_configuration_index>
-        <block type="Mage_XmlConnect_Block_Configuration" name="xmlconnect.configuration" output="toHtml"/>
+    <xmlconnect_configuration_index translate="label" parent="xmlconnect_index_index">
+        <label>XML Connect Configuration</label>
+        <block type="Mage_XmlConnect_Block_Configuration" name="xmlconnect.configuration" output="1"/>
     </xmlconnect_configuration_index>
 
     <!-- Checkout (OnePage) -->
 
-    <xmlconnect_checkout_index>
-        <block type="Mage_XmlConnect_Block_Checkout_Address_Billing" name="xmlconnect.checkout.address.billing" output="toHtml">
+    <xmlconnect_checkout_index translate="label" parent="xmlconnect_cart_index">
+        <label>XML Connect Checkout</label>
+        <block type="Mage_XmlConnect_Block_Checkout_Address_Billing" name="xmlconnect.checkout.address.billing" output="1">
             <block type="Mage_XmlConnect_Block_Customer_Address_List" name="xmlconnect.customer.address.list" as="address_list" output=""/>
         </block>
     </xmlconnect_checkout_index>
 
-    <xmlconnect_checkout_billingaddress>
-        <block type="Mage_XmlConnect_Block_Checkout_Address_Billing" name="xmlconnect.checkout.address.billing" output="toHtml">
+    <xmlconnect_checkout_billingaddress translate="label" parent="xmlconnect_checkout_index">
+        <label>XML Connect Checkout Billing Address</label>
+        <block type="Mage_XmlConnect_Block_Checkout_Address_Billing" name="xmlconnect.checkout.address.billing" output="1">
             <block type="Mage_XmlConnect_Block_Customer_Address_List" name="xmlconnect.customer.address.list" as="address_list" output=""/>
         </block>
     </xmlconnect_checkout_billingaddress>
 
-    <xmlconnect_checkout_newbillingaddressform>
-        <block type="Mage_XmlConnect_Block_Checkout_Address_Form" name="xmlconnect.checkout.new.billing.address.form" output="toHtml">
+    <xmlconnect_checkout_newbillingaddressform translate="label" parent="xmlconnect_checkout_billingaddress">
+        <label>XML Connect Checkout New Billing Address</label>
+        <block type="Mage_XmlConnect_Block_Checkout_Address_Form" name="xmlconnect.checkout.new.billing.address.form" output="1">
             <action method="setType"><type>billing</type></action>
         </block>
     </xmlconnect_checkout_newbillingaddressform>
 
-    <xmlconnect_checkout_shippingaddress>
-        <block type="Mage_XmlConnect_Block_Checkout_Address_Shipping" name="xmlconnect.checkout.address.shipping" output="toHtml">
+    <xmlconnect_checkout_shippingaddress translate="label" parent="xmlconnect_checkout_index">
+        <label>XML Connect Checkout Shipping Address</label>
+        <block type="Mage_XmlConnect_Block_Checkout_Address_Shipping" name="xmlconnect.checkout.address.shipping" output="1">
             <block type="Mage_XmlConnect_Block_Customer_Address_List" name="xmlconnect.customer.address.list" as="address_list" output=""/>
         </block>
     </xmlconnect_checkout_shippingaddress>
 
-    <xmlconnect_checkout_newshippingaddressform>
-        <block type="Mage_XmlConnect_Block_Checkout_Address_Form" name="xmlconnect.checkout.new.billing.address.form" output="toHtml">
+    <xmlconnect_checkout_newshippingaddressform translate="label" parent="xmlconnect_checkout_shippingaddress">
+        <label>XML Connect Checkout New Shipping Address</label>
+        <block type="Mage_XmlConnect_Block_Checkout_Address_Form" name="xmlconnect.checkout.new.billing.address.form" output="1">
             <action method="setType"><type>shipping</type></action>
         </block>
     </xmlconnect_checkout_newshippingaddressform>
 
-    <xmlconnect_checkout_shippingmethods>
-        <block type="Mage_XmlConnect_Block_Checkout_Shipping_Method_Available" name="xmlconnect.checkout.shipping.method.available" output="toHtml"/>
+    <xmlconnect_checkout_shippingmethods translate="label" parent="xmlconnect_checkout_index">
+        <label>XML Connect Checkout Shipping Method List</label>
+        <block type="Mage_XmlConnect_Block_Checkout_Shipping_Method_Available" name="xmlconnect.checkout.shipping.method.available" output="1"/>
     </xmlconnect_checkout_shippingmethods>
 
-    <xmlconnect_checkout_paymentmethods>
-        <block type="Mage_XmlConnect_Block_Checkout_Payment_Method_List" name="xmlconnect.checkout.payment.method.list" output="toHtml">
+    <xmlconnect_checkout_paymentmethods translate="label" parent="xmlconnect_checkout_index">
+        <label>XML Connect Checkout Payment Method List</label>
+        <block type="Mage_XmlConnect_Block_Checkout_Payment_Method_List" name="xmlconnect.checkout.payment.method.list" output="1">
             <block type="Mage_XmlConnect_Block_Checkout_Payment_Method_Ccsave" name="xmlconnect.checkout.method.ccsave" as="payment_ccsave" output=""/>
             <block type="Mage_XmlConnect_Block_Checkout_Payment_Method_Checkmo" name="xmlconnect.checkout.method.checkmo" as="payment_checkmo" output=""/>
             <block type="Mage_XmlConnect_Block_Checkout_Payment_Method_Purchaseorder" name="xmlconnect.checkout.method.purchaseorder" as="payment_purchaseorder" output=""/>
@@ -240,8 +268,9 @@
         </block>
     </xmlconnect_checkout_paymentmethods>
 
-    <xmlconnect_checkout_orderreview>
-        <block type="Mage_XmlConnect_Block_Checkout_Order_Review" name="xmlconnect.checkout.order.review" output="toHtml">
+    <xmlconnect_checkout_orderreview translate="label" parent="xmlconnect_checkout_index">
+        <label>XML Connect Order Review</label>
+        <block type="Mage_XmlConnect_Block_Checkout_Order_Review" name="xmlconnect.checkout.order.review" output="1">
             <block type="Mage_XmlConnect_Block_Checkout_Order_Review_Info" name="xmlconnect.checkout.order.info" as="order_products">
                 <action method="addItemRender"><type>default</type><block>Mage_Checkout_Block_Cart_Item_Renderer</block><template>onepage/review/item.phtml</template></action>
                 <action method="addItemRender"><type>configurable</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Configurable</block><template>onepage/review/item.phtml</template></action>
@@ -257,18 +286,21 @@
 
     <!-- Checkout with PayPal MEP -->
 
-    <xmlconnect_paypal_mep_shippingmethods>
-        <block type="Mage_XmlConnect_Block_Checkout_Shipping_Method_Available" name="xmlconnect.checkout.shipping.method.available" output="toHtml"/>
+    <xmlconnect_paypal_mep_shippingmethods translate="label" parent="xmlconnect_checkout_shippingmethods">
+        <label>XML Connect Paypal MEP Shipping Method List</label>
+        <block type="Mage_XmlConnect_Block_Checkout_Shipping_Method_Available" name="xmlconnect.checkout.shipping.method.available" output="1"/>
     </xmlconnect_paypal_mep_shippingmethods>
 
-    <xmlconnect_paypal_mep_carttotals>
-        <block type="Mage_XmlConnect_Block_Cart_Paypal_Mep_Totals" name="xmlconnect.cart.paypal.mep.totals" output="toHtml"/>
+    <xmlconnect_paypal_mep_carttotals translate="label" parent="xmlconnect_checkout_paymentmethods">
+        <label>XML Connect Paypal MEP Cart Totals</label>
+        <block type="Mage_XmlConnect_Block_Cart_Paypal_Mep_Totals" name="xmlconnect.cart.paypal.mep.totals" output="1"/>
     </xmlconnect_paypal_mep_carttotals>
 
     <!-- Checkout with PayPal MECL -->
 
-    <xmlconnect_paypal_mecl_review>
-        <block type="Mage_XmlConnect_Block_Cart_Paypal_Mecl_Review" name="xmlconnect.cart.paypal.mecl.review" output="toHtml">
+    <xmlconnect_paypal_mecl_review translate="label" parent="xmlconnect_checkout_orderreview">
+        <label>XML Connect Paypal MECL Review</label>
+        <block type="Mage_XmlConnect_Block_Cart_Paypal_Mecl_Review" name="xmlconnect.cart.paypal.mecl.review" output="1">
             <block type="Mage_XmlConnect_Block_Cart_Paypal_Mecl_Details" name="xmlconnect.cart.paypal.mecl.details" as="details">
                 <action method="addItemRender"><type>default</type><block>Mage_XmlConnect_Block_Cart_Item_Renderer</block><template></template></action>
                 <action method="addItemRender"><type>grouped</type><block>Mage_XmlConnect_Block_Cart_Item_Renderer_Grouped</block><template></template></action>
@@ -278,25 +310,29 @@
         </block>
     </xmlconnect_paypal_mecl_review>
 
-    <xmlconnect_paypal_mecl_shippingmethods>
-        <block type="Mage_XmlConnect_Block_Cart_Paypal_Mecl_Shippingmethods" name="xmlconnect.cart.paypal.mecl.shippingmethods" output="toHtml"></block>
+    <xmlconnect_paypal_mecl_shippingmethods translate="label" parent="xmlconnect_checkout_shippingmethods">
+        <label>XML Connect Paypal MECL Shipping Method List</label>
+        <block type="Mage_XmlConnect_Block_Cart_Paypal_Mecl_Shippingmethods" name="xmlconnect.cart.paypal.mecl.shippingmethods" output="1"></block>
     </xmlconnect_paypal_mecl_shippingmethods>
 
     <!-- Cms -->
 
-    <xmlconnect_cms_page>
-        <block type="Mage_XmlConnect_Block_Cms_Page" name="xmlconnect.cms.page" output="toHtml"/>
+    <xmlconnect_cms_page translate="label" parent="xmlconnect_index_index">
+        <label>XML Connect CMS Page</label>
+        <block type="Mage_XmlConnect_Block_Cms_Page" name="xmlconnect.cms.page" output="1"/>
     </xmlconnect_cms_page>
 
     <!-- Payment bridge -->
 
-    <xmlconnect_pbridge_result>
-        <block type="Mage_XmlConnect_Block_Checkout_Pbridge_Result" name="xmlconnect.checkout.pbridge.result" template="pbridge/result.phtml" output="toHtml" />
+    <xmlconnect_pbridge_result translate="label" parent="xmlconnect_checkout_paymentmethods">
+        <label>XML Connect Payment Bridge Result</label>
+        <block type="Mage_XmlConnect_Block_Checkout_Pbridge_Result" name="xmlconnect.checkout.pbridge.result" template="pbridge/result.phtml" output="1" />
     </xmlconnect_pbridge_result>
 
     <!-- Product review -->
 
-    <xmlconnect_review_form>
-        <block type="Mage_XmlConnect_Block_Review_Form" name="xmlconnect.review.form" output="toHtml"/>
+    <xmlconnect_review_form translate="label" parent="xmlconnect_customer_form">
+        <label>XML Connect Review Form</label>
+        <block type="Mage_XmlConnect_Block_Review_Form" name="xmlconnect.review.form" output="1"/>
     </xmlconnect_review_form>
 </layout>
diff --git a/app/design/adminhtml/default/default/skin/default/boxes.css b/app/design/adminhtml/default/default/skin/default/boxes.css
index dbaac45d1bbc21134cb01bbc49cb3faa79ceb04f..2cf33f38b0e1ee9e4a544178ce3cb402edf4dd64 100644
--- a/app/design/adminhtml/default/default/skin/default/boxes.css
+++ b/app/design/adminhtml/default/default/skin/default/boxes.css
@@ -385,14 +385,18 @@ select.multiselect option       { padding:3px 4px; border-bottom:1px solid #ddd;
 
 .columns .form-list             { width:auto; }
 .columns .form-list td.value    { width:280px; padding-right:5px !important; }
+.columns .form-list td.value  { white-space:nowrap; }
+.columns .form-list td.value > * { white-space:normal; }
+.columns .form-list td.value > strong,
+.columns .form-list td.value > button { display:block; }
 .columns .form-list td.value .next-toinput { width:75px; display:inline; margin-right:5px; }
-.columns .form-list td.value .next-toselect input.input-text { width:180px; display:inline; }
+.columns .form-list td.value .next-toselect input.input-text { width:195px!important; display:inline; }
 
 .fieldset-wide .form-list { width:100% !important; }
 .fieldset-wide .form-list td.value { width:auto !important; }
 .fieldset-wide .form-list td.value input.input-text,
 .fieldset-wide .form-list td.value textarea { width:98% !important; }
-.fieldset-wide .form-list td.value select { display:block; }
+/*.fieldset-wide .form-list td.value select { display:block; }*/
 .fieldset-wide .form-list td.scope-label { white-space:nowrap; width:1px; }
 .fieldset-wide .form-list td.note { width:120px; }
 
@@ -406,7 +410,6 @@ span.delete-image,
 span.delete-file                { display:block; white-space:nowrap; padding-left:25px; }
 span.delete-file                { padding:0; }
 
-
 /* Back compatibility with span forms */
 .entry-edit .field-row          { display:block; }
 .entry-edit .field-row label    { float:left; width:150px; }
@@ -482,6 +485,10 @@ button.icon-btn span { text-indent:-999em; display:block; width:16px; padding:0;
 /*.side-col .switcher     { margin-right:20px; margin-bottom:20px; }*/
 .catalog-categories .side-col .switcher { margin-right:0; margin-bottom:15px; }
 .link-storeScope { display:inline-block; vertical-align:middle; margin:0 0 1px; width:16px; height:16px; background:url(images/i_question-mark.png) 0 0 no-repeat; text-decoration:none !important; text-indent:-999em; overflow:hidden; }
+.form-list td.value .link-storeScope { vertical-align:top; margin-top:6px; }
+.storeScope .link-storeScope { float:left; margin-right:10px; }
+.storeScope .tree-storeScope { float:left; padding:7px 10px; border:1px dotted #dedede; }
+.storeScope table.stores-tree { float:left; width:auto !important; }
 
 
 /* SPACE
@@ -1508,4 +1515,5 @@ div.actions:after,
 .notification-global:after,
 .files .row:after,
 .files-wide .row:after,
-.grid tr.filter .range .range-line:after { display:block; clear:both; content:"."; font-size:0; line-height:0; height:0; overflow:hidden; }
+.grid tr.filter .range .range-line:after,
+.storeScope:after { display:block; clear:both; content:"."; font-size:0; line-height:0; height:0; overflow:hidden; }
diff --git a/app/design/adminhtml/default/default/skin/default/iestyles.css b/app/design/adminhtml/default/default/skin/default/iestyles.css
index f530b2a7c24e84c8a14d751321680a4f6112a0d4..95a364ee71531000da1cf0dc12a1cf854533296e 100644
--- a/app/design/adminhtml/default/default/skin/default/iestyles.css
+++ b/app/design/adminhtml/default/default/skin/default/iestyles.css
@@ -59,7 +59,8 @@ ul.tabs li a,
 .grid tr.filter .range .range-line,
 .centinel .authentication,
 .paypal-payment-notice,
-.product-options .options-list li { zoom:1; }
+.product-options .options-list li,
+.storeScope { zoom:1; }
 
 .clear { display:block; clear:both; height:0; font-size:0; line-height:0; overflow:hidden; }
 
diff --git a/app/design/frontend/default/default/skin/blank/css/styles.css b/app/design/frontend/default/default/skin/blank/css/styles.css
index f9aceacee1c3a4bcf20a423bc9f505c5ce9c7cb9..2bbae1714c5961445e6bf1b7ceb0d479302724be 100644
--- a/app/design/frontend/default/default/skin/blank/css/styles.css
+++ b/app/design/frontend/default/default/skin/blank/css/styles.css
@@ -425,6 +425,13 @@ tr.summary-details-excluded { font-style:italic; }
 
 /* Demo Notice */
 .demo-notice { margin:0; padding:6px 10px; background:#d75f07; font-size:12px; line-height:1.15; text-align:center; color:#fff; }
+
+/* Cookie Notice */
+.notice-cookie { border-bottom:1px solid #cfcfcf; background:#ffff90; font-size:12px; line-height:1.25; text-align:center; color:#2f2f2f; }
+.notice-cookie .notice-inner { width:870px; margin:0 auto; padding:12px 0 12px 80px; background:url(../images/i_notice.gif) 20px 25px no-repeat; text-align:left; }
+.notice-cookie .notice-inner p { margin:0 0 10px; border:1px dotted #cccc73; padding:10px; }
+.notice-cookie .notice-inner .actions { }
+
 /* ======================================================================================= */
 
 
diff --git a/app/design/frontend/default/default/skin/blue/css/styles.css b/app/design/frontend/default/default/skin/blue/css/styles.css
index 1297140c97e7dfec35f2cd13706e981d74d79b4e..b89f4ba2418fd0bfac80cb8247b200e24af806f2 100644
--- a/app/design/frontend/default/default/skin/blue/css/styles.css
+++ b/app/design/frontend/default/default/skin/blue/css/styles.css
@@ -187,6 +187,14 @@ input.input-text:focus,select:focus,textarea:focus { background-color:#fafaec; }
 .form-list li.additional-row { border-top:1px solid #ccc; margin-top:10px; padding-top:7px; }
 .form-list li.additional-row .btn-remove { float:right; margin:5px 0 0; }
 .form-list .input-range input.input-text { width:74px; }
+
+.form-list-narrow li  { margin-bottom:0; } 
+.form-list-narrow li .input-box { margin-bottom:6px; } 
+.form-list-narrow li.wide .input-box { width:260px; } 
+.form-list-narrow li.wide input.input-text, 
+.form-list-narrow li.wide textarea { width:254px } 
+.form-list-narrow li.wide select { width:260px; }
+
 /* Customer */
 .form-list .customer-name-prefix .input-box,
 .form-list .customer-name-suffix .input-box,
@@ -440,6 +448,7 @@ std ul,
 .link-print { /*background:url(../images/i_print.gif) 0 2px no-repeat; padding:2px 0 2px 25px;*/ font-weight:bold; color:#dc6809; }
 .link-rss { background:url(../images/i_rss.gif) 0 2px no-repeat; padding-left:18px; line-height:14px; white-space:nowrap; }
 .btn-remove { display:block; width:11px; height:11px; font-size:0; line-height:0; background:url(../images/btn_remove.gif) 0 0 no-repeat; text-indent:-999em; overflow:hidden; }
+.btn-previous  { display:block; width:11px; height:11px; font-size:0; line-height:0; background:url(../images/btn_previous.gif) 0 0 no-repeat; text-indent:-999em; overflow:hidden; }
 .btn-remove2 { display:block; width:16px; height:16px; font-size:0; line-height:0; background:url(../images/btn_trash.gif) 0 0 no-repeat; text-indent:-999em; overflow:hidden; }
 .btn-edit    { display:block; width:11px; height:11px; font-size:0; line-height:0; background:url(../images/btn_edit.gif) 0 0 no-repeat; text-indent:-999em; overflow:hidden; }
 
@@ -450,13 +459,23 @@ std ul,
 
 .divider { clear:both; display:block; font-size:0; line-height:0; height:1px; margin:10px 0; background:url(../images/bkg_divider1.gif) 0 50% repeat-x; text-indent:-999em; overflow:hidden; }
 
+/* Global site notices */
+.global-site-notice { border:1px solid #cfcfcf; border-width:0 0 1px; background:#ffff90; font-size:12px; line-height:1.25; text-align:center; color:#2f2f2f; }
+.global-site-notice .notice-inner { width:860px; margin:0 auto; padding:12px 0 12px 80px; background:url(../images/i_notice.gif) 20px 25px no-repeat; text-align:left; }
+.global-site-notice .notice-inner p { margin:0; border:1px dotted #cccc73; padding:10px; }
+.global-site-notice .notice-inner .actions { padding-top:10px; }
+
+/* Cookie Notice */
+.notice-cookie { }
+
 /* Noscript Notice */
-.noscript { border:1px solid #ddd; border-width:0 0 1px; background:#ffff90; font-size:12px; line-height:1.25; text-align:center; color:#2f2f2f; }
-.noscript .noscript-inner { width:950px; margin:0 auto; padding:12px 0 12px; background:url(../images/i_notice.gif) 20px 50% no-repeat; }
-.noscript p { margin:0; }
+.noscript {}
 
 /* Demo Notice */
-.demo-notice { margin:0; padding:6px 10px; background:#d75f07; font-size:12px; line-height:1.15; text-align:center; color:#fff; }
+.demo-notice { margin:0; padding:6px 10px; background:#d75f07; font-size:12px; line-height:1.15; border:0; text-align:center; color:#fff; }
+.demo-notice .notice-inner { width:auto; padding:0; background:none; text-align:center; }
+.demo-notice .notice-inner p { padding:0; border:0; }
+
 /* ======================================================================================= */
 
 
@@ -618,13 +637,16 @@ std ul,
 .block-layered-nav .block-title { border:0; padding:0; height:24px; background:url(../images/bkg_block-layered-title.gif) 0 0 no-repeat; text-indent:-999em; overflow:hidden; }
 .block-layered-nav .block-subtitle { line-height:1.35; background:#d5e8ff url(../images/bkg_block-layered1.gif) 0 50% repeat; padding:3px 9px; border:1px solid #b9ccdd; border-width:1px 0; text-transform:uppercase; color:#1f5070; }
 .block-layered-nav .block-content { border:1px solid #a0b3c3; background:#e7f1f4; }
-.block-layered-nav dt { background:url(../images/bkg_block-layered-dt.gif) 9px 11px no-repeat; padding:7px 10px 0 28px; font-weight:bold; text-transform:uppercase; }
+.block-layered-nav dt { background:url(../images/bkg_block-layered-dt.gif) 9px 11px no-repeat; padding:7px 10px 0 25px; font-weight:bold; text-transform:uppercase; }
 .block-layered-nav dd { padding:0 12px 12px; background:url(../images/bkg_block-layered-dd.gif) 0 100% repeat-x; }
 .block-layered-nav dd.last { background:none; }
-.block-layered-nav .currently li { background:#fff url(../images/bkg_block-layered-li.gif) 0 100% repeat-x; padding:4px 6px 4px 10px; }
-.block-layered-nav .currently .label { font-weight:bold; padding-left:18px; background:url(../images/bkg_block-layered-label.gif) 0 3px no-repeat; text-transform:uppercase; }
-.block-layered-nav .currently .btn-remove { margin:3px 0 0; }
-.block-layered-nav .actions { font-size:11px; padding:4px 9px; background:#cad6e4; border:1px solid #dee5e8; border-width:1px 0; text-align:right; }
+.block-layered-nav .currently li { background:#fff url(../images/bkg_block-layered-li.gif) 0 100% repeat-x; padding:6px 24px 6px 10px; position:relative; z-index:1; line-height:1.5; }
+.block-layered-nav .currently .label { font-weight:bold; padding-left:15px; background:url(../images/bkg_block-layered-label.gif) 0 4px no-repeat; text-transform:uppercase; display:inline-block; vertical-align:top; }
+.block-layered-nav .currently .value { display:inline-block; vertical-align:top; }
+.block-layered-nav .currently .btn-previous,
+.block-layered-nav .currently .btn-remove { position:absolute; right:4px; top:9px; margin:0; }
+.block-layered-nav .currently .btn-previous { right:17px; }
+.block-layered-nav .actions { font-size:11px; padding:4px 5px 4px 9px; background:#cad6e4; border:1px solid #dee5e8; border-width:1px 0; text-align:right; }
 .block-layered-nav .actions a { float:none; }
 
 /* Block: Cart */
@@ -891,8 +913,9 @@ std ul,
 /********** Product Prices > */
 
 /* Tier Prices */
-.tier-prices { margin:10px 0; padding:10px; background-color:#f4f7f7; border:1px solid #dadddd; }
-.tier-prices li { line-height:1.4; background:url(../images/i_tier.gif) no-repeat 0 3px; padding:2px 0 2px 10px; color:#424242; }
+.product-pricing,
+.tier-prices { margin:10px 0; padding:10px; background-color:#f4f7f7; border:1px solid #dadddd; color:#424242; }
+.tier-prices li { line-height:1.4; background:url(../images/i_tier.gif) no-repeat 0 3px; padding:2px 0 2px 10px; }
 .tier-prices .benefit { font-style:italic; font-weight:bold; color:#2f2f2f; }
 .tier-prices .price { font-weight:bold; color:#2f2f2f; }
 
@@ -1000,8 +1023,9 @@ std ul,
 .product-options p.required { position:absolute; right:20px; top:20px; }
 
 .product-options-bottom { background-color:#fafaec; padding:15px 20px; border:1px solid #e4e4e4; border-top:0; }
-.product-options-bottom .tier-prices { margin:0; padding:0 0 10px; border:0; background:0; }
-.product-options-bottom .tier-prices li { background:0; padding:2px 0; color:#e26703; }
+.product-options-bottom .product-pricing,
+.product-options-bottom .tier-prices { margin:0; padding:0 0 10px; border:0; background:0; color:#e26703; }
+.product-options-bottom .tier-prices li { background:0; padding:2px 0; }
 .product-options-bottom .tier-prices .price,
 .product-options-bottom .tier-prices .benefit { color:#e26703; }
 .product-options-bottom .price-box { float:left; margin:0; padding:0; }
diff --git a/app/design/frontend/default/default/skin/default/css/styles.css b/app/design/frontend/default/default/skin/default/css/styles.css
index 94cc5a16f7d9ba634ee56bdfd51fcc42f1d20e66..08200fda3bdd18c4f6de84dfaff9d6599a17aa14 100644
--- a/app/design/frontend/default/default/skin/default/css/styles.css
+++ b/app/design/frontend/default/default/skin/default/css/styles.css
@@ -188,6 +188,15 @@ input.input-text:focus,select:focus,textarea:focus { background-color:#edf7fd; }
 .form-list li.additional-row { border-top:1px solid #ccc; margin-top:10px; padding-top:7px; }
 .form-list li.additional-row .btn-remove { float:right; margin:5px 0 0; }
 .form-list .input-range input.input-text { width:74px; }
+
+
+.form-list-narrow li  { margin-bottom:0; } 
+.form-list-narrow li .input-box { margin-bottom:6px; }
+.form-list-narrow li.wide .input-box { width:260px; } 
+.form-list-narrow li.wide input.input-text, 
+.form-list-narrow li.wide textarea { width:254px } 
+.form-list-narrow li.wide select { width:260px; }
+
 /* Customer */
 .form-list .customer-name-prefix .input-box,
 .form-list .customer-name-suffix .input-box,
@@ -469,6 +478,7 @@ tr.summary-details-excluded { font-style:italic; }
 .link-print { /*background:url(../images/i_print.gif) 0 2px no-repeat; padding:2px 0 2px 25px;*/ font-weight:bold; color:#dc6809; }
 .link-rss { background:url(../images/i_rss.gif) 0 2px no-repeat; padding-left:18px; line-height:14px; white-space:nowrap; }
 .btn-remove  { display:block; width:11px; height:11px; font-size:0; line-height:0; background:url(../images/btn_remove.gif) 0 0 no-repeat; text-indent:-999em; overflow:hidden; }
+.btn-previous  { display:block; width:11px; height:11px; font-size:0; line-height:0; background:url(../images/btn_previous.gif) 0 0 no-repeat; text-indent:-999em; overflow:hidden; }
 .btn-remove2 { display:block; width:16px; height:16px; font-size:0; line-height:0; background:url(../images/btn_trash.gif) 0 0 no-repeat; text-indent:-999em; overflow:hidden; }
 .btn-edit    { display:block; width:11px; height:11px; font-size:0; line-height:0; background:url(../images/btn_edit.gif) 0 0 no-repeat; text-indent:-999em; overflow:hidden; }
 
@@ -479,13 +489,23 @@ tr.summary-details-excluded { font-style:italic; }
 
 .divider { clear:both; display:block; font-size:0; line-height:0; height:1px; margin:10px 0; background:url(../images/bkg_divider1.gif) 0 50% repeat-x; text-indent:-999em; overflow:hidden; }
 
+/* Global site notices */
+.global-site-notice { border:1px solid #cfcfcf; border-width:0 0 1px; background:#ffff90; font-size:12px; line-height:1.25; text-align:center; color:#2f2f2f; }
+.global-site-notice .notice-inner { width:860px; margin:0 auto; padding:12px 0 12px 80px; background:url(../images/i_notice.gif) 20px 25px no-repeat; text-align:left; }
+.global-site-notice .notice-inner p { margin:0; border:1px dotted #cccc73; padding:10px; }
+.global-site-notice .notice-inner .actions { padding-top:10px; }
+
+/* Cookie Notice */
+.notice-cookie { }
+
 /* Noscript Notice */
-.noscript { border:1px solid #ddd; border-width:0 0 1px; background:#ffff90; font-size:12px; line-height:1.25; text-align:center; color:#2f2f2f; }
-.noscript .noscript-inner { width:950px; margin:0 auto; padding:12px 0 12px; background:url(../images/i_notice.gif) 20px 50% no-repeat; }
-.noscript p { margin:0; }
+.noscript {}
 
 /* Demo Notice */
-.demo-notice { margin:0; padding:6px 10px; background:#d75f07; font-size:12px; line-height:1.15; text-align:center; color:#fff; }
+.demo-notice { margin:0; padding:6px 10px; background:#d75f07; font-size:12px; line-height:1.15; border:0; text-align:center; color:#fff; }
+.demo-notice .notice-inner { width:auto; padding:0; background:none; text-align:center; }
+.demo-notice .notice-inner p { padding:0; border:0; }
+
 /* ======================================================================================= */
 
 
@@ -650,13 +670,16 @@ tr.summary-details-excluded { font-style:italic; }
 .block-layered-nav .block-title { border:0; padding:0; height:24px; background:url(../images/bkg_block-layered-title.gif) 0 0 no-repeat; text-indent:-999em; overflow:hidden; }
 .block-layered-nav .block-subtitle { line-height:1.35; background:#d5e8ff url(../images/bkg_block-layered1.gif) 0 50% repeat; padding:3px 9px; border:1px solid #b9ccdd; border-width:1px 0; text-transform:uppercase; color:#1f5070; }
 .block-layered-nav .block-content { border:1px solid #a0b3c3; background:#e7f1f4; }
-.block-layered-nav dt { background:url(../images/bkg_block-layered-dt.gif) 9px 11px no-repeat; padding:7px 10px 0 28px; font-weight:bold; text-transform:uppercase; }
+.block-layered-nav dt { background:url(../images/bkg_block-layered-dt.gif) 9px 11px no-repeat; padding:7px 10px 0 25px; font-weight:bold; text-transform:uppercase; }
 .block-layered-nav dd { padding:0 12px 12px; background:url(../images/bkg_block-layered-dd.gif) 0 100% repeat-x; }
 .block-layered-nav dd.last { background:none; }
-.block-layered-nav .currently li { background:#fff url(../images/bkg_block-layered-li.gif) 0 100% repeat-x; padding:4px 6px 4px 10px; }
-.block-layered-nav .currently .label { font-weight:bold; padding-left:18px; background:url(../images/bkg_block-layered-label.gif) 0 3px no-repeat; text-transform:uppercase; }
-.block-layered-nav .currently .btn-remove { margin:3px 0 0; }
-.block-layered-nav .actions { font-size:11px; padding:4px 9px; background:#cad6e4; border:1px solid #dee5e8; border-width:1px 0; text-align:right; }
+.block-layered-nav .currently li { background:#fff url(../images/bkg_block-layered-li.gif) 0 100% repeat-x; padding:6px 24px 6px 10px; position:relative; z-index:1; line-height:1.5; }
+.block-layered-nav .currently .label { font-weight:bold; padding-left:15px; background:url(../images/bkg_block-layered-label.gif) 0 4px no-repeat; text-transform:uppercase; display:inline-block; vertical-align:top; }
+.block-layered-nav .currently .value { display:inline-block; vertical-align:top; }
+.block-layered-nav .currently .btn-previous,
+.block-layered-nav .currently .btn-remove { position:absolute; right:4px; top:9px; margin:0; }
+.block-layered-nav .currently .btn-previous { right:17px; }
+.block-layered-nav .actions { font-size:11px; padding:4px 5px 4px 9px; background:#cad6e4; border:1px solid #dee5e8; border-width:1px 0; text-align:right; }
 .block-layered-nav .actions a { float:none; }
 
 /* Block: Cart */
@@ -926,8 +949,9 @@ tr.summary-details-excluded { font-style:italic; }
 /********** Product Prices > */
 
 /* Tier Prices */
-.tier-prices { margin:10px 0; padding:10px; background-color:#f4f7f7; border:1px solid #dadddd; }
-.tier-prices li { line-height:1.4; background:url(../images/i_tier.gif) no-repeat 0 3px; padding:2px 0 2px 10px; color:#424242; }
+.product-pricing,
+.tier-prices { margin:10px 0; padding:10px; background-color:#f4f7f7; border:1px solid #dadddd; color:#424242; }
+.tier-prices li { line-height:1.4; background:url(../images/i_tier.gif) no-repeat 0 3px; padding:2px 0 2px 10px; }
 .tier-prices .benefit { font-style:italic; font-weight:bold; color:#2f2f2f; }
 .tier-prices .price { font-weight:bold; color:#2f2f2f; }
 
@@ -1030,8 +1054,9 @@ tr.summary-details-excluded { font-style:italic; }
 .product-options p.required { position:absolute; right:20px; top:20px; }
 
 .product-options-bottom { background-color:#fffada; padding:15px 20px; border:1px solid #e4e4e4; border-top:0; }
-.product-options-bottom .tier-prices { margin:0; padding:0 0 10px; border:0; background:0; }
-.product-options-bottom .tier-prices li { background:0; padding:2px 0; color:#e26703; }
+.product-options-bottom .product-pricing,
+.product-options-bottom .tier-prices { margin:0; padding:0 0 10px; border:0; background:0; color:#e26703; }
+.product-options-bottom .tier-prices li { background:0; padding:2px 0; }
 .product-options-bottom .tier-prices .price,
 .product-options-bottom .tier-prices .benefit { color:#e26703; }
 .product-options-bottom .price-box { float:left; margin:0; padding:0; }
diff --git a/app/design/frontend/default/default/skin/default/images/btn_previous.gif b/app/design/frontend/default/default/skin/default/images/btn_previous.gif
new file mode 100644
index 0000000000000000000000000000000000000000..90561b6864b1d3880859f6d87a1742a7f11e711f
Binary files /dev/null and b/app/design/frontend/default/default/skin/default/images/btn_previous.gif differ
diff --git a/app/design/frontend/default/default/skin/default/images/logo_email.gif b/app/design/frontend/default/default/skin/default/images/logo_email.gif
deleted file mode 100644
index a4d941679e111f60e1280207683983e9cd0959d9..0000000000000000000000000000000000000000
Binary files a/app/design/frontend/default/default/skin/default/images/logo_email.gif and /dev/null differ
diff --git a/app/design/frontend/default/default/skin/default/locale/de_DE/images/logo_email.gif b/app/design/frontend/default/default/skin/default/locale/de_DE/Mage_Core/logo_email.gif
similarity index 100%
rename from app/design/frontend/default/default/skin/default/locale/de_DE/images/logo_email.gif
rename to app/design/frontend/default/default/skin/default/locale/de_DE/Mage_Core/logo_email.gif
diff --git a/app/design/frontend/default/default/skin/default/locale/fr_FR/images/logo_email.gif b/app/design/frontend/default/default/skin/default/locale/fr_FR/Mage_Core/logo_email.gif
similarity index 100%
rename from app/design/frontend/default/default/skin/default/locale/fr_FR/images/logo_email.gif
rename to app/design/frontend/default/default/skin/default/locale/fr_FR/Mage_Core/logo_email.gif
diff --git a/app/design/frontend/default/iphone/Mage_Catalog/layout.xml b/app/design/frontend/default/iphone/Mage_Catalog/layout.xml
index cd75bba4169af2aa44e8b92189e50195641ff577..0e3182a1f7fcc8122b8ae2a95f179edd23e08cd1 100644
--- a/app/design/frontend/default/iphone/Mage_Catalog/layout.xml
+++ b/app/design/frontend/default/iphone/Mage_Catalog/layout.xml
@@ -44,8 +44,8 @@ Default layout, loads most of the pages
 
     <default>
         <!-- Mage_Catalog -->
-        <reference name="top.menu">
-            <block type="Mage_Catalog_Block_Navigation" name="catalog.topnav" template="navigation/top.phtml"/>
+        <reference name="header">
+            <block type="Mage_Catalog_Block_Product_Compare_Sidebar" name="catalogCompareLink" template="product/compare/sidebar.phtml"/>
         </reference>
         <reference name="left">
             <block type="Mage_Core_Block_Template" name="left.permanent.callout" template="Mage_Page::callouts/left_col.phtml">
@@ -55,7 +55,6 @@ Default layout, loads most of the pages
             </block>
         </reference>
         <reference name="right">
-            <block type="Mage_Catalog_Block_Product_Compare_Sidebar" before="cart_sidebar" name="catalog.compare.sidebar" template="product/compare/sidebar.phtml"/>
             <block type="Mage_Core_Block_Template" name="right.permanent.callout" template="Mage_Page::callouts/right_col.phtml">
                 <action method="setImgSrc"><src>images/media/col_right_callout.jpg</src></action>
                 <action method="setImgAlt" translate="alt" module="Mage_Catalog"><alt>Keep your eyes open for our special Back to School items and save A LOT!</alt></action>
@@ -72,51 +71,11 @@ Default layout, loads most of the pages
 Category default layout
 -->
 
-    <catalog_category_default translate="label">
-        <label>Catalog Category (Non-Anchor)</label>
-        <reference name="left">
-            <block type="Mage_Catalog_Block_Navigation" name="catalog.leftnav" after="currency" template="navigation/left.phtml"/>
-        </reference>
-        <reference name="content">
-            <block type="Mage_Catalog_Block_Category_View" name="category.products" template="category/view.phtml">
-                <block type="Mage_Catalog_Block_Product_List" name="product_list" template="product/list.phtml">
-                    <block type="Mage_Catalog_Block_Product_List_Toolbar" name="product_list_toolbar" template="product/list/toolbar.phtml">
-                        <block type="Mage_Page_Block_Html_Pager" name="product_list_toolbar_pager"/>
-                        <!-- The following code shows how to set your own pager increments -->
-                        <!--
-                            <action method="setDefaultListPerPage"><limit>4</limit></action>
-                            <action method="setDefaultGridPerPage"><limit>9</limit></action>
-                            <action method="addPagerLimit"><mode>list</mode><limit>2</limit></action>
-                            <action method="addPagerLimit"><mode>list</mode><limit>4</limit></action>
-                            <action method="addPagerLimit"><mode>list</mode><limit>6</limit></action>
-                            <action method="addPagerLimit"><mode>list</mode><limit>8</limit></action>
-                            <action method="addPagerLimit" translate="label"><mode>list</mode><limit>all</limit><label>All</label></action>
-                        -->
-                    </block>
-                    <action method="addColumnCountLayoutDepend"><layout>empty</layout><count>6</count></action>
-                    <action method="addColumnCountLayoutDepend"><layout>one_column</layout><count>5</count></action>
-                    <action method="addColumnCountLayoutDepend"><layout>two_columns_left</layout><count>4</count></action>
-                    <action method="addColumnCountLayoutDepend"><layout>two_columns_right</layout><count>4</count></action>
-                    <action method="addColumnCountLayoutDepend"><layout>three_columns</layout><count>3</count></action>
-                    <action method="setToolbarBlockName"><name>product_list_toolbar</name></action>
-                </block>
-            </block>
-        </reference>
-    </catalog_category_default>
-
-<!--
-Category layered navigation layout
--->
-
-    <catalog_category_layered translate="label">
-        <label>Catalog Category (Anchor)</label>
-        <reference name="left">
-            <block type="Mage_Catalog_Block_Layer_View" name="catalog.leftnav" after="currency" template="layer/view.phtml"/>
-        </reference>
+    <catalog_category_view translate="label" type="page" parent="default">
+        <label>Catalog Category</label>
         <reference name="content">
             <block type="Mage_Catalog_Block_Category_View" name="category.products" template="category/view.phtml">
                 <block type="Mage_Catalog_Block_Product_List" name="product_list" template="product/list.phtml">
-                    <!-- <action method="addReviewSummaryTemplate"><type>default</type><template>review/helper/su.phtml</template></action> -->
                     <block type="Mage_Catalog_Block_Product_List_Toolbar" name="product_list_toolbar" template="product/list/toolbar.phtml">
                         <block type="Mage_Page_Block_Html_Pager" name="product_list_toolbar_pager"/>
                         <!-- The following code shows how to set your own pager increments -->
@@ -143,21 +102,43 @@ Category layered navigation layout
                 </block>
             </block>
         </reference>
-    </catalog_category_layered>
+    </catalog_category_view>
 
-    <catalog_category_layered_nochildren translate="label">
-        <label>Catalog Category (Without Subcategories)</label>
+    <catalog_category_view_type_default translate="label" type="page" parent="catalog_category_view">
+        <label>Non Anchor Catalog Category</label>
+        <reference name="left">
+            <block type="Mage_Catalog_Block_Navigation" name="catalog.leftnav" after="currency" template="navigation/left.phtml"/>
+        </reference>
+    </catalog_category_view_type_default>
+
+    <catalog_category_view_type_default_without_children translate="label" type="page" parent="catalog_category_view_type_default">
+        <label>Non Anchor Catalog Category Without Subcategories</label>
         <remove name="right.reports.product.viewed" />
         <reference name="right">
             <block type="Mage_Reports_Block_Product_Viewed" before="right.permanent.callout" name="left.reports.product.viewed" template="product_viewed.phtml" />
         </reference>
-    </catalog_category_layered_nochildren>
+    </catalog_category_view_type_default_without_children>
+
+    <catalog_category_view_type_layered translate="label" type="page" parent="catalog_category_view">
+        <label>Anchor Catalog Category</label>
+        <reference name="left">
+            <block type="Mage_Catalog_Block_Layer_View" name="catalog.leftnav" after="currency" template="layer/view.phtml"/>
+        </reference>
+    </catalog_category_view_type_layered>
+
+    <catalog_category_view_type_layered_without_children>
+        <label>Anchor Catalog Category Without Subcategories</label>
+        <remove name="right.reports.product.viewed" />
+        <reference name="right">
+            <block type="Mage_Reports_Block_Product_Viewed" before="right.permanent.callout" name="left.reports.product.viewed" template="product_viewed.phtml" />
+        </reference>
+    </catalog_category_view_type_layered_without_children>
 
 <!--
 Compare products page
 -->
 
-    <catalog_product_compare_index translate="label">
+    <catalog_product_compare_index translate="label" type="page" parent="default">
         <label>Catalog Product Compare List</label>
         <!-- Mage_Catalog -->
         <reference name="root">
@@ -182,7 +163,7 @@ Compare products page
 Product view
 -->
 
-    <catalog_product_view translate="label">
+    <catalog_product_view translate="label" type="page" parent="default">
         <label>Catalog Product View (Any)</label>
         <!-- Mage_Catalog -->
         <reference name="root">
@@ -204,9 +185,7 @@ Product view
                 <action method="addReviewSummaryTemplate"><type>...</type><template>...</template></action>
                 -->
                 <block type="Mage_Catalog_Block_Product_View_Media" name="product.info.media" as="media" template="product/view/media.phtml"/>
-                <block type="Mage_Core_Block_Text_List" name="alert.urls" as="alert_urls" translate="label">
-                    <label>Alert Urls</label>
-                </block>
+                <container name="alert.urls" as="alert_urls" label="Alert Urls"/>
 
                 <action method="setTierPriceTemplate"><template>catalog/product/view/tierprices.phtml</template></action>
 
@@ -225,9 +204,7 @@ Product view
                 <block type="Mage_Catalog_Block_Product_View" name="product.info.addto" as="addto" template="product/view/addto.phtml"/>
                 <block type="Mage_Catalog_Block_Product_View" name="product.info.addtocart" as="addtocart" template="product/view/addtocart.phtml"/>
 
-                <block type="Mage_Core_Block_Text_List" name="product.info.extrahint" as="extrahint" translate="label">
-                    <label>Product View Extra Hint</label>
-                </block>
+                <container name="product.info.extrahint" as="extrahint" label="Product View Extra Hint"/>
 
                 <block type="Mage_Catalog_Block_Product_View" name="product.info.options.wrapper" as="product_options_wrapper" template="product/view/options/wrapper.phtml" translate="label">
                     <label>Info Column Options Wrapper</label>
@@ -272,57 +249,49 @@ Product view
 <!--
 Additional block dependant on product type
 -->
-    <PRODUCT_TYPE_simple translate="label" module="Mage_Catalog">
+    <catalog_product_view_type_simple translate="label" module="Mage_Catalog" type="page" parent="catalog_product_view">
         <label>Catalog Product View (Simple)</label>
         <reference name="product.info">
             <block type="Mage_Catalog_Block_Product_View_Type_Simple" name="product.info.simple" as="product_type_data" template="product/view/type/default.phtml">
-                <block type="Mage_Core_Block_Text_List" name="product.info.simple.extra" as="product_type_data_extra" translate="label">
-                    <label>Product Extra Info</label>
-                </block>
+                <container name="product.info.simple.extra" as="product_type_data_extra" label="Product Extra Info"/>
             </block>
         </reference>
-    </PRODUCT_TYPE_simple>
-    <PRODUCT_TYPE_configurable translate="label" module="Mage_Catalog">
+    </catalog_product_view_type_simple>
+    <catalog_product_view_type_configurable translate="label" module="Mage_Catalog" type="page" parent="catalog_product_view">
         <label>Catalog Product View (Configurable)</label>
         <reference name="product.info">
             <block type="Mage_Catalog_Block_Product_View_Type_Configurable" name="product.info.configurable" as="product_type_data" template="product/view/type/default.phtml">
-                <block type="Mage_Core_Block_Text_List" name="product.info.configurable.extra" as="product_type_data_extra" translate="label">
-                    <label>Product Extra Info</label>
-                </block>
+                <container name="product.info.configurable.extra" as="product_type_data_extra" label="Product Extra Info"/>
             </block>
         </reference>
         <reference name="product.info.options.wrapper">
             <block type="Mage_Catalog_Block_Product_View_Type_Configurable" name="product.info.options.configurable" as="options_configurable" before="-" template="product/view/type/options/configurable.phtml"/>
         </reference>
-    </PRODUCT_TYPE_configurable>
-    <PRODUCT_TYPE_grouped translate="label" module="Mage_Catalog">
+    </catalog_product_view_type_configurable>
+    <catalog_product_view_type_grouped translate="label" module="Mage_Catalog" type="page" parent="catalog_product_view">
         <label>Catalog Product View (Grouped)</label>
         <reference name="product.info">
             <block type="Mage_Catalog_Block_Product_View_Type_Grouped" name="product.info.grouped" as="product_type_data" template="product/view/type/grouped.phtml">
-                <block type="Mage_Core_Block_Text_List" name="product.info.grouped.extra" as="product_type_data_extra" translate="label">
-                    <label>Product Extra Info</label>
-                </block>
+                <container name="product.info.grouped.extra" as="product_type_data_extra" label="Product Extra Info"/>
             </block>
             <block type="Mage_Catalog_Block_Product_View_Type_Grouped" name="product.info.grouped.grid" as="product_type_data_grid" template="product/view/type/grouped_grid.phtml">
             </block>
         </reference>
-    </PRODUCT_TYPE_grouped>
-    <PRODUCT_TYPE_virtual translate="label" module="Mage_Catalog">
+    </catalog_product_view_type_grouped>
+    <catalog_product_view_type_virtual translate="label" module="Mage_Catalog" type="page" parent="catalog_product_view">
         <label>Catalog Product View (Virtual)</label>
         <reference name="product.info">
             <block type="Mage_Catalog_Block_Product_View_Type_Virtual" name="product.info.virtual" as="product_type_data" template="product/view/type/default.phtml">
-                <block type="Mage_Core_Block_Text_List" name="product.info.virtual.extra" as="product_type_data_extra" translate="label">
-                    <label>Product Extra Info</label>
-                </block>
+                <container name="product.info.virtual.extra" as="product_type_data_extra" label="Product Extra Info"/>
             </block>
         </reference>
-    </PRODUCT_TYPE_virtual>
+    </catalog_product_view_type_virtual>
 
 <!--
 Product additional images gallery popup
 -->
 
-    <catalog_product_gallery translate="label">
+    <catalog_product_gallery translate="label" type="page" parent="catalog_product_view">
         <label>Catalog Product Image Gallery Popup</label>
         <!-- Mage_Catalog -->
         <reference name="root">
@@ -337,7 +306,7 @@ Product additional images gallery popup
 SEO Site Map
 -->
 
-    <catalog_seo_sitemap translate="label">
+    <catalog_seo_sitemap translate="label" type="page" parent="default">
         <label>Catalog Seo Sitemap (Common)</label>
         <remove name="right"/>
         <remove name="left"/>
@@ -354,12 +323,11 @@ SEO Site Map
         </reference>
     </catalog_seo_sitemap>
 
-    <catalog_seo_sitemap_category translate="label">
+    <catalog_seo_sitemap_category translate="label" type="page" parent="catalog_seo_sitemap">
         <label>Catalog Seo Sitemap (Category List)</label>
         <reference name="head">
             <action method="setTitle" translate="title" module="Mage_Catalog"><title>Site Map</title></action>
         </reference>
-        <update handle="catalog_seo_sitemap" />
         <reference name="seo.sitemap.container">
             <action method="setTitle" translate="title" module="Mage_Catalog"><title>Categories</title></action>
             <block type="Mage_Catalog_Block_Seo_Sitemap_Category" name="seo.sitemap.sitemap" as="sitemap" after="pager_top" template="seo/sitemap.phtml">
@@ -373,7 +341,7 @@ SEO Site Map
         </reference>
     </catalog_seo_sitemap_category>
 
-    <catalog_seo_sitemap_category_tree translate="label">
+    <catalog_seo_sitemap_category_type_tree translate="label" type="page" parent="catalog_seo_sitemap_category">
         <label>Catalog Seo Sitemap (Category Tree)</label>
         <reference name="seo.sitemap.container">
             <remove name="seo.sitemap.pager.top" />
@@ -386,9 +354,9 @@ SEO Site Map
                 <action method="bindPager"><pager>seo.sitemap.tree.pager.bottom</pager></action>
             </block>
         </reference>
-    </catalog_seo_sitemap_category_tree>
+    </catalog_seo_sitemap_category_type_tree>
 
-    <catalog_seo_sitemap_product translate="label">
+    <catalog_seo_sitemap_product translate="label" type="page" parent="catalog_seo_sitemap">
         <label>Catalog Seo Sitemap (Product List)</label>
         <reference name="head">
             <action method="setTitle" translate="title" module="Mage_Catalog"><title>Site Map</title></action>
diff --git a/app/design/frontend/default/iphone/Mage_Catalog/product/compare/list.phtml b/app/design/frontend/default/iphone/Mage_Catalog/product/compare/list.phtml
index 9b3f34f051698d1aa2a30ed459741fb903048f0f..3ccd0df9e409dcd8d4b1afa77feac674b262234b 100644
--- a/app/design/frontend/default/iphone/Mage_Catalog/product/compare/list.phtml
+++ b/app/design/frontend/default/iphone/Mage_Catalog/product/compare/list.phtml
@@ -66,7 +66,7 @@ $_imageSize = $this->getVar('product_compare_small_image_size', 'Mage_Catalog');
                     <?php endif; ?>
                     <?php if ($this->helper('Mage_Wishlist_Helper_Data')->isAllow()) : ?>
                         <ul class="add-to-links">
-                            <li><a href="#" class="link-wishlist" onclick="setLocation('<?php echo $this->getAddToWishlistUrl($_item) ?>', true)"><?php echo $this->__('Add to Wishlist') ?></a></li>
+                            <li><a href="<?php echo $this->getAddToWishlistUrl($_item) ?>" class="link-wishlist" onclick="setLocation(this.href, true)"><?php echo $this->__('Add to Wishlist') ?></a></li>
                         </ul>
                     <?php endif; ?>
                 </td>
@@ -119,7 +119,7 @@ $_imageSize = $this->getVar('product_compare_small_image_size', 'Mage_Catalog');
                     <?php endif; ?>
                     <?php if ($this->helper('Mage_Wishlist_Helper_Data')->isAllow()) : ?>
                         <ul class="add-to-links">
-                            <li><a href="#" class="link-wishlist" onclick="setLocation('<?php echo $this->getAddToWishlistUrl($_item) ?>', true)"><?php echo $this->__('Add to Wishlist') ?></a></li>
+                            <li><a href="<?php echo $this->getAddToWishlistUrl($_item) ?>" class="link-wishlist" onclick="setLocation(this.href, true)"><?php echo $this->__('Add to Wishlist') ?></a></li>
                         </ul>
                     <?php endif; ?>
                 </td>
diff --git a/app/design/frontend/default/iphone/Mage_Catalog/product/price.phtml b/app/design/frontend/default/iphone/Mage_Catalog/product/price.phtml
index 8c72c060514f785beef67143c5620d8ce920e49d..8ae3b8ba35a1f386604c2f3877e686cc8a7cb920 100644
--- a/app/design/frontend/default/iphone/Mage_Catalog/product/price.phtml
+++ b/app/design/frontend/default/iphone/Mage_Catalog/product/price.phtml
@@ -61,32 +61,32 @@
     <?php $_finalPrice = $_taxHelper->getPrice($_product, $_product->getFinalPrice()) ?>
     <?php $_finalPriceInclTax = $_taxHelper->getPrice($_product, $_product->getFinalPrice(), true) ?>
     <?php $_weeeDisplayType = $_weeeHelper->getPriceDisplayType(); ?>
-    <?php if ($_finalPrice == $_price): ?>
+    <?php if ($_finalPrice >= $_price): ?>
         <?php if ($_taxHelper->displayBothPrices()): ?>
             <?php if ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($_product, 0)): // including ?>
                 <span class="price-excluding-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Excl. Tax:') ?></span>
                     <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_price+$_weeeTaxAmount,true,false) ?>
+                        <?php echo $_coreHelper->currency($_price + $_weeeTaxAmount, true, false) ?>
                     </span>
                 </span>
                 <span class="price-including-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Incl. Tax:') ?></span>
                     <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPriceInclTax+$_weeeTaxAmount,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false) ?>
                     </span>
                 </span>
             <?php elseif ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($_product, 1)): // incl. + weee ?>
                 <span class="price-excluding-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Excl. Tax:') ?></span>
                     <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_price+$_weeeTaxAmount,true,false) ?>
+                        <?php echo $_coreHelper->currency($_price + $_weeeTaxAmount, true, false) ?>
                     </span>
                 </span>
                 <span class="price-including-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Incl. Tax:') ?></span>
                     <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPriceInclTax+$_weeeTaxAmount,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false) ?>
                     </span>
                     <span class="weee">(
                         <?php foreach ($_weeeTaxAttributes as $_weeeTaxAttribute): ?>
@@ -100,18 +100,18 @@
                 <span class="price-excluding-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Excl. Tax:') ?></span>
                     <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_price+$_weeeTaxAmount,true,false) ?>
+                        <?php echo $_coreHelper->currency($_price + $_weeeTaxAmount, true, false) ?>
                     </span>
                 </span>
                 <span class="price-including-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Incl. Tax:') ?></span>
                     <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPriceInclTax+$_weeeTaxAmount,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false) ?>
                     </span>
                     <span class="weee">(
                         <?php foreach ($_weeeTaxAttributes as $_weeeTaxAttribute): ?>
                             <?php echo $_weeeSeparator; ?>
-                            <?php echo $_weeeTaxAttribute->getName(); ?>: <?php echo $_coreHelper->currency($_weeeTaxAttribute->getAmount()+$_weeeTaxAttribute->getTaxAmount(), true, true); ?>
+                            <?php echo $_weeeTaxAttribute->getName(); ?>: <?php echo $_coreHelper->currency($_weeeTaxAttribute->getAmount() + $_weeeTaxAttribute->getTaxAmount(), true, true); ?>
                             <?php $_weeeSeparator = ' + '; ?>
                         <?php endforeach; ?>
                         )</span>
@@ -120,7 +120,7 @@
                 <span class="price-excluding-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Excl. Tax:') ?></span>
                     <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_price,true,false) ?>
+                        <?php echo $_coreHelper->currency($_price, true, false) ?>
                     </span>
                 </span>
                 <?php foreach ($_weeeTaxAttributes as $_weeeTaxAttribute): ?>
@@ -131,31 +131,36 @@
                 <span class="price-including-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Incl. Tax:') ?></span>
                     <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPriceInclTax+$_weeeTaxAmount,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false) ?>
                     </span>
                 </span>
             <?php else: ?>
                 <span class="price-excluding-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Excl. Tax:') ?></span>
                     <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_price,true,false) ?>
+                        <?php echo $_coreHelper->currency($_price, true, false) ?>
+                        <?php if ($_finalPrice == $_price): ?>
+                            <?php echo $_coreHelper->currency($_price, true, false) ?>
+                        <?php else: ?>
+                            <?php echo $_coreHelper->currency($_finalPrice, true, false) ?>
+                        <?php endif; ?>
                     </span>
                 </span>
                 <span class="price-including-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Incl. Tax:') ?></span>
                     <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPriceInclTax,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPriceInclTax, true, false) ?>
                     </span>
                 </span>
             <?php endif; ?>
         <?php else: ?>
             <?php if ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($_product, 0)): // including ?>
                 <span class="regular-price" id="product-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_price+$_weeeTaxAmount,true,true) ?>
+                    <?php echo $_coreHelper->currency($_price + $_weeeTaxAmount,true,true) ?>
                 </span>
             <?php elseif ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($_product, 1)): // incl. + weee ?>
                 <span class="regular-price" id="product-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_price+$_weeeTaxAmount,true,true) ?>
+                    <?php echo $_coreHelper->currency($_price + $_weeeTaxAmount,true,true) ?>
                 </span>
                 <span class="weee">(
                     <?php foreach ($_weeeTaxAttributes as $_weeeTaxAttribute): ?>
@@ -166,12 +171,12 @@
                     )</span>
             <?php elseif ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($_product, 4)): // incl. + weee ?>
                 <span class="regular-price" id="product-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_price+$_weeeTaxAmount,true,true) ?>
+                    <?php echo $_coreHelper->currency($_price + $_weeeTaxAmount,true,true) ?>
                 </span>
                 <span class="weee">(
                     <?php foreach ($_weeeTaxAttributes as $_weeeTaxAttribute): ?>
                         <?php echo $_weeeSeparator; ?>
-                        <?php echo $_weeeTaxAttribute->getName(); ?>: <?php echo $_coreHelper->currency($_weeeTaxAttribute->getAmount()+$_weeeTaxAttribute->getTaxAmount(), true, true); ?>
+                        <?php echo $_weeeTaxAttribute->getName(); ?>: <?php echo $_coreHelper->currency($_weeeTaxAttribute->getAmount() + $_weeeTaxAttribute->getTaxAmount(), true, true); ?>
                         <?php $_weeeSeparator = ' + '; ?>
                     <?php endforeach; ?>
                     )</span>
@@ -183,7 +188,7 @@
                     </span>
                 <?php endforeach; ?>
                 <span class="regular-price" id="product-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_price+$_weeeTaxAmount,true,true) ?>
+                    <?php echo $_coreHelper->currency($_price + $_weeeTaxAmount,true,true) ?>
                 </span>
             <?php else: ?>
                 <span class="regular-price" id="product-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
@@ -201,13 +206,13 @@
                     <span class="price-excluding-tax">
                         <span class="label"><?php echo $_taxHelper->__('Excl. Tax:') ?></span>
                         <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                            <?php echo $_coreHelper->currency($_finalPrice+$_weeeTaxAmount,true,false) ?>
+                            <?php echo $_coreHelper->currency($_finalPrice + $_weeeTaxAmount, true, false) ?>
                         </span>
                     </span>
                 <span class="price-including-tax">
                     <span class="label"><?php echo $_taxHelper->__('Incl. Tax:') ?></span>
                     <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPriceInclTax+$_weeeTaxAmount,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false) ?>
                     </span>
                 </span>
                 </p>
@@ -215,14 +220,14 @@
             <p class="special-price">
                 <span class="price-label"><?php echo $this->__('Special Price:') ?></span>
                 <span class="price" id="product-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_finalPrice+$_weeeTaxAmount,true,false) ?>
+                    <?php echo $_coreHelper->currency($_finalPrice + $_weeeTaxAmount, true, false) ?>
                 </span>
             </p>
             <?php endif; ?>
             <p class="old-price">
                 <span class="price-label"><?php echo $this->__('Regular Price:') ?></span>
                 <span class="price" id="old-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_regularPrice+$_originalWeeeTaxAmount,true,false) ?>
+                    <?php echo $_coreHelper->currency($_regularPrice + $_originalWeeeTaxAmount, true, false) ?>
                 </span>
             </p>
 
@@ -232,7 +237,7 @@
                 <span class="price-excluding-tax">
                     <span class="label"><?php echo $_taxHelper->__('Excl. Tax:') ?></span>
                     <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPrice+$_weeeTaxAmount,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPrice + $_weeeTaxAmount, true, false) ?>
                     </span>
                 </span>
             <span class="weee">(
@@ -245,14 +250,14 @@
             <span class="price-including-tax">
                 <span class="label"><?php echo $_taxHelper->__('Incl. Tax:') ?></span>
                 <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_finalPriceInclTax+$_weeeTaxAmount,true,false) ?>
+                    <?php echo $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false) ?>
                 </span>
             </span>
             </p>
             <p class="old-price">
                 <span class="price-label"><?php echo $this->__('Regular Price:') ?></span>
                 <span class="price" id="old-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_regularPrice+$_originalWeeeTaxAmount,true,false) ?>
+                    <?php echo $_coreHelper->currency($_regularPrice + $_originalWeeeTaxAmount, true, false) ?>
                 </span>
             </p>
         <?php elseif ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($_product, 4)): // incl. + weee ?>
@@ -261,27 +266,27 @@
                 <span class="price-excluding-tax">
                     <span class="label"><?php echo $_taxHelper->__('Excl. Tax:') ?></span>
                     <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPrice+$_weeeTaxAmount,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPrice + $_weeeTaxAmount, true, false) ?>
                     </span>
                 </span>
             <span class="weee">(
                 <?php foreach ($_weeeTaxAttributes as $_weeeTaxAttribute): ?>
                     <?php echo $_weeeSeparator; ?>
-                    <?php echo $_weeeTaxAttribute->getName(); ?>: <?php echo $_coreHelper->currency($_weeeTaxAttribute->getAmount()+$_weeeTaxAttribute->getTaxAmount(), true, true); ?>
+                    <?php echo $_weeeTaxAttribute->getName(); ?>: <?php echo $_coreHelper->currency($_weeeTaxAttribute->getAmount() + $_weeeTaxAttribute->getTaxAmount(), true, true); ?>
                     <?php $_weeeSeparator = ' + '; ?>
                 <?php endforeach; ?>
                 )</span>
             <span class="price-including-tax">
                 <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Incl. Tax:') ?></span>
                 <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_finalPriceInclTax+$_weeeTaxAmount,true,false) ?>
+                    <?php echo $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false) ?>
                 </span>
             </span>
             </p>
             <p class="old-price">
                 <span class="price-label"><?php echo $this->__('Regular Price:') ?></span>
                 <span class="price" id="old-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_regularPrice+$_originalWeeeTaxAmount,true,false) ?>
+                    <?php echo $_coreHelper->currency($_regularPrice + $_originalWeeeTaxAmount, true, false) ?>
                 </span>
             </p>
         <?php elseif ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($_product, 2)): // excl. + weee + final ?>
@@ -290,7 +295,7 @@
                 <span class="price-excluding-tax">
                     <span class="label"><?php echo $_taxHelper->__('Excl. Tax:') ?></span>
                     <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPrice,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPrice, true, false) ?>
                     </span>
                 </span>
                 <?php foreach ($_weeeTaxAttributes as $_weeeTaxAttribute): ?>
@@ -301,14 +306,14 @@
                 <span class="price-including-tax">
                     <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Incl. Tax:') ?></span>
                     <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                        <?php echo $_coreHelper->currency($_finalPriceInclTax+$_weeeTaxAmount,true,false) ?>
+                        <?php echo $_coreHelper->currency($_finalPriceInclTax + $_weeeTaxAmount, true, false) ?>
                     </span>
                 </span>
             </p>
             <p class="old-price">
                 <span class="price-label"><?php echo $this->__('Regular Price:') ?></span>
                 <span class="price" id="old-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_regularPrice,true,false) ?>
+                    <?php echo $_coreHelper->currency($_regularPrice, true, false) ?>
                 </span>
             </p>
         <?php else: // excl. ?>
@@ -318,13 +323,13 @@
                     <span class="price-excluding-tax">
                         <span class="label"><?php echo $_taxHelper->__('Excl. Tax:') ?></span>
                         <span class="price" id="price-excluding-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                            <?php echo $_coreHelper->currency($_finalPrice,true,false) ?>
+                            <?php echo $_coreHelper->currency($_finalPrice, true, false) ?>
                         </span>
                     </span>
                     <span class="price-including-tax">
                         <span class="label"><?php echo $this->helper('Mage_Tax_Helper_Data')->__('Incl. Tax:') ?></span>
                         <span class="price" id="price-including-tax-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                            <?php echo $_coreHelper->currency($_finalPriceInclTax,true,false) ?>
+                            <?php echo $_coreHelper->currency($_finalPriceInclTax, true, false) ?>
                         </span>
                     </span>
                 </p>
@@ -332,14 +337,14 @@
             <p class="special-price">
                 <span class="price-label"><?php echo $this->__('Special Price:') ?></span>
                 <span class="price" id="product-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_finalPrice,true,false) ?>
+                    <?php echo $_coreHelper->currency($_finalPrice, true, false) ?>
                 </span>
             </p>
             <?php endif; ?>
             <p class="old-price">
                 <span class="price-label"><?php echo $this->__('Regular Price:') ?></span>
                 <span class="price" id="old-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                    <?php echo $_coreHelper->currency($_regularPrice,true,false) ?>
+                    <?php echo $_coreHelper->currency($_regularPrice, true, false) ?>
                 </span>
             </p>
         <?php endif; ?>
@@ -350,7 +355,7 @@
 
         <?php $_minimalPriceDisplayValue = $_minimalPrice; ?>
         <?php if ($_weeeTaxAmount && $_weeeHelper->typeOfDisplay($_product, array(0, 1, 4))): ?>
-            <?php $_minimalPriceDisplayValue = $_minimalPrice+$_weeeTaxAmount; ?>
+            <?php $_minimalPriceDisplayValue = $_minimalPrice + $_weeeTaxAmount; ?>
         <?php endif; ?>
 
         <?php if ($this->getUseLinkForAsLowAs()):?>
@@ -359,7 +364,7 @@
         <?php endif?>
             <span class="label"><?php echo $this->__('As low as:') ?></span>
             <span class="price" id="product-minimal-price-<?php echo $_id ?><?php echo $this->getIdSuffix() ?>">
-                <?php echo $_coreHelper->currency($_minimalPriceDisplayValue,true,false) ?>
+                <?php echo $_coreHelper->currency($_minimalPriceDisplayValue, true, false) ?>
             </span>
         <?php if ($this->getUseLinkForAsLowAs()):?>
         <?php else:?>
diff --git a/app/design/frontend/default/iphone/Mage_Catalog/product/view.phtml b/app/design/frontend/default/iphone/Mage_Catalog/product/view.phtml
index 52fe51a1e336caf329854254ab2ca88e150b60f5..8dcbcc8beaadbd69834a2a425161cb54c39f88cd 100644
--- a/app/design/frontend/default/iphone/Mage_Catalog/product/view.phtml
+++ b/app/design/frontend/default/iphone/Mage_Catalog/product/view.phtml
@@ -83,7 +83,11 @@
                 <?php endif; ?>
             </div>
             <div class="product-collateral">
-                <?php foreach ($this->getChildGroup('detailed_info', 'getChildHtml') as $alias => $html):?>
+                <?php $layout = $this->getLayout(); ?>
+                <?php foreach ($this->getGroupChildNames('detailed_info') as $name):?>
+                        <?php $html = $layout->renderElement($name); ?>
+                        <?php if (!$html) continue; ?>
+                        <?php $alias = $layout->getElementAlias($name); ?>
                         <div class="box-collateral <?php echo "box-{$alias}"?>">
                             <?php if ($title = $this->getChildData($alias, 'title')):?>
                             <h2><?php echo $this->escapeHtml($title); ?></h2>
diff --git a/app/design/frontend/default/iphone/Mage_Catalog/product/view/addto.phtml b/app/design/frontend/default/iphone/Mage_Catalog/product/view/addto.phtml
index 7a29901d5100ec436baafe41ada66d9699a3440f..2dcf75a5c9d4b85c584cb627b2f7ac167b56fc14 100644
--- a/app/design/frontend/default/iphone/Mage_Catalog/product/view/addto.phtml
+++ b/app/design/frontend/default/iphone/Mage_Catalog/product/view/addto.phtml
@@ -29,7 +29,7 @@
 <?php $_wishlistSubmitUrl = $this->helper('Mage_Wishlist_Helper_Data')->getAddUrl($_product); ?>
 <ul class="product-actions">
     <?php if ($this->helper('Mage_Wishlist_Helper_Data')->isAllow()) : ?>
-        <li><a href="<?php echo $_wishlistSubmitUrl ?>" onclick="productAddToCartForm.submitLight(this, '<?php echo $_wishlistSubmitUrl ?>'); return false;" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li>
+        <li><a href="<?php echo $_wishlistSubmitUrl ?>" onclick="productAddToCartForm.submitLight(this, this.href); return false;" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a></li>
     <?php endif; ?>
     <?php
         $_compareUrl = $this->helper('Mage_Catalog_Helper_Product_Compare')->getAddUrl($_product);
diff --git a/app/design/frontend/default/iphone/Mage_Catalog/product/view/addtocart.phtml b/app/design/frontend/default/iphone/Mage_Catalog/product/view/addtocart.phtml
index 86bb545e5aa890b707e1f93cf365444e1dacc128..1895ebe6c236072e553971657b7ddc5db480474e 100644
--- a/app/design/frontend/default/iphone/Mage_Catalog/product/view/addtocart.phtml
+++ b/app/design/frontend/default/iphone/Mage_Catalog/product/view/addtocart.phtml
@@ -33,6 +33,6 @@
         <input type="text" name="qty" id="qty" maxlength="12" value="" placeholder="<?php echo $this->getProductDefaultQty() * 1 ?>" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />
         <?php endif; ?>
         <button type="button" title="<?php echo $buttonTitle ?>" class="button btn-cart" onclick="productAddToCartForm.submit(this)"><span><span><?php echo $buttonTitle ?></span></span></button>
-        <?php echo $this->getChildHtml('', true, true) ?>
+        <?php echo $this->getChildHtml('', true) ?>
     </div>
 <?php endif; ?>
diff --git a/app/design/frontend/default/iphone/Mage_Catalog/product/view/addtowishlist.phtml b/app/design/frontend/default/iphone/Mage_Catalog/product/view/addtowishlist.phtml
index 2761933d8c07d528a566004f9f15e40fae1f5f03..73deee67a485ae812fbbb24ff9b77cbb50ff2ca1 100644
--- a/app/design/frontend/default/iphone/Mage_Catalog/product/view/addtowishlist.phtml
+++ b/app/design/frontend/default/iphone/Mage_Catalog/product/view/addtowishlist.phtml
@@ -28,4 +28,4 @@
 ?>
 <?php $_product = $this->getProduct(); ?>
 <?php $_wishlistSubmitUrl = $this->helper('Mage_Wishlist_Helper_Data')->getAddUrl($_product); ?>
-<a href="<?php echo $_wishlistSubmitUrl ?>" onclick="productAddToCartForm.submitLight(this, '<?php echo $_wishlistSubmitUrl ?>'); return false;" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a>
+<a href="<?php echo $_wishlistSubmitUrl ?>" onclick="productAddToCartForm.submitLight(this, this.href); return false;" class="link-wishlist"><?php echo $this->__('Add to Wishlist') ?></a>
diff --git a/app/design/frontend/default/iphone/Mage_CatalogSearch/layout.xml b/app/design/frontend/default/iphone/Mage_CatalogSearch/layout.xml
index 6e4a0223922d42348cab8dc884cd9c04eab3fd20..0eadd612bfba316627b8da9604cb56e2ba0718f8 100644
--- a/app/design/frontend/default/iphone/Mage_CatalogSearch/layout.xml
+++ b/app/design/frontend/default/iphone/Mage_CatalogSearch/layout.xml
@@ -46,7 +46,7 @@
         </reference>
     </default>
 
-    <catalogsearch_result_index translate="label">
+    <catalogsearch_result_index translate="label" type="page" parent="default">
         <label>Quick Search Form</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -74,7 +74,7 @@
         </reference>
     </catalogsearch_result_index>
 
-    <catalogsearch_advanced_index translate="label">
+    <catalogsearch_advanced_index translate="label" type="page" parent="default">
         <label>Advanced Search Form</label>
         <!-- Mage_Catalogsearch -->
         <reference name="root">
@@ -95,7 +95,7 @@
 Advanced search results
 -->
 
-    <catalogsearch_advanced_result translate="label">
+    <catalogsearch_advanced_result translate="label" type="page" parent="catalogsearch_advanced_index">
         <label>Advanced Search Result</label>
         <update handle="page_two_columns_right" />
         <!-- Mage_Catalogsearch -->
@@ -122,7 +122,7 @@ Advanced search results
         </reference>
     </catalogsearch_advanced_result>
 
-    <catalogsearch_term_popular translate="label">
+    <catalogsearch_term_popular translate="label" type="page" parent="default">
         <label>Popular Search Terms</label>
         <remove name="right"/>
         <remove name="left"/>
@@ -152,4 +152,10 @@ Advanced search results
         </reference>
     </catalogsearch_term_popular>
 
+    <catalogsearch_ajax_suggest translate="label" module="Mage_CatalogSearch" type="page" parent="ajax_index">
+        <label>Catalog Quick Search Form Suggestions</label>
+        <reference name="root">
+            <block type="Mage_CatalogSearch_Block_Autocomplete" name="autocomplete"/>
+        </reference>
+    </catalogsearch_ajax_suggest>
 </layout>
diff --git a/app/design/frontend/default/iphone/Mage_Checkout/cart/item/default.phtml b/app/design/frontend/default/iphone/Mage_Checkout/cart/item/default.phtml
index 1a148553a18b5fdb6339ffc5f21b19d2baf3155a..cf281dfa836a6cddd28119ded8ad4acd5245cf44 100644
--- a/app/design/frontend/default/iphone/Mage_Checkout/cart/item/default.phtml
+++ b/app/design/frontend/default/iphone/Mage_Checkout/cart/item/default.phtml
@@ -27,7 +27,7 @@
 <?php $_item = $this->getItem()?>
 <?php $canApplyMsrp = Mage::helper('Mage_Catalog_Helper_Data')->canApplyMsrp($_item->getProduct(), Mage_Catalog_Model_Product_Attribute_Source_Msrp_Type::TYPE_BEFORE_ORDER_CONFIRM); ?>
 <tr>
-    <td><?php if ($this->hasProductUrl()):?><a href="<?php echo $this->getProductUrl() ?>" title="<?php echo $this->escapeHtml($this->getProductName()) ?>" class="product-image"><?php endif;?><img src="<?php echo $this->getProductThumbnail()->resize(90); ?>" width="45" height="45" alt="<?php echo $this->escapeHtml($this->getProductName()) ?>" /><?php if ($this->hasProductUrl()):?></a><?php endif;?></td>
+    <td><?php if ($this->hasProductUrl()):?><a href="<?php echo $this->getProductUrl() ?>" title="<?php echo $this->escapeHtml($this->getProductName()) ?>" class="product-image"><?php endif;?><img src="<?php echo $this->getProductThumbnailUrl() ?>" width="<?php echo $this->getThumbnailSize()?>" height="<?php echo $this->getThumbnailSize()?>" alt="<?php echo $this->escapeHtml($this->getProductName()) ?>" /><?php if ($this->hasProductUrl()):?></a><?php endif;?></td>
     <td>
         <h2 class="product-name">
         <?php if ($this->hasProductUrl()):?>
@@ -165,7 +165,7 @@
     <td class="a-center item-qty">
         <b><?php echo $this->__('Qty'); ?></b><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" />
     </td>
-    <?php if ($this->helper('Mage_Tax_Helper_Data')->displayCartPriceExclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()): ?>
+    <?php if (($this->helper('Mage_Tax_Helper_Data')->displayCartPriceExclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()) && !$_item->getNoSubtotal()): ?>
     <td class="a-center">
         <?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');">
@@ -210,7 +210,7 @@
         <?php endif; ?>
     </td>
     <?php endif; ?>
-    <?php if ($this->helper('Mage_Tax_Helper_Data')->displayCartPriceInclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()): ?>
+    <?php if (($this->helper('Mage_Tax_Helper_Data')->displayCartPriceInclTax() || $this->helper('Mage_Tax_Helper_Data')->displayCartBothPrices()) && !$_item->getNoSubtotal()): ?>
     <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()): ?>
diff --git a/app/design/frontend/default/iphone/Mage_Checkout/layout.xml b/app/design/frontend/default/iphone/Mage_Checkout/layout.xml
index 2a460daabe763f0676745df3580a5db7cbbe8215..5653bcbdfd0e1639135f9d7c340ea78f85cff13d 100644
--- a/app/design/frontend/default/iphone/Mage_Checkout/layout.xml
+++ b/app/design/frontend/default/iphone/Mage_Checkout/layout.xml
@@ -45,14 +45,40 @@ Default layout, loads most of the pages
                 <action method="addItemRender"><type>simple</type><block>Mage_Checkout_Block_Cart_Item_Renderer</block><template>cart/sidebar/default.phtml</template></action>
                 <action method="addItemRender"><type>grouped</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Grouped</block><template>cart/sidebar/default.phtml</template></action>
                 <action method="addItemRender"><type>configurable</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Configurable</block><template>cart/sidebar/default.phtml</template></action>
-                <block type="Mage_Core_Block_Text_List" name="cart_sidebar.extra_actions" as="extra_actions" translate="label" module="Mage_Checkout">
-                    <label>Shopping Cart Sidebar Extra Actions</label>
-                </block>
+                <container name="cart_sidebar.extra_actions" as="extra_actions" label="Shopping Cart Sidebar Extra Actions" module="Mage_Checkout"/>
+            </block>
+        </reference>
+        <reference name="header">
+            <block type="Mage_Checkout_Block_Cart" name="checkout.cart" as="topCart">
+                <action method="setCartTemplate"><value>cartheader.phtml</value></action>
+                <action method="setEmptyTemplate"><value>cart/no_items_header.phtml</value></action>
+                <action method="chooseTemplate"/>
+                <action method="addItemRender"><type>simple</type><block>Mage_Checkout_Block_Cart_Item_Renderer</block><template>cart/item/default.phtml</template></action>
+                <action method="addItemRender"><type>grouped</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Grouped</block><template>cart/item/default.phtml</template></action>
+                <action method="addItemRender"><type>configurable</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Configurable</block><template>cart/item/default.phtml</template></action>
+                <remove name="checkout.cart.breadcrumbs"/>
+
+                <container name="checkout.cart.top_methods" as="top_methods" label="Payment Methods Before Checkout Button">
+                    <block type="Mage_Checkout_Block_Onepage_Link" name="checkout.cart.methods.onepage" template="onepage/link.phtml"/>
+                </container>
+
+                <container name="checkout.cart.form.before" as="form_before" label="Shopping Cart Form Before" htmlTag="div"/>
+
+                <container name="checkout.cart.methods" as="methods" label="Payment Methods After Checkout Button">
+                    <block type="Mage_Checkout_Block_Onepage_Link" name="checkout.cart.methods.onepage" template="onepage/link.phtml"/>
+                    <block type="Mage_Checkout_Block_Multishipping_Link" name="checkout.cart.methods.multishipping" template="multishipping/link.phtml"/>
+                </container>
+
+                <block type="Mage_Checkout_Block_Cart_Coupon" name="checkout.cart.coupon" as="coupon" template="cart/coupon.phtml"/>
+                <block type="Mage_Checkout_Block_Cart_Shipping" name="checkout.cart.shipping" as="shipping" template="cart/shipping.phtml"/>
+                <block type="Mage_Checkout_Block_Cart_Crosssell" name="checkout.cart.crosssell" as="crosssell" template="cart/crosssell.phtml"/>
+
+                <block type="Mage_Checkout_Block_Cart_Totals" name="checkout.cart.totals" as="totals" template="cart/totals.phtml"/>
             </block>
         </reference>
     </default>
 
-    <checkout_cart_index translate="label">
+    <checkout_cart_index translate="label" type="page" parent="default">
         <label>Shopping Cart</label>
         <remove name="right"/>
         <remove name="left"/>
@@ -69,20 +95,16 @@ Default layout, loads most of the pages
                 <action method="addItemRender"><type>grouped</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Grouped</block><template>cart/item/default.phtml</template></action>
                 <action method="addItemRender"><type>configurable</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Configurable</block><template>cart/item/default.phtml</template></action>
 
-                <block type="Mage_Core_Block_Text_List" name="checkout.cart.top_methods" as="top_methods" translate="label">
-                    <label>Payment Methods Before Checkout Button</label>
+                <container name="checkout.cart.top_methods" as="top_methods" label="Payment Methods Before Checkout Button">
                     <block type="Mage_Checkout_Block_Onepage_Link" name="checkout.cart.methods.onepage" template="onepage/link.phtml"/>
-                </block>
+                </container>
 
-                <block type="Mage_Page_Block_Html_Wrapper" name="checkout.cart.form.before" as="form_before" translate="label">
-                    <label>Shopping Cart Form Before</label>
-                </block>
+                <container name="checkout.cart.form.before" as="form_before" label="Shopping Cart Form Before" htmlTag="div"/>
 
-                <block type="Mage_Core_Block_Text_List" name="checkout.cart.methods" as="methods" translate="label">
-                    <label>Payment Methods After Checkout Button</label>
+                <container name="checkout.cart.methods" as="methods" label="Payment Methods After Checkout Button">
                     <block type="Mage_Checkout_Block_Onepage_Link" name="checkout.cart.methods.onepage" template="onepage/link.phtml"/>
                     <block type="Mage_Checkout_Block_Multishipping_Link" name="checkout.cart.methods.multishipping" template="multishipping/link.phtml"/>
-                </block>
+                </container>
 
                 <block type="Mage_Checkout_Block_Cart_Coupon" name="checkout.cart.coupon" as="coupon" template="cart/coupon.phtml"/>
                 <block type="Mage_Checkout_Block_Cart_Shipping" name="checkout.cart.shipping" as="shipping" template="cart/shipping.phtml"/>
@@ -90,12 +112,10 @@ Default layout, loads most of the pages
                 <block type="Mage_Checkout_Block_Cart_Totals" name="checkout.cart.totals" as="totals" template="cart/totals.phtml"/>
             </block>
         </reference>
-        <block type="Mage_Core_Block_Text_List" name="additional.product.info" translate="label">
-            <label>Additional Product Info</label>
-        </block>
+        <container name="additional.product.info" label="Additional Product Info"/>
     </checkout_cart_index>
 
-    <checkout_cart_configure translate="label">
+    <checkout_cart_configure translate="label" type="page" parent="catalog_product_view">
         <label>Configure Cart Item</label>
         <update handle="catalog_product_view"/>
         <reference name="product.info">
@@ -108,7 +128,7 @@ Multi address shipping checkout main layout,
 will be rendered on all checkout pages
 -->
 
-    <checkout_multishipping translate="label">
+    <checkout_multishipping translate="label" type="page" parent="checkout_cart_index">
         <label>Multishipping Checkout</label>
         <!-- Mage_Checkout -->
         <remove name="right"/>
@@ -122,11 +142,13 @@ will be rendered on all checkout pages
         </reference>
     </checkout_multishipping>
 
-    <checkout_multishipping_login>
+    <checkout_multishipping_login translate="label" type="page" parent="customer_account_login">
+        <label>Multishipping Checkout Login User Form</label>
         <update handle="customer_account_login"/>
     </checkout_multishipping_login>
 
-    <checkout_multishipping_register>
+    <checkout_multishipping_register translate="label" type="page" parent="customer_account_create">
+        <label>Multishipping Checkout Register User Form</label>
         <update handle="customer_account_create"/>
     </checkout_multishipping_register>
 
@@ -134,7 +156,7 @@ will be rendered on all checkout pages
 Multi address shipping checkout selection of address per item page
 -->
 
-    <checkout_multishipping_address_select translate="label">
+    <checkout_multishipping_address_select translate="label" type="page" parent="checkout_multishipping_addresses">
         <label>Multishipping Checkout Shipping Address Selection</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -143,7 +165,7 @@ Multi address shipping checkout selection of address per item page
         </reference>
     </checkout_multishipping_address_select>
 
-    <checkout_multishipping_address_selectbilling translate="label">
+    <checkout_multishipping_address_selectbilling translate="label" type="page" parent="checkout_multishipping_address_select">
         <label>Multishipping Checkout Billing Address Selection</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -153,36 +175,37 @@ Multi address shipping checkout selection of address per item page
     </checkout_multishipping_address_selectbilling>
 
 
-    <checkout_multishipping_address_newshipping translate="label">
+    <checkout_multishipping_address_newshipping translate="label" type="page" parent="checkout_multishipping_shipping">
         <label>Multishipping Checkout Shipping Address Creation</label>
         <update handle="checkout_multishipping"/>
         <update handle="checkout_multishipping_customer_address"/>
     </checkout_multishipping_address_newshipping>
 
-    <checkout_multishipping_address_newbilling translate="label">
+    <checkout_multishipping_address_newbilling translate="label" type="page" parent="checkout_multishipping_billing">
         <label>Multishipping Checkout Billing Address Creation</label>
         <update handle="checkout_multishipping"/>
         <update handle="checkout_multishipping_customer_address"/>
     </checkout_multishipping_address_newbilling>
 
-    <checkout_multishipping_address_editshipping translate="label">
+    <checkout_multishipping_address_editshipping translate="label" type="page" parent="checkout_multishipping_shipping">
         <label>Multishipping Checkout Shipping Address Edit Form</label>
         <update handle="checkout_multishipping"/>
         <update handle="checkout_multishipping_customer_address"/>
     </checkout_multishipping_address_editshipping>
 
-    <checkout_multishipping_address_editaddress>
+    <checkout_multishipping_address_editaddress translate="label" type="page" parent="checkout_multishipping_customer_address">
+        <label>Multishipping Checkout One Address Edit Form</label>
         <update handle="checkout_multishipping"/>
         <update handle="checkout_multishipping_customer_address"/>
     </checkout_multishipping_address_editaddress>
 
-    <checkout_multishipping_address_editbilling translate="label">
+    <checkout_multishipping_address_editbilling translate="label" type="page" parent="checkout_multishipping_billing">
         <label>Multishipping Checkout Billing Address Edit Form</label>
         <update handle="checkout_multishipping"/>
         <update handle="checkout_multishipping_customer_address"/>
     </checkout_multishipping_address_editbilling>
 
-    <checkout_multishipping_customer_address translate="label">
+    <checkout_multishipping_customer_address translate="label" type="page" parent="customer_address_form">
         <label>Multishipping Checkout Customer Address Edit Form</label>
         <reference name="content">
             <block type="Mage_Customer_Block_Address_Edit" name="customer_address_edit" template="address/edit.phtml"/>
@@ -193,7 +216,7 @@ Multi address shipping checkout selection of address per item page
 Multi address shipping checkout address page
 -->
 
-    <checkout_multishipping_addresses translate="label">
+    <checkout_multishipping_addresses translate="label" type="page" parent="checkout_multishipping">
         <label>Multishipping Checkout Address (Any) Form</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -210,7 +233,7 @@ Multi address shipping checkout address page
 Multi address shipping checkout shipping information
 -->
 
-    <checkout_multishipping_shipping translate="label">
+    <checkout_multishipping_shipping translate="label" type="page" parent="checkout_multishipping">
         <label>Multishipping Checkout Shipping Information Step</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -233,7 +256,7 @@ Multi address shipping checkout shipping information
 Multi address shipping checkout billing information
 -->
 
-    <checkout_multishipping_billing translate="label">
+    <checkout_multishipping_billing translate="label" type="page" parent="checkout_multishipping">
         <label>Multishipping Checkout Billing Information Step</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -255,7 +278,7 @@ Multi address shipping checkout billing information
 Multi address shipping checkout overview
 -->
 
-    <checkout_multishipping_overview translate="label">
+    <checkout_multishipping_overview translate="label" type="page" parent="checkout_multishipping">
         <label>Multishipping Checkout Overview</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -271,9 +294,7 @@ Multi address shipping checkout overview
                 </block>
                 <block type="Mage_Checkout_Block_Agreements" name="checkout.multishipping.agreements" as="agreements" template="multishipping/agreements.phtml"/>
                 <block type="Mage_Checkout_Block_Cart_Totals" name="totals" />
-                <block type="Mage_Core_Block_Text_List" name="checkout.multishipping.overview.items.after" as="items_after" translate="label">
-                    <label>Overview Items After</label>
-                </block>
+                <container name="checkout.multishipping.overview.items.after" as="items_after" label="Overview Items After"/>
             </block>
         </reference>
     </checkout_multishipping_overview>
@@ -282,7 +303,7 @@ Multi address shipping checkout overview
 Multi address shipping checkout success
 -->
 
-    <checkout_multishipping_success translate="label">
+    <checkout_multishipping_success translate="label" type="page" parent="checkout_multishipping">
         <label>Multishipping Checkout Success</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -295,7 +316,7 @@ Multi address shipping checkout success
 One page checkout main layout
 -->
 
-    <checkout_onepage_index translate="label">
+    <checkout_onepage_index translate="label" type="page" parent="checkout_cart_index">
         <label>One Page Checkout</label>
         <!-- Mage_Checkout -->
         <remove name="left"/>
@@ -305,19 +326,14 @@ One page checkout main layout
         </reference>
         <reference name="right">
             <action method="unsetChildren"></action>
-            <block type="Mage_Page_Block_Html_Wrapper" name="checkout.progress.wrapper" translate="label">
-                <label>Checkout Progress Wrapper</label>
-                <action method="setElementId"><value>checkout-progress-wrapper</value></action>
+            <container name="checkout.progress.wrapper" label="Checkout Progress Wrapper" htmlTag="div" htmlId="checkout-progress-wrapper">
                 <block type="Mage_Checkout_Block_Onepage_Progress" name="checkout.progress" before="-" template="onepage/progress.phtml"/>
-            </block>
+            </container>
         </reference>
         <reference name="content">
             <block type="Mage_Checkout_Block_Onepage" name="checkout.onepage" template="onepage.phtml">
                 <block type="Mage_Checkout_Block_Onepage_Login" name="checkout.onepage.login" as="login" template="onepage/login.phtml">
-                    <block type="Mage_Page_Block_Html_Wrapper" name="checkout.onepage.login.before" as="login_before" translate="label">
-                        <label>Login/Registration Before</label>
-                        <action method="setMayBeInvisible"><value>1</value></action>
-                    </block>
+                    <container name="checkout.onepage.login.before" as="login_before" label="Login/Registration Before" htmlTag="div"/>
                 </block>
                 <block type="Mage_Checkout_Block_Onepage_Billing" name="checkout.onepage.billing" as="billing" template="onepage/billing.phtml"/>
                 <block type="Mage_Checkout_Block_Onepage_Shipping" name="checkout.onepage.shipping" as="shipping" template="onepage/shipping.phtml"/>
@@ -339,28 +355,27 @@ One page checkout main layout
 One page checkout progress block
 -->
 
-    <checkout_onepage_progress>
-        <!-- Mage_Checkout -->
-        <remove name="right"/>
-        <remove name="left"/>
-
-        <block type="Mage_Checkout_Block_Onepage_Progress" name="root" output="toHtml" template="onepage/progress.phtml">
-            <block type="Mage_Checkout_Block_Onepage_Payment_Info" name="payment_info">
-                <action method="setInfoTemplate"><method></method><template></template></action>
+    <checkout_onepage_progress translate="label" type="page" parent="ajax_index">
+        <label>One Page Checkout Progress</label>
+        <reference name="root">
+            <block type="Mage_Checkout_Block_Onepage_Progress" name="process" template="onepage/progress.phtml">
+                <block type="Mage_Checkout_Block_Onepage_Payment_Info" name="payment_info">
+                    <action method="setInfoTemplate"><method></method><template></template></action>
+                </block>
             </block>
-        </block>
+        </reference>
     </checkout_onepage_progress>
 
 <!--
 One page checkout payment methods block
 -->
-    <checkout_onepage_paymentmethod>
-        <remove name="right"/>
-        <remove name="left"/>
-
-        <block type="Mage_Checkout_Block_Onepage_Payment_Methods" name="root" output="toHtml" template="onepage/payment/methods.phtml">
-            <action method="setMethodFormTemplate"><method>purchaseorder</method><template>payment/form/purchaseorder.phtml</template></action>
-        </block>
+    <checkout_onepage_paymentmethod translate="label" type="page" parent="ajax_index">
+        <label>One Page Checkout Choose Payment Method</label>
+        <reference name="root">
+            <block type="Mage_Checkout_Block_Onepage_Payment_Methods" name="payment_method" template="onepage/payment/methods.phtml">
+                <action method="setMethodFormTemplate"><method>purchaseorder</method><template>payment/form/purchaseorder.phtml</template></action>
+            </block>
+        </reference>
     </checkout_onepage_paymentmethod>
 
 
@@ -368,51 +383,43 @@ One page checkout payment methods block
 One page checkout shipping methods block
 -->
 
-    <checkout_onepage_shippingmethod>
-        <!-- Mage_Checkout -->
-        <remove name="right"/>
-        <remove name="left"/>
-
-        <block type="Mage_Checkout_Block_Onepage_Shipping_Method_Available" name="root" output="toHtml" template="onepage/shipping_method/available.phtml"/>
+    <checkout_onepage_shippingmethod translate="label" type="page" parent="ajax_index">
+        <label>One Page Checkout Choose Shipping Method</label>
+        <reference name="root">
+            <block type="Mage_Checkout_Block_Onepage_Shipping_Method_Available" name="shipping_method" template="onepage/shipping_method/available.phtml"/>
+        </reference>
     </checkout_onepage_shippingmethod>
 
-    <checkout_onepage_additional>
-        <!-- Mage_Checkout -->
-        <remove name="right"/>
-        <remove name="left"/>
-
-        <block type="Mage_Checkout_Block_Onepage_Shipping_Method_Additional" name="root" output="toHtml" template="onepage/shipping_method/additional.phtml">
-            <action method="setDontDisplayContainer"><param>1</param></action>
-        </block>
+    <checkout_onepage_additional translate="label" type="page" parent="ajax_index">
+        <label>One Page Checkout Additional Address Form</label>
+        <reference name="root">
+            <block type="Mage_Checkout_Block_Onepage_Shipping_Method_Additional" name="shipping_method_additional" template="onepage/shipping_method/additional.phtml">
+                <action method="setDontDisplayContainer"><param>1</param></action>
+            </block>
+        </reference>
     </checkout_onepage_additional>
 
 <!--
 One page checkout order review block
 -->
 
-    <checkout_onepage_review translate="label">
+    <checkout_onepage_review translate="label" type="page" parent="ajax_index">
         <label>One Page Checkout Overview</label>
-        <!-- Mage_Checkout -->
-        <remove name="right"/>
-        <remove name="left"/>
-
-        <block type="Mage_Checkout_Block_Onepage_Review_Info" name="root" output="toHtml" template="onepage/review/info.phtml">
-            <action method="addItemRender"><type>default</type><block>Mage_Checkout_Block_Cart_Item_Renderer</block><template>onepage/review/item.phtml</template></action>
-            <action method="addItemRender"><type>grouped</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Grouped</block><template>onepage/review/item.phtml</template></action>
-            <action method="addItemRender"><type>configurable</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Configurable</block><template>onepage/review/item.phtml</template></action>
-            <block type="Mage_Checkout_Block_Cart_Totals" name="checkout.onepage.review.info.totals" as="totals" template="onepage/review/totals.phtml"/>
-            <block type="Mage_Core_Block_Text_List" name="checkout.onepage.review.info.items.before" as="items_before" translate="label">
-                <label>Items Before</label>
-            </block>
-            <block type="Mage_Core_Block_Text_List" name="checkout.onepage.review.info.items.after" as="items_after" translate="label">
-                <label>Items After</label>
+        <reference name="root">
+            <block type="Mage_Checkout_Block_Onepage_Review_Info" name="order_review" template="onepage/review/info.phtml">
+                <action method="addItemRender"><type>default</type><block>Mage_Checkout_Block_Cart_Item_Renderer</block><template>onepage/review/item.phtml</template></action>
+                <action method="addItemRender"><type>grouped</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Grouped</block><template>onepage/review/item.phtml</template></action>
+                <action method="addItemRender"><type>configurable</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Configurable</block><template>onepage/review/item.phtml</template></action>
+                <block type="Mage_Checkout_Block_Cart_Totals" name="checkout.onepage.review.info.totals" as="totals" template="onepage/review/totals.phtml"/>
+                <container name="checkout.onepage.review.info.items.before" as="items_before" label="Items Before"/>
+                <container name="checkout.onepage.review.info.items.after" as="items_after" label="Items After"/>
+                <block type="Mage_Checkout_Block_Agreements" name="checkout.onepage.agreements" as="agreements" template="onepage/agreements.phtml"/>
+                <block type="Mage_Core_Block_Template" name="checkout.onepage.review.button" as="button" template="Mage_Checkout::onepage/review/button.phtml"/>
             </block>
-            <block type="Mage_Checkout_Block_Agreements" name="checkout.onepage.agreements" as="agreements" template="onepage/agreements.phtml"/>
-            <block type="Mage_Core_Block_Template" name="checkout.onepage.review.button" as="button" template="Mage_Checkout::onepage/review/button.phtml"/>
-        </block>
+        </reference>
     </checkout_onepage_review>
 
-    <checkout_onepage_success translate="label">
+    <checkout_onepage_success translate="label" type="page" parent="checkout_onepage_index">
         <label>One Page Checkout Success</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -421,7 +428,7 @@ One page checkout order review block
             <block type="Mage_Checkout_Block_Onepage_Success" name="checkout.success" template="success.phtml"/>
         </reference>
     </checkout_onepage_success>
-    <checkout_onepage_failure translate="label">
+    <checkout_onepage_failure translate="label" type="page" parent="checkout_onepage_index">
         <label>One Page Checkout Failure</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-right.phtml</template></action>
diff --git a/app/design/frontend/default/iphone/Mage_Cms/layout.xml b/app/design/frontend/default/iphone/Mage_Cms/layout.xml
index 924ccff79ea7f5003e093347a93e56bc84ee12e1..550835c455f794e3bf023c810b4f4b99e1ef929c 100644
--- a/app/design/frontend/default/iphone/Mage_Cms/layout.xml
+++ b/app/design/frontend/default/iphone/Mage_Cms/layout.xml
@@ -42,20 +42,18 @@ Default layout, loads most of the pages
         </reference>
     </default>
 
-    <cms_page translate="label">
+    <cms_page_view translate="label" type="page" parent="default">
         <label>CMS Pages (All)</label>
         <reference name="content">
             <block type="Mage_Core_Block_Template" name="page_content_heading" template="Mage_Cms::content_heading.phtml"/>
             <block type="Mage_Catalog_Block_Navigation" name="hp_nav" template="navigation/top.phtml" />
-            <block type="Mage_Page_Block_Html_Wrapper" name="cms.wrapper" translate="label">
-                <label>CMS Content Wrapper</label>
-                <action method="setElementClass"><value>std</value></action>
+            <container name="cms.wrapper" label="CMS Content Wrapper" htmlTag="div" htmlClass="std">
                 <block type="Mage_Cms_Block_Page" name="cms_page"/>
-            </block>
+            </container>
         </reference>
-    </cms_page>
+    </cms_page_view>
 
-    <cms_index_index translate="label">
+    <cms_index_index translate="label" type="page" parent="cms_page_view">
         <label>CMS Home Page</label>
         <reference name="content">
             <block type="Mage_Catalog_Block_Navigation" name="hp_nav" template="navigation/top.phtml" />
@@ -63,7 +61,8 @@ Default layout, loads most of the pages
         <remove name="cms.wrapper"/>
     </cms_index_index>
 
-    <cms_index_defaultindex>
+    <cms_index_defaultindex translate="label" type="page" parent="cms_page_view">
+        <label>CMS Home Default Page</label>
         <remove name="right"/>
         <remove name="left"/>
 
@@ -76,11 +75,12 @@ Default layout, loads most of the pages
         </reference>
     </cms_index_defaultindex>
 
-    <cms_index_noroute translate="label">
+    <cms_index_noroute translate="label" type="page" parent="cms_page_view">
         <label>CMS No-Route Page</label>
     </cms_index_noroute>
 
-    <cms_index_defaultnoroute>
+    <cms_index_defaultnoroute translate="label" type="page" parent="cms_page_view">
+        <label>CMS No-Route Default Page</label>
         <remove name="right"/>
         <remove name="left"/>
 
diff --git a/app/design/frontend/default/iphone/Mage_Contacts/layout.xml b/app/design/frontend/default/iphone/Mage_Contacts/layout.xml
index 18e811c5137b269688dd90130ed861d9b16024b8..275055cdcebb4d04612d9e0b2ac77a52b729cfb9 100644
--- a/app/design/frontend/default/iphone/Mage_Contacts/layout.xml
+++ b/app/design/frontend/default/iphone/Mage_Contacts/layout.xml
@@ -32,7 +32,7 @@
         </reference>
     </default>
 
-    <contacts_index_index translate="label">
+    <contacts_index_index translate="label" type="page" parent="default">
         <label>Contact Us Form</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
diff --git a/app/design/frontend/default/iphone/Mage_Customer/layout.xml b/app/design/frontend/default/iphone/Mage_Customer/layout.xml
index 73366b4c43ce70c29089d79a12d7a0de936a4002..295cc850fc34e3bc0a93a56011f0df7af41b68c7 100644
--- a/app/design/frontend/default/iphone/Mage_Customer/layout.xml
+++ b/app/design/frontend/default/iphone/Mage_Customer/layout.xml
@@ -47,41 +47,20 @@ Default layout, loads most of the pages
 -->
 
     <default>
-        <!-- Mage_Customer -->
         <reference name="top.links">
-            <action method="addLink" translate="label title" module="Mage_Customer"><label>My Account</label><url helper="Mage_Customer_Helper_Data::getAccountUrl"/><title>My Account</title><prepare/><urlParams/><position>10</position></action>
+            <block type="Mage_Customer_Block_Account_Link" name="account_links">
+                <action method="addAccountLink"><target>top.links</target><position>10</position></action>
+                <action method="addAuthLink"><target>top.links</target><position>100</position></action>
+            </block>
         </reference>
     </default>
 
-<!--
-Load this update on every page when customer is logged in
--->
-
-    <customer_logged_in>
-        <reference name="top.links">
-            <action method="addLink" translate="label title" module="Mage_Customer"><label>Log Out</label><url helper="Mage_Customer_Helper_Data::getLogoutUrl"/><title>Log Out</title><prepare/><urlParams/><position>100</position></action>
-        </reference>
-    </customer_logged_in>
-
-<!--
-Load this update on every page when customer is logged out
--->
-
-    <customer_logged_out>
-        <!---<reference name="right">
-            <block type="Mage_Customer_Block_Form_Login" name="customer_form_mini_login" before="-" template="customer/form/mini.login.phtml"/>
-        </reference>-->
-        <reference name="top.links">
-            <action method="addLink" translate="label title" module="Mage_Customer"><label>Log In</label><url helper="Mage_Customer_Helper_Data::getLoginUrl"/><title>Log In</title><prepare/><urlParams/><position>100</position></action>
-        </reference>
-        <remove name="reorder"></remove>
-    </customer_logged_out>
 
 <!--
 Layout for customer login page
 -->
 
-    <customer_account_login translate="label">
+    <customer_account_login translate="label" type="page" parent="customer_account">
         <label>Customer Account Login Form</label>
         <!-- Mage_Customer -->
         <remove name="right"/>
@@ -99,7 +78,7 @@ Layout for customer login page
 Layout for customer log out page
 -->
 
-    <customer_account_logoutsuccess translate="label">
+    <customer_account_logoutsuccess translate="label" type="page" parent="customer_account">
         <label>Customer Account Logout Success</label>
         <!-- Mage_Customer -->
         <remove name="right"/>
@@ -117,7 +96,7 @@ Layout for customer log out page
 New customer registration
 -->
 
-    <customer_account_create translate="label">
+    <customer_account_create translate="label" type="page" parent="customer_account">
         <label>Customer Account Registration Form</label>
         <!-- Mage_Customer -->
         <remove name="right"/>
@@ -128,14 +107,12 @@ New customer registration
         </reference>
         <reference name="content">
             <block type="Mage_Customer_Block_Form_Register" name="customer_form_register" template="form/register.phtml">
-                <block type="Mage_Page_Block_Html_Wrapper" name="customer.form.register.fields.before" as="form_fields_before" translate="label">
-                    <label>Form Fields Before</label>
-                </block>
+                <container name="customer.form.register.fields.before" as="form_fields_before" label="Form Fields Before" htmlTag="div"/>
             </block>
         </reference>
     </customer_account_create>
 
-    <customer_account_forgotpassword translate="label">
+    <customer_account_forgotpassword translate="label" type="page" parent="customer_account">
         <label>Customer Forgot Password Form</label>
         <remove name="right"/>
         <remove name="left"/>
@@ -149,7 +126,8 @@ New customer registration
         </reference>
     </customer_account_forgotpassword>
 
-    <customer_account_confirmation>
+    <customer_account_confirmation translate="label" type="page" parent="customer_account">
+        <label>Customer Account Confirmation</label>
         <remove name="right"/>
         <remove name="left"/>
 
@@ -162,7 +140,7 @@ New customer registration
         </reference>
     </customer_account_confirmation>
 
-    <customer_account_edit translate="label">
+    <customer_account_edit translate="label" type="page" parent="customer_account">
         <label>Customer Account Edit Form</label>
         <update handle="customer_account"/>
         <reference name="root">
@@ -181,7 +159,7 @@ New customer registration
 Customer account pages, rendered for all tabs in dashboard
 -->
 
-    <customer_account translate="label">
+    <customer_account translate="label" type="page" parent="default">
         <label>Customer My Account (All Pages)</label>
         <!--remove name="catalog.compare.sidebar"/>
         <remove name="sale.reorder.sidebar"/-->
@@ -191,10 +169,7 @@ Customer account pages, rendered for all tabs in dashboard
         </reference>
 
         <reference name="content">
-            <block type="Mage_Page_Block_Html_Wrapper" name="my.account.wrapper" translate="label">
-                <label>My Account Wrapper</label>
-                <action method="setElementClass"><value>my-account</value></action>
-            </block>
+            <container name="my.account.wrapper" label="My Account Wrapper" htmlTag="div" htmlClass="my-account"/>
         </reference>
 
         <reference name="left">
@@ -218,7 +193,7 @@ Customer account pages, rendered for all tabs in dashboard
 Customer account home dashboard layout
 -->
 
-    <customer_account_index translate="label">
+    <customer_account_index translate="label" type="page" parent="customer_account">
         <label>Customer My Account Dashboard</label>
         <update handle="customer_account"/>
         <!-- Mage_Customer -->
@@ -241,7 +216,7 @@ Customer account home dashboard layout
 Customer account address book
 -->
 
-    <customer_address_index translate="label">
+    <customer_address_index translate="label" type="page" parent="customer_account_index">
         <label>Customer My Account Address Book</label>
         <!-- Mage_Customer -->
         <update handle="customer_account"/>
@@ -254,7 +229,7 @@ Customer account address book
 Customer account address edit page
 -->
 
-    <customer_address_form translate="label">
+    <customer_address_form translate="label" type="page" parent="customer_address_index">
         <label>Customer My Account Address Edit Form</label>
         <!-- Mage_Customer -->
         <update handle="customer_account"/>
@@ -263,4 +238,4 @@ Customer account address edit page
         </reference>
     </customer_address_form>
 
-</layout>
\ No newline at end of file
+</layout>
diff --git a/app/design/frontend/default/iphone/Mage_Page/layout.xml b/app/design/frontend/default/iphone/Mage_Page/layout.xml
index 2dd4e0dfe5a370070cbf228f60b15060326ebd19..b0527350402868d689774e2cf0b6b3b733473752 100644
--- a/app/design/frontend/default/iphone/Mage_Page/layout.xml
+++ b/app/design/frontend/default/iphone/Mage_Page/layout.xml
@@ -30,9 +30,9 @@
 Default layout, loads most of the pages
 -->
 
-    <default translate="label" module="Mage_Page">
+    <default translate="label" module="Mage_Page" type="page">
         <label>All Pages</label>
-        <block type="Mage_Page_Block_Html" name="root" output="toHtml" template="1column.phtml">
+        <block type="Mage_Page_Block_Html" name="root" output="1" template="1column.phtml">
             <block type="Mage_Page_Block_Html_Head" name="head" as="head">
                 <action method="addJs"><file>prototype/prototype.js</file></action>
                 <action method="addJs"><file>lib/ccard.js</file></action>
@@ -53,9 +53,7 @@ Default layout, loads most of the pages
                 <block type="Mage_Page_Block_Js_Cookie" name="js_cookies" template="js/cookie.phtml"/>
             </block>
 
-            <block type="Mage_Core_Block_Text_List" name="after_body_start" as="after_body_start" translate="label">
-                <label>Page Top</label>
-            </block>
+            <container name="after_body_start" as="after_body_start" label="Page Top"/>
 
             <block type="Mage_Page_Block_Html_Notices" name="global_notices" as="global_notices" template="html/notices.phtml" />
 
@@ -63,69 +61,34 @@ Default layout, loads most of the pages
                 <block type="Mage_Page_Block_Template_Links" name="top.links" as="topLinks"/>
                 <block type="Mage_Page_Block_Switch" name="store_language" as="store_language" template="switch/languages.phtml"/>
                 <block type="Mage_Page_Block_Switch" name="store_switcher" as="store_switcher" template="switch/stores.phtml"/>
-                <block type="Mage_Core_Block_Text_List" name="top.menu" as="topMenu" translate="label">
-                    <label>Navigation Bar</label>
-                </block>
-                <block type="Mage_Page_Block_Html_Wrapper" name="top.container" as="topContainer" translate="label">
-                    <label>Page Header</label>
-                    <action method="setElementClass"><value>top-container</value></action>
-                </block>
-                <block type="Mage_Checkout_Block_Cart" name="checkout.cart" as="topCart">
-                    <action method="setCartTemplate"><value>cartheader.phtml</value></action>
-                    <action method="setEmptyTemplate"><value>cart/no_items_header.phtml</value></action>
-                    <action method="chooseTemplate"/>
-                    <action method="addItemRender"><type>simple</type><block>Mage_Checkout_Block_Cart_Item_Renderer</block><template>cart/item/default.phtml</template></action>
-                    <action method="addItemRender"><type>grouped</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Grouped</block><template>cart/item/default.phtml</template></action>
-                    <action method="addItemRender"><type>configurable</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Configurable</block><template>cart/item/default.phtml</template></action>
-                    <remove name="checkout.cart.breadcrumbs"/>
-
-                    <block type="Mage_Core_Block_Text_List" name="checkout.cart.top_methods" as="top_methods" translate="label">
-                        <label>Payment Methods Before Checkout Button</label>
-                        <block type="Mage_Checkout_Block_Onepage_Link" name="checkout.cart.methods.onepage" template="onepage/link.phtml"/>
-                    </block>
-
-                    <block type="Mage_Page_Block_Html_Wrapper" name="checkout.cart.form.before" as="form_before" translate="label">
-                        <label>Shopping Cart Form Before</label>
-                    </block>
-
-                    <block type="Mage_Core_Block_Text_List" name="checkout.cart.methods" as="methods" translate="label">
-                        <label>Payment Methods After Checkout Button</label>
-                        <block type="Mage_Checkout_Block_Onepage_Link" name="checkout.cart.methods.onepage" template="onepage/link.phtml"/>
-                        <block type="Mage_Checkout_Block_Multishipping_Link" name="checkout.cart.methods.multishipping" template="multishipping/link.phtml"/>
-                    </block>
-
-                    <block type="Mage_Checkout_Block_Cart_Coupon" name="checkout.cart.coupon" as="coupon" template="cart/coupon.phtml"/>
-                    <block type="Mage_Checkout_Block_Cart_Shipping" name="checkout.cart.shipping" as="shipping" template="cart/shipping.phtml"/>
-                    <block type="Mage_Checkout_Block_Cart_Crosssell" name="checkout.cart.crosssell" as="crosssell" template="cart/crosssell.phtml"/>
-
-                    <block type="Mage_Checkout_Block_Cart_Totals" name="checkout.cart.totals" as="totals" template="cart/totals.phtml"/>
-                </block>
+                <container name="top.menu" as="topMenu" label="Navigation Bar">
+                    <block type="Mage_Page_Block_Html_Topmenu" name="catalog.topnav" template="html/topmenu.phtml"/>
+                </container>
+                <container name="top.container" as="topContainer" label="Page Header" htmlTag="div" htmlClass="top-container"/>
             </block>
 
             <block type="Mage_Page_Block_Html_Breadcrumbs" name="breadcrumbs" as="breadcrumbs"/>
 
             <block type="Mage_Core_Block_Messages" name="global_messages" as="global_messages"/>
             <block type="Mage_Core_Block_Messages" name="messages" as="messages"/>
-            <block type="Mage_Core_Block_Text_List" name="content" as="content" translate="label">
-                <label>Main Content Area</label>
-            </block>
+            <container name="content" as="content" label="Main Content Area"/>
 
             <block type="Mage_Page_Block_Html_Footer" name="footer" as="footer" template="html/footer.phtml">
-                <block type="Mage_Page_Block_Html_Wrapper" name="bottom.container" as="bottomContainer" translate="label">
-                    <label>Page Footer</label>
-                    <action method="setElementClass"><value>bottom-container</value></action>
-                </block>
+                <container name="bottom.container" as="bottomContainer" label="Page Footer" htmlTag="div" htmlClass="bottom-container"/>
                 <block type="Mage_Page_Block_Template_Links" name="footer_links" as="footer_links" template="template/links.phtml"/>
             </block>
 
-            <block type="Mage_Core_Block_Text_List" name="before_body_end" as="before_body_end" translate="label">
-                <label>Page Bottom</label>
-            </block>
+            <container name="before_body_end" as="before_body_end" label="Page Bottom"/>
         </block>
     </default>
 
+    <ajax_index translate="label" type="page">
+        <label>Dynamic Page Blocks (Updated by Ajax Request)</label>
+        <block type="Mage_Page_Block_Html" name="root" output="1" template="page_part.phtml"/>
+    </ajax_index>
+
       <!-- Custom page layout handles -->
-    <page_empty translate="label">
+    <page_empty translate="label" type="page" parent="default">
         <label>All Empty Layout Pages</label>
         <reference name="root">
             <action method="setTemplate"><template>empty.phtml</template></action>
@@ -134,7 +97,7 @@ Default layout, loads most of the pages
         </reference>
     </page_empty>
 
-    <page_one_column translate="label">
+    <page_one_column translate="label" type="page" parent="default">
         <label>All One-Column Layout Pages</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -143,7 +106,7 @@ Default layout, loads most of the pages
         </reference>
     </page_one_column>
 
-    <page_two_columns_left translate="label">
+    <page_two_columns_left translate="label" type="page" parent="default">
         <label>All Two-Column Layout Pages (Left Column)</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -152,7 +115,7 @@ Default layout, loads most of the pages
         </reference>
     </page_two_columns_left>
 
-    <page_two_columns_right translate="label">
+    <page_two_columns_right translate="label" type="page" parent="default">
         <label>All Two-Column Layout Pages (Right Column)</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -161,7 +124,7 @@ Default layout, loads most of the pages
         </reference>
     </page_two_columns_right>
 
-    <page_three_columns translate="label">
+    <page_three_columns translate="label" type="page" parent="default">
         <label>All Three-Column Layout Pages</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
diff --git a/app/design/frontend/default/iphone/Mage_Persistent/layout.xml b/app/design/frontend/default/iphone/Mage_Persistent/layout.xml
index 96732d460b101f6a949517cd3877f1227234e444..c1db2b5ed2a43f1e09bf6534cdd4078a53d47e95 100644
--- a/app/design/frontend/default/iphone/Mage_Persistent/layout.xml
+++ b/app/design/frontend/default/iphone/Mage_Persistent/layout.xml
@@ -26,13 +26,6 @@
  */
 -->
 <layout version="0.1.0">
-    <customer_logged_out_psc_handle>
-        <reference name="account.links">
-            <action method="addLink" translate="label title" module="Mage_Persistent"><label helper="Mage_Persistent_Helper_Data::getPersistentName"/><url helper="Mage_Persistent_Helper_Data::getUnsetCookieUrl"/><title helper="Mage_Persistent_Helper_Data::getPersistentName"/><prepare/><urlParams/><position>9</position></action>
-            <action method="removeLinkByUrl"><url helper="Mage_Customer_Helper_Data::getLoginUrl"/></action>
-        </reference>
-    </customer_logged_out_psc_handle>
-
     <customer_account_login>
         <reference name="customer_form_login">
             <action method="setTemplate"><template>Mage_Persistent::customer/form/login.phtml</template></action>
diff --git a/app/design/frontend/default/iphone/Mage_Review/layout.xml b/app/design/frontend/default/iphone/Mage_Review/layout.xml
index e78c5d71f32bdc266294cb974ba2ccc8d9c9e624..aeeba8989fc14c33d86466def8ca10027ac4cc31 100644
--- a/app/design/frontend/default/iphone/Mage_Review/layout.xml
+++ b/app/design/frontend/default/iphone/Mage_Review/layout.xml
@@ -65,7 +65,7 @@ Product reviews page (?)
 Product reviews page
 -->
 
-    <review_product_list translate="label">
+    <review_product_list translate="label" type="page" parent="default">
         <label>Catalog Product Reviews List</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -82,12 +82,11 @@ Product reviews page
                 <block type="Mage_Catalog_Block_Product_View" name="product.info.addto" as="addto" template="product/view/addto.phtml"/>
                 <block type="Mage_Catalog_Block_Product_View" name="product.info.addtocart" as="addtocart" template="product/view/addtocart.phtml">
                     <!-- workaround: a better place for this code is in paypal.xml -->
-                    <block type="Mage_Page_Block_Html_Wrapper" name="review.product.info.addtocart.paypal.wrapper" translate="label" module="Mage_Paypal">
-                        <label>PayPal Express Checkout Shortcut Wrapper</label>
+                    <container name="review.product.info.addtocart.paypal.wrapper" label="PayPal Express Checkout Shortcut Wrapper" module="Mage_Paypal" htmlTag="div">
                         <block type="Mage_Paypal_Block_Express_Shortcut" name="review.product.info.addtocart.paypal" template="express/shortcut.phtml">
                             <action method="setIsInCatalogProduct"><value>1</value></action>
                         </block>
-                    </block>
+                    </container>
                 </block>
 
                 <block type="Mage_Catalog_Block_Product_View" name="product.tierprices" as="tierprices" template="product/view/tierprices.phtml"/>
@@ -96,17 +95,14 @@ Product reviews page
                 <block type="Mage_Core_Block_Template" name="product_review_list.count" template="Mage_Review::product/view/count.phtml" />
                 <block type="Mage_Review_Block_Product_View_List" name="product.info.product_additional_data" as="product_additional_data" template="product/view/list.phtml">
                     <block type="Mage_Review_Block_Form" name="product.review.form" as="review_form">
-                        <block type="Mage_Page_Block_Html_Wrapper" name="product.review.form.fields.before" as="form_fields_before" translate="label">
-                            <label>Review Form Fields Before</label>
-                            <action method="setMayBeInvisible"><value>1</value></action>
-                        </block>
+                        <container name="product.review.form.fields.before" as="form_fields_before" label="Review Form Fields Before" htmlTag="div"/>
                     </block>
                 </block>
             </block>
         </reference>
     </review_product_list>
 
-    <review_product_view translate="label">
+    <review_product_view translate="label" type="page" parent="review_product_list">
         <label>Catalog Product Review View</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -116,7 +112,7 @@ Product reviews page
         </reference>
     </review_product_view>
 
-    <review_customer_index translate="label">
+    <review_customer_index translate="label" type="page" parent="customer_account_index">
         <label>Customer My Account Product Reviews</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
@@ -124,7 +120,7 @@ Product reviews page
         </reference>
     </review_customer_index>
 
-    <review_customer_view translate="label">
+    <review_customer_view translate="label" type="page" parent="review_customer_index">
         <label>Customer My Account Review Details</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
diff --git a/app/design/frontend/default/iphone/Mage_Sendfriend/layout.xml b/app/design/frontend/default/iphone/Mage_Sendfriend/layout.xml
index 0bd3ca88fef879f82f193d3ee639424ad3960e12..fdbb527b3b700982b5a9e955c1b9ba31c7c4a3ff 100644
--- a/app/design/frontend/default/iphone/Mage_Sendfriend/layout.xml
+++ b/app/design/frontend/default/iphone/Mage_Sendfriend/layout.xml
@@ -26,7 +26,7 @@
  */
 -->
 <layout version="0.1.0">
-    <sendfriend_product_send translate="label">
+    <sendfriend_product_send translate="label" type="page" parent="catalog_product_view">
         <label>Catalog Product Email to a Friend</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
diff --git a/app/design/frontend/default/iphone/Mage_Shipping/tracking/popup.phtml b/app/design/frontend/default/iphone/Mage_Shipping/tracking/popup.phtml
index 892cb69a05d5b9f66703b940a6822d97a257627b..bde1dadbb4bc70cd3baa7531ab5179e2ae099dde 100644
--- a/app/design/frontend/default/iphone/Mage_Shipping/tracking/popup.phtml
+++ b/app/design/frontend/default/iphone/Mage_Shipping/tracking/popup.phtml
@@ -24,7 +24,8 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 ?>
-<?php  $_results = $this->getTrackingInfo() ?>
+<?php /** @var $this Mage_Shipping_Block_Tracking_Popup */ ?>
+<?php $_results = $this->getTrackingInfo() ?>
 <div class="shipping-tracking">
 <div class="button-set">
 <button class="form-button" onclick="window.close();window.opener.focus();"><span><?php echo $this->__('Close Window') ?></span></button>
@@ -41,12 +42,12 @@
             <?php if(is_object($track)): ?>
             <tr>
                 <td class="first label"><?php echo $this->__('Tracking Number:'); ?></td>
-                <td><?php echo $track->getTracking(); ?></td>
+                <td><?php echo $this->escapeHtml($track->getTracking()); ?></td>
             </tr>
             <?php if ($track->getCarrierTitle()): ?>
             <tr>
                 <td class="first label"><?php echo $this->__('Carrier:'); ?></td>
-                <td><?php echo $track->getCarrierTitle(); ?></td>
+                <td><?php echo $this->escapeHtml($track->getCarrierTitle()); ?></td>
             </tr>
             <?php endif; ?>
             <?php if($track->getErrorMessage()): ?>
@@ -62,7 +63,7 @@
             <?php elseif($track->getUrl()): ?>
             <tr>
                 <td class="first label"><?php echo $this->__('Track:'); ?></td>
-                <td><a href="<?php echo $track->getUrl(); ?>" target="_blank"><?php echo $track->getUrl(); ?></a></td>
+                <td><a href="<?php echo $this->escapeHtml($track->getUrl()); ?>" target="_blank"><?php echo $this->escapeHtml($track->getUrl()); ?></a></td>
             </tr>
             <?php else: ?>
                 <?php if ($track->getStatus()): ?>
diff --git a/app/design/frontend/default/iphone/Mage_Tag/layout.xml b/app/design/frontend/default/iphone/Mage_Tag/layout.xml
index 507175ef3f7664c936e404c3269cd6dcaca5a80a..2126cd52bd63393123eb60ce2682fb3158027796 100644
--- a/app/design/frontend/default/iphone/Mage_Tag/layout.xml
+++ b/app/design/frontend/default/iphone/Mage_Tag/layout.xml
@@ -67,10 +67,7 @@ Customer account home dashboard layout
          <!-- Mage_Tag -->
         <reference name="product.info.additional">
             <block type="Mage_Tag_Block_Product_List" name="product_tag_list" before="-" template="list.phtml">
-                <block type="Mage_Page_Block_Html_Wrapper" name="product.tag.list.list.before" as="list_before" translate="label">
-                    <label>Tags List Before</label>
-                    <action method="setMayBeInvisible"><value>1</value></action>
-                </block>
+                <container name="product.tag.list.list.before" as="list_before" label="Tags List Before" htmlTag="div"/>
             </block>
         </reference>
     </catalog_product_view>
@@ -79,7 +76,7 @@ Customer account home dashboard layout
 All tags page
 -->
 
-    <tag_list_index translate="label">
+    <tag_list_index translate="label" type="page" parent="default">
         <label>Tags List (All Available)</label>
         <!-- Mage_Tag -->
         <reference name="root">
@@ -90,7 +87,7 @@ All tags page
         </reference>
     </tag_list_index>
 
-    <tag_product_list translate="label">
+    <tag_product_list translate="label" type="page" parent="tag_list_index">
         <label>Tagged Products List</label>
         <!-- Mage_Tag -->
         <reference name="content">
@@ -108,7 +105,7 @@ All tags page
         </reference>
     </tag_product_list>
 
-    <tag_customer_index translate="label">
+    <tag_customer_index translate="label" type="page" parent="tag_list_index">
         <label>Customer My Account My Tags List</label>
         <update handle="customer_account"/>
         <reference name="root">
@@ -119,7 +116,7 @@ All tags page
         </reference>
     </tag_customer_index>
 
-    <tag_customer_view translate="label">
+    <tag_customer_view translate="label" type="page" parent="tag_customer_index">
         <label>Customer My Account Tag View</label>
         <update handle="customer_account"/>
         <reference name="root">
diff --git a/app/design/frontend/default/iphone/local.xml b/app/design/frontend/default/iphone/local.xml
index 7f457881f73ce5a59604746320fc535d2c248592..ed19eddc6a01cef92c2248f6dd0bb3ba7dcbf3bc 100644
--- a/app/design/frontend/default/iphone/local.xml
+++ b/app/design/frontend/default/iphone/local.xml
@@ -32,6 +32,7 @@
             <action method="addCss"><file>css/styles-ie.css</file><params/><if>lt IE 8</if></action>
             <action method="addCss"><file>css/print.css</file><params>media="print"</params></action>
             <action method="addCss"><file>css/iphone.css</file></action>
+            <action method="addCss"><file>Mage_DesignEditor::css/iphone_styles.css</file><params/><if/><condition>design_editor_active</condition></action>
         </reference>
     </default>
 </layout>
diff --git a/app/design/frontend/default/iphone/skin/default/Mage_DesignEditor/css/iphone_styles.css b/app/design/frontend/default/iphone/skin/default/Mage_DesignEditor/css/iphone_styles.css
new file mode 100644
index 0000000000000000000000000000000000000000..e219ffd0920c81fb723fec28526b85273daaf0e3
--- /dev/null
+++ b/app/design/frontend/default/iphone/skin/default/Mage_DesignEditor/css/iphone_styles.css
@@ -0,0 +1,30 @@
+/**
+ * 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_iphone
+ * @copyright       Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license         http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+
+#vde_toolbar {
+    position: relative;
+    background-color: white;
+    z-index: 100;
+}
diff --git a/app/design/frontend/default/iphone/skin/default/css/iphone.css b/app/design/frontend/default/iphone/skin/default/css/iphone.css
index 14bd89ffb94f3cacbbceb0442155857691d5b161..d72db9579b15a0848142d773ef876bbf3dcbe631 100644
--- a/app/design/frontend/default/iphone/skin/default/css/iphone.css
+++ b/app/design/frontend/default/iphone/skin/default/css/iphone.css
@@ -399,7 +399,7 @@ body > header dd.menu-box ol li.selected {
 body > header dd.menu-box ol li.selected a {
     background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA0AAAAKCAYAAABv7tTEAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYxIDY0LjE0MDk0OSwgMjAxMC8xMi8wNy0xMDo1NzowMSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNS4xIFdpbmRvd3MiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6RjdEODVBMkI5Mzc4MTFFMEE2MDE5MzgwM0I5RkE1QjIiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6RjdEODVBMkM5Mzc4MTFFMEE2MDE5MzgwM0I5RkE1QjIiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDpGN0Q4NUEyOTkzNzgxMUUwQTYwMTkzODAzQjlGQTVCMiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDpGN0Q4NUEyQTkzNzgxMUUwQTYwMTkzODAzQjlGQTVCMiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PnMJ/AIAAABLSURBVHjaYmAgHgQAsQAJ6hkSgPg/EJ8nViNMAwwHwCQUiNSQgC6RQKwGEHiPRQKvBhAwQNM4n5AGXBoJasClMYHY+IBpxKsBIMAAi14oP6lEWTAAAAAASUVORK5CYII=) no-repeat left;
 }
-    
+
 /* Navigation
 -----------------------------*/
 body > nav { background:-webkit-gradient(linear, 0 0, 0 100%, from(#1a1a1a), to(#000)); border-bottom:5px solid #3a3a3a; padding:10px 5px 0; }
@@ -547,7 +547,7 @@ body > section > .category-image img { min-width:100%; }
 #nav-container li a span {
     background:url(../images/i_arrow_small.png) no-repeat right;
      display:block;
-     padding:10px; 
+     padding:10px;
     -webkit-background-size:8px 12px;
     -webkit-background-origin:content-box;
 }
@@ -985,7 +985,7 @@ section .category-title { display:none; }
 @media(orientation:landscape) {
     .filters-block dl {
         width:33%;
-    }    
+    }
 }
 
 .filters-block dt {
@@ -1218,7 +1218,7 @@ section .category-title { display:none; }
 }
 .c-list > li:last-child { display:block; border-bottom:none; }
 .c-list > li > a {
-    background:url(../images/i_arrow_small.png) no-repeat right #fff; 
+    background:url(../images/i_arrow_small.png) no-repeat right #fff;
     -webkit-background-size:8px 12px;
     -webkit-background-origin:content-box;
     color:#2f2f2f;
@@ -1577,7 +1577,7 @@ section .category-title { display:none; }
     font-size:14px;
     color:#FFF;
     border:1px solid #FFF;
-    border-radius:5px; 
+    border-radius:5px;
     -webkit-box-shadow:0 3px 3px 0 #9F9F9F;
     -webkit-background-clip:padding-box;
 }
@@ -1707,7 +1707,7 @@ section .category-title { display:none; }
 .product-collateral h2,
 .product-collateral h4 { font-size:14px; font-weight:bold; }
 .product-specs { font-size:14px; text-align:justify; word-spacing:-0.2ex; }
-    
+
     .up-sell-box { position:relative; }
     .up-sell-box .up-sell-heading { font-size:13px; line-height:24px; height:24px; font-weight:bold; margin:0; padding:5px 0 10px; text-shadow:0 1px 0 #fff; }
     .up-sell-box .prev,
@@ -1737,12 +1737,12 @@ section .category-title { display:none; }
     .up-sell-box .up-sell h5 { font-size:12px; line-height:17px; margin:5px 0; }
     .up-sell-box .up-sell .price-box { font-size:12px; line-height:17px; }
     .up-sell li .price-box { font-weight:bold; }
-    
+
     .counter { padding:5px 0 0; text-align:center; }
     .counter span { margin:0 2px; }
     .counter span:before { content:'\2022'; color:#ddd; font-size:20px; display:inline-block; -webkit-text-stroke:1px #ddd; }
     .counter span.active:before { color:#fff; }
-    
+
 .collateral-box { margin:16px 0 0; }
     .collateral-box .tags-list { font-size:12px; padding:10px; }
         .collateral-box .tags-list a { font-weight:bold; color:#F4641E; }
@@ -1882,7 +1882,7 @@ section .category-title { display:none; }
   from {
     -webkit-transform: rotate(0deg);
   }
-  to { 
+  to {
     -webkit-transform: rotate(360deg);
   }
 }
@@ -1890,12 +1890,12 @@ section .category-title { display:none; }
     background:initial;
 }
 .compare-table .rotate {
-    -webkit-animation-name:            rotate; 
+    -webkit-animation-name:            rotate;
     -webkit-animation-duration:        1s;
     -webkit-animation-iteration-count: infinite;
     -webkit-animation-timing-function: linear;
 }
-        
+
 /* Product review
 -----------------------------*/
 .review-product-list {}
@@ -2515,7 +2515,7 @@ section .category-title { display:none; }
 .sales-order-view .order-info dd ul { float:left; }
 .sales-order-invoice .order-info dd ul li,
 .sales-order-shipment .order-info dd ul li,
-.sales-order-view .order-info dd ul li { 
+.sales-order-view .order-info dd ul li {
     display:inline-block;
     margin:0 10px 10px 0;
     font-size: 16px;
diff --git a/app/design/frontend/default/modern/Mage_Catalog/layout.xml b/app/design/frontend/default/modern/Mage_Catalog/layout.xml
index c9bc531de0f50c27eda992568d51f596d2c60175..d3c735d62689675a7e5f2e897b8940f260c0a917 100644
--- a/app/design/frontend/default/modern/Mage_Catalog/layout.xml
+++ b/app/design/frontend/default/modern/Mage_Catalog/layout.xml
@@ -45,9 +45,6 @@ Default layout, loads most of the pages
     <default>
 
         <!-- Mage_Catalog -->
-        <reference name="top.menu">
-            <block type="Mage_Catalog_Block_Navigation" name="catalog.topnav" template="navigation/top.phtml"/>
-        </reference>
         <reference name="left">
             <!--block type="Mage_Core_Block_Template" name="left.permanent.callout" template="callouts/left_col.phtml">
                 <action method="setImgSrc"><src>images/media/left_col_callout.jpg</src></action>
@@ -74,15 +71,11 @@ Default layout, loads most of the pages
 <!--
 Category default layout
 -->
-
-    <catalog_category_default translate="label">
-        <label>Catalog Category (Non-Anchor)</label>
+    <catalog_category_view translate="label" type="page" parent="default">
+        <label>Catalog Category</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-left.phtml</template></action>
         </reference>
-        <reference name="left">
-            <block type="Mage_Catalog_Block_Navigation" name="catalog.leftnav" after="currency" template="navigation/left.phtml"/>
-        </reference>
         <reference name="content">
             <block type="Mage_Catalog_Block_Category_View" name="category.products" template="category/view.phtml">
                 <block type="Mage_Catalog_Block_Product_List" name="product_list" template="product/list.phtml">
@@ -112,65 +105,44 @@ Category default layout
                 </block>
             </block>
         </reference>
-    </catalog_category_default>
+    </catalog_category_view>
 
-<!--
-Category layered navigation layout
--->
+    <catalog_category_view_type_default translate="label" type="page" parent="catalog_category_view">
+        <label>Non Anchor Catalog Category</label>
+        <reference name="left">
+            <block type="Mage_Catalog_Block_Navigation" name="catalog.leftnav" after="currency" template="navigation/left.phtml"/>
+        </reference>
+    </catalog_category_view_type_default>
 
-    <catalog_category_layered translate="label">
-        <label>Catalog Category (Anchor)</label>
-        <reference name="root">
-            <action method="setTemplate"><template>2columns-left.phtml</template></action>
+    <catalog_category_view_type_default_without_children translate="label" type="page" parent="catalog_category_view_type_default">
+        <label>Non Anchor Catalog Category Without Subcategories</label>
+        <remove name="right.reports.product.viewed"/>
+        <reference name="left">
+            <!--block type="Mage_Reports_Block_Product_Viewed" name="left.reports.product.viewed" template="product_viewed.phtml"/-->
         </reference>
+    </catalog_category_view_type_default_without_children>
+
+    <catalog_category_view_type_layered translate="label" type="page" parent="catalog_category_view">
+        <label>Anchor Catalog Category</label>
         <reference name="left">
             <block type="Mage_Catalog_Block_Layer_View" name="catalog.leftnav" after="currency" template="layer/view.phtml"/>
         </reference>
-        <reference name="content">
-            <block type="Mage_Catalog_Block_Category_View" name="category.products" template="category/view.phtml">
-                <block type="Mage_Catalog_Block_Product_List" name="product_list" template="product/list.phtml">
-                    <!-- <action method="addReviewSummaryTemplate"><type>default</type><template>review/helper/su.phtml</template></action> -->
-                    <block type="Mage_Catalog_Block_Product_List_Toolbar" name="product_list_toolbar" template="product/list/toolbar.phtml">
-                        <block type="Mage_Page_Block_Html_Pager" name="product_list_toolbar_pager"/>
-                        <!-- The following code shows how to set your own pager increments -->
-                        <!--
-                            <action method="setDefaultListPerPage"><limit>10</limit></action>
-                            <action method="setDefaultGridPerPage"><limit>8</limit></action>
-                            <action method="addPagerLimit"><mode>list</mode><limit>10</limit></action>
-                            <action method="addPagerLimit"><mode>list</mode><limit>20</limit></action>
-                            <action method="addPagerLimit"><mode>list</mode><limit>30</limit></action>
-                            <action method="addPagerLimit" translate="label"><mode>list</mode><limit>all</limit><label>All</label></action>
-                            <action method="addPagerLimit"><mode>grid</mode><limit>8</limit></action>
-                            <action method="addPagerLimit"><mode>grid</mode><limit>16</limit></action>
-                            <action method="addPagerLimit"><mode>grid</mode><limit>24</limit></action>
-                            <action method="addPagerLimit" translate="label"><mode>grid</mode><limit>all</limit><label>All</label></action>
-                        -->
-                    </block>
-                    <!--action method="addColumnCountLayoutDepend"><layout>empty</layout><count>6</count></action>
-                    <action method="addColumnCountLayoutDepend"><layout>one_column</layout><count>5</count></action>
-                    <action method="addColumnCountLayoutDepend"><layout>two_columns_left</layout><count>4</count></action>
-                    <action method="addColumnCountLayoutDepend"><layout>two_columns_right</layout><count>4</count></action>
-                    <action method="addColumnCountLayoutDepend"><layout>three_columns</layout><count>3</count></action-->
-                    <action method="setColumnCount"><count>4</count></action>
-                    <action method="setToolbarBlockName"><name>product_list_toolbar</name></action>
-                </block>
-            </block>
-        </reference>
-    </catalog_category_layered>
+    </catalog_category_view_type_layered>
 
-    <catalog_category_layered_nochildren translate="label">
-        <label>Catalog Category (Without Subcategories)</label>
+    <catalog_category_view_type_layered_without_children>
+        <label>Anchor Catalog Category Without Subcategories</label>
         <remove name="right.reports.product.viewed"/>
         <reference name="left">
             <!--block type="Mage_Reports_Block_Product_Viewed" name="left.reports.product.viewed" template="product_viewed.phtml"/-->
         </reference>
-    </catalog_category_layered_nochildren>
+    </catalog_category_view_type_layered_without_children>
+
 
 <!--
 Compare products page
 -->
 
-    <catalog_product_compare_index translate="label">
+    <catalog_product_compare_index translate="label" type="page" parent="default">
         <label>Catalog Product Compare List</label>
         <!-- Mage_Catalog -->
         <reference name="root">
@@ -189,7 +161,7 @@ Compare products page
 Product view
 -->
 
-    <catalog_product_view translate="label">
+    <catalog_product_view translate="label" type="page" parent="default">
         <label>Catalog Product View (Any)</label>
         <!-- Mage_Catalog -->
         <reference name="root">
@@ -211,9 +183,7 @@ Product view
                 <action method="addReviewSummaryTemplate"><type>...</type><template>...</template></action>
                 -->
                 <block type="Mage_Catalog_Block_Product_View_Media" name="product.info.media" as="media" template="product/view/media.phtml"/>
-                <block type="Mage_Core_Block_Text_List" name="alert.urls" as="alert_urls" translate="label">
-                    <label>Alert Urls</label>
-                </block>
+                <container name="alert.urls" as="alert_urls" label="Alert Urls"/>
 
                 <action method="setTierPriceTemplate"><template>product/view/tierprices.phtml</template></action>
 
@@ -227,9 +197,7 @@ Product view
                 <block type="Mage_Catalog_Block_Product_View" name="product.info.addto" as="addto" template="product/view/addto.phtml"/>
                 <block type="Mage_Catalog_Block_Product_View" name="product.info.addtocart" as="addtocart" template="product/view/addtocart.phtml"/>
 
-                <block type="Mage_Core_Block_Text_List" name="product.info.extrahint" as="extrahint" translate="label">
-                    <label>Product View Extra Hint</label>
-                </block>
+                <container name="product.info.extrahint" as="extrahint" label="Product View Extra Hint"/>
 
                 <block type="Mage_Catalog_Block_Product_View" name="product.info.options.wrapper" as="product_options_wrapper" template="product/view/options/wrapper.phtml" translate="label">
                     <label>Info Column Options Wrapper</label>
@@ -278,55 +246,47 @@ Product view
 <!--
 Additional block dependant on product type
 -->
-    <PRODUCT_TYPE_simple translate="label" module="Mage_Catalog">
+    <catalog_product_view_type_simple translate="label" module="Mage_Catalog" type="page" parent="catalog_product_view">
         <label>Catalog Product View (Simple)</label>
         <reference name="product.info">
             <block type="Mage_Catalog_Block_Product_View_Type_Simple" name="product.info.simple" as="product_type_data" template="product/view/type/default.phtml">
-                <block type="Mage_Core_Block_Text_List" name="product.info.simple.extra" as="product_type_data_extra" translate="label">
-                    <label>Product Extra Info</label>
-                </block>
+                <container name="product.info.simple.extra" as="product_type_data_extra" label="Product Extra Info"/>
             </block>
         </reference>
-    </PRODUCT_TYPE_simple>
-    <PRODUCT_TYPE_configurable translate="label" module="Mage_Catalog">
+    </catalog_product_view_type_simple>
+    <catalog_product_view_type_configurable translate="label" module="Mage_Catalog" type="page" parent="catalog_product_view">
         <label>Catalog Product View (Configurable)</label>
         <reference name="product.info">
             <block type="Mage_Catalog_Block_Product_View_Type_Configurable" name="product.info.configurable" as="product_type_data" template="product/view/type/default.phtml">
-                <block type="Mage_Core_Block_Text_List" name="product.info.configurable.extra" as="product_type_data_extra" translate="label">
-                    <label>Product Extra Info</label>
-                </block>
+                <container name="product.info.configurable.extra" as="product_type_data_extra" label="Product Extra Info"/>
             </block>
         </reference>
         <reference name="product.info.options.wrapper">
             <block type="Mage_Catalog_Block_Product_View_Type_Configurable" name="product.info.options.configurable" as="options_configurable" before="-" template="product/view/type/options/configurable.phtml"/>
         </reference>
-    </PRODUCT_TYPE_configurable>
-    <PRODUCT_TYPE_grouped translate="label" module="Mage_Catalog">
+    </catalog_product_view_type_configurable>
+    <catalog_product_view_type_grouped translate="label" module="Mage_Catalog" type="page" parent="catalog_product_view">
         <label>Catalog Product View (Grouped)</label>
         <reference name="product.info">
             <block type="Mage_Catalog_Block_Product_View_Type_Grouped" name="product.info.grouped" as="product_type_data" template="product/view/type/grouped.phtml">
-                <block type="Mage_Core_Block_Text_List" name="product.info.grouped.extra" as="product_type_data_extra" translate="label">
-                    <label>Product Extra Info</label>
-                </block>
+                <container name="product.info.grouped.extra" as="product_type_data_extra" label="Product Extra Info"/>
             </block>
         </reference>
-    </PRODUCT_TYPE_grouped>
-    <PRODUCT_TYPE_virtual translate="label" module="Mage_Catalog">
+    </catalog_product_view_type_grouped>
+    <catalog_product_view_type_virtual translate="label" module="Mage_Catalog" type="page" parent="catalog_product_view">
         <label>Catalog Product View (Virtual)</label>
         <reference name="product.info">
             <block type="Mage_Catalog_Block_Product_View_Type_Virtual" name="product.info.virtual" as="product_type_data" template="product/view/type/default.phtml">
-                <block type="Mage_Core_Block_Text_List" name="product.info.virtual.extra" as="product_type_data_extra" translate="label">
-                    <label>Product Extra Info</label>
-                </block>
+                <container name="product.info.virtual.extra" as="product_type_data_extra" label="Product Extra Info"/>
             </block>
         </reference>
-    </PRODUCT_TYPE_virtual>
+    </catalog_product_view_type_virtual>
 
 <!--
 Product additional images gallery popup
 -->
 
-    <catalog_product_gallery translate="label">
+    <catalog_product_gallery translate="label" type="page" parent="catalog_product_view">
         <label>Catalog Product Image Gallery Popup</label>
         <!-- Mage_Catalog -->
         <reference name="root">
@@ -341,7 +301,7 @@ Product additional images gallery popup
 SEO Site Map
 -->
 
-    <catalog_seo_sitemap translate="label">
+    <catalog_seo_sitemap translate="label" type="page" parent="default">
         <label>Catalog Seo Sitemap (Common)</label>
         <remove name="right"/>
         <remove name="left"/>
@@ -358,12 +318,11 @@ SEO Site Map
         </reference>
     </catalog_seo_sitemap>
 
-    <catalog_seo_sitemap_category translate="label">
+    <catalog_seo_sitemap_category translate="label" type="page" parent="catalog_seo_sitemap">
         <label>Catalog Seo Sitemap (Category List)</label>
         <reference name="head">
             <action method="setTitle" translate="title" module="Mage_Catalog"><title>Site Map</title></action>
         </reference>
-        <update handle="catalog_seo_sitemap" />
         <reference name="seo.sitemap.container">
             <action method="setTitle" translate="title" module="Mage_Catalog"><title>Categories</title></action>
             <block type="Mage_Catalog_Block_Seo_Sitemap_Category" name="seo.sitemap.sitemap" as="sitemap" after="pager_top" template="seo/sitemap.phtml">
@@ -377,7 +336,7 @@ SEO Site Map
         </reference>
     </catalog_seo_sitemap_category>
 
-    <catalog_seo_sitemap_category_tree translate="label">
+    <catalog_seo_sitemap_category_type_tree translate="label" type="page" parent="catalog_seo_sitemap_category">
         <label>Catalog Seo Sitemap (Category Tree)</label>
         <reference name="seo.sitemap.container">
             <remove name="seo.sitemap.pager.top" />
@@ -390,9 +349,9 @@ SEO Site Map
                 <action method="bindPager"><pager>seo.sitemap.tree.pager.bottom</pager></action>
             </block>
         </reference>
-    </catalog_seo_sitemap_category_tree>
+    </catalog_seo_sitemap_category_type_tree>
 
-    <catalog_seo_sitemap_product translate="label">
+    <catalog_seo_sitemap_product translate="label" type="page" parent="catalog_seo_sitemap">
         <label>Catalog Seo Sitemap (Product List)</label>
         <reference name="head">
             <action method="setTitle" translate="title" module="Mage_Catalog"><title>Site Map</title></action>
diff --git a/app/design/frontend/default/modern/Mage_CatalogSearch/layout.xml b/app/design/frontend/default/modern/Mage_CatalogSearch/layout.xml
index 73073969cab31244b2ffee36b975e6f624843611..3644f0cf6eaa524e3538d87e58702c1511d866fd 100644
--- a/app/design/frontend/default/modern/Mage_CatalogSearch/layout.xml
+++ b/app/design/frontend/default/modern/Mage_CatalogSearch/layout.xml
@@ -46,7 +46,7 @@
         </reference>
     </default>
 
-    <catalogsearch_result_index translate="label" module="Mage_CatalogSearch">
+    <catalogsearch_result_index translate="label" module="Mage_CatalogSearch" type="page" parent="default">
         <label>Quick Search Form</label>
         <update handle="page_two_columns_left" />
         <reference name="root">
@@ -75,7 +75,7 @@
         </reference>
     </catalogsearch_result_index>
 
-    <catalogsearch_advanced_index translate="label" module="Mage_CatalogSearch">
+    <catalogsearch_advanced_index translate="label" module="Mage_CatalogSearch" type="page" parent="default">
         <label>Advanced Search Form</label>
         <!-- Mage_Catalogsearch -->
         <reference name="root">
@@ -97,7 +97,7 @@
 Advanced search results
 -->
 
-    <catalogsearch_advanced_result translate="label" module="Mage_CatalogSearch">
+    <catalogsearch_advanced_result translate="label" module="Mage_CatalogSearch" type="page" parent="catalogsearch_advanced_index">
         <label>Advanced Search Result</label>
         <update handle="page_two_columns_left" />
         <!-- Mage_Catalogsearch -->
@@ -124,7 +124,7 @@ Advanced search results
         </reference>
     </catalogsearch_advanced_result>
 
-    <catalogsearch_term_popular translate="label" module="Mage_CatalogSearch">
+    <catalogsearch_term_popular translate="label" module="Mage_CatalogSearch" type="page" parent="default">
         <label>Popular Search Terms</label>
         <remove name="right"/>
         <remove name="left"/>
@@ -140,4 +140,10 @@ Advanced search results
         </reference>
     </catalogsearch_term_popular>
 
+    <catalogsearch_ajax_suggest translate="label" module="Mage_CatalogSearch" type="page" parent="ajax_index">
+        <label>Catalog Quick Search Form Suggestions</label>
+        <reference name="root">
+            <block type="Mage_CatalogSearch_Block_Autocomplete" name="autocomplete"/>
+        </reference>
+    </catalogsearch_ajax_suggest>
 </layout>
diff --git a/app/design/frontend/default/modern/Mage_Checkout/layout.xml b/app/design/frontend/default/modern/Mage_Checkout/layout.xml
index ad1bb5e20931498afbb8acc5c5328b75fdc3d95d..5b9048304309309d19608b9c0bf6c9a6026b917f 100644
--- a/app/design/frontend/default/modern/Mage_Checkout/layout.xml
+++ b/app/design/frontend/default/modern/Mage_Checkout/layout.xml
@@ -45,9 +45,7 @@ Default layout, loads most of the pages
                 <action method="addItemRender"><type>simple</type><block>Mage_Checkout_Block_Cart_Item_Renderer</block><template>cart/sidebar/default.phtml</template></action>
                 <action method="addItemRender"><type>grouped</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Grouped</block><template>cart/sidebar/default.phtml</template></action>
                 <action method="addItemRender"><type>configurable</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Configurable</block><template>cart/sidebar/default.phtml</template></action>
-                <block type="Mage_Core_Block_Text_List" name="cart_sidebar.extra_actions" as="extra_actions" translate="label" module="Mage_Checkout">
-                    <label>Shopping Cart Sidebar Extra Actions</label>
-                </block>
+                <container name="cart_sidebar.extra_actions" as="extra_actions" label="Shopping Cart Sidebar Extra Actions" module="Mage_Checkout"/>
             </block>
         </reference>
         <reference name="head">
@@ -56,7 +54,7 @@ Default layout, loads most of the pages
 
     </default>
 
-    <checkout_cart_index translate="label">
+    <checkout_cart_index translate="label" type="page" parent="default">
         <label>Shopping Cart</label>
         <remove name="right"/>
         <remove name="left"/>
@@ -73,20 +71,16 @@ Default layout, loads most of the pages
                 <action method="addItemRender"><type>grouped</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Grouped</block><template>cart/item/default.phtml</template></action>
                 <action method="addItemRender"><type>configurable</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Configurable</block><template>cart/item/default.phtml</template></action>
 
-                <block type="Mage_Core_Block_Text_List" name="checkout.cart.top_methods" as="top_methods" translate="label">
-                    <label>Payment Methods Before Checkout Button</label>
+                <container name="checkout.cart.top_methods" as="top_methods" label="Payment Methods Before Checkout Button">
                     <block type="Mage_Checkout_Block_Onepage_Link" name="checkout.cart.methods.onepage" template="onepage/link.phtml"/>
-                </block>
+                </container>
 
-                <block type="Mage_Page_Block_Html_Wrapper" name="checkout.cart.form.before" as="form_before" translate="label">
-                    <label>Shopping Cart Form Before</label>
-                </block>
+                <container name="checkout.cart.form.before" as="form_before" label="Shopping Cart Form Before" htmlTag="div"/>
 
-                <block type="Mage_Core_Block_Text_List" name="checkout.cart.methods" as="methods" translate="label">
-                    <label>Payment Methods After Checkout Button</label>
+                <container name="checkout.cart.methods" as="methods" label="Payment Methods After Checkout Button">
                     <block type="Mage_Checkout_Block_Onepage_Link" name="checkout.cart.methods.onepage" template="onepage/link.phtml"/>
                     <block type="Mage_Checkout_Block_Multishipping_Link" name="checkout.cart.methods.multishipping" template="multishipping/link.phtml"/>
-                </block>
+                </container>
 
                 <block type="Mage_Checkout_Block_Cart_Coupon" name="checkout.cart.coupon" as="coupon" template="cart/coupon.phtml"/>
                 <block type="Mage_Checkout_Block_Cart_Shipping" name="checkout.cart.shipping" as="shipping" template="cart/shipping.phtml"/>
@@ -95,12 +89,10 @@ Default layout, loads most of the pages
                 <block type="Mage_Checkout_Block_Cart_Totals" name="checkout.cart.totals" as="totals" template="cart/totals.phtml"/>
             </block>
         </reference>
-        <block type="Mage_Core_Block_Text_List" name="additional.product.info" translate="label">
-            <label>Additional Product Info</label>
-        </block>
+        <container name="additional.product.info" label="Additional Product Info"/>
     </checkout_cart_index>
 
-    <checkout_cart_configure translate="label">
+    <checkout_cart_configure translate="label" type="page" parent="catalog_product_view">
         <label>Configure Cart Item</label>
         <update handle="catalog_product_view"/>
     </checkout_cart_configure>
@@ -110,7 +102,7 @@ Multi address shipping checkout main layout,
 will be rendered on all checkout pages
 -->
 
-    <checkout_multishipping translate="label">
+    <checkout_multishipping translate="label" type="page" parent="checkout_cart_index">
         <label>Multishipping Checkout</label>
         <!-- Mage_Checkout -->
         <remove name="right"/>
@@ -124,11 +116,13 @@ will be rendered on all checkout pages
         </reference>
     </checkout_multishipping>
 
-    <checkout_multishipping_login>
+    <checkout_multishipping_login translate="label" type="page" parent="customer_account_login">
+        <label>Multishipping Checkout Login User Form</label>
         <update handle="customer_account_login"/>
     </checkout_multishipping_login>
 
-    <checkout_multishipping_register>
+    <checkout_multishipping_register translate="label" type="page" parent="customer_account_create">
+        <label>Multishipping Checkout Register User Form</label>
         <update handle="customer_account_create"/>
     </checkout_multishipping_register>
 
@@ -136,7 +130,7 @@ will be rendered on all checkout pages
 Multi address shipping checkout selection of address per item page
 -->
 
-    <checkout_multishipping_address_select translate="label">
+    <checkout_multishipping_address_select translate="label" type="page" parent="checkout_multishipping_addresses">
         <label>Multishipping Checkout Shipping Address Selection</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -145,7 +139,7 @@ Multi address shipping checkout selection of address per item page
         </reference>
     </checkout_multishipping_address_select>
 
-    <checkout_multishipping_address_selectbilling translate="label">
+    <checkout_multishipping_address_selectbilling translate="label" parent="checkout_multishipping_address_select">
         <label>Multishipping Checkout Billing Address Selection</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -155,36 +149,37 @@ Multi address shipping checkout selection of address per item page
     </checkout_multishipping_address_selectbilling>
 
 
-    <checkout_multishipping_address_newshipping translate="label">
+    <checkout_multishipping_address_newshipping translate="label" type="page" parent="checkout_multishipping_shipping">
         <label>Multishipping Checkout Shipping Address Creation</label>
         <update handle="checkout_multishipping"/>
         <update handle="checkout_multishipping_customer_address"/>
     </checkout_multishipping_address_newshipping>
 
-    <checkout_multishipping_address_newbilling translate="label">
+    <checkout_multishipping_address_newbilling translate="label" type="page" parent="checkout_multishipping_billing">
         <label>Multishipping Checkout Billing Address Creation</label>
         <update handle="checkout_multishipping"/>
         <update handle="checkout_multishipping_customer_address"/>
     </checkout_multishipping_address_newbilling>
 
-    <checkout_multishipping_address_editshipping translate="label">
+    <checkout_multishipping_address_editshipping translate="label" type="page" parent="checkout_multishipping_shipping">
         <label>Multishipping Checkout Shipping Address Edit Form</label>
         <update handle="checkout_multishipping"/>
         <update handle="checkout_multishipping_customer_address"/>
     </checkout_multishipping_address_editshipping>
 
-    <checkout_multishipping_address_editaddress>
+    <checkout_multishipping_address_editaddress translate="label" type="page" parent="checkout_multishipping_customer_address">
+        <label>Multishipping Checkout One Address Edit Form</label>
         <update handle="checkout_multishipping"/>
         <update handle="checkout_multishipping_customer_address"/>
     </checkout_multishipping_address_editaddress>
 
-    <checkout_multishipping_address_editbilling translate="label">
+    <checkout_multishipping_address_editbilling translate="label" type="page" parent="checkout_multishipping_billing">
         <label>Multishipping Checkout Billing Address Edit Form</label>
         <update handle="checkout_multishipping"/>
         <update handle="checkout_multishipping_customer_address"/>
     </checkout_multishipping_address_editbilling>
 
-    <checkout_multishipping_customer_address translate="label">
+    <checkout_multishipping_customer_address translate="label" type="page" parent="customer_address_form">
         <label>Multishipping Checkout Customer Address Edit Form</label>
         <reference name="content">
             <block type="Mage_Customer_Block_Address_Edit" name="customer_address_edit" template="address/edit.phtml"/>
@@ -195,7 +190,7 @@ Multi address shipping checkout selection of address per item page
 Multi address shipping checkout address page
 -->
 
-    <checkout_multishipping_addresses translate="label">
+    <checkout_multishipping_addresses translate="label" type="page" parent="checkout_multishipping">
         <label>Multishipping Checkout Address (Any) Form</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -212,7 +207,7 @@ Multi address shipping checkout address page
 Multi address shipping checkout shipping information
 -->
 
-    <checkout_multishipping_shipping translate="label">
+    <checkout_multishipping_shipping translate="label" type="page" parent="checkout_multishipping">
         <label>Multishipping Checkout Shipping Information Step</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -235,7 +230,7 @@ Multi address shipping checkout shipping information
 Multi address shipping checkout billing information
 -->
 
-    <checkout_multishipping_billing translate="label">
+    <checkout_multishipping_billing translate="label" type="page" parent="checkout_multishipping">
         <label>Multishipping Checkout Billing Information Step</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -257,7 +252,7 @@ Multi address shipping checkout billing information
 Multi address shipping checkout overview
 -->
 
-    <checkout_multishipping_overview translate="label">
+    <checkout_multishipping_overview translate="label" type="page" parent="checkout_multishipping">
         <label>Multishipping Checkout Overview</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -273,9 +268,7 @@ Multi address shipping checkout overview
                 </block>
                 <block type="Mage_Checkout_Block_Agreements" name="checkout.multishipping.agreements" as="agreements" template="multishipping/agreements.phtml"/>
                 <block type="Mage_Checkout_Block_Cart_Totals" name="totals" />
-                <block type="Mage_Core_Block_Text_List" name="checkout.multishipping.overview.items.after" as="items_after" translate="label">
-                    <label>Overview Items After</label>
-                </block>
+                <container name="checkout.multishipping.overview.items.after" as="items_after" label="Overview Items After"/>
             </block>
         </reference>
     </checkout_multishipping_overview>
@@ -284,7 +277,7 @@ Multi address shipping checkout overview
 Multi address shipping checkout success
 -->
 
-    <checkout_multishipping_success translate="label">
+    <checkout_multishipping_success translate="label" type="page" parent="checkout_multishipping">
         <label>Multishipping Checkout Success</label>
         <update handle="checkout_multishipping"/>
         <!-- Mage_Checkout -->
@@ -297,7 +290,7 @@ Multi address shipping checkout success
 One page checkout main layout
 -->
 
-    <checkout_onepage_index translate="label">
+    <checkout_onepage_index translate="label" type="page" parent="checkout_cart_index">
         <label>One Page Checkout</label>
         <!-- Mage_Checkout -->
         <remove name="right"/>
@@ -307,19 +300,14 @@ One page checkout main layout
         </reference>
         <reference name="left">
             <action method="unsetChildren"></action>
-            <block type="Mage_Page_Block_Html_Wrapper" name="checkout.progress.wrapper" translate="label">
-                <label>Checkout Progress Wrapper</label>
-                <action method="setElementId"><value>checkout-progress-wrapper</value></action>
+            <container name="checkout.progress.wrapper" label="Checkout Progress Wrapper" htmlTag="div" htmlId="checkout-progress-wrapper">
                 <block type="Mage_Checkout_Block_Onepage_Progress" name="checkout.progress" before="-" template="onepage/progress.phtml"/>
-            </block>
+            </container>
         </reference>
         <reference name="content">
             <block type="Mage_Checkout_Block_Onepage" name="checkout.onepage" template="onepage.phtml">
                 <block type="Mage_Checkout_Block_Onepage_Login" name="checkout.onepage.login" as="login" template="onepage/login.phtml">
-                    <block type="Mage_Page_Block_Html_Wrapper" name="checkout.onepage.login.before" as="login_before" translate="label">
-                        <label>Login/Registration Before</label>
-                        <action method="setMayBeInvisible"><value>1</value></action>
-                    </block>
+                    <container name="checkout.onepage.login.before" as="login_before" label="Login/Registration Before" htmlTag="div"/>
                 </block>
                 <block type="Mage_Checkout_Block_Onepage_Billing" name="checkout.onepage.billing" as="billing" template="onepage/billing.phtml"/>
                 <block type="Mage_Checkout_Block_Onepage_Shipping" name="checkout.onepage.shipping" as="shipping" template="onepage/shipping.phtml"/>
@@ -341,28 +329,27 @@ One page checkout main layout
 One page checkout progress block
 -->
 
-    <checkout_onepage_progress>
-        <!-- Mage_Checkout -->
-        <remove name="right"/>
-        <remove name="left"/>
-
-        <block type="Mage_Checkout_Block_Onepage_Progress" name="root" output="toHtml" template="onepage/progress.phtml">
-            <block type="Mage_Checkout_Block_Onepage_Payment_Info" name="payment_info">
-                <action method="setInfoTemplate"><method></method><template></template></action>
+    <checkout_onepage_progress translate="label" type="page" parent="ajax_index">
+        <label>One Page Checkout Progress</label>
+        <reference name="root">
+            <block type="Mage_Checkout_Block_Onepage_Progress" name="progress" template="onepage/progress.phtml">
+                <block type="Mage_Checkout_Block_Onepage_Payment_Info" name="payment_info">
+                    <action method="setInfoTemplate"><method></method><template></template></action>
+                </block>
             </block>
-        </block>
+        </reference>
     </checkout_onepage_progress>
 
 <!--
 One page checkout payment methods block
 -->
-    <checkout_onepage_paymentmethod>
-        <remove name="right"/>
-        <remove name="left"/>
-
-        <block type="Mage_Checkout_Block_Onepage_Payment_Methods" name="root" output="toHtml" template="onepage/payment/methods.phtml">
-            <action method="setMethodFormTemplate"><method>purchaseorder</method><template>payment/form/purchaseorder.phtml</template></action>
-        </block>
+    <checkout_onepage_paymentmethod translate="label" type="page" parent="ajax_index">
+        <label>One Page Checkout Choose Payment Method</label>
+        <reference name="root">
+            <block type="Mage_Checkout_Block_Onepage_Payment_Methods" name="payment_method" template="onepage/payment/methods.phtml">
+                <action method="setMethodFormTemplate"><method>purchaseorder</method><template>payment/form/purchaseorder.phtml</template></action>
+            </block>
+        </reference>
     </checkout_onepage_paymentmethod>
 
 
@@ -370,51 +357,43 @@ One page checkout payment methods block
 One page checkout shipping methods block
 -->
 
-    <checkout_onepage_shippingmethod>
-        <!-- Mage_Checkout -->
-        <remove name="right"/>
-        <remove name="left"/>
-
-        <block type="Mage_Checkout_Block_Onepage_Shipping_Method_Available" name="root" output="toHtml" template="onepage/shipping_method/available.phtml"/>
+    <checkout_onepage_shippingmethod translate="label" type="page" parent="ajax_index">
+        <label>One Page Checkout Choose Shipping Method</label>
+        <reference name="root">
+            <block type="Mage_Checkout_Block_Onepage_Shipping_Method_Available" name="shipping_method" template="onepage/shipping_method/available.phtml"/>
+        </reference>
     </checkout_onepage_shippingmethod>
 
-    <checkout_onepage_additional>
-        <!-- Mage_Checkout -->
-        <remove name="right"/>
-        <remove name="left"/>
-
-        <block type="Mage_Checkout_Block_Onepage_Shipping_Method_Additional" name="root" output="toHtml" template="onepage/shipping_method/additional.phtml">
-            <action method="setDontDisplayContainer"><param>1</param></action>
-        </block>
+    <checkout_onepage_additional translate="label" type="page" parent="ajax_index">
+        <label>One Page Checkout Additional Address Form</label>
+        <reference name="root">
+            <block type="Mage_Checkout_Block_Onepage_Shipping_Method_Additional" name="shipping_method_available" template="onepage/shipping_method/additional.phtml">
+                <action method="setDontDisplayContainer"><param>1</param></action>
+            </block>
+        </reference>
     </checkout_onepage_additional>
 
 <!--
 One page checkout order review block
 -->
 
-    <checkout_onepage_review translate="label">
+    <checkout_onepage_review translate="label" type="page" parent="ajax_index">
         <label>One Page Checkout Overview</label>
-        <!-- Mage_Checkout -->
-        <remove name="right"/>
-        <remove name="left"/>
-
-        <block type="Mage_Checkout_Block_Onepage_Review_Info" name="root" output="toHtml" template="onepage/review/info.phtml">
-            <action method="addItemRender"><type>default</type><block>Mage_Checkout_Block_Cart_Item_Renderer</block><template>onepage/review/item.phtml</template></action>
-            <action method="addItemRender"><type>grouped</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Grouped</block><template>onepage/review/item.phtml</template></action>
-            <action method="addItemRender"><type>configurable</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Configurable</block><template>onepage/review/item.phtml</template></action>
-            <block type="Mage_Checkout_Block_Cart_Totals" name="checkout.onepage.review.info.totals" as="totals" template="onepage/review/totals.phtml"/>
-            <block type="Mage_Core_Block_Text_List" name="checkout.onepage.review.info.items.before" as="items_before" translate="label">
-                <label>Items Before</label>
-            </block>
-            <block type="Mage_Core_Block_Text_List" name="checkout.onepage.review.info.items.after" as="items_after" translate="label">
-                <label>Items After</label>
+        <reference name="root">
+            <block type="Mage_Checkout_Block_Onepage_Review_Info" name="order_review" template="onepage/review/info.phtml">
+                <action method="addItemRender"><type>default</type><block>Mage_Checkout_Block_Cart_Item_Renderer</block><template>onepage/review/item.phtml</template></action>
+                <action method="addItemRender"><type>grouped</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Grouped</block><template>onepage/review/item.phtml</template></action>
+                <action method="addItemRender"><type>configurable</type><block>Mage_Checkout_Block_Cart_Item_Renderer_Configurable</block><template>onepage/review/item.phtml</template></action>
+                <block type="Mage_Checkout_Block_Cart_Totals" name="checkout.onepage.review.info.totals" as="totals" template="onepage/review/totals.phtml"/>
+                <container name="checkout.onepage.review.info.items.before" as="items_before" label="Items Before"/>
+                <container name="checkout.onepage.review.info.items.after" as="items_after" label="Items After"/>
+                <block type="Mage_Checkout_Block_Agreements" name="checkout.onepage.agreements" as="agreements" template="onepage/agreements.phtml"/>
+                <block type="Mage_Core_Block_Template" name="checkout.onepage.review.button" as="button" template="Mage_Checkout::onepage/review/button.phtml"/>
             </block>
-            <block type="Mage_Checkout_Block_Agreements" name="checkout.onepage.agreements" as="agreements" template="onepage/agreements.phtml"/>
-            <block type="Mage_Core_Block_Template" name="checkout.onepage.review.button" as="button" template="Mage_Checkout::onepage/review/button.phtml"/>
-        </block>
+        </reference>
     </checkout_onepage_review>
 
-    <checkout_onepage_success translate="label">
+    <checkout_onepage_success translate="label" type="page" parent="checkout_onepage_index">
         <label>One Page Checkout Success</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-left.phtml</template></action>
@@ -423,7 +402,8 @@ One page checkout order review block
             <block type="Mage_Checkout_Block_Onepage_Success" name="checkout.success" template="success.phtml"/>
         </reference>
     </checkout_onepage_success>
-    <checkout_onepage_failure translate="label">
+
+    <checkout_onepage_failure translate="label" type="page" parent="checkout_onepage_index">
         <label>One Page Checkout Failure</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-left.phtml</template></action>
diff --git a/app/design/frontend/default/modern/Mage_Contacts/layout.xml b/app/design/frontend/default/modern/Mage_Contacts/layout.xml
index a6798c446ac4545a89019f64f27cebb06e30f9fd..4bff5ed630e038675e149decd57fd89a56309d48 100644
--- a/app/design/frontend/default/modern/Mage_Contacts/layout.xml
+++ b/app/design/frontend/default/modern/Mage_Contacts/layout.xml
@@ -32,7 +32,7 @@
         </reference>
     </default>
 
-    <contacts_index_index translate="label">
+    <contacts_index_index translate="label" type="page" parent="cms_page_view">
         <label>Contact Us Form</label>
         <reference name="head">
             <action method="setTitle" translate="title" module="Mage_Contacts"><title>Contact Us</title></action>
diff --git a/app/design/frontend/default/modern/Mage_Customer/layout.xml b/app/design/frontend/default/modern/Mage_Customer/layout.xml
index d38b2f7268d6d5d8147894bcc59d5d8f2e7d9708..37ae5a22540eee1d4571c10d4585afbf42c4fd39 100644
--- a/app/design/frontend/default/modern/Mage_Customer/layout.xml
+++ b/app/design/frontend/default/modern/Mage_Customer/layout.xml
@@ -47,41 +47,19 @@ Default layout, loads most of the pages
 -->
 
     <default>
-        <!-- Mage_Customer -->
         <reference name="top.links">
-            <action method="addLink" translate="label title" module="Mage_Customer"><label>My Account</label><url helper="Mage_Customer_Helper_Data::getAccountUrl"/><title>My Account</title><prepare/><urlParams/><position>10</position></action>
+            <block type="Mage_Customer_Block_Account_Link" name="account_links">
+                <action method="addAccountLink"><target>top.links</target><position>10</position></action>
+                <action method="addAuthLink"><target>top.links</target><position>100</position></action>
+            </block>
         </reference>
     </default>
 
-<!--
-Load this update on every page when customer is logged in
--->
-
-    <customer_logged_in>
-        <reference name="top.links">
-            <action method="addLink" translate="label title" module="Mage_Customer"><label>Log Out</label><url helper="Mage_Customer_Helper_Data::getLogoutUrl"/><title>Log Out</title><prepare/><urlParams/><position>100</position></action>
-        </reference>
-    </customer_logged_in>
-
-<!--
-Load this update on every page when customer is logged out
--->
-
-    <customer_logged_out>
-        <!---<reference name="right">
-            <block type="Mage_Customer_Block_Form_Login" name="customer_form_mini_login" before="-" template="customer/form/mini.login.phtml"/>
-        </reference>-->
-        <reference name="top.links">
-            <action method="addLink" translate="label title" module="Mage_Customer"><label>Log In</label><url helper="Mage_Customer_Helper_Data::getLoginUrl"/><title>Log In</title><prepare/><urlParams/><position>100</position></action>
-        </reference>
-        <remove name="reorder"></remove>
-    </customer_logged_out>
-
 <!--
 Layout for customer login page
 -->
 
-    <customer_account_login translate="label">
+    <customer_account_login translate="label" type="page" parent="customer_account">
         <label>Customer Account Login Form</label>
         <!-- Mage_Customer -->
         <remove name="right"/>
@@ -99,7 +77,7 @@ Layout for customer login page
 Layout for customer log out page
 -->
 
-    <customer_account_logoutsuccess translate="label">
+    <customer_account_logoutsuccess translate="label" type="page" parent="customer_account">
         <label>Customer Account Logout Success</label>
         <!-- Mage_Customer -->
         <remove name="right"/>
@@ -117,7 +95,7 @@ Layout for customer log out page
 New customer registration
 -->
 
-    <customer_account_create translate="label">
+    <customer_account_create translate="label" type="page" parent="customer_account">
         <label>Customer Account Registration Form</label>
         <!-- Mage_Customer -->
         <remove name="right"/>
@@ -131,14 +109,12 @@ New customer registration
         </reference>
         <reference name="content">
             <block type="Mage_Customer_Block_Form_Register" name="customer_form_register" template="form/register.phtml">
-                <block type="Mage_Page_Block_Html_Wrapper" name="customer.form.register.fields.before" as="form_fields_before" translate="label">
-                    <label>Form Fields Before</label>
-                </block>
+                <container name="customer.form.register.fields.before" as="form_fields_before" label="Form Fields Before" htmlTag="div"/>
             </block>
         </reference>
     </customer_account_create>
 
-    <customer_account_forgotpassword translate="label">
+    <customer_account_forgotpassword translate="label" type="page" parent="customer_account">
         <label>Customer Forgot Password Form</label>
         <remove name="right"/>
         <remove name="left"/>
@@ -155,7 +131,8 @@ New customer registration
         </reference>
     </customer_account_forgotpassword>
 
-    <customer_account_confirmation>
+    <customer_account_confirmation translate="label" type="page" parent="customer_account">
+        <label>Customer Account Confirmation</label>
         <remove name="right"/>
         <remove name="left"/>
 
@@ -168,7 +145,7 @@ New customer registration
         </reference>
     </customer_account_confirmation>
 
-    <customer_account_edit translate="label">
+    <customer_account_edit translate="label" type="page" parent="customer_account_create">
         <label>Customer Account Edit Form</label>
         <update handle="customer_account"/>
         <reference name="root">
@@ -183,7 +160,7 @@ New customer registration
 Customer account pages, rendered for all tabs in dashboard
 -->
 
-    <customer_account translate="label">
+    <customer_account translate="label" type="page" parent="default">
         <label>Customer My Account (All Pages)</label>
         <!-- Mage_Customer -->
         <reference name="root">
@@ -191,10 +168,7 @@ Customer account pages, rendered for all tabs in dashboard
         </reference>
 
         <reference name="content">
-            <block type="Mage_Page_Block_Html_Wrapper" name="my.account.wrapper" translate="label">
-                <label>My Account Wrapper</label>
-                <action method="setElementClass"><value>my-account</value></action>
-            </block>
+            <container name="my.account.wrapper" label="My Account Wrapper" htmlTag="div" htmlClass="my-account"/>
         </reference>
 
         <reference name="left">
@@ -212,7 +186,7 @@ Customer account pages, rendered for all tabs in dashboard
 Customer account home dashboard layout
 -->
 
-    <customer_account_index translate="label">
+    <customer_account_index translate="label" type="page" parent="customer_account">
         <label>Customer My Account Dashboard</label>
         <update handle="customer_account"/>
         <!-- Mage_Customer -->
@@ -237,7 +211,7 @@ Customer account home dashboard layout
 Customer account address book
 -->
 
-    <customer_address_index translate="label">
+    <customer_address_index translate="label" type="page" parent="customer_account_index">
         <label>Customer My Account Address Book</label>
         <!-- Mage_Customer -->
         <update handle="customer_account"/>
@@ -250,7 +224,7 @@ Customer account address book
 Customer account address edit page
 -->
 
-    <customer_address_form translate="label">
+    <customer_address_form translate="label" type="page" parent="customer_address_index">
         <label>Customer My Account Address Edit Form</label>
         <!-- Mage_Customer -->
         <update handle="customer_account"/>
@@ -262,4 +236,4 @@ Customer account address edit page
         </reference>
     </customer_address_form>
 
-</layout>
\ No newline at end of file
+</layout>
diff --git a/app/design/frontend/default/modern/Mage_Newsletter/layout.xml b/app/design/frontend/default/modern/Mage_Newsletter/layout.xml
index 26944eaa61d7361026713e03c9717793ced14fc8..a78cacff2dc168c43a1884bd288f1750e1fa2e9a 100644
--- a/app/design/frontend/default/modern/Mage_Newsletter/layout.xml
+++ b/app/design/frontend/default/modern/Mage_Newsletter/layout.xml
@@ -52,15 +52,12 @@ Customer account pages, rendered for all tabs in dashboard
         </reference>
     </customer_account>
 
-    <newsletter_manage_index translate="label">
+    <newsletter_manage_index translate="label" type="page" parent="customer_account_index">
         <label>Customer My Account Newsletter Subscriptions</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
             <block type="Mage_Customer_Block_Newsletter" name="customer_newsletter">
-                <block type="Mage_Page_Block_Html_Wrapper" name="customer.newsletter.form.before" as="form_before" translate="label">
-                    <label>Newsletter Subscription Form Before</label>
-                    <action method="setMayBeInvisible"><value>1</value></action>
-                </block>
+                <container name="customer.newsletter.form.before" as="form_before" label="Newsletter Subscription Form Before" htmlTag="div"/>
             </block>
         </reference>
     </newsletter_manage_index>
diff --git a/app/design/frontend/default/modern/Mage_Page/layout.xml b/app/design/frontend/default/modern/Mage_Page/layout.xml
index 264ee3815c5d47a9c18a85e95ea3df374dae70bd..c5a4162ca9a68748774069b9e6e5058bb3d43451 100644
--- a/app/design/frontend/default/modern/Mage_Page/layout.xml
+++ b/app/design/frontend/default/modern/Mage_Page/layout.xml
@@ -30,9 +30,9 @@
 Default layout, loads most of the pages
 -->
 
-    <default translate="label" module="Mage_Page">
+    <default translate="label" module="Mage_Page" type="page">
         <label>All Pages</label>
-        <block type="Mage_Page_Block_Html" name="root" output="toHtml" template="2columns-left.phtml">
+        <block type="Mage_Page_Block_Html" name="root" output="1" template="2columns-left.phtml">
 
             <block type="Mage_Page_Block_Html_Head" name="head" as="head">
                 <action method="addJs"><file>prototype/prototype.js</file></action>
@@ -50,63 +50,50 @@ Default layout, loads most of the pages
                 <action method="addJs"><file>Mage_Page::js/cookies.js</file></action>
             </block>
 
-            <block type="Mage_Core_Block_Text_List" name="after_body_start" as="after_body_start" translate="label">
-                <label>Page Top</label>
-            </block>
+            <container name="after_body_start" as="after_body_start" label="Page Top"/>
 
             <block type="Mage_Page_Block_Html_Notices" name="global_notices" as="global_notices" template="html/notices.phtml" />
 
             <block type="Mage_Page_Block_Html_Header" name="header" as="header">
-                <block type="Mage_Core_Block_Text_List" name="top.menu" as="topMenu" translate="label">
-                    <label>Navigation Bar</label>
-                </block>
+                <container name="top.menu" as="topMenu" label="Navigation Bar">
+                    <block type="Mage_Page_Block_Html_Topmenu" name="catalog.topnav" template="html/topmenu.phtml"/>
+                </container>
                 <block type="Mage_Page_Block_Switch" name="store_language" as="store_language" template="switch/languages.phtml"/>
                 <block type="Mage_Page_Block_Template_Links" name="top.links" as="topLinks"/>
-                <block type="Mage_Page_Block_Html_Wrapper" name="top.bar" as="topBar" translate="label">
-                    <label>Breadcrumbs</label>
-                    <action method="setElementClass"><value>top-bar</value></action>
+                <container name="top.bar" as="topBar" label="Breadcrumbs" htmlTag="div" htmlClass="top-bar">
                     <block type="Mage_Page_Block_Html_Breadcrumbs" name="breadcrumbs" as="breadcrumbs"/>
-                </block>
-                <block type="Mage_Page_Block_Html_Wrapper" name="top.container" as="topContainer" translate="label">
-                    <label>Page Header</label>
-                    <action method="setElementClass"><value>top-container</value></action>
-                </block>
+                </container>
+                <container name="top.container" as="topContainer" label="Page Header" htmlTag="div" htmlClass="top-container"/>
             </block>
 
-            <block type="Mage_Core_Block_Text_List" name="left" as="left" translate="label">
-                <label>Left Column</label>
-            </block>
+            <container name="left" as="left" label="Left Column"/>
 
             <block type="Mage_Core_Block_Messages" name="global_messages" as="global_messages"/>
             <block type="Mage_Core_Block_Messages" name="messages" as="messages"/>
 
-            <block type="Mage_Core_Block_Text_List" name="content" as="content" translate="label">
-                <label>Main Content Area</label>
-            </block>
+            <container name="content" as="content" label="Main Content Area"/>
 
-            <block type="Mage_Core_Block_Text_List" name="right" as="right" translate="label">
-                <label>Right Column</label>
-            </block>
+            <container name="right" as="right" label="Right Column"/>
 
             <block type="Mage_Page_Block_Html_Footer" name="footer" as="footer" template="html/footer.phtml">
-                <block type="Mage_Page_Block_Html_Wrapper" name="bottom.container" as="bottomContainer" translate="label">
-                    <label>Page Footer</label>
-                    <action method="setElementClass"><value>bottom-container</value></action>
-                </block>
+                <container name="bottom.container" as="bottomContainer" label="Page Footer" htmlTag="div" htmlClass="bottom-container"/>
                 <block type="Mage_Page_Block_Template_Links" name="footer_links" as="footer_links" template="template/links.phtml"/>
                 <block type="Mage_Page_Block_Switch" name="store_switcher" as="store_switcher" template="switch/stores.phtml"/>
             </block>
 
-            <block type="Mage_Core_Block_Text_List" name="before_body_end" as="before_body_end" translate="label">
-                <label>Page Bottom</label>
-            </block>
+            <container name="before_body_end" as="before_body_end" label="Page Bottom"/>
         </block>
     </default>
 
-    <print translate="label" module="Mage_Page">
+    <ajax_index translate="label" type="page">
+        <label>Dynamic Page Blocks (Updated by Ajax Request)</label>
+        <block type="Mage_Page_Block_Html" name="root" output="1" template="page_part.phtml"/>
+    </ajax_index>
+
+    <print translate="label" module="Mage_Page" type="page">
         <label>All Pages (Print Version)</label>
         <!-- Mage_Page -->
-        <block type="Mage_Page_Block_Html" name="root" output="toHtml" template="print.phtml">
+        <block type="Mage_Page_Block_Html" name="root" output="1" template="print.phtml">
 
             <block type="Mage_Page_Block_Html_Head" name="head" as="head">
                 <action method="addJs"><file>prototype/prototype.js</file></action>
@@ -116,15 +103,15 @@ Default layout, loads most of the pages
                 <action method="addJs"><file>varien/js.js</file></action>
             </block>
 
-            <block type="Mage_Core_Block_Text_List" name="content" as="content" translate="label">
-                <label>Main Content Area</label>
-            </block>
+            <container name="after_body_start" as="after_body_start" label="Page Top"/>
+
+            <container name="content" as="content" label="Main Content Area"/>
 
         </block>
     </print>
 
      <!-- Custom page layout handles -->
-    <page_empty translate="label">
+    <page_empty translate="label" type="page" parent="default">
         <label>All Empty Layout Pages</label>
         <reference name="root">
             <action method="setTemplate"><template>empty.phtml</template></action>
@@ -134,7 +121,7 @@ Default layout, loads most of the pages
         </reference>
     </page_empty>
 
-    <page_one_column translate="label">
+    <page_one_column translate="label" type="page" parent="default">
         <label>All One-Column Layout Pages</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -144,7 +131,7 @@ Default layout, loads most of the pages
         </reference>
     </page_one_column>
 
-    <page_two_columns_left translate="label">
+    <page_two_columns_left translate="label" type="page" parent="default">
         <label>All Two-Column Layout Pages (Left Column)</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-left.phtml</template></action>
@@ -154,7 +141,7 @@ Default layout, loads most of the pages
         </reference>
     </page_two_columns_left>
 
-    <page_two_columns_right translate="label">
+    <page_two_columns_right translate="label" type="page" parent="default">
         <label>All Two-Column Layout Pages (Right Column)</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-right.phtml</template></action>
@@ -164,7 +151,7 @@ Default layout, loads most of the pages
         </reference>
     </page_two_columns_right>
 
-    <page_three_columns translate="label">
+    <page_three_columns translate="label" type="page" parent="default">
         <label>All Three-Column Layout Pages</label>
         <reference name="root">
             <action method="setTemplate"><template>3columns.phtml</template></action>
diff --git a/app/design/frontend/default/modern/Mage_Persistent/layout.xml b/app/design/frontend/default/modern/Mage_Persistent/layout.xml
index fcd528af940aa431d987a1e9d706cc2f76186fbb..57294ff6257c02255afedfe5221a95b2ea3bacf5 100644
--- a/app/design/frontend/default/modern/Mage_Persistent/layout.xml
+++ b/app/design/frontend/default/modern/Mage_Persistent/layout.xml
@@ -26,12 +26,6 @@
  */
 -->
 <layout version="0.1.0">
-    <customer_logged_out_psc_handle>
-        <reference name="top.links">
-            <action method="addLink" translate="label title" module="Mage_Persistent"><label helper="Mage_Persistent_Helper_Data::getPersistentName"/><url helper="Mage_Persistent_Helper_Data::getUnsetCookieUrl"/><title helper="Mage_Persistent_Helper_Data::getPersistentName"/><prepare/><urlParams/><position>9</position></action>
-        </reference>
-    </customer_logged_out_psc_handle>
-
     <customer_account_login>
         <reference name="customer_form_login">
             <action method="setTemplate"><template>Mage_Persistent::customer/form/login.phtml</template></action>
diff --git a/app/design/frontend/default/modern/Mage_Review/layout.xml b/app/design/frontend/default/modern/Mage_Review/layout.xml
index 5d74aa94c124a3980d223b764f4ad6e71316b89f..821b1dc7dbaec57c9aeb32de55c2f394e2b9c58c 100644
--- a/app/design/frontend/default/modern/Mage_Review/layout.xml
+++ b/app/design/frontend/default/modern/Mage_Review/layout.xml
@@ -66,7 +66,7 @@ Product reviews page (?)
 Product reviews page
 -->
 
-    <review_product_list translate="label">
+    <review_product_list translate="label" type="page" parent="default">
         <label>Catalog Product Reviews List</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-left.phtml</template></action>
@@ -83,12 +83,11 @@ Product reviews page
                 <block type="Mage_Catalog_Block_Product_View" name="product.info.addto" as="addto" template="product/view/addto.phtml"/>
                 <block type="Mage_Catalog_Block_Product_View" name="product.info.addtocart" as="addtocart" template="product/view/addtocart.phtml">
                     <!-- workaround: a better place for this code is in paypal.xml -->
-                    <block type="Mage_Page_Block_Html_Wrapper" name="review.product.info.addtocart.paypal.wrapper" translate="label" module="Mage_Paypal">
-                        <label>PayPal Express Checkout Shortcut Wrapper</label>
+                    <container name="review.product.info.addtocart.paypal.wrapper" label="PayPal Express Checkout Shortcut Wrapper" module="Mage_Paypal" htmlTag="div">
                         <block type="Mage_Paypal_Block_Express_Shortcut" name="review.product.info.addtocart.paypal" template="express/shortcut.phtml">
                             <action method="setIsInCatalogProduct"><value>1</value></action>
                         </block>
-                    </block>
+                    </container>
                 </block>
                 <block type="Mage_Catalog_Block_Product_View" name="product.tierprices" as="tierprices" template="product/view/tierprices.phtml"/>
                 <block type="Mage_Core_Block_Template" name="product.info.other" as="other" template="Mage_Review::product/view/other.phtml"/>
@@ -96,17 +95,14 @@ Product reviews page
                 <block type="Mage_Core_Block_Template" name="product_review_list.count" template="Mage_Review::product/view/count.phtml" />
                 <block type="Mage_Review_Block_Product_View_List" name="product.info.product_additional_data" as="product_additional_data" template="product/view/list.phtml">
                     <block type="Mage_Review_Block_Form" name="product.review.form" as="review_form">
-                        <block type="Mage_Page_Block_Html_Wrapper" name="product.review.form.fields.before" as="form_fields_before" translate="label">
-                            <label>Review Form Fields Before</label>
-                            <action method="setMayBeInvisible"><value>1</value></action>
-                        </block>
+                        <container name="product.review.form.fields.before" as="form_fields_before" label="Review Form Fields Before" htmlTag="div"/>
                     </block>
                 </block>
             </block>
         </reference>
     </review_product_list>
 
-    <review_product_view translate="label">
+    <review_product_view translate="label" type="page" parent="review_product_list">
         <label>Catalog Product Review View</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-left.phtml</template></action>
@@ -116,7 +112,7 @@ Product reviews page
         </reference>
     </review_product_view>
 
-    <review_customer_index translate="label">
+    <review_customer_index translate="label" type="page" parent="customer_account_index">
         <label>Customer My Account Product Reviews</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
@@ -124,7 +120,7 @@ Product reviews page
         </reference>
     </review_customer_index>
 
-    <review_customer_view translate="label">
+    <review_customer_view translate="label" type="page" parent="review_customer_index">
         <label>Customer My Account Review Details</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
diff --git a/app/design/frontend/default/modern/Mage_Rss/layout.xml b/app/design/frontend/default/modern/Mage_Rss/layout.xml
index 8568f092c1057963e3c32179e8bac9c7e66adaed..704ba52ff1c4f24d7e4a35c307c51e06e89e3183 100644
--- a/app/design/frontend/default/modern/Mage_Rss/layout.xml
+++ b/app/design/frontend/default/modern/Mage_Rss/layout.xml
@@ -35,7 +35,7 @@
 <!--
 Default layout, loads most of the pages
 -->
-    <rss_index_index translate="label">
+    <rss_index_index translate="label" type="page" parent="default">
         <label>RSS Feeds List</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-left.phtml</template></action>
@@ -45,50 +45,47 @@ Default layout, loads most of the pages
         </reference>
     </rss_index_index>
 
-    <rss_index_nofeed>
-        <block type="Mage_Core_Block_Template" name="root" output="toHtml" template="Mage_Rss::nofeed.phtml"/>
+    <rss_index_nofeed translate="label" type="page" parent="rss_index_index">
+        <label>RSS No Feed</label>
+        <block type="Mage_Core_Block_Template" name="root" output="1" template="Mage_Rss::nofeed.phtml"/>
     </rss_index_nofeed>
 
-    <rss_index_wishlist>
-        <block type="Mage_Rss_Block_Wishlist" name="rss.wishlist" output="toHtml"/>
+    <rss_index_wishlist translate="label" type="page" parent="rss_index_index">
+        <label>RSS Wishlist</label>
+        <block type="Mage_Rss_Block_Wishlist" name="rss.wishlist" output="1"/>
     </rss_index_wishlist>
 <!--
 Catalog layout
 -->
-    <rss_catalog_new>
-        <block type="Mage_Rss_Block_Catalog_New" output="toHtml" name="rss.catalog.new"/>
+    <rss_catalog_new translate="label" type="page" parent="rss_index_index">
+        <label>RSS New</label>
+        <block type="Mage_Rss_Block_Catalog_New" output="1" name="rss.catalog.new"/>
     </rss_catalog_new>
 
-    <rss_catalog_special>
-        <block type="Mage_Rss_Block_Catalog_Special" output="toHtml" name="rss.catalog.special"/>
+    <rss_catalog_special translate="label" type="page" parent="rss_catalog_new">
+        <label>RSS Special</label>
+        <block type="Mage_Rss_Block_Catalog_Special" output="1" name="rss.catalog.special"/>
     </rss_catalog_special>
 
-    <rss_catalog_salesrule>
-        <block type="Mage_Rss_Block_Catalog_Salesrule" output="toHtml" name="rss.catalog.salesrule"/>
+    <rss_catalog_salesrule translate="label" type="page" parent="rss_catalog_new">
+        <label>RSS Sales Rule</label>
+        <block type="Mage_Rss_Block_Catalog_Salesrule" output="1" name="rss.catalog.salesrule"/>
     </rss_catalog_salesrule>
 
-    <rss_catalog_tag>
-        <block type="Mage_Rss_Block_Catalog_Tag" output="toHtml" name="rss.catalog.tag" />
+    <rss_catalog_tag translate="label" type="page" parent="rss_catalog_new">
+        <label>RSS Tag</label>
+        <block type="Mage_Rss_Block_Catalog_Tag" output="1" name="rss.catalog.tag" />
     </rss_catalog_tag>
 
-    <rss_catalog_notifystock>
-        <block type="Mage_Rss_Block_Catalog_NotifyStock" output="toHtml" name="rss.catalog.notifystock" />
-    </rss_catalog_notifystock>
-
-    <rss_catalog_review>
-        <block type="Mage_Rss_Block_Catalog_Review" output="toHtml" name="rss.catalog.review" />
-    </rss_catalog_review>
-
-    <rss_catalog_category>
-        <block type="Mage_Rss_Block_Catalog_Category" output="toHtml" name="rss.catalog.category" />
+    <rss_catalog_category translate="label" type="page" parent="rss_catalog_new">
+        <label>RSS Catalog Category</label>
+        <block type="Mage_Rss_Block_Catalog_Category" output="1" name="rss.catalog.category" />
     </rss_catalog_category>
 <!--
 Order layout
 -->
-    <rss_order_new>
-        <block type="Mage_Rss_Block_Order_New" output="toHtml" name="rss.order.new"/>
-    </rss_order_new>
-    <rss_order_status>
-        <block type="Mage_Rss_Block_Order_Status" output="toHtml" name="rss.order.status"/>
+    <rss_order_status translate="label" type="page" parent="rss_index_index">
+        <label>RSS Order Status</label>
+        <block type="Mage_Rss_Block_Order_Status" output="1" name="rss.order.status"/>
     </rss_order_status>
 </layout>
diff --git a/app/design/frontend/default/modern/Mage_Sales/layout.xml b/app/design/frontend/default/modern/Mage_Sales/layout.xml
index 7fd68aae47674844b68f1d42699116a724b8a53b..725507f3df537ea18dea67091f5f2f5cfc901ca4 100644
--- a/app/design/frontend/default/modern/Mage_Sales/layout.xml
+++ b/app/design/frontend/default/modern/Mage_Sales/layout.xml
@@ -31,13 +31,11 @@
 <!--
 Customer account pages, rendered for all tabs in dashboard
 -->
-
-
-    <customer_logged_in>
+    <default>
         <reference name="left">
             <block type="Mage_Sales_Block_Reorder_Sidebar" name="sale.reorder.sidebar" as="reorder" template="reorder/sidebar.phtml"/>
         </reference>
-    </customer_logged_in>
+    </default>
     <checkout_onepage_index>
         <remove name="sale.reorder.sidebar"/>
     </checkout_onepage_index>
@@ -68,21 +66,19 @@ Customer account home dashboard layout
 
     </customer_account_index>
 
-    <sales_order_history translate="label">
+    <sales_order_history translate="label" type="page" parent="sales_order_view">
         <label>Customer My Account Order History</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
             <block type="Mage_Sales_Block_Order_History" name="sales.order.history">
-                <block type="Mage_Core_Block_Text_List" name="sales.order.history.info" as="info" translate="label">
-                    <label>Order History Info</label>
-                </block>
+                <container name="sales.order.history.info" as="info" label="Order History Info"/>
             </block>
             <block type="Mage_Customer_Block_Account_Dashboard" name="customer.account.link.back" template="account/link/back.phtml"/>
         </reference>
     </sales_order_history>
 
 
-    <sales_order_view translate="label">
+    <sales_order_view translate="label" type="page" parent="default">
         <label>Customer My Account Order View</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
@@ -109,7 +105,7 @@ Customer account home dashboard layout
         </reference>
     </sales_order_view>
 
-    <sales_order_invoice translate="label">
+    <sales_order_invoice translate="label" type="page" parent="sales_order_view">
         <label>Customer My Account Order Invoice View</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
@@ -137,7 +133,7 @@ Customer account home dashboard layout
         </reference>
     </sales_order_invoice>
 
-    <sales_order_shipment translate="label">
+    <sales_order_shipment translate="label" type="page" parent="sales_order_view">
         <label>Customer My Account Order Shipment View</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
@@ -159,7 +155,7 @@ Customer account home dashboard layout
         </reference>
     </sales_order_shipment>
 
-    <sales_order_creditmemo translate="label">
+    <sales_order_creditmemo translate="label" type="page" parent="sales_order_view">
         <label>Customer My Account Order Creditmemo View</label>
         <update handle="customer_account"/>
         <reference name="my.account.wrapper">
@@ -187,14 +183,15 @@ Customer account home dashboard layout
         </reference>
     </sales_order_creditmemo>
 
-    <sales_order_reorder>
+    <sales_order_reorder translate="label" type="page" parent="sales_order_view">
+        <label>Sales Reorder</label>
         <update handle="customer_account"/>
         <reference name="content">
             <block type="Mage_Sales_Block_Order_View" name="sales.order.view"/>
         </reference>
     </sales_order_reorder>
 
-    <sales_order_print translate="label">
+    <sales_order_print translate="label" type="page" parent="print">
         <label>Sales Order Print View</label>
         <reference name="content">
             <block type="Mage_Sales_Block_Order_Print" name="sales.order.print" template="order/print.phtml">
@@ -211,7 +208,7 @@ Customer account home dashboard layout
         </reference>
     </sales_order_print>
 
-    <sales_order_printinvoice translate="label">
+    <sales_order_printinvoice translate="label" type="page" parent="sales_order_print">
         <label>Sales Invoice Print View</label>
         <reference name="content">
             <block type="Mage_Sales_Block_Order_Print_Invoice" name="sales.order.print.invoice" template="order/print/invoice.phtml">
@@ -226,7 +223,7 @@ Customer account home dashboard layout
         </reference>
     </sales_order_printinvoice>
 
-    <sales_order_printshipment translate="label">
+    <sales_order_printshipment translate="label" type="page" parent="sales_order_print">
         <label>Sales Shipment Print View</label>
         <reference name="content">
             <block type="Mage_Sales_Block_Order_Print_Shipment" name="sales.order.print.shipment" template="order/print/shipment.phtml">
@@ -235,7 +232,8 @@ Customer account home dashboard layout
         </reference>
     </sales_order_printshipment>
 
-    <sales_order_printcreditmemo>
+    <sales_order_printcreditmemo translate="label" type="page" parent="sales_order_print">
+        <label>Sales Creditmemo Print View</label>
         <reference name="content">
             <block type="Mage_Sales_Block_Order_Print_Creditmemo" name="sales.order.print.creditmemo" template="order/print/creditmemo.phtml">
                 <action method="addItemRender"><type>default</type><block>Mage_Sales_Block_Order_Item_Renderer_Default</block><template>order/creditmemo/items/renderer/default.phtml</template></action>
@@ -252,7 +250,8 @@ Customer account home dashboard layout
 <!--
 Email layouts section
 -->
-    <sales_email_order_items>
+    <sales_email_order_items translate="label" type="page" parent="sales_order_view">
+        <label>Email Order Items List</label>
         <block type="Mage_Sales_Block_Order_Email_Items" name="items" template="email/items.phtml">
             <action method="addItemRender"><type>default</type><block>Mage_Sales_Block_Order_Email_Items_Order_Default</block><template>email/items/order/default.phtml</template></action>
             <action method="addItemRender"><type>grouped</type><block>Mage_Sales_Block_Order_Email_Items_Order_Grouped</block><template>email/items/order/default.phtml</template></action>
@@ -266,7 +265,8 @@ Email layouts section
         </block>
     </sales_email_order_items>
 
-    <sales_email_order_invoice_items>
+    <sales_email_order_invoice_items translate="label" type="page" parent="sales_order_invoice">
+        <label>Email Invoice Items List</label>
         <block type="Mage_Sales_Block_Order_Email_Invoice_Items" name="items" template="email/invoice/items.phtml">
             <action method="addItemRender"><type>default</type><block>Mage_Sales_Block_Order_Email_Items_Default</block><template>email/items/invoice/default.phtml</template></action>
             <action method="addItemRender"><type>grouped</type><block>Mage_Sales_Block_Order_Email_Items_Order_Grouped</block><template>email/items/invoice/default.phtml</template></action>
@@ -278,13 +278,15 @@ Email layouts section
         </block>
     </sales_email_order_invoice_items>
 
-    <sales_email_order_shipment_items>
+    <sales_email_order_shipment_items translate="label" type="page" parent="sales_order_shipment">
+        <label>Email Shipment Items List</label>
         <block type="Mage_Sales_Block_Order_Email_Shipment_Items" name="items" template="email/shipment/items.phtml">
             <action method="addItemRender"><type>default</type><block>Mage_Sales_Block_Order_Email_Items_Default</block><template>email/items/shipment/default.phtml</template></action>
         </block>
     </sales_email_order_shipment_items>
 
-    <sales_email_order_creditmemo_items>
+    <sales_email_order_creditmemo_items translate="label" type="page" parent="sales_order_creditmemo">
+        <label>Email Creditmemo Items List</label>
         <block type="Mage_Sales_Block_Order_Email_Creditmemo_Items" name="items" template="email/creditmemo/items.phtml">
             <action method="addItemRender"><type>default</type><block>Mage_Sales_Block_Order_Email_Items_Default</block><template>email/items/creditmemo/default.phtml</template></action>
             <action method="addItemRender"><type>grouped</type><block>Mage_Sales_Block_Order_Email_Items_Order_Grouped</block><template>email/items/creditmemo/default.phtml</template></action>
@@ -300,7 +302,7 @@ Email layouts section
 Guest
 -->
 
-    <sales_guest_form translate="label">
+    <sales_guest_form translate="label" type="page" parent="sales_guest_view">
         <label>Returns</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -311,7 +313,7 @@ Guest
     </sales_guest_form>
 
 
-    <sales_guest_view translate="label">
+    <sales_guest_view translate="label" type="page" parent="default">
         <label>Customer My Account Order View</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -340,7 +342,7 @@ Guest
         </reference>
     </sales_guest_view>
 
-    <sales_guest_invoice translate="label">
+    <sales_guest_invoice translate="label" type="page" parent="sales_guest_view">
         <label>Customer My Account Order Invoice View</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -370,7 +372,7 @@ Guest
         </reference>
     </sales_guest_invoice>
 
-    <sales_guest_shipment translate="label">
+    <sales_guest_shipment translate="label" type="page" parent="sales_guest_view">
         <label>Customer My Account Order Shipment View</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -394,7 +396,7 @@ Guest
         </reference>
     </sales_guest_shipment>
 
-    <sales_guest_creditmemo translate="label">
+    <sales_guest_creditmemo translate="label" type="page" parent="sales_guest_view">
         <label>Customer My Account Order Creditmemo View</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
@@ -424,7 +426,8 @@ Guest
         </reference>
     </sales_guest_creditmemo>
 
-    <sales_guest_reorder>
+    <sales_guest_reorder translate="label" type="page" parent="sales_guest_view">
+        <label>Sales Guest Reorder</label>
         <reference name="root">
             <action method="setTemplate"><template>1column.phtml</template></action>
         </reference>
@@ -433,7 +436,7 @@ Guest
         </reference>
     </sales_guest_reorder>
 
-    <sales_guest_print translate="label">
+    <sales_guest_print translate="label" type="page" parent="print">
         <label>Sales Order Print View</label>
         <reference name="content">
             <block type="Mage_Sales_Block_Order_Print" name="sales.order.print" template="order/print.phtml">
@@ -450,7 +453,7 @@ Guest
         </reference>
     </sales_guest_print>
 
-    <sales_guest_printinvoice translate="label">
+    <sales_guest_printinvoice translate="label" type="page" parent="sales_guest_print">
         <label>Sales Invoice Print View</label>
         <reference name="content">
             <block type="Mage_Sales_Block_Order_Print_Invoice" name="sales.order.print.invoice" template="order/print/invoice.phtml">
@@ -465,7 +468,7 @@ Guest
         </reference>
     </sales_guest_printinvoice>
 
-    <sales_guest_printshipment translate="label">
+    <sales_guest_printshipment translate="label" type="page" parent="sales_guest_print">
         <label>Sales Shipment Print View</label>
         <reference name="content">
             <block type="Mage_Sales_Block_Order_Print_Shipment" name="sales.order.print.shipment" template="order/print/shipment.phtml">
@@ -474,7 +477,8 @@ Guest
         </reference>
     </sales_guest_printshipment>
 
-    <sales_guest_printcreditmemo>
+    <sales_guest_printcreditmemo translate="label" type="page" parent="sales_guest_print">
+        <label>Sales Creditmemo Print View</label>
         <reference name="content">
             <block type="Mage_Sales_Block_Order_Print_Creditmemo" name="sales.order.print.creditmemo" template="order/print/creditmemo.phtml">
                 <action method="addItemRender"><type>default</type><block>Mage_Sales_Block_Order_Item_Renderer_Default</block><template>order/creditmemo/items/renderer/default.phtml</template></action>
diff --git a/app/design/frontend/default/modern/Mage_Sendfriend/layout.xml b/app/design/frontend/default/modern/Mage_Sendfriend/layout.xml
index befd58dd9c4e8b74a8f4d5415406d2b5339c05e6..337d7120668ff884226929c74ec54f6f6c13df36 100644
--- a/app/design/frontend/default/modern/Mage_Sendfriend/layout.xml
+++ b/app/design/frontend/default/modern/Mage_Sendfriend/layout.xml
@@ -26,7 +26,7 @@
  */
 -->
 <layout version="0.1.0">
-    <sendfriend_product_send translate="label">
+    <sendfriend_product_send translate="label" type="page" parent="catalog_product_view">
         <label>Catalog Product Email to a Friend</label>
         <reference name="root">
             <action method="setTemplate"><template>2columns-left.phtml</template></action>
diff --git a/app/design/frontend/default/modern/Mage_Tag/layout.xml b/app/design/frontend/default/modern/Mage_Tag/layout.xml
index b91487556ea0b521f4ee1fef3324f7a520c79d54..8adae8eec34487c2c4b1a1b9e1cc000fe6762fc4 100644
--- a/app/design/frontend/default/modern/Mage_Tag/layout.xml
+++ b/app/design/frontend/default/modern/Mage_Tag/layout.xml
@@ -70,10 +70,7 @@ Customer account home dashboard layout
             <action method="addTab" translate="title" module="Mage_Tag"><alias>product.tags</alias><title>Product Tags</title><block>Mage_Tag_Block_Product_List</block><template>list.phtml</template></action>
         </reference>
         <reference name="product.tags">
-            <block type="Mage_Page_Block_Html_Wrapper" name="product.tag.list.list.before" as="list_before" translate="label">
-                <label>Tags List Before</label>
-                <action method="setMayBeInvisible"><value>1</value></action>
-            </block>
+            <container name="product.tag.list.list.before" as="list_before" label="Tags List Before" htmlTag="div"/>
         </reference>
     </catalog_product_view>
 
@@ -81,7 +78,7 @@ Customer account home dashboard layout
 All tags page
 -->
 
-    <tag_list_index translate="label">
+    <tag_list_index translate="label" type="page" parent="default">
         <label>Tags List (All Available)</label>
         <!-- Mage_Tag -->
         <reference name="root">
@@ -92,7 +89,7 @@ All tags page
         </reference>
     </tag_list_index>
 
-    <tag_product_list translate="label">
+    <tag_product_list translate="label" type="page" parent="tag_list_index">
         <label>Tagged Products List</label>
         <!-- Mage_Tag -->
         <reference name="content">
@@ -110,7 +107,7 @@ All tags page
         </reference>
     </tag_product_list>
 
-    <tag_customer_index translate="label">
+    <tag_customer_index translate="label" type="page" parent="tag_list_index">
         <label>Customer My Account My Tags List</label>
         <update handle="customer_account"/>
         <reference name="root">
@@ -121,7 +118,7 @@ All tags page
         </reference>
     </tag_customer_index>
 
-    <tag_customer_view translate="label">
+    <tag_customer_view translate="label" type="page" parent="tag_customer_index">
         <label>Customer My Account Tag View</label>
         <update handle="customer_account"/>
         <reference name="root">
diff --git a/app/design/frontend/default/modern/Mage_Wishlist/layout.xml b/app/design/frontend/default/modern/Mage_Wishlist/layout.xml
index 76d8ec45ea3db486b76b6f4367fe47a3647b5526..c18223c6b4a60c3f3fcb01a6ce908ceeeade7353 100644
--- a/app/design/frontend/default/modern/Mage_Wishlist/layout.xml
+++ b/app/design/frontend/default/modern/Mage_Wishlist/layout.xml
@@ -72,7 +72,7 @@ Customer account home dashboard layout
 Wishlist pages
 -->
 
-    <wishlist_index_index translate="label">
+    <wishlist_index_index translate="label" type="page" parent="customer_account_index">
         <label>Customer My Account My Wishlist</label>
         <!-- Mage_Wishlist -->
         <update handle="customer_account"/>
@@ -84,7 +84,7 @@ Wishlist pages
         </reference>
     </wishlist_index_index>
 
-    <wishlist_index_share translate="label">
+    <wishlist_index_share translate="label" type="page" parent="wishlist_index_index">
         <label>Customer My Account Wishlist Sharing Form</label>
         <!-- Mage_Wishlist -->
         <update handle="customer_account"/>
@@ -96,7 +96,7 @@ Wishlist pages
         </reference>
     </wishlist_index_share>
 
-    <wishlist_index_configure translate="label">
+    <wishlist_index_configure translate="label" type="page" parent="wishlist_index_index">
         <label>Configure Wishlist Item</label>
         <update handle="catalog_product_view"/>
         <reference name="product.info">
@@ -108,7 +108,7 @@ Wishlist pages
         </reference>
     </wishlist_index_configure>
 
-    <wishlist_shared_index translate="label">
+    <wishlist_shared_index translate="label" type="page" parent="wishlist_index_share">
         <label>Customer Shared Wishlist View</label>
         <!-- Mage_Wishlist -->
         <reference name="content">
diff --git a/app/design/frontend/default/modern/skin/default/images/logo_email.gif b/app/design/frontend/default/modern/skin/default/Mage_Core/logo_email.gif
similarity index 100%
rename from app/design/frontend/default/modern/skin/default/images/logo_email.gif
rename to app/design/frontend/default/modern/skin/default/Mage_Core/logo_email.gif
diff --git a/app/design/frontend/default/modern/skin/default/css/styles.css b/app/design/frontend/default/modern/skin/default/css/styles.css
index f66070fca801d51b92a684b9ce357a0a5b5d2b1d..530ade3180454706ad3df1e22c4006ecd02539b6 100644
--- a/app/design/frontend/default/modern/skin/default/css/styles.css
+++ b/app/design/frontend/default/modern/skin/default/css/styles.css
@@ -189,6 +189,14 @@ p.control input.radio { margin-right:6px; }
 .form-list li.additional-row { border-top:1px solid #ccc; margin-top:10px; padding-top:7px; }
 .form-list li.additional-row .btn-remove { float:right; margin:5px 0 0; }
 .form-list .input-range input.input-text { width:74px; }
+
+.form-list-narrow li  { margin-bottom:0; } 
+.form-list-narrow li .input-box { margin-bottom:6px; } 
+.form-list-narrow li.wide .input-box { width:260px; } 
+.form-list-narrow li.wide input.input-text, 
+.form-list-narrow li.wide textarea { width:254px } 
+.form-list-narrow li.wide select { width:260px; }
+
 /* Customer */
 .form-list .customer-name-prefix .input-box,
 .form-list .customer-name-suffix .input-box,
@@ -434,6 +442,7 @@ tr.summary-details-excluded { font-style:italic; }
 .link-print { /*background:url(../images/i_print.gif) 0 2px no-repeat; padding:3px 0 3px 25px;*/ }
 .link-rss { background:url(../images/i_rss.gif) 0 1px no-repeat; padding-left:18px; line-height:14px; white-space:nowrap; }
 .btn-remove { display:block; width:12px; height:12px; font-size:0; line-height:0; background:url(../images/btn_remove.gif) 0 0 no-repeat; text-indent:-999em; overflow:hidden; }
+.btn-previous { display:block; width:12px; height:12px; font-size:0; line-height:0; background:url(../images/btn_previous.gif) 0 0 no-repeat; text-indent:-999em; overflow:hidden; }
 .btn-remove2 { display:block; width:16px; height:16px; font-size:0; line-height:0; background:url(../images/btn_trash.gif) 0 0 no-repeat; text-indent:-999em; overflow:hidden; }
 .btn-edit    { display:block; width:12px; height:12px; font-size:0; line-height:0; background:url(../images/btn_edit.gif) 0 0 no-repeat; text-indent:-999em; overflow:hidden; }
 
@@ -444,13 +453,23 @@ tr.summary-details-excluded { font-style:italic; }
 
 .divider { clear:both; display:block; font-size:0; line-height:0; height:1px; background:#ccc; margin:10px 0; text-indent:-999em; overflow:hidden; }
 
+/* Global site notices */
+.global-site-notice { border:1px solid #cfcfcf; border-width:0 0 1px; background:#ffff90; font-size:12px; line-height:1.25; text-align:center; color:#2f2f2f; }
+.global-site-notice .notice-inner { width:860px; margin:0 auto; padding:12px 0 12px 80px; background:url(../images/i_notice.gif) 20px 25px no-repeat; text-align:left; }
+.global-site-notice .notice-inner p { margin:0; border:1px dotted #cccc73; padding:10px; }
+.global-site-notice .notice-inner .actions { padding-top:10px; }
+
+/* Cookie Notice */
+.notice-cookie { }
+
 /* Noscript Notice */
-.noscript { border:1px solid #ddd; border-width:0 0 1px; background:#ffff90; font-size:12px; line-height:1.25; text-align:center; color:#2f2f2f; }
-.noscript .noscript-inner { width:950px; margin:0 auto; padding:12px 0 12px; background:url(../images/i_notice.gif) 20px 50% no-repeat; }
-.noscript p { margin:0; }
+.noscript {}
 
 /* Demo Notice */
-.demo-notice { margin:0; padding:6px 10px; background:#d75f07; font-size:11px; line-height:1.15; text-align:center; color:#fff; }
+.demo-notice { margin:0; padding:6px 10px; background:#d75f07; font-size:12px; line-height:1.15; border:0; text-align:center; color:#fff; }
+.demo-notice .notice-inner { width:auto; padding:0; background:none; text-align:center; }
+.demo-notice .notice-inner p { padding:0; border:0; }
+
 /* ======================================================================================= */
 
 
@@ -604,9 +623,12 @@ tr.summary-details-excluded { font-style:italic; }
 .block-layered-nav dd li { line-height:1.35; margin:0 0 3px; }
 .block-layered-nav dd a { color:#444; }
 .block-layered-nav .currently ol { padding:6px 0 0; }
-.block-layered-nav .currently li { padding:2px 10px; }
-.block-layered-nav .currently .label { font-weight:bold; }
-.block-layered-nav .currently .btn-remove { margin:2px 0 0; }
+.block-layered-nav .currently li { padding:2px 36px 2px 10px; position:relative; z-index:1; }
+.block-layered-nav .currently .label { font-weight:bold; display:inline-block; vertical-align:top; }
+.block-layered-nav .currently .value { display:inline-block; vertical-align:top; }
+.block-layered-nav .currently .btn-previous,
+.block-layered-nav .currently .btn-remove { position:absolute; right:8px; top:3px; margin:0; }
+.block-layered-nav .currently .btn-previous { right:22px; }
 .block-layered-nav .actions { padding:5px 10px; margin:0; }
 .block-layered-nav .actions a { float:none; }
 
@@ -863,9 +885,10 @@ tr.summary-details-excluded { font-style:italic; }
 .price-box-bundle { padding:0 0 10px 0; }
 .price-box-bundle .price-box { margin:0 !important; padding:0 !important; }
 .price-box-bundle .price { color:#222; }
-f/********** Product Prices > */
+/********** Product Prices > */
 
 /* Tier Prices */
+.product-pricing,
 .tier-prices { margin:10px 0; padding:10px; background:#f4f9ea; border:1px solid #ddd; }
 .tier-prices .benefit { font-style:italic; font-weight:bold; }
 .tier-prices .price { font-weight:bold;; }
@@ -968,6 +991,7 @@ f/********** Product Prices > */
 .product-options p.required { position:absolute; right:15px; top:10px; }
 
 .product-options-bottom { background-color:#f6f6f6; padding:15px 20px; border:1px solid #e4e4e4; border-top:0; }
+.product-options-bottom .product-pricing,
 .product-options-bottom .tier-prices { margin:0; padding:0 0 10px; border:0; background:0; }
 .product-options-bottom .price-box { float:left; margin:0; }
 .product-options-bottom .add-to-links { clear:both; padding:5px 0 0; text-align:right; }
diff --git a/app/etc/modules/Mage_All.xml b/app/etc/modules/Mage_All.xml
index 36f71f0e2490efa7f7a01b3c54948662eabdd13e..927e6815fb92e9b3490c827af727c9038f88a9fe 100644
--- a/app/etc/modules/Mage_All.xml
+++ b/app/etc/modules/Mage_All.xml
@@ -101,6 +101,7 @@
             <depends>
                 <Mage_Eav/>
                 <Mage_Dataflow/>
+                <Mage_Directory/>
             </depends>
         </Mage_Customer>
         <Mage_Catalog>
diff --git a/app/etc/modules/Mage_CurrencySymbol.xml b/app/etc/modules/Mage_CurrencySymbol.xml
new file mode 100644
index 0000000000000000000000000000000000000000..670a321c93539e1c2dd16c2a6688054df87728cb
--- /dev/null
+++ b/app/etc/modules/Mage_CurrencySymbol.xml
@@ -0,0 +1,38 @@
+<?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    Mage
+ * @package     Mage_CurrencySymbol
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<config>
+    <modules>
+        <Mage_CurrencySymbol>
+            <active>true</active>
+            <codePool>core</codePool>
+            <depends>
+                <Mage_Widget/>
+            </depends>
+        </Mage_CurrencySymbol>
+    </modules>
+</config>
diff --git a/app/etc/modules/Mage_DesignEditor.xml b/app/etc/modules/Mage_DesignEditor.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e192335c6d8f1c51e20a6f46978ff63a1a2309ae
--- /dev/null
+++ b/app/etc/modules/Mage_DesignEditor.xml
@@ -0,0 +1,39 @@
+<?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    Mage
+ * @package     Mage_Persistent
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<config>
+    <modules>
+        <Mage_DesignEditor>
+            <active>true</active>
+            <codePool>core</codePool>
+            <depends>
+                <Mage_Adminhtml/>
+                <Mage_Page/>
+            </depends>
+        </Mage_DesignEditor>
+    </modules>
+</config>
diff --git a/app/locale/de_DE/Mage_Catalog.csv b/app/locale/de_DE/Mage_Catalog.csv
index 4b0469e34d1c2a0846257b4edc4f8f3cfe3917eb..cb06cf26f7c2e0adaff23f551c08aa19575fceb9 100644
--- a/app/locale/de_DE/Mage_Catalog.csv
+++ b/app/locale/de_DE/Mage_Catalog.csv
@@ -723,7 +723,7 @@
 "Update product image","Produktbild aktualisieren"
 "Update product link","Produktlink aktualisieren"
 "Update product tier prices","Produktstaffelpreise aktualisieren"
-"Url Rewrite Management","URL-Überschreiben Verwaltung"
+"URL Rewrite Management","URL-Überschreiben Verwaltung"
 "Use Canonical Link Meta Tag For Products","Canonical Link Element für Produkte verwenden"
 "Use Config Settings","Konfigurations-Einstellungen verwenden"
 "Use In Search Results Layered Navigation","Filternavigation auf Suchergebnisseiten verwenden"
diff --git a/app/locale/de_DE/Mage_CurrencySymbol.csv b/app/locale/de_DE/Mage_CurrencySymbol.csv
new file mode 100644
index 0000000000000000000000000000000000000000..e9d934780f00e7869e065694a76218b432454a6e
--- /dev/null
+++ b/app/locale/de_DE/Mage_CurrencySymbol.csv
@@ -0,0 +1,10 @@
+"Custom currency symbols were applied successfully.","Benutzerdefinierte Währungssymbole wurden erfolgreich angewandt."
+"Manage Currency","Währung verwalten"
+"Manage Currency Rates","Währungskurse verwalten"
+"Rates","Kurse"
+"Save Currency Symbols","Währungssymbole speichern"
+"Symbols","Symbole"
+"System","System"
+"Use Default","Standardvorgaben verwenden"
+"Use Standard","Standard verwenden"
+"Use Website","Website verwenden"
diff --git a/app/locale/de_DE/Mage_Downloadable.csv b/app/locale/de_DE/Mage_Downloadable.csv
index a3bc1f03d28f7c52340c9aa7452bbdae226d03a9..74747645f43b7f3843a9d2a448b853a22ceff240 100644
--- a/app/locale/de_DE/Mage_Downloadable.csv
+++ b/app/locale/de_DE/Mage_Downloadable.csv
@@ -19,7 +19,7 @@
 "Downloadable Information","Herunterladbare Informationen"
 "Downloadable Product","Herunterladbares Produkt"
 "Downloadable Product Options","Herunterladbare Produktoptionen"
-"Downloadable product Section","Abschnitt Herunterladbares Produkt"
+"Downloadable Product Section","Abschnitt Herunterladbares Produkt"
 "Edit","Bearbeiten"
 "Edit item parameters","Artikelangaben ändern"
 "Excl. Tax","Steuer weglassen"
diff --git a/app/locale/de_DE/Mage_Rss.csv b/app/locale/de_DE/Mage_Rss.csv
index 076c6e3d62a13ec9a3cf13cdcafd4c88353a39b1..a87df1ef5562c27fe658817f3896f7926e938266 100644
--- a/app/locale/de_DE/Mage_Rss.csv
+++ b/app/locale/de_DE/Mage_Rss.csv
@@ -41,7 +41,7 @@
 "Regular Price:","Normalpreis:"
 "Review: %s <br/>","Bericht: %s <br/>"
 "Rss Config","RSS Konfig"
-"Rss Feeds Section","RSS-Feeds Sektion"
+"RSS Feeds Section","RSS-Feeds Sektion"
 "Shipping &amp; Handling","Versand und Abwicklung"
 "Special Products","Sonderangebote"
 "Store: %s <br/>","Geschäft: %s <br/>"
diff --git a/app/locale/en_US/Mage_Catalog.csv b/app/locale/en_US/Mage_Catalog.csv
index 6b42d257f67ab873cd087f489d7d94149d5218e7..d3b7812152f467ccc270f0f095c525158f8f814a 100644
--- a/app/locale/en_US/Mage_Catalog.csv
+++ b/app/locale/en_US/Mage_Catalog.csv
@@ -654,7 +654,7 @@
 "Update product link","Update product link"
 "Update product tier prices","Update product tier prices"
 "Upload new product image ","Upload new product image "
-"Url Rewrite Management","Url Rewrite Management"
+"URL Rewrite Management","URL Rewrite Management"
 "Use Canonical Link Meta Tag For Categories","Use Canonical Link Meta Tag For Categories"
 "Use Canonical Link Meta Tag For Products","Use Canonical Link Meta Tag For Products"
 "Use Categories Path for Product URLs","Use Categories Path for Product URLs"
diff --git a/app/locale/en_US/Mage_CurrencySymbol.csv b/app/locale/en_US/Mage_CurrencySymbol.csv
new file mode 100644
index 0000000000000000000000000000000000000000..54f0641102b65d36e5c77e942630ae1ef3bb64fe
--- /dev/null
+++ b/app/locale/en_US/Mage_CurrencySymbol.csv
@@ -0,0 +1,10 @@
+"Custom currency symbols were applied successfully.","Custom currency symbols were applied successfully."
+"Manage Currency","Manage Currency"
+"Manage Currency Rates","Manage Currency Rates"
+"Rates","Rates"
+"Save Currency Symbols","Save Currency Symbols"
+"Symbols","Symbols"
+"System","System"
+"Use Default","Use Default"
+"Use Standard","Use Standard"
+"Use Website","Use Website"
diff --git a/app/locale/en_US/Mage_Downloadable.csv b/app/locale/en_US/Mage_Downloadable.csv
index 0540957ea540265d13b79ed071e0cf7f2ccd7d4e..fe4fef165e70ab055ece7e3a3af2c84570d61292 100644
--- a/app/locale/en_US/Mage_Downloadable.csv
+++ b/app/locale/en_US/Mage_Downloadable.csv
@@ -18,7 +18,7 @@
 "Downloadable Information","Downloadable Information"
 "Downloadable Product","Downloadable Product"
 "Downloadable Product Options","Downloadable Product Options"
-"Downloadable product Section","Downloadable product Section"
+"Downloadable Product Section","Downloadable Product Section"
 "Excl. Tax","Excl. Tax"
 "File","File"
 "From:","From:"
diff --git a/app/locale/en_US/Mage_Rss.csv b/app/locale/en_US/Mage_Rss.csv
index a109f236276d651f7b464a8a7370a8a236f91cc9..9271b6ce5076f03c86e944808fbd186b7b5e6325 100644
--- a/app/locale/en_US/Mage_Rss.csv
+++ b/app/locale/en_US/Mage_Rss.csv
@@ -39,7 +39,7 @@
 "RSS Feeds List","RSS Feeds List"
 "Review: %s <br/>","Review: %s <br/>"
 "Rss Config","Rss Config"
-"Rss Feeds Section","Rss Feeds Section"
+"RSS Feeds Section","RSS Feeds Section"
 "Shipping &amp; Handling","Shipping &amp; Handling"
 "Special Products","Special Products"
 "Store: %s <br/>","Store: %s <br/>"
diff --git a/app/locale/es_ES/Mage_Catalog.csv b/app/locale/es_ES/Mage_Catalog.csv
index 4bbad0dd3ec6197d32176467cd554e7a9327c408..4998675b92b84fb00043c9734d00e4f7ab5dae9b 100644
--- a/app/locale/es_ES/Mage_Catalog.csv
+++ b/app/locale/es_ES/Mage_Catalog.csv
@@ -723,7 +723,7 @@
 "Update product image","Actualizar imagen de producto"
 "Update product link","Actualizar enlace de producto"
 "Update product tier prices","Actualizar precios de capa de productos"
-"Url Rewrite Management","Gestionar reescritura Url"
+"URL Rewrite Management","Gestionar reescritura Url"
 "Use Canonical Link Meta Tag For Products","Utilizar metaetiqueta de enlace canónico para productos"
 "Use Config Settings","Usar Opciones de Configuración"
 "Use In Search Results Layered Navigation","Utilizar en navegación en capas de resultados de búsqueda"
diff --git a/app/locale/es_ES/Mage_CurrencySymbol.csv b/app/locale/es_ES/Mage_CurrencySymbol.csv
new file mode 100644
index 0000000000000000000000000000000000000000..283cccb1b7c1bdff3e4bee961c2bef92b932ac17
--- /dev/null
+++ b/app/locale/es_ES/Mage_CurrencySymbol.csv
@@ -0,0 +1,10 @@
+"Custom currency symbols were applied successfully.","Los símbolos personalizados de divisas se aplicaron con éxito."
+"Manage Currency","Gestión de divisas"
+"Manage Currency Rates","Tasa de cambio de divisas"
+"Rates","Tasas"
+"Save Currency Symbols","Guardar símbolos de divisas"
+"Symbols","Símbolos"
+"System","Sistema"
+"Use Default","Utilizar la opción por defecto"
+"Use Standard","Utilizar la opción estándar"
+"Use Website","Utilizar el sitio web"
diff --git a/app/locale/es_ES/Mage_Downloadable.csv b/app/locale/es_ES/Mage_Downloadable.csv
index 54647d19417001f8de667839886e1c4253460a3f..c3444fc7108d3c5f3d8d2e12cbb2d2915d93eb5f 100644
--- a/app/locale/es_ES/Mage_Downloadable.csv
+++ b/app/locale/es_ES/Mage_Downloadable.csv
@@ -19,7 +19,7 @@
 "Downloadable Information","Información Descargable"
 "Downloadable Product","Producto Descargable"
 "Downloadable Product Options","Opciones de Producto Descargable"
-"Downloadable product Section","Sección de productos Descargables"
+"Downloadable Product Section","Sección de productos Descargables"
 "Edit","Editar"
 "Edit item parameters","Editar parámetros del artículo"
 "Excl. Tax","Impuestos no incluidos"
diff --git a/app/locale/es_ES/Mage_Rss.csv b/app/locale/es_ES/Mage_Rss.csv
index 1cd9a7b7a567b5ce17ca14d6b22d9e5a3cc6a843..dbf795c056e4fc69ab99197cb415f374c7ae1ba2 100644
--- a/app/locale/es_ES/Mage_Rss.csv
+++ b/app/locale/es_ES/Mage_Rss.csv
@@ -41,7 +41,7 @@
 "Regular Price:","Precio habitual:"
 "Review: %s <br/>","Reseña: %s <br/>"
 "Rss Config","Configuración de RSS"
-"Rss Feeds Section","Sección de fuentes RSS"
+"RSS Feeds Section","Sección de fuentes RSS"
 "Shipping &amp; Handling","Envío y preparación"
 "Special Products","Productos especiales"
 "Store: %s <br/>","Tienda: %s <br/>"
diff --git a/app/locale/fr_FR/Mage_Catalog.csv b/app/locale/fr_FR/Mage_Catalog.csv
index 0f52c14c50adfa0832cbf01017c16f6f505eedf0..aae21f51adfa0079101c56a05384a97b7e735304 100644
--- a/app/locale/fr_FR/Mage_Catalog.csv
+++ b/app/locale/fr_FR/Mage_Catalog.csv
@@ -723,7 +723,7 @@
 "Update product image","Mettre à jour l'image du produit"
 "Update product link","Mettre à jour le lien du produit"
 "Update product tier prices","Mettre à jour le niveau des prix du produit"
-"Url Rewrite Management","Gestion de réécriture de l'url"
+"URL Rewrite Management","Gestion de réécriture de l'url"
 "Use Canonical Link Meta Tag For Products","Utiliser les méta-données du lien canonique pour les produits"
 "Use Config Settings","Utiliser les Paramètres de Configuration"
 "Use In Search Results Layered Navigation","Utiliser dans la navigation par couches des résultats de navigation"
diff --git a/app/locale/fr_FR/Mage_CurrencySymbol.csv b/app/locale/fr_FR/Mage_CurrencySymbol.csv
new file mode 100644
index 0000000000000000000000000000000000000000..8d917abad9740ba7b9b1e8f8161d637f1a131e06
--- /dev/null
+++ b/app/locale/fr_FR/Mage_CurrencySymbol.csv
@@ -0,0 +1,10 @@
+"Custom currency symbols were applied successfully.","Les symboles des devises ont été chargés avec succès."
+"Manage Currency","Gérer les devises"
+"Manage Currency Rates","Gérer le taux des devises"
+"Rates","Taux"
+"Save Currency Symbols","Enregistrer les symboles des devises"
+"Symbols","Symboles"
+"System","Système"
+"Use Default","Utiliser la valeur par défaut"
+"Use Standard","Utiliser la valeur standard"
+"Use Website","Utiliser le site web"
diff --git a/app/locale/fr_FR/Mage_Downloadable.csv b/app/locale/fr_FR/Mage_Downloadable.csv
index efcfb7357025768abc9540a9219ee9912f39d731..6a4e114f89fffa841f9a13a1ef2847fa56486da7 100644
--- a/app/locale/fr_FR/Mage_Downloadable.csv
+++ b/app/locale/fr_FR/Mage_Downloadable.csv
@@ -19,7 +19,7 @@
 "Downloadable Information","Information téléchargeables"
 "Downloadable Product","Produit téléchargeable"
 "Downloadable Product Options","Options de produit téléchargeable"
-"Downloadable product Section","Section de produit téléchargeable"
+"Downloadable Product Section","Section de produit téléchargeable"
 "Edit","Éditer"
 "Edit item parameters","Modifier les paramètres de l'objet"
 "Excl. Tax","Taxe non comprise"
diff --git a/app/locale/fr_FR/Mage_Rss.csv b/app/locale/fr_FR/Mage_Rss.csv
index b8b428a37ffc96f65519ec1a99575d6b19fdad44..584b9a27c4754ddcacedaffa8a3a35525bed421c 100644
--- a/app/locale/fr_FR/Mage_Rss.csv
+++ b/app/locale/fr_FR/Mage_Rss.csv
@@ -41,7 +41,7 @@
 "Regular Price:","Prix habituel:"
 "Review: %s <br/>","Critique : %s <br/>"
 "Rss Config","Configuration RSS"
-"Rss Feeds Section","Section des flux RSS"
+"RSS Feeds Section","Section des flux RSS"
 "Shipping &amp; Handling","Expédition &amp; Traitement"
 "Special Products","Produits spéciaux"
 "Store: %s <br/>","Boutique : %s <br/>"
diff --git a/app/locale/fr_FR/Mage_Sales.csv b/app/locale/fr_FR/Mage_Sales.csv
index 7d72d5e585f07f3213698c5ab5700b37560196d6..60ed85d8af67485380088e1601bc713ac050cd0d 100644
--- a/app/locale/fr_FR/Mage_Sales.csv
+++ b/app/locale/fr_FR/Mage_Sales.csv
@@ -677,7 +677,7 @@
 "Value","Valeur"
 "View All","Voir tout"
 "View Another Order","Voir autre commande"
-"Void","Annuler"
+"Void","Nulle"
 "Void invoice","Annuler la facture"
 "Voided authorization.","Autorisation annulée"
 "Website","Site"
diff --git a/app/locale/nl_NL/Mage_Catalog.csv b/app/locale/nl_NL/Mage_Catalog.csv
index fe0cd1b64ea77a113643057ed62a16fbc22d0300..945485c687d0f93acac46dce48b2abfca2a60bd1 100644
--- a/app/locale/nl_NL/Mage_Catalog.csv
+++ b/app/locale/nl_NL/Mage_Catalog.csv
@@ -723,7 +723,7 @@
 "Update product image","Update product afbeelding"
 "Update product link","Update product link"
 "Update product tier prices","Update product niveau prijzen"
-"Url Rewrite Management","Url Rewrite Management"
+"URL Rewrite Management","URL Rewrite Management"
 "Use Canonical Link Meta Tag For Products","Gebruik een Kanonieke Link Meta Label Voor Product"
 "Use Config Settings","Gebruik Configuratiesettings"
 "Use In Search Results Layered Navigation","Gebruik in Zoek Resultaten een Gelaagde Navigatie"
diff --git a/app/locale/nl_NL/Mage_CurrencySymbol.csv b/app/locale/nl_NL/Mage_CurrencySymbol.csv
new file mode 100644
index 0000000000000000000000000000000000000000..c55c97131a270db2bd1f49fe01b028416279c5e3
--- /dev/null
+++ b/app/locale/nl_NL/Mage_CurrencySymbol.csv
@@ -0,0 +1,10 @@
+"Custom currency symbols were applied successfully.","Klandizie muntsoort symbolen zijn succesvol toegepast."
+"Manage Currency","Beheer Muntsoort"
+"Manage Currency Rates","Beheer Wisselkoersen"
+"Rates","Tarieven"
+"Save Currency Symbols","Bewaar Muntsoort Symbolen"
+"Symbols","Symbolen"
+"System","Systeem"
+"Use Default","Gebruik Standaard"
+"Use Standard","Gebruik Standaard"
+"Use Website","Gebruik Website"
diff --git a/app/locale/nl_NL/Mage_Downloadable.csv b/app/locale/nl_NL/Mage_Downloadable.csv
index cfb80ac28831636da5b53606a236f571e6f11c12..49512396ea06c49b8bf08c7f5530cbf5650929bc 100644
--- a/app/locale/nl_NL/Mage_Downloadable.csv
+++ b/app/locale/nl_NL/Mage_Downloadable.csv
@@ -19,7 +19,7 @@
 "Downloadable Information","Downloadbare informatie"
 "Downloadable Product","Downloadbaar Product"
 "Downloadable Product Options","Downloadbaar Product Opties"
-"Downloadable product Section","Downloadbaar product Gedeelte"
+"Downloadable Product Section","Downloadbaar product Gedeelte"
 "Edit","Bewerken"
 "Edit item parameters","Parameters van artikel bewerken"
 "Excl. Tax","Excl. BTW"
diff --git a/app/locale/nl_NL/Mage_Rss.csv b/app/locale/nl_NL/Mage_Rss.csv
index 48d6a31916e5e03be5287e5272c24a8e26dd663f..fcce4a148f61d09762e488b858c81703b6bfc207 100644
--- a/app/locale/nl_NL/Mage_Rss.csv
+++ b/app/locale/nl_NL/Mage_Rss.csv
@@ -41,7 +41,7 @@
 "Regular Price:","Normale prijs:"
 "Review: %s <br/>","Beoordeling: %s <br/>"
 "Rss Config","Rss Instellingen"
-"Rss Feeds Section","Rss Feeds Gedeelte"
+"RSS Feeds Section","Rss Feeds Gedeelte"
 "Shipping &amp; Handling","Verzending &amp; in Behandeling"
 "Special Products","Speciale Producten"
 "Store: %s <br/>","Winkel: %s <br/>"
diff --git a/app/locale/pt_BR/Mage_Catalog.csv b/app/locale/pt_BR/Mage_Catalog.csv
index 1b401b39571988bc279d157b87f3761636fea7ff..2c4c44ec33dff7fc238206fe0785fc030196c1bc 100644
--- a/app/locale/pt_BR/Mage_Catalog.csv
+++ b/app/locale/pt_BR/Mage_Catalog.csv
@@ -724,7 +724,7 @@
 "Update product image","Atualização da imagem do produto"
 "Update product link","Atualização do link do produto"
 "Update product tier prices","Atualização dos preços do nível do produto"
-"Url Rewrite Management","Gestão de Reescrita de URL"
+"URL Rewrite Management","Gestão de Reescrita de URL"
 "Use Canonical Link Meta Tag For Products","Use Meta Marca Link Canônico Para Produtos"
 "Use Config Settings","Utilizar opções de configuração"
 "Use In Search Results Layered Navigation","Use Em Resultados de Pesquisa de Navegação em Camadas"
diff --git a/app/locale/pt_BR/Mage_Downloadable.csv b/app/locale/pt_BR/Mage_Downloadable.csv
index 65c55a135e369c9ff8ccd61bc76e9a85965d53f0..ef7f3bf70d49ad55e6332cc7ad98e698ec2c2976 100644
--- a/app/locale/pt_BR/Mage_Downloadable.csv
+++ b/app/locale/pt_BR/Mage_Downloadable.csv
@@ -19,7 +19,7 @@
 "Downloadable Information","Informação Transferível"
 "Downloadable Product","Produto Descarregável"
 "Downloadable Product Options","Opções de Produto Descarregável"
-"Downloadable product Section","Seção de Produto Descarregável"
+"Downloadable Product Section","Seção de Produto Descarregável"
 "Edit","Editar"
 "Edit item parameters","Editar parâmetros de item"
 "Excl. Tax","Excluir taxas"
diff --git a/app/locale/pt_BR/Mage_Rss.csv b/app/locale/pt_BR/Mage_Rss.csv
index 07e281c3f6f243c474619eb3c448228719f453bf..f9ffbf3b01ed9aa780aca1006fa1324a63371323 100644
--- a/app/locale/pt_BR/Mage_Rss.csv
+++ b/app/locale/pt_BR/Mage_Rss.csv
@@ -41,7 +41,7 @@
 "Regular Price:","Preço Normal:"
 "Review: %s <br/>","Avaliação: %s <br/>"
 "Rss Config","Configuração de RSS"
-"Rss Feeds Section","Escolha de RSS Feeds"
+"RSS Feeds Section","Escolha de RSS Feeds"
 "Shipping &amp; Handling","Transporte &amp; Manuseio"
 "Special Products","Produtos especiais"
 "Store: %s <br/>","Loja: %s <br/>"
diff --git a/app/locale/zh_CN/Mage_Catalog.csv b/app/locale/zh_CN/Mage_Catalog.csv
index e2525f49556e8e03733b150efa8954a8726c06f3..73684e29199147185a4bd074827463bf230b0ea7 100644
--- a/app/locale/zh_CN/Mage_Catalog.csv
+++ b/app/locale/zh_CN/Mage_Catalog.csv
@@ -723,7 +723,7 @@
 "Update product image","更新产品图像"
 "Update product link","更新产品链接"
 "Update product tier prices","更新产品层价格"
-"Url Rewrite Management","URL重写管理"
+"URL Rewrite Management","URL重写管理"
 "Use Canonical Link Meta Tag For Products","为产品使用标准的链接元数据标签"
 "Use Config Settings","使用配置设置"
 "Use In Search Results Layered Navigation","使用搜索结果内层次导航"
diff --git a/app/locale/zh_CN/Mage_Downloadable.csv b/app/locale/zh_CN/Mage_Downloadable.csv
index 5b35a008b00b1dec0abcf61861ed7369f8790446..b6acdc620d8d0b1a5bc750527eec24d415b1214b 100644
--- a/app/locale/zh_CN/Mage_Downloadable.csv
+++ b/app/locale/zh_CN/Mage_Downloadable.csv
@@ -19,7 +19,7 @@
 "Downloadable Information","可下载的信息"
 "Downloadable Product","可下载产品"
 "Downloadable Product Options","可下载产品选项"
-"Downloadable product Section","可下载产品区域"
+"Downloadable Product Section","可下载产品区域"
 "Edit","编辑"
 "Edit item parameters","编辑项目参数"
 "Excl. Tax","不含税"
diff --git a/app/locale/zh_CN/Mage_Rss.csv b/app/locale/zh_CN/Mage_Rss.csv
index 91e748960df2710e9505e68dde1c05cc5f514480..2f1cc54827b4a20c67e2b7318f91aa1dac740a13 100644
--- a/app/locale/zh_CN/Mage_Rss.csv
+++ b/app/locale/zh_CN/Mage_Rss.csv
@@ -41,7 +41,7 @@
 "Regular Price:","常规价格:"
 "Review: %s <br/>","评价:%s <br/>"
 "Rss Config","RSS 配置"
-"Rss Feeds Section","RSS 订阅源区域"
+"RSS Feeds Section","RSS 订阅源区域"
 "Shipping &amp; Handling","运送与手续费"
 "Special Products","特殊商品"
 "Store: %s <br/>","商店:%s <br/>"
diff --git a/dev/tests/integration/etc/integration-tests-config.xml b/dev/tests/integration/etc/integration-tests-config.xml
index 268d596fec063428f7656a5ef3b2949b8bc8bdba..417105e664aaa9897f55743f9e392543fb5108fb 100644
--- a/dev/tests/integration/etc/integration-tests-config.xml
+++ b/dev/tests/integration/etc/integration-tests-config.xml
@@ -38,5 +38,8 @@
                 </observers>
             </controller_front_init_before>
         </events>
+        <rewrites>
+            <Mage_Core_Model_Cookie>Magento_Test_Cookie</Mage_Core_Model_Cookie>
+        </rewrites>
     </global>
 </config>
diff --git a/dev/tests/integration/framework/Magento/Test/Bootstrap.php b/dev/tests/integration/framework/Magento/Test/Bootstrap.php
index 9706ca220d2c3a4b5314751f7331776b7a36af6f..8c00f7f935444465d203f7f57810294fb3c24917 100644
--- a/dev/tests/integration/framework/Magento/Test/Bootstrap.php
+++ b/dev/tests/integration/framework/Magento/Test/Bootstrap.php
@@ -199,6 +199,17 @@ class Magento_Test_Bootstrap
         $this->_installDir = "{$tmpDir}/sandbox-{$this->_dbVendorName}-{$sandboxUniqueId}";
         $this->_installEtcDir = $this->_installDir . '/etc';
 
+        $this->_options = array(
+            'etc_dir'     => $this->_installEtcDir,
+            'var_dir'     => $this->_installDir,
+            'tmp_dir'     => $this->_installDir . DIRECTORY_SEPARATOR . 'tmp',
+            'cache_dir'   => $this->_installDir . DIRECTORY_SEPARATOR . 'cache',
+            'log_dir'     => $this->_installDir . DIRECTORY_SEPARATOR . 'log',
+            'session_dir' => $this->_installDir . DIRECTORY_SEPARATOR . 'session',
+            'media_dir'   => $this->_installDir . DIRECTORY_SEPARATOR . 'media',
+            'upload_dir'  => $this->_installDir . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . 'upload',
+        );
+
         $this->_db = $this->_instantiateDb();
 
         $this->_cleanupAction = $cleanupAction;
@@ -229,11 +240,8 @@ class Magento_Test_Bootstrap
 
     /**
      * Initialize an already installed Magento application
-     *
-     * @param string $scopeCode
-     * @param string $scopeType
      */
-    public function initialize($scopeCode = '', $scopeType = 'store')
+    public function initialize()
     {
         if (!class_exists('Mage', false)) {
             require_once $this->_magentoDir . '/app/bootstrap.php';
@@ -244,28 +252,9 @@ class Magento_Test_Bootstrap
                 Mage::register('_singleton/Mage_Core_Model_Resource', $resource);
             }
         }
-        $this->_options = array(
-            'etc_dir'     => $this->_installEtcDir,
-            'var_dir'     => $this->_installDir,
-            'tmp_dir'     => $this->_installDir . DIRECTORY_SEPARATOR . 'tmp',
-            'cache_dir'   => $this->_installDir . DIRECTORY_SEPARATOR . 'cache',
-            'log_dir'     => $this->_installDir . DIRECTORY_SEPARATOR . 'log',
-            'session_dir' => $this->_installDir . DIRECTORY_SEPARATOR . 'session',
-            'media_dir'   => $this->_installDir . DIRECTORY_SEPARATOR . 'media',
-            'upload_dir'  => $this->_installDir . DIRECTORY_SEPARATOR . 'media' . DIRECTORY_SEPARATOR . 'upload',
-        );
-
         Mage::setIsDeveloperMode($this->_developerMode);
-        Mage::app($scopeCode, $scopeType, $this->_options);
-    }
-
-    /**
-     * Remove cached configuration and reinitialize the application
-     */
-    public function refreshConfiguration()
-    {
-        Mage::app()->cleanCache(array(Mage_Core_Model_Config::CACHE_TAG));
-        $this->initialize();
+        Mage::$headersSentThrowsException = false;
+        Mage::app('', 'store', $this->_options);
     }
 
     /**
@@ -293,14 +282,6 @@ class Magento_Test_Bootstrap
         return $this->_options;
     }
 
-    /**
-     * Perform requested cleanup operations
-     */
-    public function __destruct()
-    {
-        $this->_cleanup();
-    }
-
     /**
      * Perform a cleanup action
      */
@@ -391,6 +372,8 @@ class Magento_Test_Bootstrap
      */
     protected function _emulateEnvironment()
     {
+        // emulate HTTP request
+        $_SERVER['HTTP_HOST'] = 'localhost';
         // emulate entry point to ensure that tests generate invariant URLs
         $_SERVER['SCRIPT_FILENAME'] = 'index.php';
         // prevent session_start, because it may rely on cookies
@@ -502,7 +485,7 @@ class Magento_Test_Bootstrap
         $this->initialize();
         /**
          * Initialization of front controller with all routers.
-         * Should be here as needed only once after installation process. 
+         * Should be here as needed only once after installation process.
          */
         Mage::app()->getFrontController();
     }
@@ -532,21 +515,4 @@ class Magento_Test_Bootstrap
         }
         return $result;
     }
-
-    /**
-     * Removes cache polluted by other tests. Leaves performance critical cache (configuration, ddl) untouched.
-     *
-     * @return null
-     */
-    public function cleanupCache()
-    {
-        Mage::app()->getCache()->clean(
-            Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG,
-            array(Mage_Core_Model_Config::CACHE_TAG,
-                Varien_Db_Adapter_Pdo_Mysql::DDL_CACHE_TAG,
-                'DB_PDO_MSSQL_DDL', // Varien_Db_Adapter_Pdo_Mssql::DDL_CACHE_TAG
-                'DB_ORACLE_DDL', // Varien_Db_Adapter_Oracle::DDL_CACHE_TAG
-            )
-        );
-    }
 }
diff --git a/dev/tests/integration/framework/Magento/Test/Cookie.php b/dev/tests/integration/framework/Magento/Test/Cookie.php
new file mode 100644
index 0000000000000000000000000000000000000000..69c2d2570302894184455367c5bcab4a084206b0
--- /dev/null
+++ b/dev/tests/integration/framework/Magento/Test/Cookie.php
@@ -0,0 +1,70 @@
+<?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
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Replacement for the native cookie model that doesn't send cookie headers in testing environment
+ */
+class Magento_Test_Cookie extends Mage_Core_Model_Cookie
+{
+    /**
+     * Dummy function, which sets value directly to $_COOKIE super-global array instead of calling setcookie()
+     *
+     * @param string $name The cookie name
+     * @param string $value The cookie value
+     * @param int $period Lifetime period
+     * @param string $path
+     * @param string $domain
+     * @param int|bool $secure
+     * @param bool $httponly
+     * @return Magento_Test_Cookie
+     *
+     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
+     */
+    public function set($name, $value, $period = null, $path = null, $domain = null, $secure = null, $httponly = null)
+    {
+        $_COOKIE[$name] = $value;
+        return $this;
+    }
+
+    /**
+     * Dummy function, which removes value directly from $_COOKIE super-global array instead of calling setcookie()
+     *
+     * @param string $name
+     * @param string $path
+     * @param string $domain
+     * @param int|bool $secure
+     * @param int|bool $httponly
+     * @return Magento_Test_Cookie
+     *
+     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
+     */
+    public function delete($name, $path = null, $domain = null, $secure = null, $httponly = null)
+    {
+        unset($_COOKIE[$name]);
+        return $this;
+    }
+}
diff --git a/dev/tests/integration/framework/Magento/Test/Listener/Annotation/Config.php b/dev/tests/integration/framework/Magento/Test/Listener/Annotation/Config.php
index 6f76834550b74bfafc88297b055856819d120477..6e8dfc6a3d32941b370ea9919ddfd3a9b5b2bfb9 100644
--- a/dev/tests/integration/framework/Magento/Test/Listener/Annotation/Config.php
+++ b/dev/tests/integration/framework/Magento/Test/Listener/Annotation/Config.php
@@ -35,6 +35,13 @@ class Magento_Test_Listener_Annotation_Config
      */
     protected static $_listenerDefault;
 
+    /**
+     * Whether the execution is happening between 'startTest' and 'stopTest'
+     *
+     * @var bool
+     */
+    protected static $_isWithinTest = false;
+
     /**
      * @var Magento_Test_Listener
      */
@@ -164,6 +171,7 @@ class Magento_Test_Listener_Annotation_Config
     public function startTest()
     {
         $this->_assignConfigData();
+        self::$_isWithinTest = true;
     }
 
     /**
@@ -171,6 +179,7 @@ class Magento_Test_Listener_Annotation_Config
      */
     public function endTest()
     {
+        self::$_isWithinTest = false;
         $this->_restoreConfigData();
     }
 
@@ -179,6 +188,9 @@ class Magento_Test_Listener_Annotation_Config
      */
     public function initFrontControllerBefore()
     {
+        if (!self::$_isWithinTest) {
+            return;
+        }
         $this->_assignConfigData();
     }
 }
diff --git a/dev/tests/integration/framework/Magento/Test/Listener/Annotation/Isolation.php b/dev/tests/integration/framework/Magento/Test/Listener/Annotation/Isolation.php
index fc8a5dfa7b1532ebf560e9f5f32181f0e78b7855..bc3f59cf8f7bdf39f90af1a6053343c75ce93038 100644
--- a/dev/tests/integration/framework/Magento/Test/Listener/Annotation/Isolation.php
+++ b/dev/tests/integration/framework/Magento/Test/Listener/Annotation/Isolation.php
@@ -58,12 +58,37 @@ class Magento_Test_Listener_Annotation_Isolation
     protected function _isolateApp()
     {
         if ($this->_hasNonIsolatedTests) {
-            Magento_Test_Bootstrap::getInstance()->cleanupCache();
+            $this->_cleanupCache();
             Magento_Test_Bootstrap::getInstance()->initialize();
             $this->_hasNonIsolatedTests = false;
         }
     }
 
+    /**
+     * Remove cache polluted by other tests excluding performance critical cache (configuration, ddl)
+     */
+    protected function _cleanupCache()
+    {
+        /*
+         * Cache cleanup relies on the initialized config object, which could be polluted from within a test.
+         * For instance, any test could explicitly call Mage::reset() to destroy the config object.
+         */
+        $expectedOptions = Magento_Test_Bootstrap::getInstance()->getAppOptions();
+        $actualOptions = Mage::getConfig() ? Mage::getConfig()->getOptions()->getData() : array();
+        $isConfigPolluted = array_intersect_assoc($expectedOptions, $actualOptions) !== $expectedOptions;
+        if ($isConfigPolluted) {
+            Magento_Test_Bootstrap::getInstance()->initialize();
+        }
+        Mage::app()->getCache()->clean(
+            Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG,
+            array(Mage_Core_Model_Config::CACHE_TAG,
+                Varien_Db_Adapter_Pdo_Mysql::DDL_CACHE_TAG,
+                'DB_PDO_MSSQL_DDL', // Varien_Db_Adapter_Pdo_Mssql::DDL_CACHE_TAG
+                'DB_ORACLE_DDL', // Varien_Db_Adapter_Oracle::DDL_CACHE_TAG
+            )
+        );
+    }
+
     /**
      * Isolate application before running test case
      */
diff --git a/dev/tests/integration/framework/Magento/Test/Response.php b/dev/tests/integration/framework/Magento/Test/Response.php
index fc73a2613c8715e1a7978ec3ae9855e503d5186b..e107f6d0bf2d7a7f0ad71b0bb09802a586a59165 100644
--- a/dev/tests/integration/framework/Magento/Test/Response.php
+++ b/dev/tests/integration/framework/Magento/Test/Response.php
@@ -31,9 +31,13 @@
 class Magento_Test_Response extends Mage_Core_Controller_Response_Http
 {
     /**
-     * Redefined in order to prevent exception in parent class.
+     * Prevent generating exceptions if headers are already sent
+     *
+     * Prevents throwing an exception in Zend_Controller_Response_Abstract::canSendHeaders()
      * All functionality that depend on headers validation should be covered with unit tests by mocking response.
      *
+     * @param bool $throw
+     * @return bool
      * @SuppressWarnings(PHPMD.UnusedFormalParameter)
      */
     public function canSendHeaders($throw = false)
diff --git a/dev/tests/integration/framework/Magento/Test/TestCase/ControllerAbstract.php b/dev/tests/integration/framework/Magento/Test/TestCase/ControllerAbstract.php
index 6ae0ff7ad46098046de14d4c63b943af06989211..8354959407f1b4a0b48661ca402f7175bd0e565f 100644
--- a/dev/tests/integration/framework/Magento/Test/TestCase/ControllerAbstract.php
+++ b/dev/tests/integration/framework/Magento/Test/TestCase/ControllerAbstract.php
@@ -25,6 +25,12 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
+/**
+ * Abstract class for the controller tests
+ *
+ * @SuppressWarnings(PHPMD.NumberOfChildren)
+ * @SuppressWarnings(PHPMD.numberOfChildren)
+ */
 abstract class Magento_Test_TestCase_ControllerAbstract extends PHPUnit_Framework_TestCase
 {
     protected $_runCode     = '';
diff --git a/dev/tests/integration/framework/bootstrap.php b/dev/tests/integration/framework/bootstrap.php
index 0a9a84d25262779fa69e65b6b671195b0fc30718..0730ae19add6f481de2535c92301e489ccf486ff 100644
--- a/dev/tests/integration/framework/bootstrap.php
+++ b/dev/tests/integration/framework/bootstrap.php
@@ -26,6 +26,9 @@
  */
 
 require __DIR__ . '/Magento/Test/Bootstrap.php';
+require __DIR__ . '/../../static/testsuite/Utility/Classes.php';
+
+Utility_Files::init(new Utility_Files(realpath(__DIR__ . '/../../../..')));
 
 $baseDir = dirname(__DIR__);
 
@@ -37,6 +40,7 @@ set_include_path(implode(
     PATH_SEPARATOR,
     array(
         "$baseDir/framework",
+        "$baseDir/testsuite",
         get_include_path()
     )
 ));
diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/BootstrapTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/BootstrapTest.php
index c11d8a4b2010f0bf53781a1ce484e2b502187a3b..d08d76a3d8f18da2855238644741d7040152ebba 100644
--- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/BootstrapTest.php
+++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/BootstrapTest.php
@@ -200,7 +200,7 @@ class Magento_Test_BootstrapTest extends PHPUnit_Framework_TestCase
         $this->_callBootstrapConstructor();
     }
 
-    public function testConstructorDestructorCleanupNone()
+    public function testConstructorCleanupNone()
     {
         $this->_db
             ->expects($this->never())
@@ -215,32 +215,29 @@ class Magento_Test_BootstrapTest extends PHPUnit_Framework_TestCase
             ->method('_cleanupFilesystem')
         ;
         $this->_callBootstrapConstructor(null, Magento_Test_Bootstrap::CLEANUP_NONE);
-        $this->_bootstrap->__destruct();
     }
 
-    public function testConstructorDestructorCleanupUninstall()
+    public function testConstructorCleanupUninstall()
     {
         $this->_db
-            ->expects($this->exactly(2))
+            ->expects($this->exactly(1))
             ->method('cleanup')
         ;
         $this->_bootstrap
-            ->expects($this->exactly(2))
+            ->expects($this->exactly(1))
             ->method('_cleanupFilesystem')
         ;
         $this->_callBootstrapConstructor(null, Magento_Test_Bootstrap::CLEANUP_UNINSTALL);
-        $this->_bootstrap->__destruct();
     }
 
-    public function testConstructorDestructorCleanupRestoreDb()
+    public function testConstructorCleanupRestoreDb()
     {
         $this->_db
-            ->expects($this->exactly(2))
+            ->expects($this->exactly(1))
             ->method('restoreBackup')
             ->with(Magento_Test_Bootstrap::DB_BACKUP_NAME)
         ;
         $this->_callBootstrapConstructor(null, Magento_Test_Bootstrap::CLEANUP_RESTORE_DB);
-        $this->_bootstrap->__destruct();
     }
 
     /**
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
new file mode 100644
index 0000000000000000000000000000000000000000..e6f5b9bcb16e8fcff624eea4be3e5ecb1a654732
--- /dev/null
+++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/CookieTest.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.
+ *
+ * @category    Magento
+ * @package     Magento
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Magento_Test_CookieTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * Name of the sample cookie to be used in tests
+     */
+    const SAMPLE_COOKIE_NAME = 'sample_cookie';
+
+    /**
+     * @var Magento_Test_Cookie
+     */
+    protected $_model;
+
+    protected function setUp()
+    {
+        $this->_model = new Magento_Test_Cookie();
+    }
+
+    public function testSet()
+    {
+        $cookieValue = 'some_cookie_value';
+        $this->assertFalse($this->_model->get(self::SAMPLE_COOKIE_NAME));
+        $this->_model->set(self::SAMPLE_COOKIE_NAME, $cookieValue);
+        $this->assertEquals($cookieValue, $this->_model->get(self::SAMPLE_COOKIE_NAME));
+        $this->assertEquals($cookieValue, $_COOKIE[self::SAMPLE_COOKIE_NAME]);
+    }
+
+    public function testDelete()
+    {
+        $this->_model->set(self::SAMPLE_COOKIE_NAME, 'some_value');
+        $this->_model->delete(self::SAMPLE_COOKIE_NAME);
+        $this->assertFalse($this->_model->get(self::SAMPLE_COOKIE_NAME));
+        $this->assertArrayNotHasKey(self::SAMPLE_COOKIE_NAME, $_COOKIE);
+    }
+}
diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Listener/Annotation/ConfigTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Listener/Annotation/ConfigTest.php
index bf56e11dc9bc44ca85357155f4fb8aa862d29f8b..9998354ee2452c2ad626ef9cd6cf4ef5284cd464 100644
--- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Listener/Annotation/ConfigTest.php
+++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/Listener/Annotation/ConfigTest.php
@@ -135,11 +135,28 @@ class Magento_Test_Listener_Annotation_ConfigTest extends PHPUnit_Framework_Test
         $this->_annotation->endTest();
     }
 
+    /**
+     * @magentoConfigFixture some/config/path some_config_value
+     */
+    public function testInitFrontControllerBeforeOutOfScope()
+    {
+        $this->_annotation
+            ->expects($this->never())
+            ->method('_getConfigValue')
+        ;
+        $this->_annotation
+            ->expects($this->never())
+            ->method('_setConfigValue')
+        ;
+        $this->_annotation->initFrontControllerBefore();
+    }
+
     /**
      * @magentoConfigFixture web/unsecure/base_url http://example.com/
      */
     public function testInitFrontControllerBefore()
     {
+        $this->_annotation->startTest();
         $this->_annotation
             ->expects($this->at(0))
             ->method('_getConfigValue')
@@ -152,5 +169,6 @@ class Magento_Test_Listener_Annotation_ConfigTest extends PHPUnit_Framework_Test
             ->with('web/unsecure/base_url', 'http://example.com/')
         ;
         $this->_annotation->initFrontControllerBefore();
+        $this->_annotation->endTest();
     }
 }
diff --git a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/ResponseTest.php b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/ResponseTest.php
index dae3eb2c75b4e85515073df3015cdba40dbd1fcb..bc1d0e1d45e4729872dd33225ca8176cd1230914 100644
--- a/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/ResponseTest.php
+++ b/dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/ResponseTest.php
@@ -34,4 +34,3 @@ class Magento_Test_ResponseTest extends PHPUnit_Framework_TestCase
         $this->assertTrue($response->canSendHeaders(false));
     }
 }
-
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 3c8e50b63b962c66c9a7823600664667ddba83de..585d6de157c5fe92796302709dc806d7df8fda3a 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
@@ -99,9 +99,13 @@ class Magento_Test_TestCase_ControllerAbstractTest extends Magento_Test_TestCase
      */
     public function testAssertRedirect()
     {
-        $this->getResponse()->setRedirect('http://magentocommerce.com');
+        /*
+         * 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
+         */
+        $setRedirectMethod = new ReflectionMethod('Zend_Controller_Response_Http', 'setRedirect');
+        $setRedirectMethod->invoke($this->getResponse(), 'http://magentocommerce.com');
         $this->assertRedirect();
         $this->assertRedirect('http://magentocommerce.com');
     }
 }
-
diff --git a/dev/tests/integration/testsuite/Mage/Admin/Model/SessionTest.php b/dev/tests/integration/testsuite/Mage/Admin/Model/SessionTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..99cf084c7cbf2a967f8c823d51f41b4a8ba354ad
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Admin/Model/SessionTest.php
@@ -0,0 +1,95 @@
+<?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_Admin
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Admin
+ * @magentoDataFixture Mage/Admin/_files/user.php
+ */
+class Mage_Admin_Model_SessionTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Admin_Model_Session
+     */
+    protected $_model;
+
+    public function setUp()
+    {
+        $this->_model = new Mage_Admin_Model_Session();
+    }
+
+    public function testLoginFailed()
+    {
+        $result = $this->_model->login('not_exists', 'not_exists');
+        $this->assertFalse($result);
+    }
+
+    /**
+     * @magentoAppIsolation enabled
+     */
+    public function testLoginSuccessful()
+    {
+        $result = $this->_model->login(Mage_Admin_Utility_User::CRED_USERNAME, Mage_Admin_Utility_User::CRED_PASSWORD);
+        $this->assertInstanceOf('Mage_Admin_Model_User', $result);
+        $this->assertGreaterThan(time() - 10, $this->_model->getUpdatedAt());
+    }
+
+    public function testLogout()
+    {
+        $this->_model->login(Mage_Admin_Utility_User::CRED_USERNAME, Mage_Admin_Utility_User::CRED_PASSWORD);
+        $this->assertNotEmpty($this->_model->getData());
+        $this->_model->getCookie()->set($this->_model->getSessionName(), 'session_id');
+        $this->_model->logout();
+        $this->assertEmpty($this->_model->getData());
+        $this->assertEmpty($this->_model->getCookie()->get($this->_model->getSessionName()));
+    }
+
+    /**
+     * Disabled form security in order to prevent exit from the app
+     * @magentoConfigFixture current_store admin/security/session_lifetime 100
+     */
+    public function testIsLoggedIn()
+    {
+        $this->_model->login(Mage_Admin_Utility_User::CRED_USERNAME, Mage_Admin_Utility_User::CRED_PASSWORD);
+        $this->assertTrue($this->_model->isLoggedIn());
+
+        $this->_model->setUpdatedAt(time() - 101);
+        $this->assertFalse($this->_model->isLoggedIn());
+    }
+
+    /**
+     * Disabled form security in order to prevent exit from the app
+     * @magentoConfigFixture current_store admin/security/session_lifetime 59
+     */
+    public function testIsLoggedInWithIgnoredLifetime()
+    {
+        $this->_model->login(Mage_Admin_Utility_User::CRED_USERNAME, Mage_Admin_Utility_User::CRED_PASSWORD);
+        $this->assertTrue($this->_model->isLoggedIn());
+
+        $this->_model->setUpdatedAt(time() - 101);
+        $this->assertTrue($this->_model->isLoggedIn());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Admin/Model/UserTest.php b/dev/tests/integration/testsuite/Mage/Admin/Model/UserTest.php
index b440a7ffb8b1ea4a69674542411e211ce457c208..1ffc241da1c8ef4a26386c36ef5d505821bd969f 100644
--- a/dev/tests/integration/testsuite/Mage/Admin/Model/UserTest.php
+++ b/dev/tests/integration/testsuite/Mage/Admin/Model/UserTest.php
@@ -48,7 +48,7 @@ class Mage_Admin_Model_UserTest extends PHPUnit_Framework_TestCase
     {
         $this->_model->loadByUsername('non_existing_user');
         $this->assertNull($this->_model->getId(), 'The admin user has an unexpected ID');
-        $this->_model->loadByUsername('user');
+        $this->_model->loadByUsername(Mage_Admin_Utility_User::CRED_USERNAME);
         $this->assertNotEmpty($this->_model->getId(), 'The admin user should have been loaded');
     }
 }
diff --git a/dev/tests/integration/testsuite/Mage/Admin/Utility/User.php b/dev/tests/integration/testsuite/Mage/Admin/Utility/User.php
new file mode 100644
index 0000000000000000000000000000000000000000..2525520f9a5a8dad6a9f97c469a6e6d6709807b9
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Admin/Utility/User.php
@@ -0,0 +1,127 @@
+<?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_Admin
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Utility for managing admin user creation/destruction
+ */
+class Mage_Admin_Utility_User
+{
+    const CRED_USERNAME = 'user';
+    const CRED_PASSWORD = 'password';
+
+    /**
+     * @var Mage_Admin_Utility_User
+     */
+    protected static  $_instance;
+
+    /**
+     * @var Mage_Admin_Model_User
+     */
+    protected $_user;
+
+    /**
+     * @var Mage_Admin_Model_Role
+     */
+    protected $_roleUser;
+
+    /**
+     * Protected constructor - just to prohibit manual creation of this class
+     */
+    protected function __construct()
+    {
+    }
+
+    /**
+     * Returns instance of the class
+     *
+     * @return Mage_Admin_Utility_User
+     */
+    public static function getInstance()
+    {
+        if (!self::$_instance) {
+            self::$_instance = new self();
+        }
+        return self::$_instance;
+    }
+
+    /**
+     * Creates admin user and other stuff, needed for him
+     *
+     * @return Mage_Admin_Utility_User
+     */
+    public function createAdmin()
+    {
+        if ($this->_user) {
+            return $this;
+        }
+
+        $this->_user = new Mage_Admin_Model_User();
+        $this->_user->setData(array(
+            'firstname' => 'firstname',
+            'lastname'  => 'lastname',
+            'email'     => 'admin@example.com',
+            'username'  => self::CRED_USERNAME,
+            'password'  => self::CRED_PASSWORD,
+            'is_active' => 1
+        ));
+        $this->_user->save();
+
+        $roleAdmin = new Mage_Admin_Model_Role();
+        $roleAdmin->load('Administrators', 'role_name');
+
+        $this->_roleUser = new Mage_Admin_Model_Role();
+        $this->_roleUser->setData(array(
+            'parent_id'  => $roleAdmin->getId(),
+            'tree_level' => $roleAdmin->getTreeLevel() + 1,
+            'role_type'  => Mage_Admin_Model_Acl::ROLE_TYPE_USER,
+            'user_id'    => $this->_user->getId(),
+            'role_name'  => $this->_user->getFirstname(),
+        ));
+        $this->_roleUser->save();
+
+        return $this;
+    }
+
+    /**
+     * Destroys created user and all his stuff
+     * @return Mage_Admin_Utility_User
+     */
+    public function destroyAdmin()
+    {
+        if (!$this->_user) {
+            return $this;
+        }
+
+        $this->_roleUser->delete();
+        $this->_roleUser = null;
+
+        $this->_user->delete();
+        $this->_user = null;
+
+        return $this;
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Admin/_files/user.php b/dev/tests/integration/testsuite/Mage/Admin/_files/user.php
index b1be18ccb0611b115b77231d467e1f150d3f676c..2e20aff394b2bdd8197debe90444989ad3b2b46c 100644
--- a/dev/tests/integration/testsuite/Mage/Admin/_files/user.php
+++ b/dev/tests/integration/testsuite/Mage/Admin/_files/user.php
@@ -19,32 +19,11 @@
  * needs please refer to http://www.magentocommerce.com for more information.
  *
  * @category    Magento
- * @package     Mage_Adminhtml
+ * @package     Mage_Admin
  * @subpackage  integration_tests
  * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-$user = new Mage_Admin_Model_User();
-$user->setData(array(
-    'firstname' => 'firstname',
-    'lastname'  => 'lastname',
-    'email'     => 'admin@example.com',
-    'username'  => 'user',
-    'password'  => 'password',
-    'is_active' => 1
-));
-$user->save();
-
-$roleAdmin = new Mage_Admin_Model_Role();
-$roleAdmin->load('Administrators', 'role_name');
-
-$roleUser = new Mage_Admin_Model_Role();
-$roleUser->setData(array(
-    'parent_id'  => $roleAdmin->getId(),
-    'tree_level' => $roleAdmin->getTreeLevel() + 1,
-    'role_type'  => Mage_Admin_Model_Acl::ROLE_TYPE_USER,
-    'user_id'    => $user->getId(),
-    'role_name'  => $user->getFirstname(),
-));
-$roleUser->save();
+Mage_Admin_Utility_User::getInstance()
+    ->createAdmin();
diff --git a/dev/tests/integration/testsuite/Mage/Admin/_files/user_rollback.php b/dev/tests/integration/testsuite/Mage/Admin/_files/user_rollback.php
new file mode 100644
index 0000000000000000000000000000000000000000..f49c7518c8af331af577889b4bdebedf462d95d0
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Admin/_files/user_rollback.php
@@ -0,0 +1,29 @@
+<?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_Admin
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+Mage_Admin_Utility_User::getInstance()
+    ->destroyAdmin();
diff --git a/dev/tests/integration/testsuite/Mage/Adminhtml/Block/Dashboard/GraphTest.php b/dev/tests/integration/testsuite/Mage/Adminhtml/Block/Dashboard/GraphTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..23bfc2ea3f88da543022b792e9413d2cf4b0e71f
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Adminhtml/Block/Dashboard/GraphTest.php
@@ -0,0 +1,48 @@
+<?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_Adminhtml
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Adminhtml
+ */
+class Mage_Adminhtml_Block_Dashboard_GraphTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Adminhtml_Block_Dashboard_Graph
+     */
+    protected $_block;
+
+    protected function setUp()
+    {
+        $this->_block = new Mage_Adminhtml_Block_Dashboard_Graph;
+        $this->_block->setDataHelperName('Mage_Adminhtml_Helper_Dashboard_Order');
+    }
+
+    public function testGetChartUrl()
+    {
+        $this->assertStringStartsWith('http://chart.apis.google.com/chart', $this->_block->getChartUrl());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Adminhtml/Model/ObserverTest.php b/dev/tests/integration/testsuite/Mage/Adminhtml/Model/ObserverTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..d089a106c51f4b40385cd59aad371a2c1f3c3be3
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Adminhtml/Model/ObserverTest.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.
+ *
+ * @category    Magento
+ * @package     Mage_Adminhtml
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Adminhtml
+ */
+class Mage_Adminhtml_Model_ObserverTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Adminhtml_Model_Observer
+     */
+    protected $_model;
+
+    public function setUp()
+    {
+        $this->_model = new Mage_Adminhtml_Model_Observer();
+    }
+
+    public function testActionPreDispatchAdminNotLogged()
+    {
+        $request = Mage::app()->getRequest();
+        $this->assertEmpty($request->getRouteName());
+        $this->assertEmpty($request->getControllerName());
+        $this->assertEmpty($request->getActionName());
+
+        $observer = $this->_buildObserver();
+        $this->_model->actionPreDispatchAdmin($observer);
+
+        $this->assertEquals('adminhtml', $request->getRouteName());
+        $this->assertEquals('index', $request->getControllerName());
+        $this->assertEquals('login', $request->getActionName());
+    }
+
+    /**
+     * @magentoDataFixture adminUserFixture
+     * @magentoAppIsolation enabled
+     */
+    public function testActionPreDispatchAdminLoggedRedirect()
+    {
+        $observer = $this->_buildObserver();
+        $this->_model->actionPreDispatchAdmin($observer);
+
+        $response = Mage::app()->getResponse();
+        $code = $response->getHttpResponseCode();
+        $this->assertTrue($code >= 300 && $code < 400);
+
+        $session = Mage::getSingleton('Mage_Admin_Model_Session');
+        $this->assertTrue($session->isLoggedIn());
+    }
+
+    /**
+     * @magentoDataFixture adminUserFixture
+     * @magentoAppIsolation enabled
+     * @magentoConfigFixture current_store admin/security/use_form_key 0
+     */
+    public function testActionPreDispatchAdminLoggedNoRedirect()
+    {
+        $observer = $this->_buildObserver();
+        $this->_model->actionPreDispatchAdmin($observer);
+
+        $response = Mage::app()->getResponse();
+        $code = $response->getHttpResponseCode();
+        $this->assertFalse($code >= 300 && $code < 400);
+
+        $session = Mage::getSingleton('Mage_Admin_Model_Session');
+        $this->assertTrue($session->isLoggedIn());
+    }
+
+    /**
+     * Builds a dummy observer for testing adminPreDispath method
+     *
+     * @return Varien_Object
+     */
+    protected function _buildObserver()
+    {
+        $request = Mage::app()->getRequest();
+        $request->setPost(
+            'login',
+            array(
+                'username' => Mage_Admin_Utility_User::CRED_USERNAME,
+                'password' => Mage_Admin_Utility_User::CRED_PASSWORD
+            )
+        );
+
+        $controller = new Varien_Object(array('request' => $request));
+        $event = new Varien_Object(array('controller_action' => $controller));
+        $observer = new Varien_Object(array('event' => $event));
+        return $observer;
+    }
+
+    public static function adminUserFixture()
+    {
+        Mage_Admin_Utility_User::getInstance()
+            ->createAdmin();
+    }
+
+    public static function adminUserFixtureRollback()
+    {
+        Mage_Admin_Utility_User::getInstance()
+            ->destroyAdmin();
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Adminhtml/Utility/Controller.php b/dev/tests/integration/testsuite/Mage/Adminhtml/Utility/Controller.php
new file mode 100644
index 0000000000000000000000000000000000000000..e8b5d5cf7d4d7ef517fa4c6382def2144b2886ef
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Adminhtml/Utility/Controller.php
@@ -0,0 +1,67 @@
+<?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_Adminhtml
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * A parent class for adminhtml controllers - contains directives for admin user creation and logging in
+ * @SuppressWarnings(PHPMD.NumberOfChildren)
+ * @SuppressWarnings(PHPMD.numberOfChildren)
+ */
+class Mage_Adminhtml_Utility_Controller extends Magento_Test_TestCase_ControllerAbstract
+{
+    /**
+     * @var Mage_Admin_Model_Session
+     */
+    protected $_session;
+
+    protected function setUp()
+    {
+        parent::setUp();
+
+        Mage::getSingleton('Mage_Core_Model_Resource')->getConnection('write')
+            ->beginTransaction();
+
+        Mage::getSingleton('Mage_Adminhtml_Model_Url')->turnOffSecretKey();
+        Mage_Admin_Utility_User::getInstance()
+            ->createAdmin();
+
+        $this->_session = new Mage_Admin_Model_Session();
+        $this->_session->login(Mage_Admin_Utility_User::CRED_USERNAME, Mage_Admin_Utility_User::CRED_PASSWORD);
+    }
+
+    protected function tearDown()
+    {
+        $this->_session->logout();
+        Mage_Admin_Utility_User::getInstance()
+            ->destroyAdmin();
+        Mage::getSingleton('Mage_Adminhtml_Model_Url')->turnOnSecretKey();
+
+        Mage::getSingleton('Mage_Core_Model_Resource')->getConnection('write')
+            ->rollBack();
+
+        parent::tearDown();
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Adminhtml/_files/form_key_disabled.php b/dev/tests/integration/testsuite/Mage/Adminhtml/_files/form_key_disabled.php
new file mode 100644
index 0000000000000000000000000000000000000000..5e09b4ca1949e0c34c7f8d25f167254a4f4e9c3f
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Adminhtml/_files/form_key_disabled.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.
+ *
+ * @category    Magento
+ * @package     Mage_Adminhtml
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+Mage::getSingleton('Mage_Adminhtml_Model_Url')->turnOffSecretKey();
diff --git a/dev/tests/integration/testsuite/Mage/Adminhtml/_files/form_key_disabled_rollback.php b/dev/tests/integration/testsuite/Mage/Adminhtml/_files/form_key_disabled_rollback.php
new file mode 100644
index 0000000000000000000000000000000000000000..0052ce181adb51f3f4527e747e54e41b945fa1e3
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Adminhtml/_files/form_key_disabled_rollback.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.
+ *
+ * @category    Magento
+ * @package     Mage_Adminhtml
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+Mage::getSingleton('Mage_Adminhtml_Model_Url')->turnOnSecretKey();
diff --git a/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/Customer/GroupControllerTest.php b/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/Customer/GroupControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..d056cdaa560f2a6b1099478a5fd1a5318bd409f2
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/Customer/GroupControllerTest.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.
+ *
+ * @category    Mage
+ * @package     Mage_Adminhtml
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Adminhtml
+ */
+class Mage_Adminhtml_Customer_GroupControllerTest extends Mage_Adminhtml_Utility_Controller
+{
+    public function testNewAction()
+    {
+        $this->dispatch('admin/customer_group/new');
+        $responseBody = $this->getResponse()->getBody();
+        $this->assertStringMatchesFormat('%a<div class="content-header">%ANew Customer Group%a', $responseBody);
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/Permissions/UserControllerTest.php b/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/Permissions/UserControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..9ba8fcc910f36e1f14439043e52b1693fb2da126
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/Permissions/UserControllerTest.php
@@ -0,0 +1,41 @@
+<?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_Adminhtml
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Adminhtml
+ */
+class Mage_Adminhtml_Permissions_UserControllerTest extends Mage_Adminhtml_Utility_Controller
+{
+    /**
+     * @covers Mage_Adminhtml_Controller_Action::_addContent
+     */
+    public function testIndexAction()
+    {
+        $this->dispatch('admin/permissions_user/index');
+        $this->assertStringMatchesFormat('%a<div class="content-header">%aUsers%a', $this->getResponse()->getBody());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/Sales/Order/CreateControllerTest.php b/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/Sales/Order/CreateControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..71b5c8cccb0bc128c0a63b1529520c58469f3445
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/Sales/Order/CreateControllerTest.php
@@ -0,0 +1,40 @@
+<?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_Adminhtml
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Adminhtml
+ */
+class Mage_Adminhtml_Sales_Order_CreateControllerTest extends Mage_Adminhtml_Utility_Controller
+{
+    public function testLoadBlockAction()
+    {
+        $this->getRequest()->setParam('block', ',');
+        $this->getRequest()->setParam('json', 1);
+        $this->dispatch('admin/sales_order_create/loadBlock');
+        $this->assertEquals('{"message":""}', $this->getResponse()->getBody());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/Sales/OrderControllerTest.php b/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/Sales/OrderControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..bed99d2534a09785716c575ed1b82f1b5d01a26b
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/Sales/OrderControllerTest.php
@@ -0,0 +1,47 @@
+<?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  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Adminhtml
+ */
+class Mage_Adminhtml_Sales_OrderControllerTest extends Mage_Adminhtml_Utility_Controller
+{
+    public function testIndexAction()
+    {
+        $this->dispatch('admin/sales_order/index');
+        $this->assertContains('Total 0 records found', $this->getResponse()->getBody());
+    }
+
+    /**
+     * @magentoDataFixture Mage/Sales/_files/order.php
+     */
+    public function testIndexActionWithOrder()
+    {
+        $this->dispatch('admin/sales_order/index');
+        $this->assertContains('Total 1 records found', $this->getResponse()->getBody());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/System/ConfigControllerTest.php b/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/System/ConfigControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..d99ba1cb45573f6b62c1ddb9dc795cf4e953dd9a
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/System/ConfigControllerTest.php
@@ -0,0 +1,38 @@
+<?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_Adminhtml
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Adminhtml
+ */
+class Mage_Adminhtml_System_ConfigControllerTest extends Mage_Adminhtml_Utility_Controller
+{
+    public function testEditAction()
+    {
+        $this->dispatch('admin/system_config/edit');
+        $this->assertContains('<ul id="system_config_tabs"', $this->getResponse()->getBody());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/System/DesignControllerTest.php b/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/System/DesignControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..62d1cc67bb7d1a679381c4fe2b8c989b66af1f6d
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/System/DesignControllerTest.php
@@ -0,0 +1,41 @@
+<?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_Adminhtml
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Adminhtml
+ */
+class Mage_Adminhtml_System_DesignControllerTest extends Mage_Adminhtml_Utility_Controller
+{
+    /**
+     * @covers Mage_Adminhtml_Controller_Action::_addLeft
+     */
+    public function testEditAction()
+    {
+        $this->dispatch('admin/system_design/edit');
+        $this->assertStringMatchesFormat('%A<a%Aid="design_tabs_general"%A', $this->getResponse()->getBody());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/System/VariableControllerTest.php b/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/System/VariableControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..738cc93ccce824c1a7eb3a93b52523f813ded3cb
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Adminhtml/controllers/System/VariableControllerTest.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.
+ *
+ * @category    Mage
+ * @package     Mage_Adminhtml
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Adminhtml
+ */
+class Mage_Adminhtml_System_VariableControllerTest extends Mage_Adminhtml_Utility_Controller
+{
+    /**
+     * @covers Mage_Adminhtml_Controller_Action::_addLeft
+     */
+    public function testEditAction()
+    {
+        $this->dispatch('admin/system_variable/edit');
+        $body = $this->getResponse()->getBody();
+        $this->assertContains('function toggleValueElement(element) {', $body);
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Authorizenet/controllers/Directpost/PaymentControllerTest.php b/dev/tests/integration/testsuite/Mage/Authorizenet/controllers/Directpost/PaymentControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..e2fcf7aa10658e33cb86ab1bf3e3a03051e82794
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Authorizenet/controllers/Directpost/PaymentControllerTest.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.
+ *
+ * @category    Magento
+ * @package     Mage_Authorizenet
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Authorizenet
+ */
+class Mage_Authorizenet_Directpost_PaymentControllerTest extends Magento_Test_TestCase_ControllerAbstract
+{
+    public function testResponseActionValidationFiled()
+    {
+        $this->getRequest()->setPost('controller_action_name', 'onepage');
+        $this->dispatch('authorizenet/directpost_payment/response');
+        $this->assertContains(
+            'authorizenet/directpost_payment/redirect/success/0/error_msg/Response hash validation failed.'
+                . ' Transaction declined.',
+            $this->getResponse()->getBody()
+        );
+    }
+
+    public function testRedirectActionErrorMessage()
+    {
+        $this->getRequest()->setParam('success', '0');
+        $this->getRequest()->setParam('error_msg', 'Error message');
+        $this->dispatch('authorizenet/directpost_payment/redirect');
+        $this->assertContains(
+            'window.top.directPostModel.showError("Error message");',
+            $this->getResponse()->getBody()
+        );
+    }
+
+}
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/Block/Product/AbstractTest.php b/dev/tests/integration/testsuite/Mage/Catalog/Block/Product/AbstractTest.php
index 0f8a359470f1ef7b299cb2074c3377c0ce5f2fd8..333874086dc29831e10a5a3caffc99867ed8bf05 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/Block/Product/AbstractTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Block/Product/AbstractTest.php
@@ -25,14 +25,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-/**
- * Empty class for testing
- */
-class Mage_Catalog_Block_Product_AbstractTestAbstract extends Mage_Catalog_Block_Product_Abstract
-{
-
-}
-
 /**
  * Test class for Mage_Catalog_Block_Product_Abstract.
  *
@@ -43,7 +35,7 @@ class Mage_Catalog_Block_Product_AbstractTestAbstract extends Mage_Catalog_Block
 class Mage_Catalog_Block_Product_AbstractTest extends PHPUnit_Framework_TestCase
 {
     /**
-     * @var Mage_Catalog_Block_Product_AbstractTestAbstract
+     * @var Mage_Catalog_Block_Product_Abstract
      */
     protected $_block;
 
@@ -59,7 +51,7 @@ class Mage_Catalog_Block_Product_AbstractTest extends PHPUnit_Framework_TestCase
 
     protected function setUp()
     {
-        $this->_block = new Mage_Catalog_Block_Product_AbstractTestAbstract;
+        $this->_block = $this->getMockForAbstractClass('Mage_Catalog_Block_Product_Abstract');
         $this->_product = new Mage_Catalog_Model_Product();
         $this->_product->load(1);
         $this->_product->addData(array(
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/Block/Product/ListTest.php b/dev/tests/integration/testsuite/Mage/Catalog/Block/Product/ListTest.php
index d3f1bfb733bdd5f61be2035fdec2d853b25bf97e..8bc2859e198402e9c775e8d6fafdc098af84e174 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/Block/Product/ListTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Block/Product/ListTest.php
@@ -68,29 +68,33 @@ class Mage_Catalog_Block_Product_ListTest extends PHPUnit_Framework_TestCase
      */
     public function testToolbarCoverage()
     {
-        $this->_block->setLayout(new Mage_Core_Model_Layout());
+        $parent = $this->_getLayout()->createBlock('Mage_Catalog_Block_Product_List', 'parent');
 
         /* Prepare toolbar block */
-        $toolbar = $this->_block->getToolbarBlock();
+        $toolbar = $parent->getToolbarBlock();
         $this->assertInstanceOf('Mage_Catalog_Block_Product_List_Toolbar', $toolbar, 'Default Toolbar');
 
-        $this->_block->setChild('toolbar', $toolbar);
+        $parent->setChild('toolbar', $toolbar);
         /* In order to initialize toolbar collection block toHtml should be called before toolbar toHtml */
-        $this->assertEmpty($this->_block->toHtml(), 'Block HTML'); /* Template not specified */
-        $this->assertEquals('grid', $this->_block->getMode(), 'Default Mode'); /* default mode */
-        $this->assertNotEmpty($this->_block->getToolbarHtml(), 'Toolbar HTML'); /* toolbar for one simple product */
+        $this->assertEmpty($parent->toHtml(), 'Block HTML'); /* Template not specified */
+        $this->assertEquals('grid', $parent->getMode(), 'Default Mode'); /* default mode */
+        $this->assertNotEmpty($parent->getToolbarHtml(), 'Toolbar HTML'); /* toolbar for one simple product */
     }
 
 
     public function testGetAdditionalHtmlEmpty()
     {
+        $this->_block->setLayout($this->_getLayout());
         $this->assertEmpty($this->_block->getAdditionalHtml());
     }
 
     public function testGetAdditionalHtml()
     {
-        $this->_block->setChild('additional', new Mage_Core_Block_Text(array('text' => 'test')));
-        $this->assertEquals('test', $this->_block->getAdditionalHtml());
+        $layout = $this->_getLayout();
+        $parent = $layout->createBlock('Mage_Catalog_Block_Product_List');
+        $childBlock = $layout->createBlock('Mage_Core_Block_Text', 'test', array('text' => 'test'));
+        $layout->setChild($parent->getNameInLayout(), $childBlock->getNameInLayout(), 'additional');
+        $this->assertEquals('test', $parent->getAdditionalHtml());
     }
 
     public function testSetCollection()
@@ -113,4 +117,9 @@ class Mage_Catalog_Block_Product_ListTest extends PHPUnit_Framework_TestCase
         $this->_block->prepareSortableFieldsByCategory($category);
         $this->assertEquals('name', $this->_block->getSortBy());
     }
+
+    protected function _getLayout()
+    {
+        return Mage::app()->getLayout();
+    }
 }
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/Block/Product/ViewTest.php b/dev/tests/integration/testsuite/Mage/Catalog/Block/Product/ViewTest.php
index 2f702efdaeb8ba9bc58b094e94482db9a386f14a..67de42e31ea480cadbc9114a24a589a15b129aaa 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/Block/Product/ViewTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Block/Product/ViewTest.php
@@ -58,7 +58,7 @@ class Mage_Catalog_Block_Product_ViewTest extends PHPUnit_Framework_TestCase
         $layout = new Mage_Core_Model_Layout();
         $headBlock = new Mage_Core_Block_Template();
         $layout->addBlock($headBlock, 'head');
-        $this->_block->setLayout($layout);
+        $layout->addBlock($this->_block);
 
         $this->assertNotEmpty($headBlock->getTitle());
         $this->assertEquals($this->_product->getMetaTitle(), $headBlock->getTitle());
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/Helper/Product/CompareTest.php b/dev/tests/integration/testsuite/Mage/Catalog/Helper/Product/CompareTest.php
index 17c1af84744ed77a4478e09b88433df9bc40aba8..a05022c97f5a06b41e27dce7d05229b36f4aa8be 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/Helper/Product/CompareTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Helper/Product/CompareTest.php
@@ -49,7 +49,7 @@ class Mage_Catalog_Helper_Product_CompareTest extends PHPUnit_Framework_TestCase
         $this->assertContains('/catalog/product_compare/index/', $empty->getListUrl());
 
         $this->_populateCompareList();
-        $this->assertContains('/catalog/product_compare/index/items/10,11/', $this->_helper->getListUrl());
+        $this->assertRegExp('#/catalog/product_compare/index/items/(?:10,11|11,10)/#', $this->_helper->getListUrl());
     }
 
     public function testGetAddUrl()
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 8a1221fe1a4069a7ad030f3c54f8f9ba87f320c9..d8807118236ea960679b3c407eac0b506dd0cfd4 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/Helper/Product/ViewTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Helper/Product/ViewTest.php
@@ -45,7 +45,11 @@ class Mage_Catalog_Helper_Product_ViewTest extends PHPUnit_Framework_TestCase
     protected function setUp()
     {
         $this->_helper = new Mage_Catalog_Helper_Product_View;
-        $this->_controller = new Mage_Catalog_ProductController(new Magento_Test_Request, new Magento_Test_Response);
+        $request = new Magento_Test_Request();
+        $request->setRouteName('catalog')
+            ->setControllerName('product')
+            ->setActionName('view');
+        $this->_controller = new Mage_Catalog_ProductController($request, new Magento_Test_Response);
     }
 
     /**
@@ -56,18 +60,22 @@ class Mage_Catalog_Helper_Product_ViewTest extends PHPUnit_Framework_TestCase
         Mage::getSingleton('Mage_Catalog_Model_Session')->unsLastViewedProductId();
     }
 
+    /**
+     * @magentoAppIsolation enabled
+     */
     public function testInitProductLayout()
     {
         $uniqid = uniqid();
         $product = new Mage_Catalog_Model_Product;
         $product->setTypeId(Mage_Catalog_Model_Product_Type::DEFAULT_TYPE)->setId(99)->setUrlKey($uniqid);
+        Mage::register('product', $product);
+
         $this->_helper->initProductLayout($product, $this->_controller);
         $rootBlock = $this->_controller->getLayout()->getBlock('root');
         $this->assertInstanceOf('Mage_Page_Block_Html', $rootBlock);
         $this->assertContains("product-{$uniqid}", $rootBlock->getBodyClass());
         $handles = $this->_controller->getLayout()->getUpdate()->getHandles();
-        $this->arrayHasKey('PRODUCT_99', $handles);
-        $this->arrayHasKey('PRODUCT_TYPE_simple', $handles);
+        $this->assertContains('catalog_product_view_type_simple', $handles);
     }
 
     /**
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/Model/AbstractTest.php b/dev/tests/integration/testsuite/Mage/Catalog/Model/AbstractTest.php
index bf17bcb9767a09bf9bcdef78cad260d2dc945121..3d48f054e26926ee024b7a7c19ed0f6bf5361ddf 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/Model/AbstractTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Model/AbstractTest.php
@@ -25,17 +25,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-/**
- * The class is not really abstract, therefore can be tested with a dummy descendant.
- *
- * @SuppressWarnings(PHPMD.LongVariable)
- */
-class Mage_Catalog_Model_AbstractTestAbstract extends Mage_Catalog_Model_Abstract
-{
-    protected $_resourceCollectionName = 'Mage_Catalog_Model_Resource_Product_Collection';
-    protected $_resourceName = 'Mage_Catalog_Model_Resource_Product';
-}
-
 /**
  * @group module:Mage_Catalog
  */
@@ -46,13 +35,17 @@ class Mage_Catalog_Model_AbstractTest extends PHPUnit_Framework_TestCase
      */
     protected $_model;
 
-    /**
-     * Sets up the fixture, for example, opens a network connection.
-     * This method is called before a test is executed.
-     */
     protected function setUp()
     {
-        $this->_model = new Mage_Catalog_Model_AbstractTestAbstract;
+        $this->_model = $this->getMockForAbstractClass('Mage_Catalog_Model_Abstract');
+
+        $resourceProperty = new ReflectionProperty(get_class($this->_model), '_resourceName');
+        $resourceProperty->setAccessible(true);
+        $resourceProperty->setValue($this->_model, 'Mage_Catalog_Model_Resource_Product');
+
+        $collectionProperty = new ReflectionProperty(get_class($this->_model), '_resourceCollectionName');
+        $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 e7405acf0c64cb5d83e0ccfd679f6dfaa1cd67bf..925e280d7c9729797f235b97f3eecb1ed0a93859 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/Model/CategoryTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Model/CategoryTest.php
@@ -115,13 +115,6 @@ class Mage_Catalog_Model_CategoryTest extends PHPUnit_Framework_TestCase
         $this->assertContains(Mage::app()->getStore()->getId(), $this->_model->getStoreIds());
     }
 
-    public function testGetLayoutUpdateHandle()
-    {
-        $this->assertEquals('catalog_category_default', $this->_model->getLayoutUpdateHandle());
-        $this->_model->setIsAnchor(true);
-        $this->assertEquals('catalog_category_layered', $this->_model->getLayoutUpdateHandle());
-    }
-
     public function testSetGetStoreId()
     {
         $this->assertEquals(Mage::app()->getStore()->getId(), $this->_model->getStoreId());
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/Price/AlgorithmAdvancedTest.php b/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/Price/AlgorithmAdvancedTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..f1c57b7d2a4c0b7b7076e2dd1b694cf9c35ece5f
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/Price/AlgorithmAdvancedTest.php
@@ -0,0 +1,100 @@
+<?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_Catalog
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Test class for Mage_Catalog_Model_Layer_Filter_Price.
+ *
+ * @group module:Mage_Catalog
+ * @magentoDataFixture Mage/Catalog/Model/Layer/Filter/Price/_files/products_advanced.php
+ */
+class Mage_Catalog_Model_Layer_Filter_Price_AlgorithmAdvancedTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * Algorithm model
+     *
+     * @var Mage_Catalog_Model_Layer_Filter_Price_Algorithm
+     */
+    protected $_model;
+
+    protected function setUp()
+    {
+        $this->_model = new Mage_Catalog_Model_Layer_Filter_Price_Algorithm();
+    }
+
+    /**
+     * Prepare price filter model
+     *
+     * @param Magento_Test_Request|null $request
+     * @return void
+     */
+    protected function _prepareFilter($request = null)
+    {
+        $layer = new Mage_Catalog_Model_Layer();
+        $layer->setCurrentCategory(4);
+        $layer->setState(new Mage_Catalog_Model_Layer_State());
+        $filter = new Mage_Catalog_Model_Layer_Filter_Price();
+        $filter->setLayer($layer)->setAttributeModel(new Varien_Object(array('attribute_code' => 'price')));
+        if (!is_null($request)) {
+            $filter->apply($request, new Mage_Core_Block_Text());
+            $interval = $filter->getInterval();
+            if ($interval) {
+                $this->_model->setLimits($interval[0], $interval[1]);
+            }
+        }
+        $collection = $layer->getProductCollection();
+        $this->_model->setPricesModel($filter)->setStatistics(
+            $collection->getMinPrice(),
+            $collection->getMaxPrice(),
+            $collection->getPriceStandardDeviation(),
+            $collection->getSize()
+        );
+    }
+
+    public function testWithoutLimits()
+    {
+        $this->markTestIncomplete('Bug MAGE-6498');
+        $request = new Magento_Test_Request();
+        $request->setParam('price', null);
+        $this->_prepareFilter();
+        $this->assertEquals(array(
+            0 => array('from' => 0, 'to' => 20, 'count' => 3),
+            1 => array('from' => 20, 'to' => '', 'count' => 4)
+        ), $this->_model->calculateSeparators());
+    }
+
+    public function testWithLimits()
+    {
+        $this->markTestIncomplete('Bug MAGE-6561');
+        $request = new Magento_Test_Request();
+        $request->setParam('price', '10-100');
+        $this->_prepareFilter($request);
+        $this->assertEquals(array(
+            0 => array('from' => 10, 'to' => 20, 'count' => 2),
+            1 => array('from' => 20, 'to' => 100, 'count' => 2)
+        ), $this->_model->calculateSeparators());
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Catalog/Model/Layer/Filter/Price/AlgorithmTest.php b/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/Price/AlgorithmBaseTest.php
similarity index 59%
rename from dev/tests/unit/testsuite/Mage/Catalog/Model/Layer/Filter/Price/AlgorithmTest.php
rename to dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/Price/AlgorithmBaseTest.php
index e51e5d846f3f7b171bfda7de929441c1a215f7ba..501fec0c2b063188635466a732919d8786ed811b 100644
--- a/dev/tests/unit/testsuite/Mage/Catalog/Model/Layer/Filter/Price/AlgorithmTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/Price/AlgorithmBaseTest.php
@@ -26,14 +26,16 @@
  */
 
 /**
- * Test class for Mage_Catalog_Model_Layer_Filter_Price_Algorithm.
+ * Test class for Mage_Catalog_Model_Layer_Filter_Price.
  *
  * @group module:Mage_Catalog
- * @magentoConfigFixture current_store catalog/layered_navigation/price_range_calculation auto
+ * @magentoDataFixture Mage/Catalog/Model/Layer/Filter/Price/_files/products_base.php
  */
-class Mage_Catalog_Model_Layer_Filter_Price_AlgorithmTest extends PHPUnit_Framework_TestCase
+class Mage_Catalog_Model_Layer_Filter_Price_AlgorithmBaseTest extends PHPUnit_Framework_TestCase
 {
     /**
+     * Algorithm model
+     *
      * @var Mage_Catalog_Model_Layer_Filter_Price_Algorithm
      */
     protected $_model;
@@ -46,9 +48,22 @@ class Mage_Catalog_Model_Layer_Filter_Price_AlgorithmTest extends PHPUnit_Framew
     /**
      * @dataProvider pricesSegmentationDataProvider
      */
-    public function testPricesSegmentation($prices, $intervalsNumber, $intervalItems)
+    public function testPricesSegmentation($categoryId, $intervalsNumber, $intervalItems)
     {
-        $this->_model->setLimits()->setPrices($prices);
+        $this->markTestIncomplete('Bug MAGE-6498');
+        // ini_set('memory_limit', '128M');
+        $layer = new Mage_Catalog_Model_Layer();
+        $layer->setCurrentCategory($categoryId);
+        $filter = new Mage_Catalog_Model_Layer_Filter_Price();
+        $filter->setLayer($layer)->setAttributeModel(new Varien_Object(array('attribute_code' => 'price')));
+        $collection = $layer->getProductCollection();
+        $this->_model->setPricesModel($filter)->setStatistics(
+            $collection->getMinPrice(),
+            $collection->getMaxPrice(),
+            $collection->getPriceStandardDeviation(),
+            $collection->getSize()
+        );
+
         if (!is_null($intervalsNumber)) {
             $this->assertEquals($intervalsNumber, $this->_model->getIntervalsNumber());
         }
@@ -62,25 +77,21 @@ class Mage_Catalog_Model_Layer_Filter_Price_AlgorithmTest extends PHPUnit_Framew
             $this->assertEquals($intervalItems[$i]['to'], $items[$i]['to']);
             $this->assertEquals($intervalItems[$i]['count'], $items[$i]['count']);
         }
+        // ini_restore('memory_limit');
     }
 
     public function pricesSegmentationDataProvider()
     {
-        return include(__DIR__ . '/_files/_algorithm_data.php');
-    }
-
-    public function testPriceLimits()
-    {
-        $this->_model->setLimits()->setPrices(array(5, 10, 15, 20, 50, 100, 150));
-        $this->assertEquals(array(
-            0 => array('from' => 0, 'to' => 20, 'count' => 3),
-            1 => array('from' => 20, 'to' => '', 'count' => 4)
-        ), $this->_model->calculateSeparators());
+        $testCases = include(dirname(__FILE__) . '/_files/_algorithm_base_data.php');
+        $result = array();
+        foreach ($testCases as $index => $testCase) {
+            $result[] = array(
+                $index + 4, //category id
+                $testCase[1],
+                $testCase[2]
+            );
+        }
 
-        $this->_model->setLimits(10, 100);
-        $this->assertEquals(array(
-            0 => array('from' => 10, 'to' => 20, 'count' => 2),
-            1 => array('from' => 20, 'to' => 100, 'count' => 2)
-        ), $this->_model->calculateSeparators());
+        return $result;
     }
 }
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/Price/_files/_algorithm_base_data.php b/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/Price/_files/_algorithm_base_data.php
new file mode 100644
index 0000000000000000000000000000000000000000..4fc9732150e4f7ab9f78ad6c5fec1ba0ee049f18
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/Price/_files/_algorithm_base_data.php
@@ -0,0 +1,220 @@
+<?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_Catalog
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Test cases for pricesSegmentationDataProvider
+ */
+$testCases = array(
+    // no products, no prices
+    array(array(), 1, array()),
+    // small prices
+    array(range(0.01, 0.08, 0.01), 2, array(
+        array(
+            'from'  => 0,
+            'to'    => 0.05,
+            'count' => 4,
+        ),
+        array(
+            'from'  => 0.05,
+            'to'    => '',
+            'count' => 4,
+        ),
+    )),
+    // zero price test
+    array(array(0, 0.71, 0.89), 2, array(
+        array(
+            'from'  => 0,
+            'to'    => 0,
+            'count' => 1,
+        ),
+        array(
+            'from'  => 0.5,
+            'to'    => '',
+            'count' => 2,
+        ),
+    )),
+    // first quantile should be skipped
+    array(
+        array(
+            0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01,
+            0.01, 0.03, 0.05, 0.05, 0.06, 0.07, 0.07, 0.08, 0.08, 0.09, 0.15
+        ), 3, array(
+            array(
+                'from'  => 0,
+                'to'    => 0.05,
+                'count' => 12,
+            ),
+            array(
+                'from'  => 0.05,
+                'to'    => '',
+                'count' => 9,
+            ),
+        )
+    ),
+    // test if best rounding factor is used
+    array(
+        array(10.19, 10.2, 10.2, 10.2, 10.21),
+        2,
+        array(
+            array(
+                'from'  => 10.19,
+                'to'    => 10.19,
+                'count' => 1,
+            ),
+            array(
+                'from'  => 10.2,
+                'to'    => '',
+                'count' => 4,
+            ),
+        )
+    ),
+    // quantiles interception
+    array(
+        array(
+            5.99, 5.99, 7.99, 8.99, 8.99, 9.99, 9.99, 9.99, 9.99, 9.99,
+            14.6, 15.99, 16, 16.99, 17, 17.5, 18.99, 19, 20.99, 24.99
+        ), 3, array(
+            array(
+                'from'  => 0,
+                'to'    => 9,
+                'count' => 5,
+            ),
+            array(
+                'from'  => 9.99,
+                'to'    => 9.99,
+                'count' => 5,
+            ),
+            array(
+                'from'  => 10,
+                'to'    => '',
+                'count' => 10,
+            ),
+        )
+    ),
+    // test if best rounding factor is used
+    array(
+        array(10.18, 10.19, 10.19, 10.19, 10.2),
+        2,
+        array(
+            array(
+                'from'  => 0,
+                'to'    => 10.2,
+                'count' => 4,
+            ),
+            array(
+                'from'  => 10.2,
+                'to'    => 10.2,
+                'count' => 1,
+            ),
+        )
+    ),
+    // test many equal values
+    array(
+        array_merge(array(10.57), array_fill(0, 20, 10.58), array(10.59)),
+        6,
+        array(
+            array(
+                'from'  => 10.57,
+                'to'    => 10.57,
+                'count' => 1,
+            ),
+            array(
+                'from'  => 10.58,
+                'to'    => 10.58,
+                'count' => 20,
+            ),
+            array(
+                'from'  => 10.59,
+                'to'    => 10.59,
+                'count' => 1,
+            ),
+        )
+    ),
+    // test preventing low count in interval and rounding factor to have lower priority
+    array(
+        array(
+            0.01, 0.01, 0.01, 0.02, 0.02, 0.03, 0.03, 0.04, 0.04, 0.04,
+            0.05, 0.05, 0.05, 0.06, 0.06, 0.06, 0.06, 0.07, 0.07, 0.08, 0.08,
+            2.99, 5.99, 5.99, 5.99, 5.99, 5.99, 5.99, 5.99, 5.99, 5.99, 13.50,
+            15.99, 41.95, 69.99, 89.99, 99.99, 99.99, 160.99, 161.94,
+            199.99, 199.99, 199.99, 239.99, 329.99, 447.98, 550.00, 599.99,
+            699.99, 750.00, 847.97, 1599.99, 2699.99, 4999.95
+        ), 7, array(
+            array(
+                'from'  => 0,
+                'to'    => 0.05,
+                'count' => 10,
+            ),
+            // this is important, that not 0.06 is used to prevent low count in interval
+            array(
+                'from'  => 0.05,
+                'to'    => 0.07,
+                'count' => 7,
+            ),
+            array(
+                'from'  => 0.07,
+                'to'    => 5,
+                'count' => 5,
+            ),
+            array(
+                'from'  => 5.99,
+                'to'    => 5.99,
+                'count' => 9,
+            ),
+            array(
+                'from'  => 10,
+                'to'    => 100,
+                'count' => 7,
+            ),
+            array(
+                'from'  => 100,
+                'to'    => 500,
+                'count' => 8,
+            ),
+            array(
+                'from'  => 500,
+                'to'    => '',
+                'count' => 8,
+            ),
+        )
+    ),
+    // large numbers test
+    array(array(100000, 400000, 600000, 900000), 2, array(
+        array(
+            'from'  => 0,
+            'to'    => 500000,
+            'count' => 2,
+        ),
+        array(
+            'from'  => 500000,
+            'to'    => '',
+            'count' => 2,
+        ),
+    )),
+);
+
+return $testCases;
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/Price/_files/products_advanced.php b/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/Price/_files/products_advanced.php
new file mode 100644
index 0000000000000000000000000000000000000000..05d6be00e400550a5f9e549c9a8ad587d0ea5d7d
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/Price/_files/products_advanced.php
@@ -0,0 +1,82 @@
+<?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_Catalog
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Products generation to test base data
+ */
+
+$prices = array(5, 10, 15, 20, 50, 100, 150);
+
+$installer = new Mage_Catalog_Model_Resource_Setup('catalog_setup');
+/**
+ * After installation system has two categories: root one with ID:1 and Default category with ID:2
+ */
+$category = new Mage_Catalog_Model_Category();
+
+$category->setId(3)
+    ->setName('Root Category')
+    ->setParentId(2) /**/
+    ->setPath('1/2/3')
+    ->setLevel(2)
+    ->setAvailableSortBy('name')
+    ->setDefaultSortBy('name')
+    ->setIsActive(true)
+    ->setPosition(1)
+    ->save();
+
+$category = new Mage_Catalog_Model_Category();
+$category->setId(4)
+    ->setName('PLN Category')
+    ->setParentId(3)
+    ->setPath('1/2/3/4')
+    ->setLevel(3)
+    ->setAvailableSortBy('name')
+    ->setDefaultSortBy('name')
+    ->setIsActive(true)
+    ->setIsAnchor(true)
+    ->setPosition(1)
+    ->save();
+
+$lastProductId = 0;
+foreach ($prices as $price) {
+    $product = new Mage_Catalog_Model_Product();
+    $productId = $lastProductId + 1;
+    $product->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE)
+        ->setId($productId)
+        ->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default'))
+        ->setStoreId(1)
+        ->setWebsiteIds(array(1))
+        ->setName('Simple Product ' . $productId)
+        ->setSku('simple-' . $productId)
+        ->setPrice($price)
+        ->setWeight(18)
+        ->setCategoryIds(array(4))
+        ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
+        ->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
+        ->save();
+    ++$lastProductId;
+}
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/Price/_files/products_base.php b/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/Price/_files/products_base.php
new file mode 100644
index 0000000000000000000000000000000000000000..a9adc39c07633ca599bbba628368022f1e48e21b
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/Price/_files/products_base.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    Magento
+ * @package     Mage_Catalog
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Products generation to test base data
+ */
+
+$testCases = include(dirname(__FILE__) . '/_algorithm_base_data.php');
+
+$installer = new Mage_Catalog_Model_Resource_Setup('catalog_setup');
+/**
+ * After installation system has two categories: root one with ID:1 and Default category with ID:2
+ */
+$category = new Mage_Catalog_Model_Category();
+
+$category->setId(3)
+    ->setName('Root Category')
+    ->setParentId(2) /**/
+    ->setPath('1/2/3')
+    ->setLevel(2)
+    ->setAvailableSortBy('name')
+    ->setDefaultSortBy('name')
+    ->setIsActive(true)
+    ->setPosition(1)
+    ->save();
+
+$lastProductId = 0;
+foreach ($testCases as $index => $testCase) {
+    $category = new Mage_Catalog_Model_Category();
+    $position = $index + 1;
+    $categoryId = $index + 4;
+    $category->setId($categoryId)
+        ->setName('Category ' . $position)
+        ->setParentId(3)
+        ->setPath('1/2/3/' . $categoryId)
+        ->setLevel(3)
+        ->setAvailableSortBy('name')
+        ->setDefaultSortBy('name')
+        ->setIsActive(true)
+        ->setIsAnchor(true)
+        ->setPosition($position)
+        ->save();
+
+    foreach ($testCase[0] as $price) {
+        $product = new Mage_Catalog_Model_Product();
+        $productId = $lastProductId + 1;
+        $product->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE)
+            ->setId($productId)
+            ->setAttributeSetId($installer->getAttributeSetId('catalog_product', 'Default'))
+            ->setStoreId(1)
+            ->setWebsiteIds(array(1))
+            ->setName('Simple Product ' . $productId)
+            ->setSku('simple-' . $productId)
+            ->setPrice($price)
+            ->setWeight(18)
+            ->setCategoryIds(array($categoryId))
+            ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
+            ->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
+            ->save();
+        ++$lastProductId;
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/PriceTest.php b/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/PriceTest.php
index 4ae94c8722c938d8167c91f3990b729939eaaa3a..569daf5a62b87e3b130b153ff3c101af4fc094ff 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/PriceTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Model/Layer/Filter/PriceTest.php
@@ -64,8 +64,8 @@ class Mage_Catalog_Model_Layer_Filter_PriceTest extends PHPUnit_Framework_TestCa
      */
     public function testGetPriceRangeManual()
     {
-        $this->markTestIncomplete('MAGE-4937');
-        $this->assertEquals(15, $this->_model->getPriceRange());
+        // what you set is what you get
+        $this->assertEquals(1.5, $this->_model->getPriceRange());
     }
 
     public function testGetMaxPriceInt()
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/Model/Product/Type/AbstractTest.php b/dev/tests/integration/testsuite/Mage/Catalog/Model/Product/Type/AbstractTest.php
index fd6f3c8d03f22107ac5c93566c3d0659103ce8fa..dff1ee13bd02b623a6d05f7ad35e60cbf3289f5e 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/Model/Product/Type/AbstractTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/Model/Product/Type/AbstractTest.php
@@ -25,13 +25,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-/**
- * The Mage_Catalog_Model_Product_Type_Abstract is a fake abstract
- */
-class Mage_Catalog_Model_Product_Type_AbstractTestAbstract extends Mage_Catalog_Model_Product_Type_Abstract
-{
-}
-
 /**
  * @group module:Mage_Catalog
  */
@@ -44,7 +37,7 @@ class Mage_Catalog_Model_Product_Type_AbstractTest extends PHPUnit_Framework_Tes
 
     protected function setUp()
     {
-        $this->_model = new Mage_Catalog_Model_Product_Type_AbstractTestAbstract;
+        $this->_model = $this->getMockForAbstractClass('Mage_Catalog_Model_Product_Type_Abstract');
     }
 
     public function testGetRelationInfo()
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/WidgetTest.php b/dev/tests/integration/testsuite/Mage/Catalog/WidgetTest.php
index 1b6a6157404a5c35b3321ef8908fb8cafa09c031..e0d054bd12870d2036ffc945d87a0209ed397660 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/WidgetTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/WidgetTest.php
@@ -42,7 +42,7 @@ class Mage_Catalog_WidgetTest extends PHPUnit_Framework_TestCase
         $this->assertArrayHasKey('list_names', $templates);
         $this->assertArrayHasKey('list_images', $templates);
 
-        $blocks = $config->xpath('supported_blocks');
+        $blocks = $config->xpath('supported_containers');
         $blocks = (array) $blocks[0]->children();
         $this->assertArrayHasKey('left_column', $blocks);
         $this->assertArrayHasKey('main_content', $blocks);
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/controllers/CategoryControllerTest.php b/dev/tests/integration/testsuite/Mage/Catalog/controllers/CategoryControllerTest.php
index 2c1d1fca09f9e6c2bd4533dde388b24f3fb6b4b2..c99ef771a7e91878e3b960e2a7ec4ade45163d0c 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/controllers/CategoryControllerTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/controllers/CategoryControllerTest.php
@@ -46,9 +46,8 @@ class Mage_Catalog_CategoryControllerTest extends Magento_Test_TestCase_Controll
                 '$categoryId' => 5,
                 '$expectedProductCount' => 1,
                 array(
-                    'CATEGORY_5',
-                    'catalog_category_default',
-                    'catalog_category_layered_nochildren',
+                    'catalog_category_view_type_default',
+                    'catalog_category_view_type_default_without_children',
                 ),
                 array(
                     'categorypath-category-1-category-1-1-category-1-1-1-html',
@@ -63,8 +62,7 @@ class Mage_Catalog_CategoryControllerTest extends Magento_Test_TestCase_Controll
                 '$categoryId' => 4,
                 '$expectedProductCount' => 2,
                 array(
-                    'CATEGORY_4',
-                    'catalog_category_layered',
+                    'catalog_category_view_type_layered',
                 ),
                 array(
                     'categorypath-category-1-category-1-1-html',
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/controllers/ProductControllerTest.php b/dev/tests/integration/testsuite/Mage/Catalog/controllers/ProductControllerTest.php
index 9f82f4bebdab850ea44dd29580d107c8d1fbc683..987302d80ff6e468f71c7c0eca4cde47de170371 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/controllers/ProductControllerTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/controllers/ProductControllerTest.php
@@ -64,8 +64,7 @@ class Mage_Catalog_ProductControllerTest extends Magento_Test_TestCase_Controlle
 
         /* Layout updates */
         $handles = Mage::app()->getLayout()->getUpdate()->getHandles();
-        $this->assertContains('PRODUCT_TYPE_simple', $handles);
-        $this->assertContains('PRODUCT_1', $handles);
+        $this->assertContains('catalog_product_view_type_simple', $handles);
 
         $responseBody = $this->getResponse()->getBody();
         /* Product info */
diff --git a/dev/tests/integration/testsuite/Mage/Catalog/controllers/Seo/SitemapControllerTest.php b/dev/tests/integration/testsuite/Mage/Catalog/controllers/Seo/SitemapControllerTest.php
index 1e18d444c3359e98c7a6724abb59cbe8d4183e43..f2fd1c1e2554566bdad69126a777cf813185127a 100644
--- a/dev/tests/integration/testsuite/Mage/Catalog/controllers/Seo/SitemapControllerTest.php
+++ b/dev/tests/integration/testsuite/Mage/Catalog/controllers/Seo/SitemapControllerTest.php
@@ -73,7 +73,7 @@ class Mage_Catalog_Seo_SitemapControllerTest extends Magento_Test_TestCase_Contr
 
         /* Layout updates */
         $handles = Mage::app()->getLayout()->getUpdate()->getHandles();
-        $this->assertContains('catalog_seo_sitemap_category_tree', $handles);
+        $this->assertContains('catalog_seo_sitemap_category_type_tree', $handles);
     }
 
     public function testProductAction()
diff --git a/dev/tests/integration/testsuite/Mage/CatalogSearch/_files/query.php b/dev/tests/integration/testsuite/Mage/CatalogSearch/_files/query.php
new file mode 100644
index 0000000000000000000000000000000000000000..b4e9c05dd0dbea207110f316c244ebe2158c2d2a
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/CatalogSearch/_files/query.php
@@ -0,0 +1,37 @@
+<?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_CatalogSearch
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+$query = Mage::getModel('Mage_CatalogSearch_Model_Query');
+$query->setStoreId(1);
+$query
+    ->setQueryText('query_text')
+    ->setNumResults(1)
+    ->setPopularity(1)
+    ->setDisplayInTerms(1)
+    ->setIsActive(1)
+    ->setIsProcessed(1)
+    ->save();
diff --git a/dev/tests/integration/testsuite/Mage/CatalogSearch/controllers/AjaxControllerTest.php b/dev/tests/integration/testsuite/Mage/CatalogSearch/controllers/AjaxControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..bfeb0f612b640f15078b300cd04de651ee671bcf
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/CatalogSearch/controllers/AjaxControllerTest.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.
+ *
+ * @category    Magento
+ * @package     Mage_CatalogSearch
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_CatalogSearch
+ */
+class Mage_CatalogSearch_AjaxControllerTest extends Magento_Test_TestCase_ControllerAbstract
+{
+    /**
+     * @magentoDataFixture Mage/CatalogSearch/_files/query.php
+     */
+    public function testSuggestAction()
+    {
+        $this->getRequest()->setParam('q', 'query_text');
+        $this->dispatch('catalogsearch/ajax/suggest');
+        $this->assertContains('query_text', $this->getResponse()->getBody());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Checkout/controllers/OnepageControllerTest.php b/dev/tests/integration/testsuite/Mage/Checkout/controllers/OnepageControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..2861b3af5c8c5686c49b30a81065aadba858bfcd
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Checkout/controllers/OnepageControllerTest.php
@@ -0,0 +1,60 @@
+<?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_Checkout
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @magentoDataFixture Mage/Sales/_files/quote.php
+ */
+class Mage_Checkout_OnepageControllerTest extends Magento_Test_TestCase_ControllerAbstract
+{
+    protected function _enableQuote()
+    {
+        $quote = new Mage_Sales_Model_Quote();
+        $quote->load('test01', 'reserved_order_id');
+        Mage::getSingleton('Mage_Checkout_Model_Session')->setQuoteId($quote->getId());
+    }
+
+    public function testProgressAction()
+    {
+        $this->_enableQuote();
+        $this->dispatch('checkout/onepage/progress');
+        $this->assertContains('Checkout', $this->getResponse()->getBody());
+    }
+
+    public function testShippingMethodAction()
+    {
+        $this->_enableQuote();
+        $this->dispatch('checkout/onepage/shippingmethod');
+        $this->assertContains('no quotes are available', $this->getResponse()->getBody());
+    }
+
+    public function testReviewAction()
+    {
+        $this->_enableQuote();
+        $this->dispatch('checkout/onepage/review');
+        $this->assertContains('checkout-review', $this->getResponse()->getBody());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Core/Block/AbstractTest.php b/dev/tests/integration/testsuite/Mage/Core/Block/AbstractTest.php
index 19a235e43a44ae0191a5db9d0c08ae42e6b7fb30..0a94a2acc355cb7f88b33fad3c3b98b3476c460e 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Block/AbstractTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Block/AbstractTest.php
@@ -25,10 +25,6 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-class Mage_Core_Block_AbstractTestAbstract extends Mage_Core_Block_Abstract
-{
-}
-
 /**
  * @group module:Mage_Core
  */
@@ -39,9 +35,18 @@ class Mage_Core_Block_AbstractTest extends PHPUnit_Framework_TestCase
      */
     protected $_block;
 
+    /**
+     * @var Mage_Core_Model_Layout
+     */
+    protected $_layout = null;
+
+    protected static $_mocks = array();
+
     protected function setUp()
     {
-        $this->_block = new Mage_Core_Block_AbstractTestAbstract;
+        $this->_block = $this->getMockForAbstractClass(
+            'Mage_Core_Block_Abstract', array(array('module_name' => 'Mage_Core'))
+        );
     }
 
     public function testGetRequest()
@@ -49,75 +54,87 @@ class Mage_Core_Block_AbstractTest extends PHPUnit_Framework_TestCase
         $this->assertInstanceOf('Mage_Core_Controller_Request_Http', $this->_block->getRequest());
     }
 
-    public function testSetGetParentBlock()
+    public function testGetParentBlock()
     {
-        $this->assertEmpty($this->_block->getParentBlock());
-        $parentBlock = new Mage_Core_Block_Text;
-        $this->_block->setParentBlock($parentBlock);
-        $this->assertSame($parentBlock, $this->_block->getParentBlock());
-    }
+        // Without layout
+        $this->assertFalse($this->_block->getParentBlock());
 
-    public function testSetGetIsAnonymous()
-    {
-        $this->assertFalse($this->_block->getIsAnonymous());
-        $this->_block->setIsAnonymous(true);
-        $this->assertTrue($this->_block->getIsAnonymous());
-    }
+        // Need to create blocks through layout
+        $parentBlock = $this->_createBlockWithLayout('block1', 'block1', 'Mage_Core_Block_Text');
+        $childBlock = $this->_createBlockWithLayout('block2', 'block2');
 
-    public function testSetGetAnonSuffix()
-    {
-        $this->assertEquals('', $this->_block->getAnonSuffix());
-        $this->_block->setAnonSuffix('suffix');
-        $this->assertEquals('suffix', $this->_block->getAnonSuffix());
+        $this->assertEmpty($childBlock->getParentBlock());
+        $parentBlock->setChild('block2', $childBlock);
+        $this->assertSame($parentBlock, $childBlock->getParentBlock());
     }
 
-    public function testGetSetBlockAlias()
+    public function testGetBlockAlias()
     {
+        // Without layout
         $this->assertEmpty($this->_block->getBlockAlias());
-        $this->_block->setBlockAlias('alias');
-        $this->assertEquals('alias', $this->_block->getBlockAlias());
+        $this->assertInternalType('string', $this->_block->getBlockAlias());
+
+        // Without alias
+        $block1 = $this->_createBlockWithLayout('name1');
+        $this->assertEquals('name1', $block1->getBlockAlias());
+        // With alias
+        $block2 = $this->_createBlockWithLayout('name2', 'alias');
+        $this->assertEquals('alias', $block2->getBlockAlias());
+        // Change block's alias while changing parent
+        $blockParent = $this->_createBlockWithLayout('parent', 'parent');
+        $blockChild = $this->_createBlockWithLayout('child', 'child');
+        $this->assertEquals('child', $blockChild->getBlockAlias());
+        $blockParent->setChild('parent_child', $blockChild);
+        $this->assertEquals('parent_child', $blockChild->getBlockAlias());
     }
 
     public function testSetGetNameInLayout()
     {
-        // basic setting/getting
+        // Basic setting/getting
         $this->assertEmpty($this->_block->getNameInLayout());
         $name = uniqid('name');
         $this->_block->setNameInLayout($name);
         $this->assertEquals($name, $this->_block->getNameInLayout());
 
-        // setting second time, along with the layout
+        // Setting second time, along with the layout
         $layout = Mage::app()->getLayout();
         $layout->createBlock('Mage_Core_Block_Template', $name);
         $block = $layout->getBlock($name);
         $this->assertInstanceOf('Mage_Core_Block_Abstract', $block);
         $block->setNameInLayout($name);
         $this->assertInstanceOf('Mage_Core_Block_Abstract', $layout->getBlock($name));
+        $this->assertEquals($name, $block->getNameInLayout());
+        $this->assertTrue($layout->hasElement($name));
+        $newName = 'new_name';
+        $block->setNameInLayout($newName);
+        $this->assertTrue($layout->hasElement($newName));
+        $this->assertFalse($layout->hasElement($name));
     }
 
     /**
-     * @covers Mage_Core_Block_Abstract::getSortedChildren
+     * @covers Mage_Core_Block_Abstract::getChildNames
      * @covers Mage_Core_Block_Abstract::insert
      */
-    public function testGetSortedChildren()
-    {
-        $cloneOne = clone $this->_block;
-        $cloneOne->setNameInLayout('block.clone1');
-        $cloneTwo = clone $this->_block;
-        $cloneTwo->setNameInLayout('block.clone2');
-        $cloneThree = clone $this->_block;
-        $cloneThree->setNameInLayout('block.clone3');
-        $cloneFour = clone $this->_block;
-        $cloneFour->setNameInLayout('block.clone4');
-
-        $this->_block->insert($cloneOne, '', false); // add one block
-        $this->_block->insert($cloneTwo, 'block.clone1', false); // add second to the 1st position
-        $this->_block->insert($cloneThree, 'block.clone1', false); // add third to the 2nd position
-        $this->_block->insert($cloneFour, 'block.clone3', true); // add fourth block to the 3rd position
+    public function testGetChildNames()
+    {
+        // Without layout
+        $this->assertEquals(array(), $this->_block->getChildNames());
+
+        // With layout
+        $parent = $this->_createBlockWithLayout('parent', 'parent');
+        $block1 = $this->_createBlockWithLayout('block1');
+        $block2 = $this->_createBlockWithLayout('block2');
+        $block3 = $this->_createBlockWithLayout('block3');
+        $block4 = $this->_createBlockWithLayout('block4');
+
+        $parent->insert($block1); // add one block
+        $parent->insert($block2, 'block1', false); // add second to the 1st position
+        $parent->insert($block3, 'block1', false); // add third to the 2nd position
+        $parent->insert($block4, 'block3', true); // add fourth block to the 3rd position
 
         $this->assertEquals(array(
-            'block.clone2', 'block.clone3', 'block.clone4', 'block.clone1'
-        ), $this->_block->getSortedChildren());
+            'block2', 'block3', 'block4', 'block1'
+        ), $parent->getChildNames());
     }
 
     public function testSetAttribute()
@@ -129,64 +146,88 @@ class Mage_Core_Block_AbstractTest extends PHPUnit_Framework_TestCase
 
     public function testSetGetUnsetChild()
     {
-        $layout = Mage::app()->getLayout();
-        $this->_block->setLayout($layout);
+        // Without layout
+        $child = clone $this->_block;
+        $this->_block->setChild('child', $child);
+        $this->assertFalse($this->_block->getChildBlock('child'));
+
+        // With layout
+        $parent = $this->_createBlockWithLayout('parent', 'parent');
 
-        // regular block
-        $blockOne = new Mage_Core_Block_Template;
+        // Regular block
         $nameOne = uniqid('block.');
-        $blockOne->setNameInLayout($nameOne);
-        $layout->setBlock($nameOne, $blockOne);
-        $this->_block->setChild('block1', $blockOne);
-        $this->assertSame($blockOne, $this->_block->getChild('block1'));
-
-        // block factory name
-        $blockTwo = new Mage_Core_Block_Template;
-        $blockTwo->setLayout($layout);
+        $blockOne = $this->_createBlockWithLayout($nameOne, $nameOne);
+        $parent->setChild('block1', $blockOne);
+        $this->assertSame($blockOne, $parent->getChildBlock('block1'));
+
+        // Block factory name
+        $blockTwo = $this->_createBlockWithLayout('parent_block2', 'parent_block2');
         $blockTwo->setChild('block2', $nameOne);
-        $this->assertSame($blockOne, $blockTwo->getChild('block2'));
+        $this->assertSame($blockOne, $blockTwo->getChildBlock('block2'));
 
-        // anonymous block
-        $blockThree = new Mage_Core_Block_Template;
-        $blockThree->setIsAnonymous(true);
-        $this->_block->setChild('block3', $blockThree);
-        $this->assertSame($blockThree, $this->_block->getChild('block3'));
+        // No name block
+        $blockThree = $this->_createBlockWithLayout('');
+        $parent->setChild('block3', $blockThree);
+        $this->assertSame($blockThree, $parent->getChildBlock('block3'));
 
-        // unset
-        $this->_block->unsetChild('block3');
-        $this->assertNotSame($blockThree, $this->_block->getChild('block3'));
-        $this->_block->insert($blockOne, '', true, 'block1');
-        $this->assertContains($nameOne, $this->_block->getSortedChildren());
-        $this->_block->unsetChild('block1');
-        $this->assertNotSame($blockOne, $this->_block->getChild('block1'));
-        $this->assertNotContains($nameOne, $this->_block->getSortedChildren());
+        // Unset
+        $parent->unsetChild('block3');
+        $this->assertNotSame($blockThree, $parent->getChildBlock('block3'));
+        $parent->insert($blockOne, '', true, 'block1');
+        $this->assertContains($nameOne, $parent->getChildNames());
+        $parent->unsetChild('block1');
+        $this->assertNotSame($blockOne, $parent->getChildBlock('block1'));
+        $this->assertNotContains($nameOne, $parent->getChildNames());
     }
 
     public function testUnsetCallChild()
     {
-        $blockOne = new Mage_Core_Block_Template;
-        $blockOne->setSomeValue(true);
-        $this->_block->setChild('block1', $blockOne);
-        $this->assertSame($blockOne, $this->_block->getChild('block1'));
-        $this->_block->unsetCallChild('block1', 'getSomeValue', true, array());
-        $this->assertNotSame($blockOne, $this->_block->getChild('block1'));
+        $blockParent = $this->_createBlockWithLayout('parent', 'parent');
+        $block = $this->_createBlockWithLayout('block1', 'block1');
+        $block->setSomeValue(true);
+        $blockParent->setChild('block1', $block);
+        $this->assertSame($block, $blockParent->getChildBlock('block1'));
+        $blockParent->unsetCallChild('block1', 'getSomeValue', true, array());
+        $this->assertNotSame($block, $blockParent->getChildBlock('block1'));
     }
 
     /**
      * @covers Mage_Core_Block_Abstract::unsetChildren
-     * @covers Mage_Core_Block_Abstract::getChild
+     * @covers Mage_Core_Block_Abstract::getChildBlock
      */
     public function testUnsetChildren()
     {
-        $this->assertEquals(array(), $this->_block->getChild());
-        $blockOne = new Mage_Core_Block_Template;
-        $blockTwo = new Mage_Core_Block_Template;
-        $this->_block->setChild('block1', $blockOne);
-        $this->_block->setChild('block2', $blockTwo);
-        $this->assertSame($blockOne, $this->_block->getChild('block1'));
-        $this->assertSame($blockTwo, $this->_block->getChild('block2'));
-        $this->_block->unsetChildren();
-        $this->assertEquals(array(), $this->_block->getChild());
+        $parent = $this->_createBlockWithLayout('block', 'block');
+        $this->assertEquals(array(), $parent->getChildNames());
+        $blockOne = $this->_createBlockWithLayout('block1', 'block1');
+        $blockTwo = $this->_createBlockWithLayout('block2', 'block2');
+        $parent->setChild('block1', $blockOne);
+        $parent->setChild('block2', $blockTwo);
+        $this->assertSame($blockOne, $parent->getChildBlock('block1'));
+        $this->assertSame($blockTwo, $parent->getChildBlock('block2'));
+        $parent->unsetChildren();
+        $this->assertEquals(array(), $parent->getChildNames());
+    }
+
+    public function testGetChildBlock()
+    {
+        // Without layout
+        $child = new Mage_Core_Block_Text;
+        $childAlias = 'child_alias';
+        $childName = 'child';
+        $parentName = 'parent';
+        $this->assertFalse($this->_block->getChildBlock($childAlias));
+
+        // With layout
+        $layout = new Mage_Core_Model_Layout;
+        $layout->addBlock($this->_block, $parentName);
+        $layout->addBlock($child, $childName);
+
+        $this->_block->setChild($childAlias, $child);
+        $result = $this->_block->getChildBlock($childAlias);
+        $this->assertInstanceOf('Mage_Core_Block_Text', $result);
+        $this->assertEquals($childName, $result->getNameInLayout());
+        $this->assertEquals($child, $result);
     }
 
     /**
@@ -195,139 +236,172 @@ class Mage_Core_Block_AbstractTest extends PHPUnit_Framework_TestCase
      */
     public function testGetChildHtml()
     {
-        $blockOne = new Mage_Core_Block_Text;
-        $blockOne->setText('one')->setNameInLayout(uniqid('block.one.'));
-        $blockTwo = new Mage_Core_Block_Text;
-        $blockTwo->setText('two')->setNameInLayout(uniqid('block.two.'));
-        $this->_block->insert($blockTwo, '', false, 'block2'); // make block2 1st
-        $this->_block->insert($blockOne, '', false, 'block1'); // make block1 1st
-
-        $this->assertEquals('one', $this->_block->getChildHtml('block1'));
-        $this->assertEquals('two', $this->_block->getChildHtml('block2'));
+        // Without layout
+        $this->assertEmpty($this->_block->getChildHtml());
+        $this->assertEmpty($this->_block->getChildHtml('block'));
 
-        // unsorted children will render in the order they were added
-        $this->assertEquals('twoone', $this->_block->getChildHtml());
+        // With layout
+        $parent = $this->_createBlockWithLayout('parent', 'parent');
+        $blockOne = $this->_createBlockWithLayout('block1', 'block1', 'Mage_Core_Block_Text');
+        $blockTwo = $this->_createBlockWithLayout('block2', 'block2', 'Mage_Core_Block_Text');
+        $blockOne->setText('one');
+        $blockTwo->setText('two');
+        $parent->insert($blockTwo, '', false, 'block2'); // make block2 1st
+        $parent->insert($blockOne, '', false, 'block1'); // make block1 1st
 
-        // hack: rendering sorted children requires layout
-        $layout = new Mage_Core_Model_Layout;
-        $this->_block->setLayout($layout);
-        $blockOne->setLayout($layout);
-        $layout->setBlock($blockOne->getNameInLayout(), $blockOne);
-        $blockTwo->setLayout($layout);
-        $layout->setBlock($blockTwo->getNameInLayout(), $blockTwo);
+        $this->assertEquals('one', $parent->getChildHtml('block1'));
+        $this->assertEquals('two', $parent->getChildHtml('block2'));
 
-        // sorted will render in the designated order
-        $this->assertEquals('onetwo', $this->_block->getChildHtml('', true, true));
+        // Sorted will render in the designated order
+        $this->assertEquals('onetwo', $parent->getChildHtml('', true, true));
 
-        // getChildChildHtml
+        // GetChildChildHtml
         $blockTwo->setChild('block11', $blockOne);
-        $this->assertEquals('one', $this->_block->getChildChildHtml('block2'));
-        $this->assertEquals('', $this->_block->getChildChildHtml(''));
-        $this->assertEquals('', $this->_block->getChildChildHtml('block3'));
+        $this->assertEquals('one', $parent->getChildChildHtml('block2'));
+        $this->assertEquals('', $parent->getChildChildHtml(''));
+        $this->assertEquals('', $parent->getChildChildHtml('block3'));
     }
 
-    /**
-     * @covers Mage_Core_Block_Abstract::getSortedChildBlocks
-     * @covers Mage_Core_Block_Abstract::append
-     */
-    public function testGetSortedChildBlocks()
+    public function testGetChildChildHtml()
     {
-        list($blocks, $names) = $this->_createSampleBlocks(2);
-        $this->_block->append($blocks[0], 'block1')->append($blocks[1], 'block2');
-        $result = $this->_block->getSortedChildBlocks();
-        $this->assertArrayHasKey($names[0], $result);
-        $this->assertArrayHasKey($names[1], $result);
-        $this->assertSame($names[0], key($result));
-        $this->assertSame($blocks[0], $result[$names[0]]);
-        $this->assertSame($blocks[1], $result[$names[1]]);
+        // Without layout
+        $this->assertEmpty($this->_block->getChildChildHtml('alias'));
+
+        // With layout
+        $parent1 = $this->_createBlockWithLayout('parent1', 'parent1');
+        $parent2 = $this->_createBlockWithLayout('parent2', 'parent2');
+
+        $block1 = $this->_createBlockWithLayout('block1', 'block1', 'Mage_Core_Block_Text');
+        $block2 = $this->_createBlockWithLayout('block2', 'block2', 'Mage_Core_Block_Text');
+        $block3 = $this->_createBlockWithLayout('block3', 'block3', 'Mage_Core_Block_Text');
+        $block4 = $this->_createBlockWithLayout('block4', 'block4', 'Mage_Core_Block_Text');
+
+        $block1->setText('one');
+        $block2->setText('two');
+        $block3->setText('three');
+        $block4->setText('four');
+
+        $parent1->insert($parent2);
+        $parent2->insert($block1, '', false, 'block1');
+        $parent2->insert($block2, '', false, 'block2');
+        $parent2->insert($block3, '', true, 'block3');
+        $parent1->insert($block4);
+        $this->assertEquals('twoonethree', $parent1->getChildChildHtml('parent2'));
     }
 
-    /**
-     * @covers Mage_Core_Block_Abstract::insert
-     * @see testGetSortedChildren()
-     */
-    public function testInsert()
-    {
-        // invalid block from layout
-        $blockZero = new Mage_Core_Block_Template;
-        $blockZero->setLayout(Mage::app()->getLayout());
-        $this->assertInstanceOf('Mage_Core_Block_Abstract', $blockZero->insert(uniqid('block.')));
-
-        // anonymous block
-        $blockOne = new Mage_Core_Block_Template;
-        $blockOne->setIsAnonymous(true);
-        $this->_block->insert($blockOne);
-        $this->assertContains('.child0', $this->_block->getSortedChildren());
-
-        // block with alias, to the last position
-        $blockTwo = new Mage_Core_Block_Template;
-        $blockTwo->setNameInLayout('block.two');
-        $this->_block->insert($blockTwo, '', true, 'block_two');
-        $this->assertContains('block.two', $this->_block->getSortedChildren());
-        $this->assertSame($blockTwo, $this->_block->getChild('block_two'));
-
-        // unknown sibling, to the 1st position
-        $blockThree = new Mage_Core_Block_Template;
-        $blockThree->setNameInLayout('block.three');
-        $this->_block->insert($blockThree, 'wrong_sibling', false, 'block_three');
-        $this->assertContains('block.three', $this->_block->getSortedChildren());
-        $this->assertSame(0, array_search('block.three', $this->_block->getSortedChildren()));
-
-        $blockFour = new Mage_Core_Block_Template;
-        $blockFour->setNameInLayout('block.four');
-        $this->_block->insert($blockFour, 'wrong_sibling', true, 'block_four');
-        $this->assertContains('block.four', $this->_block->getSortedChildren());
-        $this->assertSame(3, array_search('block.four', $this->_block->getSortedChildren()));
+    public function testGetBlockHtml()
+    {
+        // Without layout
+        $block1 = new Mage_Core_Block_Text;
+        $block1->setText('Block text');
+        $block1->setNameInLayout('block');
+        $html = $this->_block->getBlockHtml('block');
+        $this->assertInternalType('string', $html);
+        $this->assertEmpty($html);
+
+        // With layout
+        $expected = 'Block2';
+        $block2 = $this->_createBlockWithLayout('block2', 'block2', 'Mage_Core_Block_Text');
+        $block3 = $this->_createBlockWithLayout('block3', 'block3');
+        $block2->setText($expected);
+        $html = $block3->getBlockHtml('block2');
+        $this->assertInternalType('string', $html);
+        $this->assertEquals($expected, $html);
     }
 
-    /**
-     * @covers Mage_Core_Block_Abstract::addToChildGroup
-     * @covers Mage_Core_Block_Abstract::getChildGroup
-     */
-    public function testAddToChildGroup()
+    public function testInsertWithoutLayout()
     {
-        list($blocks, ) = $this->_createSampleBlocks(2);
-        $this->_block->append($blocks[0], 'block1')->append($blocks[1], 'block2');
+        $child = clone $this->_block;
+        $this->assertFalse($this->_block->insert($child));
+    }
 
-        // addToChildGroup()
-        $this->assertEquals(array(), $this->_block->getChildGroup('group'));
-        $this->_block->addToChildGroup('group', $blocks[0]);
-        $this->_block->addToChildGroup('group', $blocks[1]);
+    public function testInsertBlockWithoutName()
+    {
+        $parent = $this->_createBlockWithLayout('parent', 'parent');
+        $block = $this->_createBlockWithLayout('');
+        $parent->setChild('', $block);
+        $this->assertContains('ANONYMOUS_0', $parent->getChildNames());
+    }
 
-        // getChildGroup() without callback
-        $group = $this->_block->getChildGroup('group');
-        $this->assertEquals(array('block1' => $blocks[0], 'block2' => $blocks[1]), $group);
+    public function testInsertBlockWithAlias()
+    {
+        $parent = $this->_createBlockWithLayout('parent', 'parent');
+        $block = $this->_createBlockWithLayout('block_name');
+        $parent->insert($block, '', true, 'block_alias');
+        $this->assertContains('block_name', $parent->getChildNames());
+        $this->assertSame($block, $parent->getChildBlock('block_alias'));
+    }
+
+    public function testInsertWithSibling()
+    {
+        $name1 = 'block_one';
+        $parent = $this->_createBlockWithLayout('parent', 'parent');
+        $blockOne = $this->_createBlockWithLayout($name1);
+        $parent->insert($blockOne);
+        $this->assertContains($name1, $parent->getChildNames());
 
-        // getChildGroup() with callback and skipping empty results
-        $group = $this->_block->getChildGroup('group', 'getChildHtml');
-        $this->assertEquals(array(), $group);
+        $name2 = 'block_two';
+        $blockTwo = $this->_createBlockWithLayout($name2);
+        $parent->insert($blockTwo, 'wrong_sibling', false);
+        $this->assertSame(0, array_search($name2, $parent->getChildNames()));
+
+        $name3 = 'block_three';
+        $blockThree = $this->_createBlockWithLayout($name3);
+        $parent->insert($blockThree, $name2, false);
+        $this->assertSame(0, array_search($name3, $parent->getChildNames()));
+
+        $name4 = 'block_four';
+        $blockFour = $this->_createBlockWithLayout($name4);
+        $parent->insert($blockFour, $name1, true);
+        $this->assertSame(3, array_search($name4, $parent->getChildNames()));
 
-        // getChildGroup() with callback and not skipping empty results
-        $group = $this->_block->getChildGroup('group', 'getChildHtml', false);
-        $this->assertEquals(array('block1' => '', 'block2' => ''), $group);
     }
 
+    public function testAppend()
+    {
+        $parent = $this->_createBlockWithLayout('parent', 'parent');
+        $child1 = $this->_createBlockWithLayout('child1');
+        $parent->append($child1, 'child1');
+        $child2 = $this->_createBlockWithLayout('child2');
+        $parent->append($child2);
+        $this->assertEquals(array('child1', 'child2'), $parent->getChildNames());
+    }
+
+    /**
+     * @covers Mage_Core_Block_Abstract::addToParentGroup
+     * @covers Mage_Core_Block_Abstract::getGroupChildNames
+     */
     public function testAddToParentGroup()
     {
-        list($blocks, ) = $this->_createSampleBlocks(2);
-        $this->_block->append($blocks[0], 'block1')->append($blocks[1], 'block2');
-        $blocks[0]->addToParentGroup('group');
-        $blocks[1]->addToParentGroup('group');
-        $group = $this->_block->getChildGroup('group');
-        $this->assertArrayHasKey('block1', $group);
-        $this->assertArrayHasKey('block2', $group);
-        $this->assertSame($group['block1'], $blocks[0], 'The same instance is expected.');
-        $this->assertSame($group['block2'], $blocks[1], 'The same instance is expected.');
+        // Without layout
+        $this->assertFalse($this->_block->addToParentGroup('default_group'));
+
+        // With layout
+        $parent = $this->_createBlockWithLayout('parent', 'parent');
+        $block1 = $this->_createBlockWithLayout('block1', 'block1');
+        $block2 = $this->_createBlockWithLayout('block2', 'block2');
+        $parent->setChild('block1', $block1)->setChild('block2', $block2);
+        $block1->addToParentGroup('group');
+        $block2->addToParentGroup('group');
+        $group = $parent->getGroupChildNames('group');
+        $this->assertContains('block1', $group);
+        $this->assertContains('block2', $group);
+        $this->assertSame($group[0], 'block1');
+        $this->assertSame($group[1], 'block2');
     }
 
     public function testGetChildData()
     {
-        $block = new Mage_Core_Block_Template();
+        $parent = $this->_createBlockWithLayout('parent', 'parent');
+        $block = $this->_createBlockWithLayout('block', 'block', 'Mage_Core_Block_Template');
         $block->setSomeValue('value');
-        $this->_block->setChild('block1', $block);
-        $this->assertEquals(array('some_value' => 'value'), $this->_block->getChildData('block1'));
-        $this->assertEquals('value', $this->_block->getChildData('block1', 'some_value'));
-        $this->assertNull($this->_block->getChildData('unknown_block'));
+        $parent->setChild('block1', $block);
+        $this->assertEquals(
+            array('type' => 'Mage_Core_Block_TemplateMock', 'some_value' => 'value'),
+            $parent->getChildData('block1')
+        );
+        $this->assertEquals('value', $parent->getChildData('block1', 'some_value'));
+        $this->assertNull($parent->getChildData('unknown_block'));
     }
 
     public function testSetFrameTags()
@@ -378,11 +452,11 @@ class Mage_Core_Block_AbstractTest extends PHPUnit_Framework_TestCase
 
     public function testGetSetMessagesBlock()
     {
-        // get one from layout
+        // Get one from layout
         $this->_block->setLayout(new Mage_Core_Model_Layout);
         $this->assertInstanceOf('Mage_Core_Block_Messages', $this->_block->getMessagesBlock());
 
-        // set explicitly
+        // Set explicitly
         $messages = new Mage_Core_Block_Messages;
         $this->_block->setMessagesBlock($messages);
         $this->assertSame($messages, $this->_block->getMessagesBlock());
@@ -396,10 +470,10 @@ class Mage_Core_Block_AbstractTest extends PHPUnit_Framework_TestCase
 
     public function testHelper()
     {
-        // without layout
+        // Without layout
         $this->assertInstanceOf('Mage_Core_Helper_Data', $this->_block->helper('Mage_Core_Helper_Data'));
 
-        // with layout
+        // With layout
         $this->_block->setLayout(new Mage_Core_Model_Layout);
         $helper = $this->_block->helper('Mage_Core_Helper_Data');
 
@@ -486,16 +560,6 @@ class Mage_Core_Block_AbstractTest extends PHPUnit_Framework_TestCase
         $this->assertEquals('var s = \\\'text\\\';', $this->_block->jsQuoteEscape($script));
     }
 
-    public function testCountChildren()
-    {
-        $this->assertEquals(0, $this->_block->countChildren());
-        $this->_block->setChild('block1', new Mage_Core_Block_Text)
-            ->setChild('block2', new Mage_Core_Block_Text)
-            ->setChild('block3', new Mage_Core_Block_Text)
-        ;
-        $this->assertEquals(3, $this->_block->countChildren());
-    }
-
     public function testGetCacheKeyInfo()
     {
         $name = uniqid('block.');
@@ -566,19 +630,33 @@ class Mage_Core_Block_AbstractTest extends PHPUnit_Framework_TestCase
         $layout = false;
         if ($withLayout) {
             $layout = new Mage_Core_Model_Layout;
-            $this->_block->setLayout($layout);
         }
         for ($i = 0; $i < $qty; $i++) {
-            $block = new $className;
             $name = uniqid('block.');
-            $block->setNameInLayout($name);
-            $blocks[] = $block;
-            $names[] = $name;
             if ($layout) {
-                $block->setLayout($layout);
-                $layout->setBlock($name, $block);
+                $block = $layout->createBlock($className, $name);
+                $layout->insertBlock('', $name, $name);
+            } else {
+                $block = new $className;
+                $block->setNameInLayout($name);
             }
+            $blocks[] = $block;
+            $names[] = $name;
         }
         return array($blocks, $names);
     }
+
+    protected function _createBlockWithLayout($name = 'block', $alias = null,
+        $type = 'Mage_Core_Block_Abstract'
+    ) {
+        $mockClass = $type . 'Mock';
+        if (!isset(self::$_mocks[$mockClass])) {
+            self::$_mocks[$mockClass] = $this->getMockForAbstractClass($type, array(), $type . 'Mock');
+        }
+        if (is_null($this->_layout)) {
+            $this->_layout = new Mage_Core_Model_Layout;
+        }
+        $block = $this->_layout->addBlock($mockClass, $name, '', $alias);
+        return $block;
+    }
 }
diff --git a/dev/tests/integration/testsuite/Mage/Core/Block/FlushTest.php b/dev/tests/integration/testsuite/Mage/Core/Block/FlushTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..69c2286c8e0d567af308767cfc561e7b2431f40d
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Core/Block/FlushTest.php
@@ -0,0 +1,80 @@
+<?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  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Core
+ */
+class Mage_Core_Block_FlushTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Layout
+     */
+    protected $_layout;
+
+    /**
+     * @var Mage_Core_Block_Text_List
+     */
+    protected $_block;
+
+    protected function setUp()
+    {
+        $this->_layout = new Mage_Core_Model_Layout;
+        $this->_block = $this->_layout->createBlock('Mage_Core_Block_Flush');
+    }
+
+    public function testToHtml()
+    {
+        $children = array(
+            array('block1', 'Mage_Core_Block_Text', 'text1'),
+            array('block2', 'Mage_Core_Block_Text', 'text2'),
+            array('block3', 'Mage_Core_Block_Text', 'text3'),
+        );
+        foreach ($children as $child) {
+            $this->_layout->addBlock($child[1], $child[0], $this->_block->getNameInLayout())->setText($child[2]);
+        }
+        ob_start();
+        $this->_block->toHtml();
+        $html = ob_get_clean();
+        $this->assertEquals('text1text2text3', $html);
+    }
+
+    public function testToHtmlWithContainer()
+    {
+        $listName = $this->_block->getNameInLayout();
+        $block1 = $this->_layout->addBlock('Mage_Core_Block_Text', '', $listName);
+        $this->_layout->insertContainer($listName, 'container');
+        $block2 = $this->_layout->addBlock('Mage_Core_Block_Text', '', 'container');
+        $block3 = $this->_layout->addBlock('Mage_Core_Block_Text', '', $listName);
+        $block1->setText('text1');
+        $block2->setText('text2');
+        $block3->setText('text3');
+        ob_start();
+        $this->_block->toHtml();
+        $html = ob_get_clean();
+        $this->assertEquals('text1text2text3', $html);
+    }
+}
\ No newline at end of file
diff --git a/dev/tests/integration/testsuite/Mage/Core/Block/Text/ListTest.php b/dev/tests/integration/testsuite/Mage/Core/Block/Text/ListTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..7599bf4cbae2bf85ebdfd166de35eaeb6ced7af9
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Core/Block/Text/ListTest.php
@@ -0,0 +1,77 @@
+<?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  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Core
+ */
+class Mage_Core_Block_Text_ListTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Layout
+     */
+    protected $_layout;
+
+    /**
+     * @var Mage_Core_Block_Text_List
+     */
+    protected $_block;
+
+    protected function setUp()
+    {
+        $this->_layout = new Mage_Core_Model_Layout;
+        $this->_block = $this->_layout->createBlock('Mage_Core_Block_Text_List');
+    }
+
+    public function testToHtml()
+    {
+        $children = array(
+            array('block1', 'Mage_Core_Block_Text', 'text1'),
+            array('block2', 'Mage_Core_Block_Text', 'text2'),
+            array('block3', 'Mage_Core_Block_Text', 'text3'),
+        );
+        foreach ($children as $child) {
+            $this->_layout->addBlock($child[1], $child[0], $this->_block->getNameInLayout())
+                ->setText($child[2]);
+        }
+        $html = $this->_block->toHtml();
+        $this->assertEquals('text1text2text3', $html);
+    }
+
+    public function testToHtmlWithContainer()
+    {
+        $listName = $this->_block->getNameInLayout();
+        $block1 = $this->_layout->addBlock('Mage_Core_Block_Text', '', $listName);
+        $this->_layout->insertContainer($listName, 'container');
+        $block2 = $this->_layout->addBlock('Mage_Core_Block_Text', '', 'container');
+        $block3 = $this->_layout->addBlock('Mage_Core_Block_Text', '', $listName);
+        $block1->setText('text1');
+        $block2->setText('text2');
+        $block3->setText('text3');
+        $html = $this->_block->toHtml();
+        $this->assertEquals('text1text2text3', $html);
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Core/Controller/RequestHttpTest.php b/dev/tests/integration/testsuite/Mage/Core/Controller/RequestHttpTest.php
index 858c98152e6ff57c84208a5cfe791ebd4d315f1e..b6d073e261f61f2e38cc2530707e7351c1c9f229 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Controller/RequestHttpTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Controller/RequestHttpTest.php
@@ -135,10 +135,10 @@ class Mage_Core_Controller_RequestHttpTest extends PHPUnit_Framework_TestCase
 
     public function testGetHttpHost()
     {
-        $this->assertFalse($this->_model->getHttpHost());
-        $_SERVER['HTTP_HOST'] = 'localhost:80';
-        $this->assertEquals($_SERVER['HTTP_HOST'], $this->_model->getHttpHost(false));
         $this->assertEquals('localhost', $this->_model->getHttpHost());
+        $_SERVER['HTTP_HOST'] = 'example.com:80';
+        $this->assertEquals($_SERVER['HTTP_HOST'], $this->_model->getHttpHost(false));
+        $this->assertEquals('example.com', $this->_model->getHttpHost());
     }
 
     public function testSetPost()
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 c175acf053f85bf150cc36a81a84263b6d81f19f..78e9da57d344b57bf178dd34f6719bbf2c7aad40 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Controller/Varien/ActionTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Controller/Varien/ActionTest.php
@@ -83,9 +83,18 @@ class Mage_Core_Controller_Varien_ActionTest extends PHPUnit_Framework_TestCase
         $this->assertEquals('test/controller/action', $this->_model->getFullActionName('/'));
     }
 
-    public function testGetLayout()
+    /**
+     * @param string $controllerClass
+     * @param string $expectedArea
+     * @dataProvider controllerAreaDesignDataProvider
+     * @magentoAppIsolation enabled
+     */
+    public function testGetLayout($controllerClass, $expectedArea)
     {
-        $this->assertInstanceOf('Mage_Core_Model_Layout', $this->_model->getLayout());
+        /** @var $controller Mage_Core_Controller_Varien_Action */
+        $controller = new $controllerClass(new Magento_Test_Request(), new Magento_Test_Response());
+        $this->assertInstanceOf('Mage_Core_Model_Layout', $controller->getLayout());
+        $this->assertEquals($expectedArea, $controller->getLayout()->getArea());
     }
 
     /**
@@ -102,17 +111,49 @@ class Mage_Core_Controller_Varien_ActionTest extends PHPUnit_Framework_TestCase
         $this->assertInstanceOf('Mage_Core_Block_Abstract', $this->_model->getLayout()->getBlock('root'));
     }
 
+    public function testGetDefaultLayoutHandle()
+    {
+        $this->_model->getRequest()
+            ->setRouteName('Test')
+            ->setControllerName('Controller')
+            ->setActionName('Action');
+        $this->assertEquals('test_controller_action', $this->_model->getDefaultLayoutHandle());
+    }
+
     /**
      * @magentoAppIsolation enabled
      */
     public function testAddActionLayoutHandles()
+    {
+        $this->_model->getRequest()
+            ->setRouteName('Test')
+            ->setControllerName('Controller')
+            ->setActionName('Action');
+        $this->_model->addActionLayoutHandles();
+        $handles = $this->_model->getLayout()->getUpdate()->getHandles();
+        $this->assertContains('test_controller_action', $handles);
+        $this->assertNotContains('STORE_' . Mage::app()->getStore()->getCode(), $handles);
+    }
+
+    /**
+     * @magentoAppIsolation enabled
+     */
+    public function testAddPageLayoutHandles()
     {
         $this->_model->getRequest()->setRouteName('test')
             ->setControllerName('controller')
             ->setActionName('action');
-        $this->_model->addActionLayoutHandles();
+        $this->_model->addPageLayoutHandles(array());
+        $this->assertEmpty($this->_model->getLayout()->getUpdate()->getHandles());
+
+        $this->_model->getRequest()->setRouteName('catalog')
+            ->setControllerName('product')
+            ->setActionName('view');
+        $this->_model->addPageLayoutHandles(array('type' => 'simple'));
         $handles = $this->_model->getLayout()->getUpdate()->getHandles();
-        $this->assertContains('test_controller_action', $handles);
+        $this->assertContains('default', $handles);
+        $this->assertContains('catalog_product_view', $handles);
+        $this->assertContains('catalog_product_view_type_simple', $handles);
     }
 
     /**
@@ -159,29 +200,39 @@ class Mage_Core_Controller_Varien_ActionTest extends PHPUnit_Framework_TestCase
         $this->assertNotEmpty($this->_model->getResponse()->getBody());
     }
 
-    public function preDispatchDetectDesignDataProvider()
-    {
-        return array(
-            'install'  => array('Mage_Install_Controller_Action',    'install',   'default/default/default'),
-            'backend'  => array('Mage_Adminhtml_Controller_Action',  'adminhtml', 'default/default/default'),
-            'frontend' => array('Mage_Core_Controller_Front_Action', 'frontend',  'default/iphone/default'),
-        );
-    }
-
     /**
      * @magentoConfigFixture               install/design/theme/full_name   default/default/default
      * @magentoConfigFixture               adminhtml/design/theme/full_name default/default/default
      * @magentoConfigFixture current_store design/theme/full_name           default/iphone/default
      * @magentoAppIsolation  enabled
-     * @dataProvider         preDispatchDetectDesignDataProvider
+     *
+     * @dataProvider controllerAreaDesignDataProvider
+     *
+     * @param string $controllerClass
+     * @param string $expectedArea
+     * @param string $expectedStore
+     * @param string $expectedDesign
      */
-    public function testPreDispatchDetectDesign($controllerClass, $expectedArea, $expectedDesign)
+    public function testPreDispatch($controllerClass, $expectedArea, $expectedStore, $expectedDesign)
     {
         /** @var $controller Mage_Core_Controller_Varien_Action */
         $controller = new $controllerClass(new Magento_Test_Request(), new Magento_Test_Response());
         $controller->preDispatch();
         $this->assertEquals($expectedArea, Mage::getDesign()->getArea());
-        $this->assertEquals($expectedDesign, Mage::getDesign()->getDesignTheme());
+        $this->assertEquals($expectedStore, Mage::app()->getStore()->getCode());
+        if ($expectedDesign) {
+            $this->assertEquals($expectedDesign, Mage::getDesign()->getDesignTheme());
+        }
+    }
+
+    public function controllerAreaDesignDataProvider()
+    {
+        return array(
+            'install'  => array('Mage_Install_Controller_Action',    'install',   'default', 'default/default/default'),
+            'frontend' => array('Mage_Core_Controller_Front_Action', 'frontend',  'default', 'default/iphone/default'),
+            'backend'  => array('Mage_Adminhtml_Controller_Action',  'adminhtml', 'admin',   'default/default/default'),
+            'api'      => array('Mage_Api_Controller_Action',        'adminhtml', 'admin',   ''),
+        );
     }
 
     public function testNoRouteAction()
diff --git a/dev/tests/integration/testsuite/Mage/Core/Helper/AbstractTest.php b/dev/tests/integration/testsuite/Mage/Core/Helper/AbstractTest.php
index 360bcae3555adccbeb82180a86c8bd99acd9f1d1..860ff885665d4c784c4ac3f302f33be01cdb4825 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Helper/AbstractTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Helper/AbstractTest.php
@@ -25,23 +25,24 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-class Mage_Core_Helper_AbstractTestAbstract extends Mage_Core_Helper_Abstract
-{
-}
-
 /**
  * @group module:Mage_Core
  */
 class Mage_Core_Helper_AbstractTest extends PHPUnit_Framework_TestCase
 {
     /**
-     * @var Mage_Core_Helper_Abstract
+     * @var Mage_Core_Helper_Abstract|PHPUnit_Framework_MockObject_MockObject
      */
     protected $_helper = null;
 
     protected function setUp()
     {
-        $this->_helper = new Mage_Core_Helper_AbstractTestAbstract;
+        $this->_helper = $this->getMock('Mage_Core_Helper_Abstract', array('_getModuleName'));
+        $this->_helper
+            ->expects($this->any())
+            ->method('_getModuleName')
+            ->will($this->returnValue('Mage_Core'))
+        ;
     }
 
     /**
diff --git a/dev/tests/integration/testsuite/Mage/Core/Helper/HttpTest.php b/dev/tests/integration/testsuite/Mage/Core/Helper/HttpTest.php
index 264a377b95bae45eb9139c194ba4e45cf6ae892f..c4a560c221a4f8380350d86223011fb756bbd50d 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Helper/HttpTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Helper/HttpTest.php
@@ -57,8 +57,9 @@ class Mage_Core_Helper_HttpTest extends PHPUnit_Framework_TestCase
 
     public function testGetHttpMethods()
     {
+        $host = 'localhost';
         $this->assertEquals(false, $this->_helper->getHttpAcceptCharset());
-        $this->assertEquals(false, $this->_helper->getHttpHost());
+        $this->assertEquals($host, $this->_helper->getHttpHost());
         $this->assertEquals(false, $this->_helper->getHttpReferer());
         $this->assertEquals(false, $this->_helper->getHttpAcceptLanguage());
         $this->assertEquals(false, $this->_helper->getHttpUserAgent());
diff --git a/dev/tests/integration/testsuite/Mage/Core/Helper/JsTest.php b/dev/tests/integration/testsuite/Mage/Core/Helper/JsTest.php
index 8c54e49bc4fba9656164d6939d42f0ed44ce649d..66e008aa96f492e6b8ccea39cd6ff96edf750a9c 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Helper/JsTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Helper/JsTest.php
@@ -50,16 +50,18 @@ class Mage_Core_Helper_JsTest extends PHPUnit_Framework_TestCase
     public function testGetTranslatorScript()
     {
         $this->assertEquals(
-            '<script type="text/javascript">var Translator = new Translate('
-            . $this->_helper->getTranslateJson()
-            . ');</script>',
+            '<script type="text/javascript">//<![CDATA['
+            . "\nvar Translator = new Translate({$this->_helper->getTranslateJson()});\n"
+            . '//]]></script>',
             $this->_helper->getTranslatorScript()
         );
     }
 
     public function testGetScript()
     {
-        $this->assertEquals('<script type="text/javascript">script</script>', $this->_helper->getScript('script'));
+        $this->assertEquals("<script type=\"text/javascript\">//<![CDATA[\ntest\n//]]></script>",
+            $this->_helper->getScript('test')
+        );
     }
 
     public function testIncludeScript()
diff --git a/dev/tests/integration/testsuite/Mage/Core/Helper/UrlTest.php b/dev/tests/integration/testsuite/Mage/Core/Helper/UrlTest.php
index 8ae6e207217c47a3bbd3eeb4016b3532e5d47d09..25609d14ce4244f3534b1f33c3c527452318d862 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Helper/UrlTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Helper/UrlTest.php
@@ -49,12 +49,12 @@ class Mage_Core_Helper_UrlTest extends PHPUnit_Framework_TestCase
 
     public function testGetCurrentBase64Url()
     {
-        $this->assertEquals('aHR0cDovLw,,', $this->_helper->getCurrentBase64Url());
+        $this->assertEquals('aHR0cDovL2xvY2FsaG9zdA,,', $this->_helper->getCurrentBase64Url());
     }
 
     public function testGetEncodedUrl()
     {
-        $this->assertEquals('aHR0cDovLw,,', $this->_helper->getEncodedUrl());
+        $this->assertEquals('aHR0cDovL2xvY2FsaG9zdA,,', $this->_helper->getEncodedUrl());
         $this->assertEquals('aHR0cDovL2V4YW1wbGUuY29tLw,,', $this->_helper->getEncodedUrl('http://example.com/'));
     }
 
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/CacheTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/CacheTest.php
index 950e68d8d917cea1409b6442ca3d50f812c72e64..d42c67040353e5ef93202a5f6c59da00c08a082d 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/CacheTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/CacheTest.php
@@ -60,6 +60,9 @@ class Mage_Core_Model_CacheTest extends PHPUnit_Framework_TestCase
         $this->assertInstanceOf($expectedBackendClass, $backend);
     }
 
+    /**
+     * @return array
+     */
     public function constructorDataProvider()
     {
         return array(
@@ -80,6 +83,7 @@ class Mage_Core_Model_CacheTest extends PHPUnit_Framework_TestCase
         if ($extensionRequired) {
             if (!extension_loaded($extensionRequired)) {
                 $this->markTestSkipped("The PHP extension '{$extensionRequired}' is required for this test.");
+
             }
         }
         $model = new Mage_Core_Model_Cache(array('backend' => $optionCode));
@@ -196,15 +200,38 @@ class Mage_Core_Model_CacheTest extends PHPUnit_Framework_TestCase
         $this->assertInstanceOf('Zend_Db_Adapter_Abstract', $this->_model->getDbAdapter());
     }
 
-    public function testCanUseAndBanUse()
+    /**
+     * @return Mage_Core_Model_Cache
+     */
+    public function testCanUse()
     {
-        $actualCacheOptions = $this->_model->canUse('');
-        $this->assertEquals(array('config' => true), $actualCacheOptions);
-
+        $this->assertEquals(array('config' => true), $this->_model->canUse(''));
         $this->assertTrue($this->_model->canUse('config'));
+        return $this->_model;
+    }
 
-        $this->_model->banUse('config');
-        $this->assertFalse($this->_model->canUse('config'));
+    /**
+     * @depends testCanUse
+     * @param Mage_Core_Model_Cache $model
+     * @return Mage_Core_Model_CacheTest
+     */
+    public function testBanUse(Mage_Core_Model_Cache $model)
+    {
+        $this->assertTrue($model->canUse('config'));
+        $model->banUse('config');
+        $this->assertFalse($model->canUse('config'));
+        return $model;
+    }
+
+    /**
+     * @depends testBanUse
+     * @param Mage_Core_Model_Cache $model
+     */
+    public function testAllowUse(Mage_Core_Model_Cache $model)
+    {
+        $this->assertFalse($model->canUse('config'));
+        $model->allowUse('config');
+        $this->assertTrue($model->canUse('config'));
     }
 
     /**
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 977cebc839602b60a0b5d82887877fed667044e3..eed63d6c49fab44e361fa66f02e1da5a104791d3 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Config/DataTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Config/DataTest.php
@@ -41,13 +41,22 @@ 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);
-        Magento_Test_Bootstrap::getInstance()->refreshConfiguration();
+        self::_refreshConfiguration();
     }
 
     public static function tearDownAfterClass()
     {
         Mage::app()->getConfig()->deleteConfig(self::SAMPLE_CONFIG_PATH);
-        Magento_Test_Bootstrap::getInstance()->refreshConfiguration();
+        self::_refreshConfiguration();
+    }
+
+    /**
+     * Remove cached configuration and reinitialize the application
+     */
+    protected static function _refreshConfiguration()
+    {
+        Mage::app()->cleanCache(array(Mage_Core_Model_Config::CACHE_TAG));
+        Magento_Test_Bootstrap::getInstance()->initialize();
     }
 
     protected function setUp()
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 6a92944596f076405c2f28a3baa8ebdb5553f587..eb9c1073dabe6aa365b3471b29fb1de62129b5c5 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Design/PackageTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Design/PackageTest.php
@@ -194,9 +194,9 @@ class Mage_Core_Model_Design_PackageTest extends PHPUnit_Framework_TestCase
                 'ru_RU',
             ),
             'lib skin file inside theme' => array(
-                'jquery/jquery-no-conflict.js',
+                'mage/jquery-no-conflict.js',
                 array('_skin' => 'theme_nested_skin'),
-                $prefix . 'custom_theme/skin/theme_nested_skin/jquery/jquery-no-conflict.js',
+                $prefix . 'custom_theme/skin/theme_nested_skin/mage/jquery-no-conflict.js',
             ),
             'primary theme fallback - same theme & default skin' => array(
                 'fixture_script_two.js',
@@ -214,9 +214,9 @@ class Mage_Core_Model_Design_PackageTest extends PHPUnit_Framework_TestCase
                 $prefix . 'default/skin/default/fixture_script_four.js',
             ),
             'lib fallback' => array(
-                'jquery/jquery-no-conflict.js',
+                'mage/jquery-no-conflict.js',
                 array('_skin' => 'default'),
-                '%s/pub/js/jquery/jquery-no-conflict.js',
+                '%s/pub/js/mage/jquery-no-conflict.js',
             ),
         );
     }
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Layout/StructureTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Layout/StructureTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..60ed81994f38bba73194947348d12796549f5e6e
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Layout/StructureTest.php
@@ -0,0 +1,64 @@
+<?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  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Core
+ */
+class Mage_Core_Model_Layout_StructureTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Layout_Structure
+     */
+    protected $_model;
+
+    protected function setUp()
+    {
+        $this->_model = new Mage_Core_Model_Layout_Structure;
+    }
+
+    /**
+     * If several parents with the same name exist
+     */
+    public function testGetParentName()
+    {
+        $parent = 'parent';
+        $child1 = 'child1';
+        $child2 = 'child2';
+        $this->_model->insertElement('', $parent, 'container');
+        $this->assertEmpty($this->_model->getParentName($parent));
+
+        $this->_model->insertElement($parent, $child1, 'block');
+        $parentName = $this->_model->getParentName($child1);
+        $this->assertEquals($parent, $parentName);
+
+        $this->_model->insertElement('', $parent, 'block');
+        $this->assertEmpty($this->_model->getParentName($parent));
+        $this->_model->insertElement($parent, $child2, 'block');
+        $parentName = $this->_model->getParentName($child2);
+        $this->assertEquals($parent, $parentName);
+    }
+}
\ No newline at end of file
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Layout/UpdateTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Layout/UpdateTest.php
index 02a696860d85511f546cf2ac828fb170ff9ad0f0..9d41d6fdd52d01e2b1a04489f14de8d353452a26 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Layout/UpdateTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Layout/UpdateTest.php
@@ -35,21 +35,242 @@ class Mage_Core_Model_Layout_UpdateTest extends PHPUnit_Framework_TestCase
      */
     protected $_model;
 
-    public static function setUpBeforeClass()
+    protected function setUp()
     {
         /* Point application to predefined layout fixtures */
         Mage::getConfig()->setOptions(array(
             'design_dir' => dirname(__DIR__) . '/_files/design',
         ));
         Mage::getDesign()->setDesignTheme('test/default/default');
-
         /* Disable loading and saving layout cache */
         Mage::app()->getCacheInstance()->banUse('layout');
+
+        $this->_model = new Mage_Core_Model_Layout_Update(array(
+            'area'    => 'frontend',
+            'package' => 'test',
+            'theme'   => 'default',
+        ));
     }
 
-    protected function setUp()
+    public function testGetElementClass()
+    {
+        $this->assertEquals('Mage_Core_Model_Layout_Element', $this->_model->getElementClass());
+    }
+
+    public function testAddUpdate()
+    {
+        $this->assertEmpty($this->_model->asArray());
+        $this->assertEmpty($this->_model->asString());
+        $this->_model->addUpdate('test');
+        $this->assertEquals(array('test'), $this->_model->asArray());
+        $this->assertEquals('test', $this->_model->asString());
+    }
+
+    public function testAddHandle()
+    {
+        $this->assertEmpty($this->_model->getHandles());
+        $this->_model->addHandle('test');
+        $this->assertEquals(array('test'), $this->_model->getHandles());
+    }
+
+    public function testRemoveHandle()
+    {
+        $this->_model->addHandle('test');
+        $this->_model->removeHandle('test');
+        $this->assertEmpty($this->_model->getHandles());
+    }
+
+    public function testAddPageHandles()
+    {
+        /* add a non-page handle to verify that it won't be affected during page handles manipulation */
+        $nonPageHandles = array('non_page_handle');
+        $this->_model->addHandle($nonPageHandles);
+
+        $this->assertFalse($this->_model->addPageHandles(array('non_existing_handle')));
+        $this->assertEmpty($this->_model->getPageHandles());
+        $this->assertEquals($nonPageHandles, $this->_model->getHandles());
+
+        /* test that only the first existing handle is taken into account */
+        $handlesToTry = array('catalog_product_view_type_simple', 'catalog_category_view');
+        $expectedPageHandles = array('default', 'catalog_product_view', 'catalog_product_view_type_simple');
+        $this->assertTrue($this->_model->addPageHandles($handlesToTry));
+        $this->assertEquals($expectedPageHandles, $this->_model->getPageHandles());
+        $this->assertEquals(array_merge($nonPageHandles, $expectedPageHandles), $this->_model->getHandles());
+
+        /* test that new handles override the previous ones */
+        $expectedPageHandles = array('default', 'catalog_category_view', 'catalog_category_view_type_default');
+        $this->assertTrue($this->_model->addPageHandles(array('catalog_category_view_type_default')));
+        $this->assertEquals($expectedPageHandles, $this->_model->getPageHandles());
+        $this->assertEquals(array_merge($nonPageHandles, $expectedPageHandles), $this->_model->getHandles());
+    }
+
+    /**
+     * @dataProvider getPageLayoutHandlesDataProvider
+     */
+    public function testGetPageLayoutHandles($inputPageHandle, $expectedResult)
+    {
+        $layoutUtility = new Mage_Core_Utility_Layout($this);
+        $model = $layoutUtility->getLayoutUpdateFromFixture(__DIR__ . '/_files/_page_types.xml');
+        $this->assertSame($expectedResult, $model->getPageLayoutHandles($inputPageHandle));
+    }
+
+    public function getPageLayoutHandlesDataProvider()
+    {
+        return array(
+            'non-existing handle'      => array('non_existing_handle', array()),
+            'non page type handle'     => array('not_a_page_type', array()),
+            'page type with no parent' => array('default', array('default')),
+            'page type with parent'    => array(
+                'catalog_category_default', array('default', 'catalog_category_default')
+            ),
+            'deeply nested page type'  => array(
+                'catalog_category_layered', array('default', 'catalog_category_default', 'catalog_category_layered')
+            ),
+        );
+    }
+
+    public function testGetPageTypesHierarchy()
+    {
+        $layoutUtility = new Mage_Core_Utility_Layout($this);
+        $model = $layoutUtility->getLayoutUpdateFromFixture(__DIR__ . '/_files/_page_types.xml');
+        $expected = require(__DIR__ . '/_files/_page_types_hierarchy.php');
+        $actual = $model->getPageTypesHierarchy();
+        $this->assertEquals($expected, $actual);
+    }
+
+    /**
+     * Test that, regarding of the current area, page types hierarchy getter retrieves the front-end page types
+     */
+    public function testGetPageTypesHierarchyFromBackend()
+    {
+        $area = Mage::getDesign()->getArea();
+        $this->assertEquals('frontend', $area, 'Test assumes that front-end is the current area.');
+
+        /* use new instance to ensure that in-memory caching, if any, won't affect test results */
+        $model = new Mage_Core_Model_Layout_Update();
+        $frontendPageTypes = $model->getPageTypesHierarchy();
+        $this->assertNotEmpty($frontendPageTypes);
+
+        Mage::getDesign()->setArea('adminhtml');
+        try {
+            $backendPageTypes = $this->_model->getPageTypesHierarchy();
+            $this->assertSame($frontendPageTypes, $backendPageTypes);
+        } catch (Exception $e) {
+            Mage::getDesign()->setArea($area);
+            throw $e;
+        }
+        Mage::getDesign()->setArea($area);
+    }
+
+    /**
+     * @dataProvider pageTypeExistsDataProvider
+     */
+    public function testPageTypeExists($inputPageType, $expectedResult)
     {
-        $this->_model = new Mage_Core_Model_Layout_Update();
+        $layoutUtility = new Mage_Core_Utility_Layout($this);
+        $model = $layoutUtility->getLayoutUpdateFromFixture(__DIR__ . '/_files/_page_types.xml');
+        $this->assertSame($expectedResult, $model->pageTypeExists($inputPageType));
+    }
+
+    public function pageTypeExistsDataProvider()
+    {
+        return array(
+            'non-existing handle'  => array('non_existing_handle', false),
+            'non page type handle' => array('not_a_page_type',     false),
+            'existing page type'   => array('default',             true),
+        );
+    }
+
+    /**
+     * @dataProvider getPageTypeLabelDataProvider
+     */
+    public function testGetPageTypeLabel($inputPageType, $expectedResult)
+    {
+        $layoutUtility = new Mage_Core_Utility_Layout($this);
+        $model = $layoutUtility->getLayoutUpdateFromFixture(__DIR__ . '/_files/_page_types.xml');
+        $this->assertSame($expectedResult, $model->getPageTypeLabel($inputPageType));
+    }
+
+    public function getPageTypeLabelDataProvider()
+    {
+        return array(
+            'non-existing handle'  => array('non_existing_handle', false),
+            'non page type handle' => array('not_a_page_type',     false),
+            'existing page type'   => array('default',             'All Pages'),
+        );
+    }
+
+    /**
+     * @dataProvider getPageTypeParentDataProvider
+     */
+    public function testGetPageTypeParent($inputPageType, $expectedResult)
+    {
+        $layoutUtility = new Mage_Core_Utility_Layout($this);
+        $model = $layoutUtility->getLayoutUpdateFromFixture(__DIR__ . '/_files/_page_types.xml');
+        $this->assertSame($expectedResult, $model->getPageTypeParent($inputPageType));
+    }
+
+    public function getPageTypeParentDataProvider()
+    {
+        return array(
+            'non-existing handle'      => array('non_existing_handle',      false),
+            'non page type handle'     => array('not_a_page_type',          false),
+            'page type with no parent' => array('default',                  null),
+            'page type with parent'    => array('catalog_category_default', 'default'),
+            'deeply nested page type'  => array('catalog_category_layered', 'catalog_category_default'),
+        );
+    }
+
+    public function testLoad()
+    {
+        $layoutHandle = 'layout_test_handle';
+        $expectedText = 'Text declared in the frontend/test/test_theme';
+        $model = new Mage_Core_Model_Layout_Update(
+            array('area' => 'frontend', 'package' => 'test', 'theme'=> 'test_theme')
+        );
+        $this->assertNotContains($layoutHandle, $model->getHandles());
+        $this->assertNotContains($expectedText, $model->asString());
+        $model->load($layoutHandle);
+        $this->assertContains($layoutHandle, $model->getHandles());
+        $this->assertContains($expectedText, $model->asString());
+    }
+
+    /**
+     * @magentoAppIsolation enabled
+     */
+    public function testLoadCache()
+    {
+        Mage::app()->getCacheInstance()->allowUse('layout');
+
+        $layoutHandle = 'layout_test_handle';
+        $expectedTextThemeOne = 'Text declared in the frontend/test/test_theme';
+        $expectedTextThemeTwo = 'Text declared in the frontend/test/cache_test_theme';
+
+        $model = new Mage_Core_Model_Layout_Update(
+            array('area' => 'frontend', 'package' => 'test', 'theme'=> 'test_theme')
+        );
+        $model->load($layoutHandle);
+        $this->assertContains($expectedTextThemeOne, $model->asString());
+        $this->assertNotContains($expectedTextThemeTwo, $model->asString());
+
+        $model = new Mage_Core_Model_Layout_Update(
+            array('area' => 'frontend', 'package' => 'test', 'theme'=> 'cache_test_theme')
+        );
+        $model->load($layoutHandle);
+        $this->assertContains($expectedTextThemeTwo, $model->asString());
+        $this->assertNotContains($expectedTextThemeOne, $model->asString());
+    }
+
+    /**
+     * @magentoDataFixture Mage/Core/Model/Layout/_files/db_layout_update.php
+     */
+    public function testFetchDbLayoutUpdates()
+    {
+        $this->_model->load('fixture_handle');
+        $this->assertStringMatchesFormat(
+            '<reference name="root">%w<block type="Mage_Core_Block_Template" template="dummy.phtml"/>%w</reference>',
+            trim($this->_model->asString())
+        );
     }
 
     public function testGetFileLayoutUpdatesXmlFromTheme()
@@ -62,7 +283,7 @@ class Mage_Core_Model_Layout_UpdateTest extends PHPUnit_Framework_TestCase
         $expectedXmlStr = $this->_readLayoutFileContents(
             __DIR__ . '/../_files/design/frontend/test/default/Mage_Core/layout.xml'
         );
-        $actualXml = $this->_model->getFileLayoutUpdatesXml('frontend', 'test', 'default');
+        $actualXml = $this->_model->getFileLayoutUpdatesXml();
         $this->assertXmlStringEqualsXmlString($expectedXmlStr, $actualXml->asNiceXml());
     }
 
@@ -76,7 +297,7 @@ class Mage_Core_Model_Layout_UpdateTest extends PHPUnit_Framework_TestCase
         $expectedXmlStr = $this->_readLayoutFileContents(
             __DIR__ . '/../../../../../../../../app/code/core/Mage/Page/view/frontend/layout.xml'
         );
-        $actualXml = $this->_model->getFileLayoutUpdatesXml('frontend', 'test', 'default');
+        $actualXml = $this->_model->getFileLayoutUpdatesXml();
         $this->assertXmlStringEqualsXmlString($expectedXmlStr, $actualXml->asNiceXml());
     }
 
@@ -128,7 +349,7 @@ class Mage_Core_Model_Layout_UpdateTest extends PHPUnit_Framework_TestCase
     public function testGetFileLayoutUpdatesXmlException($configFixture)
     {
         $this->_replaceConfigLayoutUpdates($configFixture);
-        $this->_model->getFileLayoutUpdatesXml('frontend', 'test', 'default');
+        $this->_model->getFileLayoutUpdatesXml();
     }
 
     public function getFileLayoutUpdatesXmlExceptionDataProvider()
@@ -172,7 +393,21 @@ class Mage_Core_Model_Layout_UpdateTest extends PHPUnit_Framework_TestCase
         $expectedXmlStr = $this->_readLayoutFileContents(
             __DIR__ . '/../_files/design/frontend/test/default/Mage_Core/layout.xml'
         );
-        $actualXml = $this->_model->getFileLayoutUpdatesXml('frontend', 'test', 'default');
+        $actualXml = $this->_model->getFileLayoutUpdatesXml();
         $this->assertXmlStringEqualsXmlString($expectedXmlStr, $actualXml->asNiceXml());
     }
+
+    public function testGetContainers()
+    {
+        $layoutUtility = new Mage_Core_Utility_Layout($this);
+        $model = $layoutUtility->getLayoutUpdateFromFixture(__DIR__ . '/_files/_page_types.xml');
+        $model->addPageHandles(array('catalog_product_view_type_configurable'));
+        $model->load();
+        $expected = array(
+            'content'                         => 'Main Content Area',
+            'product.info.extrahint'          => 'Product View Extra Hint',
+            'product.info.configurable.extra' => 'Configurable Product Extra Info',
+        );
+        $this->assertSame($expected, $model->getContainers());
+    }
 }
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Layout/_files/_page_types.xml b/dev/tests/integration/testsuite/Mage/Core/Model/Layout/_files/_page_types.xml
new file mode 100644
index 0000000000000000000000000000000000000000..e359b68925ce90005469764d3459cd5a8e1ecc73
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Layout/_files/_page_types.xml
@@ -0,0 +1,67 @@
+<?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     Mage_Core
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<layouts>
+    <!-- Note: some page types have been intentionally declared before parents they refer to -->
+    <sales_order_print type="page" parent="print">
+        <label>Sales Order Print View</label>
+    </sales_order_print>
+    <print type="page">
+        <label>All Pages (Print Version)</label>
+    </print>
+    <sales_guest_print type="page" parent="print">
+        <label>Sales Order Print View (Guest)</label>
+    </sales_guest_print>
+    <not_a_page_type translate="label">
+        <label>Handle that Is Not a Page Type</label>
+    </not_a_page_type>
+    <catalog_category_layered type="page" parent="catalog_category_default">
+        <label>Catalog Category (Anchor)</label>
+    </catalog_category_layered>
+    <catalog_category_default type="page" parent="default">
+        <label>Catalog Category (Non-Anchor)</label>
+    </catalog_category_default>
+    <default type="page">
+        <label>All Pages</label>
+        <container name="content" as="content" label="Main Content Area"/>
+    </default>
+    <catalog_product_view type="page" parent="catalog_category_default">
+        <label>Catalog Product View (Any)</label>
+        <container name="product.info.extrahint" as="extrahint" label="Product View Extra Hint"/>
+    </catalog_product_view>
+    <catalog_product_view_type_simple type="page" parent="catalog_product_view">
+        <label>Catalog Product View (Simple)</label>
+    </catalog_product_view_type_simple>
+    <catalog_product_view_type_configurable type="page" parent="catalog_product_view">
+        <label>Catalog Product View (Configurable)</label>
+        <container name="product.info.configurable.extra" as="product_type_data_extra" label="Configurable Product Extra Info"/>
+    </catalog_product_view_type_configurable>
+    <catalog_product_view_type_grouped type="page" parent="catalog_product_view">
+        <label>Catalog Product View (Grouped)</label>
+    </catalog_product_view_type_grouped>
+</layouts>
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Layout/_files/_page_types_hierarchy.php b/dev/tests/integration/testsuite/Mage/Core/Model/Layout/_files/_page_types_hierarchy.php
new file mode 100644
index 0000000000000000000000000000000000000000..daad6348d303e2d646a9c17554deabc8d77653c7
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Layout/_files/_page_types_hierarchy.php
@@ -0,0 +1,84 @@
+<?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  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+?>
+<?php
+return array(
+    'print' => array(
+        'name'     => 'print',
+        'label'    => 'All Pages (Print Version)',
+        'children' => array(
+            'sales_order_print' => array(
+                'name'     => 'sales_order_print',
+                'label'    => 'Sales Order Print View',
+                'children' => array(),
+            ),
+            'sales_guest_print' => array(
+                'name'     => 'sales_guest_print',
+                'label'    => 'Sales Order Print View (Guest)',
+                'children' => array(),
+            ),
+        ),
+    ),
+    'default' => array(
+        'name'     => 'default',
+        'label'    => 'All Pages',
+        'children' => array(
+            'catalog_category_default' => array(
+                'name'     => 'catalog_category_default',
+                'label'    => 'Catalog Category (Non-Anchor)',
+                'children' => array(
+                    'catalog_category_layered' => array(
+                        'name'     => 'catalog_category_layered',
+                        'label'    => 'Catalog Category (Anchor)',
+                        'children' => array(),
+                    ),
+                    'catalog_product_view' => array(
+                        'name'     => 'catalog_product_view',
+                        'label'    => 'Catalog Product View (Any)',
+                        'children' => array(
+                            'catalog_product_view_type_simple' => array(
+                                'name'     => 'catalog_product_view_type_simple',
+                                'label'    => 'Catalog Product View (Simple)',
+                                'children' => array(),
+                            ),
+                            'catalog_product_view_type_configurable' => array(
+                                'name'     => 'catalog_product_view_type_configurable',
+                                'label'    => 'Catalog Product View (Configurable)',
+                                'children' => array(),
+                            ),
+                            'catalog_product_view_type_grouped' => array(
+                                'name'     => 'catalog_product_view_type_grouped',
+                                'label'    => 'Catalog Product View (Grouped)',
+                                'children' => array(),
+                            ),
+                        ),
+                    ),
+                ),
+            ),
+        ),
+    ),
+);
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Layout/_files/db_layout_update.php b/dev/tests/integration/testsuite/Mage/Core/Model/Layout/_files/db_layout_update.php
new file mode 100644
index 0000000000000000000000000000000000000000..6f695aa640e5a0bfbfdcad16662de3f2a3bdea9b
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Layout/_files/db_layout_update.php
@@ -0,0 +1,40 @@
+<?php
+/**
+ * A layout update stored in database
+ *
+ * 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  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+$layoutUpdate = new Mage_Core_Model_Layout_Data;
+$layoutUpdate->setData((array(
+    'handle' => 'fixture_handle',
+    'xml' => '<reference name="root"><block type="Mage_Core_Block_Template" template="dummy.phtml"/></reference>',
+    'sort_order' => 0,
+    'store_id' => 1,
+    'area' => 'frontend',
+    'package' => 'test',
+    'theme' => 'default',
+)));
+$layoutUpdate->save();
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/LayoutTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/LayoutTest.php
index 5d9d3055c33ef63067af5355d6fea8606ea894e8..b30e2adc2a549db8654c933671b6e38d2ed60a9e 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/LayoutTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/LayoutTest.php
@@ -33,7 +33,7 @@ class Mage_Core_Model_LayoutTest extends PHPUnit_Framework_TestCase
     /**
      * @var Mage_Core_Model_Layout
      */
-    protected $_model;
+    protected $_layout;
 
     public static function setUpBeforeClass()
     {
@@ -49,28 +49,52 @@ class Mage_Core_Model_LayoutTest extends PHPUnit_Framework_TestCase
 
     protected function setUp()
     {
-        $this->_model = new Mage_Core_Model_Layout();
-        $this->_model->getUpdate()->addHandle('layout_test_handle_main');
-        $this->_model->getUpdate()->load('layout_test_handle_extra');
+        $this->_layout = new Mage_Core_Model_Layout();
+        $this->_layout->getUpdate()->addHandle('layout_test_handle_main');
+        $this->_layout->getUpdate()->load('layout_test_handle_extra');
     }
 
-    public function testGetUpdate()
+    /**
+     * @param array $inputArguments
+     * @param string $expectedArea
+     * @dataProvider constructorDataProvider
+     */
+    public function testConstructor(array $inputArguments, $expectedArea)
     {
-        $this->assertInstanceOf('Mage_Core_Model_Layout_Update', $this->_model->getUpdate());
+        $layout = new Mage_Core_Model_Layout($inputArguments);
+        $this->assertEquals($expectedArea, $layout->getArea());
+    }
+
+    /**
+     * @expectedException Magento_Exception
+     */
+    public function testConstructorWrongStructure()
+    {
+        new Mage_Core_Model_Layout(array('structure' => false));
+    }
+
+    public function constructorDataProvider()
+    {
+        return array(
+            'default area'  => array(array(), Mage_Core_Model_Design_Package::DEFAULT_AREA),
+            'frontend area' => array(array('area' => 'frontend'), 'frontend'),
+            'backend area'  => array(array('area' => 'adminhtml'), 'adminhtml'),
+            'structure'     => array(
+                array('structure' => new Mage_Core_Model_Layout_Structure), Mage_Core_Model_Design_Package::DEFAULT_AREA
+            ),
+        );
     }
 
-    public function testGetSetArea()
+    public function testGetUpdate()
     {
-        $this->assertEmpty($this->_model->getArea());
-        $this->_model->setArea('frontend');
-        $this->assertEquals('frontend', $this->_model->getArea());
+        $this->assertInstanceOf('Mage_Core_Model_Layout_Update', $this->_layout->getUpdate());
     }
 
     public function testGetSetDirectOutput()
     {
-        $this->assertFalse($this->_model->getDirectOutput());
-        $this->_model->setDirectOutput(true);
-        $this->assertTrue($this->_model->getDirectOutput());
+        $this->assertFalse($this->_layout->isDirectOutput());
+        $this->_layout->setDirectOutput(true);
+        $this->assertTrue($this->_layout->isDirectOutput());
     }
 
     /**
@@ -80,13 +104,13 @@ class Mage_Core_Model_LayoutTest extends PHPUnit_Framework_TestCase
      */
     public function testGenerateXmlAndBlocks()
     {
-        $this->_model->generateXml();
+        $this->_layout->generateXml();
         /* Generate fixture
         file_put_contents(__DIR__ . '/_files/_layout_update.xml', $this->_model->getNode()->asNiceXml());
         */
-        $this->assertXmlStringEqualsXmlFile(__DIR__ . '/_files/_layout_update.xml', $this->_model->getXmlString());
+        $this->assertXmlStringEqualsXmlFile(__DIR__ . '/_files/_layout_update.xml', $this->_layout->getXmlString());
 
-        $this->assertEquals(array(), $this->_model->getAllBlocks());
+        $this->assertEquals(array(), $this->_layout->getAllBlocks());
 
         $expectedBlocks = array(
             'root',
@@ -101,48 +125,59 @@ class Mage_Core_Model_LayoutTest extends PHPUnit_Framework_TestCase
             'index_notifications',
             'index_notifications_copy'
         );
-        $this->_model->generateBlocks();
+        $this->_layout->generateBlocks();
 
-        $actualBlocks = $this->_model->getAllBlocks();
+        $actualBlocks = $this->_layout->getAllBlocks();
         $this->assertEquals($expectedBlocks, array_keys($actualBlocks));
 
         /** @var $block Mage_Adminhtml_Block_Page_Head */
-        $block = $this->_model->getBlock('head');
+        $block = $this->_layout->getBlock('head');
         $this->assertEquals('Magento Admin', $block->getTitle());
 
-        $block = $this->_model->getBlock('head.calendar');
-        $this->assertSame($this->_model->getBlock('head'), $block->getParentBlock());
+        $block = $this->_layout->getBlock('head.calendar');
+        $this->assertSame($this->_layout->getBlock('head'), $block->getParentBlock());
 
         /** @var $block Mage_Core_Block_Template */
-        $block = $this->_model->getBlock('root');
+        $block = $this->_layout->getBlock('root');
         $this->assertEquals('popup.phtml', $block->getTemplate());
     }
 
+    public function testRenderElement()
+    {
+        $utility = new Mage_Core_Utility_Layout($this);
+        $layout = $utility->getLayoutFromFixture(__DIR__ . '/_files/valid_layout_updates.xml');
+        $layout->getUpdate()->load('a_handle');
+        $layout->generateXml()->generateBlocks();
+        $this->assertEmpty($layout->renderElement('nonexisting_element'));
+        $this->assertEquals('Value: 1Value: 2', $layout->renderElement('container1'));
+        $this->assertEquals('Value: 1', $layout->renderElement('block1'));
+    }
+
     public function testSetUnsetBlock()
     {
         $expectedBlockName = 'block_' . __METHOD__;
         $expectedBlock = new Mage_Core_Block_Text();
 
-        $this->_model->setBlock($expectedBlockName, $expectedBlock);
-        $this->assertSame($expectedBlock, $this->_model->getBlock($expectedBlockName));
+        $this->_layout->setBlock($expectedBlockName, $expectedBlock);
+        $this->assertSame($expectedBlock, $this->_layout->getBlock($expectedBlockName));
 
-        $this->_model->unsetBlock($expectedBlockName);
-        $this->assertFalse($this->_model->getBlock($expectedBlockName));
+        $this->_layout->unsetElement($expectedBlockName);
+        $this->assertFalse($this->_layout->getBlock($expectedBlockName));
+        $this->assertFalse($this->_layout->hasElement($expectedBlockName));
     }
 
     /**
      * @dataProvider createBlockDataProvider
      */
-    public function testCreateBlock($blockType, $blockName, array $blockData, $expectedName, $expectedAnonSuffix = null)
+    public function testCreateBlock($blockType, $blockName, array $blockData, $expectedName)
     {
         $expectedData = $blockData + array('type' => $blockType);
 
-        $block = $this->_model->createBlock($blockType, $blockName, $blockData);
+        $block = $this->_layout->createBlock($blockType, $blockName, $blockData);
 
-        $this->assertEquals($this->_model, $block->getLayout());
+        $this->assertEquals($this->_layout, $block->getLayout());
         $this->assertRegExp($expectedName, $block->getNameInLayout());
         $this->assertEquals($expectedData, $block->getData());
-        $this->assertEquals($expectedAnonSuffix, $block->getAnonSuffix());
     }
 
     public function createBlockDataProvider()
@@ -154,54 +189,149 @@ class Mage_Core_Model_LayoutTest extends PHPUnit_Framework_TestCase
                 array('type' => 'Mage_Core_Block_Template'),
                 '/^some_block_name_full_class$/'
             ),
-            'anonymous block' => array(
+            'no name block' => array(
                 'Mage_Core_Block_Text_List',
                 '',
-                array('type' => 'Mage_Core_Block_Text_List',
-                'key1' => 'value1'),
+                array(
+                    'type' => 'Mage_Core_Block_Text_List',
+                    'key1' => 'value1'
+                ),
                 '/^ANONYMOUS_.+/'
             ),
-            'anonymous suffix' => array(
-                'Mage_Core_Block_Template',
-                '.some_anonymous_suffix',
-                array('type' => 'Mage_Core_Block_Template'),
-                '/^ANONYMOUS_.+/',
-                'some_anonymous_suffix'
-            )
         );
     }
 
-    public function testCreateBlockNotExists()
+    /**
+     * @dataProvider blockNotExistsDataProvider
+     * @expectedException Mage_Core_Exception
+     */
+    public function testCreateBlockNotExists($name)
+    {
+        $this->_layout->createBlock($name);
+    }
+
+    public function blockNotExistsDataProvider()
+    {
+        return array(
+            array(''),
+            array('block_not_exists'),
+        );
+    }
+
+    public function testAddBlock()
+    {
+        $parentName = 'parent';
+        $name1 = 'block1';
+        $block = $this->_layout->addBlock('Mage_Core_Block_Text', $name1, $parentName . '', 'alias1');
+        $this->assertInstanceOf('Mage_Core_Block_Text', $block);
+        $this->assertTrue($this->_layout->hasElement($name1));
+        $this->assertEquals($parentName, $this->_layout->getParentName($name1));
+        $this->assertEquals('alias1', $this->_layout->getElementAlias($name1));
+        $this->assertEquals($name1, $this->_layout->getChildName($parentName, 'alias1'));
+
+        $name2 = 'block2';
+        $block2 = $this->_layout->addBlock(new Mage_Core_Block_Text, $name2, $parentName, 'alias2', true, $name1);
+        $this->assertInstanceOf('Mage_Core_Block_Text', $block2);
+        $this->assertEquals(array($name1, $name2), $this->_layout->getChildNames($parentName));
+        $this->assertTrue($this->_layout->hasElement($name2));
+    }
+
+    public function testGetChildBlock()
+    {
+        $block = $this->_layout->addBlock('Mage_Core_Block_Text', 'block', 'parent', 'block_alias');
+        $this->_layout->insertContainer('parent', 'container', 'container_alias');
+        $this->assertSame($block, $this->_layout->getChildBlock('parent', 'block_alias'));
+        $this->assertFalse($this->_layout->getChildBlock('parent', 'container_alias'));
+    }
+
+    public function testGetChildBlocks()
+    {
+        $block1 = $this->_layout->addBlock('Mage_Core_Block_Text', 'block1', 'parent');
+        $this->_layout->insertContainer('parent', 'container');
+        $block2 = $this->_layout->addBlock('Mage_Core_Block_Template', 'block2', 'parent');
+        $this->assertEquals(array($block1, $block2), $this->_layout->getChildBlocks('parent'));
+    }
+
+    /**
+     * @expectedException Mage_Core_Exception
+     */
+    public function testAddBlockInvalidType()
+    {
+        $this->_layout->addBlock('invalid_name', 'child', 'parent', 'alias', true, 'sibling');
+    }
+
+    public function testIsContainer()
+    {
+        $block = 'block';
+        $container = 'container';
+        $this->_layout->addBlock('Mage_Core_Block_Text', $block);
+        $this->_layout->insertContainer('', $container);
+        $this->assertFalse($this->_layout->isContainer($block));
+        $this->assertTrue($this->_layout->isContainer($container));
+        $this->assertFalse($this->_layout->isContainer('invalid_name'));
+    }
+
+    public function testRenameElement()
+    {
+        $blockName = 'block';
+        $expBlockName = 'block_renamed';
+        $containerName = 'container';
+        $expContainerName = 'container_renamed';
+        $block = $this->_layout->createBlock('Mage_Core_Block_Text', $blockName);
+        $this->_layout->insertContainer('', $containerName);
+
+        $this->assertEquals($block, $this->_layout->getBlock($blockName));
+        $this->_layout->renameElement($blockName, $expBlockName);
+        $this->assertEquals($block, $this->_layout->getBlock($expBlockName));
+
+        $this->_layout->hasElement($containerName);
+        $this->_layout->renameElement($containerName, $expContainerName);
+        $this->_layout->hasElement($expContainerName);
+    }
+
+    /**
+     * @covers Mage_Core_Model_Layout::getParentName
+     * @covers Mage_Core_Model_Layout::getElementAlias
+     */
+    public function testGetParentName()
     {
-        $this->assertFalse($this->_model->createBlock(''));
-        $this->assertFalse($this->_model->createBlock('block_not_exists'));
+        $parent = 'block1';
+        $child = 'block2';
+        $alias = 'alias';
+        $this->_layout->createBlock('Mage_Core_Block_Text', $parent);
+        $this->assertEmpty($this->_layout->getParentName($parent));
+        $this->assertEquals($parent, $this->_layout->getElementAlias($parent));
+
+        $this->_layout->addBlock('Mage_Core_Block_Text', $child, $parent, $alias);
+        $this->assertEquals($parent, $this->_layout->getParentName($child));
+        $this->assertEquals($alias, $this->_layout->getElementAlias($child));
     }
 
     /**
-     * @covers Mage_Core_Model_Layout::addBlock
-     * @covers Mage_Core_Model_Layout::addOutputBlock
+     * @covers Mage_Core_Model_Layout::addOutputElement
      * @covers Mage_Core_Model_Layout::getOutput
-     * @covers Mage_Core_Model_Layout::removeOutputBlock
+     * @covers Mage_Core_Model_Layout::removeOutputElement
      */
     public function testGetOutput()
     {
         $blockName = 'block_' . __METHOD__;
         $expectedText = "some_text_for_$blockName";
 
-        $block = new Mage_Core_Block_Text();
+        $block = $this->_layout->addBlock('Mage_Core_Block_Text', $blockName);
         $block->setText($expectedText);
-        $this->_model->addBlock($block, $blockName);
 
-        $this->_model->addOutputBlock($blockName);
-        $this->assertEquals($expectedText, $this->_model->getOutput());
+        $this->_layout->addOutputElement($blockName);
+        // add the same element twice should not produce output duplicate
+        $this->_layout->addOutputElement($blockName);
+        $this->assertEquals($expectedText, $this->_layout->getOutput());
 
-        $this->_model->removeOutputBlock($blockName);
-        $this->assertEmpty($this->_model->getOutput());
+        $this->_layout->removeOutputElement($blockName);
+        $this->assertEmpty($this->_layout->getOutput());
     }
 
     public function testGetMessagesBlock()
     {
-        $this->assertInstanceOf('Mage_Core_Block_Messages', $this->_model->getMessagesBlock());
+        $this->assertInstanceOf('Mage_Core_Block_Messages', $this->_layout->getMessagesBlock());
     }
 
     /**
@@ -211,9 +341,9 @@ class Mage_Core_Model_LayoutTest extends PHPUnit_Framework_TestCase
      */
     public function testGetBlockSingleton($blockType, $expectedClassName)
     {
-        $block = $this->_model->getBlockSingleton($blockType);
+        $block = $this->_layout->getBlockSingleton($blockType);
         $this->assertInstanceOf($expectedClassName, $block);
-        $this->assertSame($block, $this->_model->getBlockSingleton($blockType));
+        $this->assertSame($block, $this->_layout->getBlockSingleton($blockType));
     }
 
     public function getBlockSingletonDataProvider()
@@ -225,9 +355,9 @@ class Mage_Core_Model_LayoutTest extends PHPUnit_Framework_TestCase
 
     public function testHelper()
     {
-        $helper = $this->_model->helper('Mage_Core_Helper_Data');
+        $helper = $this->_layout->helper('Mage_Core_Helper_Data');
         $this->assertInstanceOf('Mage_Core_Helper_Data', $helper);
-        $this->assertSame($this->_model, $helper->getLayout());
+        $this->assertSame($this->_layout, $helper->getLayout());
     }
 
     /**
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Resource/Db/AbstractTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Resource/Db/AbstractTest.php
index 5d4da746c2c3877d4c8d8278c18356ed26fdd8f0..ed9bf915098820eef75a27a7d27bcd7fcadf9bc7 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Resource/Db/AbstractTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Resource/Db/AbstractTest.php
@@ -25,54 +25,44 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-class Mage_Core_Model_Resource_Db_AbstractTestAbstract extends Mage_Core_Model_Resource_Db_Abstract
-{
-    protected function _construct()
-    {
-        return $this;
-    }
-
-    public function getResources()
-    {
-        return $this->_resources;
-    }
-
-    public function setMainTable($mainTable, $idFieldName = null)
-    {
-        return parent::_setMainTable($mainTable, $idFieldName);
-    }
-}
-
 /**
  * @group module:Mage_Core
  */
 class Mage_Core_Model_Resource_Db_AbstractTest extends PHPUnit_Framework_TestCase
 {
     /**
-     * @var Mage_Core_Model_Resource_Db_AbstractTestAbstract
+     * @var Mage_Core_Model_Resource_Db_Abstract
      */
     protected $_model;
 
     public function setUp()
     {
-        $this->_model = new Mage_Core_Model_Resource_Db_AbstractTestAbstract();
+        $this->_model = $this->getMockForAbstractClass('Mage_Core_Model_Resource_Db_Abstract');
     }
 
     public function testConstruct()
     {
-        $model = new Mage_Core_Model_Resource_Db_AbstractTestAbstract();
-        $this->assertInstanceOf('Mage_Core_Model_Resource', $model->getResources());
+        $resourceProperty = new ReflectionProperty(get_class($this->_model), '_resources');
+        $resourceProperty->setAccessible(true);
+        $this->assertInstanceOf('Mage_Core_Model_Resource', $resourceProperty->getValue($this->_model));
     }
 
     public function testSetMainTable()
     {
+        if (!method_exists('ReflectionMethod', 'setAccessible')) {
+            $this->markTestSkipped('Test requires ReflectionMethod::setAccessible (PHP 5 >= 5.3.2).');
+        }
+
+        $setMainTableMethod = new ReflectionMethod($this->_model, '_setMainTable');
+        $setMainTableMethod->setAccessible(true);
+
         $tableName = $this->_model->getTable('core_website');
         $idFieldName = 'website_id';
 
-        $this->_model->setMainTable($tableName);
+        $setMainTableMethod->invoke($this->_model, $tableName);
         $this->assertEquals($tableName, $this->_model->getMainTable());
 
-        $this->_model->setMainTable($tableName, $idFieldName);
+        $setMainTableMethod->invoke($this->_model, $tableName, $idFieldName);
         $this->assertEquals($tableName, $this->_model->getMainTable());
         $this->assertEquals($idFieldName, $this->_model->getIdFieldName());
     }
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Resource/SessionTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Resource/SessionTest.php
index b8796a4b331b26f93b057cdaef0270dceb92abfe..17e459142687d6707da1d7ca182e965588d99625 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Resource/SessionTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Resource/SessionTest.php
@@ -40,11 +40,6 @@ class Mage_Core_Model_Resource_SessionTest extends PHPUnit_Framework_TestCase
         $this->_model = new Mage_Core_Model_Resource_Session();
     }
 
-    public function testGetLifeTime()
-    {
-        $this->assertGreaterThan(0, $this->_model->getLifeTime());
-    }
-
     public function testHasConnection()
     {
         $this->assertTrue($this->_model->hasConnection());
@@ -71,4 +66,12 @@ class Mage_Core_Model_Resource_SessionTest extends PHPUnit_Framework_TestCase
         $this->_model->destroy($sessionId);
         $this->assertEmpty($this->_model->read($sessionId));
     }
+
+    public function testGc()
+    {
+        $this->_model->write('test', 'test');
+        $this->assertEquals('test', $this->_model->read('test'));
+        $this->_model->gc(-1);
+        $this->assertEmpty($this->_model->read('test'));
+    }
 }
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Session/Abstract/VarienTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Session/Abstract/VarienTest.php
index 90e7d9d74099907e5d8cf7f42ef4a280de5aae5c..bde922595d8cdece787e181f6bb221619da8f7f8 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Session/Abstract/VarienTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Session/Abstract/VarienTest.php
@@ -32,6 +32,8 @@
 class Mage_Core_Model_Session_Abstract_VarienTest extends PHPUnit_Framework_TestCase
 {
     /**
+     * @param string $saveMethod
+     * @param string $iniValue
      * @dataProvider sessionSaveMethodDataProvider
      */
     public function testSessionSaveMethod($saveMethod, $iniValue)
@@ -40,7 +42,7 @@ class Mage_Core_Model_Session_Abstract_VarienTest extends PHPUnit_Framework_Test
 
         // depending on configuration some values cannot be set as default save session handlers.
         $origSessionHandler = ini_set('session.save_handler', $iniValue);
-        if ($iniValue && (ini_get($iniValue) != $iniValue)) {
+        if ($iniValue && (ini_get('session.save_handler') != $iniValue)) {
             $this->markTestSkipped("Can't  set '$iniValue' as session save handler");
         }
         ini_set('session.save_handler', $origSessionHandler);
@@ -54,11 +56,15 @@ class Mage_Core_Model_Session_Abstract_VarienTest extends PHPUnit_Framework_Test
         if ($iniValue) {
             $this->assertEquals(ini_get('session.save_handler'), $iniValue);
         }
+        ini_set('session.save_handler', $origSessionHandler);
     }
 
+    /**
+     * @return array
+     */
     public function sessionSaveMethodDataProvider()
     {
-        $testCases = array(
+        return array(
             array('db', 'user'),
             array('memcache', 'memcache'),
             array('memcached', 'memcached'),
@@ -66,7 +72,5 @@ class Mage_Core_Model_Session_Abstract_VarienTest extends PHPUnit_Framework_Test
             array('', ''),
             array('dummy', ''),
         );
-
-        return $testCases;
     }
 }
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Session/AbstractTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Session/AbstractTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..852a5c2bec4e1e4f3bda98149e3692efcab697f2
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Session/AbstractTest.php
@@ -0,0 +1,180 @@
+<?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  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Core
+ */
+class Mage_Core_Model_Session_AbstractTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Session_Abstract
+     */
+    protected $_model;
+
+    public function setUp()
+    {
+        $this->_model = $this->getMockForAbstractClass('Mage_Core_Model_Session_Abstract');
+    }
+
+    public function testGetCookie()
+    {
+        $cookie = $this->_model->getCookie();
+        $this->assertInstanceOf('Mage_Core_Model_Cookie', $cookie);
+        $this->assertSame($cookie, $this->_model->getCookie());
+    }
+
+    public function testInit()
+    {
+        $this->_model->init('test');
+        $this->_model->setTestData('test');
+        $data = $this->_model->getData();
+        $this->assertArrayHasKey('test_data', $data);
+        $this->assertSame($_SESSION['test'], $data);
+    }
+
+    public function testGetData()
+    {
+        $this->_model->setData(array('test_key' => 'test_value'));
+        $this->assertEquals('test_value', $this->_model->getData('test_key', true));
+        $this->assertNull($this->_model->getData('test_key'));
+    }
+
+    public function testGetSessionId()
+    {
+        $this->assertEquals(session_id(), $this->_model->getSessionId());
+    }
+
+    public function testGetSessionName()
+    {
+        $this->assertEquals(session_name(), $this->_model->getSessionName());
+    }
+
+    public function testSetSessionName()
+    {
+        $this->_model->setSessionName('test');
+        $this->assertEquals('test', $this->_model->getSessionName());
+    }
+
+    public function testUnsetAll()
+    {
+        $data = array('key' => 'value');
+        $this->_model->setData($data);
+
+        $this->assertEquals($data, $this->_model->getData());
+        $this->_model->unsetAll();
+
+        $this->assertEquals(array(), $this->_model->getData());
+    }
+
+    public function testValidate()
+    {
+        $this->assertInstanceOf('Mage_Core_Model_Session_Abstract', $this->_model->validate());
+    }
+
+    public function testGetValidateHttpUserAgentSkip()
+    {
+        $agents = $this->_model->getValidateHttpUserAgentSkip();
+        $this->assertContains('Shockwave Flash', $agents);
+        $this->assertContains('Adobe Flash Player\s{1,}\w{1,10}', $agents);
+    }
+
+    public function testSetSessionId()
+    {
+        $sessionId = $this->_model->getSessionId();
+        $this->_model->setSessionId();
+        $this->assertEquals($sessionId, $this->_model->getSessionId());
+
+        $this->_model->setSessionId('test');
+        $this->assertEquals('test', $this->_model->getSessionId());
+    }
+
+    /**
+     * @magentoConfigFixture current_store web/session/use_frontend_sid 1
+     */
+    public function testSetSessionIdFromParam()
+    {
+        $this->assertNotEquals('test_id', $this->_model->getSessionId());
+        $_GET[$this->_model->getSessionIdQueryParam()] = 'test-id';
+        $this->_model->setSessionId();
+
+        $this->assertEquals('test-id', $this->_model->getSessionId());
+
+        /* Use not valid identifier */
+        $_GET[$this->_model->getSessionIdQueryParam()] = 'test_id';
+        $this->_model->setSessionId();
+        $this->assertEquals('test-id', $this->_model->getSessionId());
+    }
+
+    public function testGetEncryptedSessionId()
+    {
+        $sessionId = $this->_model->getEncryptedSessionId();
+        $this->_model->setSessionId('new-id');
+        $this->assertEquals($sessionId, $this->_model->getEncryptedSessionId());
+    }
+
+    public function testGetSessionIdQueryParam()
+    {
+        $this->assertEquals(
+            Mage_Core_Model_Session_Abstract::SESSION_ID_QUERY_PARAM,
+            $this->_model->getSessionIdQueryParam()
+        );
+    }
+
+    public function testSetGetSkipSessionIdFlag()
+    {
+        $this->assertFalse($this->_model->getSkipSessionIdFlag());
+        $this->_model->setSkipSessionIdFlag(true);
+        $this->assertTrue($this->_model->getSkipSessionIdFlag());
+    }
+
+
+    public function testGetSessionIdForHost()
+    {
+        $_SERVER['HTTP_HOST'] = 'localhost';
+        $this->_model->init('test');
+        $this->assertEmpty($this->_model->getSessionIdForHost('localhost'));
+        $this->assertNotEmpty($this->_model->getSessionIdForHost('test'));
+    }
+
+    public function testIsValidForHost()
+    {
+        $_SERVER['HTTP_HOST'] = 'localhost';
+        $this->_model->init('test');
+        $this->assertFalse($this->_model->isValidForHost('test.com'));
+        $this->assertTrue($this->_model->isValidForHost('localhost'));
+    }
+
+    public function testGetSessionSaveMethod()
+    {
+        $this->assertEquals('files', $this->_model->getSessionSaveMethod());
+    }
+
+    public function testGetSessionSavePath()
+    {
+        $this->assertEquals(Mage::getBaseDir('session'), $this->_model->getSessionSavePath());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/StoreTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/StoreTest.php
index e2526e0e8b265bcef829050a3d450465c1dd41dd..ea922f85529cee553e904e0cbf86aa4acf872c0e 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/StoreTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/StoreTest.php
@@ -153,9 +153,6 @@ class Mage_Core_Model_StoreTest extends PHPUnit_Framework_TestCase
      */
     public function testGetPriceFilter()
     {
-        if (!Magento_Test_Bootstrap::canTestHeaders()) {
-            $this->markTestSkipped('Currency operations use cookie and require ability to send headers.');
-        }
         $this->assertInstanceOf('Mage_Directory_Model_Currency_Filter', $this->_model->getPriceFilter());
     }
 
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Translate/InlineTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/Translate/InlineTest.php
index 424f3162b5adde4b8a301760d04c53989aa3cf33..99afa437326427e73687b07895000e559cea301d 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Translate/InlineTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Translate/InlineTest.php
@@ -108,6 +108,8 @@ class Mage_Core_Model_Translate_InlineTest extends PHPUnit_Framework_TestCase
     }
 
     /**
+     * @param string $originalText
+     * @param string $expectedText
      * @dataProvider processResponseBodyDataProvider
      */
     public function testProcessResponseBody($originalText, $expectedText)
@@ -115,7 +117,7 @@ class Mage_Core_Model_Translate_InlineTest extends PHPUnit_Framework_TestCase
         $actualText = $originalText;
         $this->_model->processResponseBody($actualText);
         $this->markTestIncomplete('Bug MAGE-2494');
-        $this->assertEquals($expectedText, $actualText);
+        $this->assertXmlStringEqualsXmlString($expectedText, $actualText);
     }
 
     public function processResponseBodyDataProvider()
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Translate/_files/_inline_page_expected.html b/dev/tests/integration/testsuite/Mage/Core/Model/Translate/_files/_inline_page_expected.html
index 486efb9e573d51be85efa68b3d0f36183319b058..0e1a82a8992a59630ecc6da9a413a58f046fcf4e 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Translate/_files/_inline_page_expected.html
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Translate/_files/_inline_page_expected.html
@@ -1,3 +1,30 @@
+<!--
+/**
+ * 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     Mage_Core
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
         "http://www.w3.org/TR/html4/loose.dtd">
 <html>
@@ -10,7 +37,7 @@
     </div>
 <script type="text/javascript" src="http://localhost/pub/js/prototype/window.js"></script>
 <link rel="stylesheet" type="text/css" href="http://localhost/pub/js/prototype/windows/themes/default.css"/>
-<link rel="stylesheet" type="text/css" href="http://localhost/pub/js/prototype/windows/themes/magento.css"/>
+<link rel="stylesheet" type="text/css" href="http://localhost/pub/media/skin/frontend/default/default/en_US/Mage_Core/prototype/magento.css"/>
 
 <script type="text/javascript" src="http://localhost/pub/js/mage/translate_inline.js"></script>
 <link rel="stylesheet" type="text/css" href="http://localhost/pub/js/mage/translate_inline.css"/>
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/Translate/_files/_inline_page_original.html b/dev/tests/integration/testsuite/Mage/Core/Model/Translate/_files/_inline_page_original.html
index 11d54d57191901fa38392b2aed017c5bebba8091..03d715507be21f625d4052cb502a276e7ba54b55 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/Translate/_files/_inline_page_original.html
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/Translate/_files/_inline_page_original.html
@@ -1,3 +1,30 @@
+<!--
+/**
+ * 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     Mage_Core
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
         "http://www.w3.org/TR/html4/loose.dtd">
 <html>
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/UrlTest.php b/dev/tests/integration/testsuite/Mage/Core/Model/UrlTest.php
index e9f846ea440a5cb27e4bc3a18fbf9f2ed217229e..4d0875b1483de5ada4da6f0fb3982b29b453dfe9 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/UrlTest.php
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/UrlTest.php
@@ -146,7 +146,7 @@ class Mage_Core_Model_UrlTest extends PHPUnit_Framework_TestCase
     /**
      * Note: isolation flushes the URL memory cache
      * @magentoAppIsolation enabled
-     * @magentoConfigFixture current_store web/secure/base_url      http://sample.com/base_path/
+     * @magentoConfigFixture current_store web/secure/base_url        http://sample.com/base_path/
      * @magentoConfigFixture current_store web/secure/base_link_url   https://sample.com/base_link_path/
      * @magentoConfigFixture current_store web/secure/use_in_frontend 1
      */
@@ -259,6 +259,10 @@ class Mage_Core_Model_UrlTest extends PHPUnit_Framework_TestCase
         $this->assertEquals(array('id' => 100, 'parent_id' => 50), $this->_model->getRouteParams());
     }
 
+    /**
+     * Note: isolation flushes the URL memory cache
+     * @magentoAppIsolation enabled
+     */
     public function testGetRouteUrl()
     {
         $this->assertEquals('http://localhost/index.php/', $this->_model->getRouteUrl());
@@ -303,6 +307,10 @@ class Mage_Core_Model_UrlTest extends PHPUnit_Framework_TestCase
         $this->assertEquals('value', $this->_model->getFragment());
     }
 
+    /**
+     * Note: isolation flushes the URL memory cache
+     * @magentoAppIsolation enabled
+     */
     public function testGetUrl()
     {
         $result = $this->_model->getUrl('catalog/product/view', array(
@@ -320,6 +328,10 @@ class Mage_Core_Model_UrlTest extends PHPUnit_Framework_TestCase
         $this->assertEquals('%22%27%3E%3C', $this->_model->escape('"\'><'));
     }
 
+    /**
+     * Note: isolation flushes the URL memory cache
+     * @magentoAppIsolation enabled
+     */
     public function testGetDirectUrl()
     {
         $this->assertEquals('http://localhost/index.php/fancy_uri?foo=bar',
@@ -327,9 +339,17 @@ class Mage_Core_Model_UrlTest extends PHPUnit_Framework_TestCase
         );
     }
 
+    /**
+     * Note: isolation flushes the URL memory cache
+     * @magentoAppIsolation enabled
+     *
+     * Note: to enforce SID in URLs, base URL must be different from the current $_SERVER['HTTP_HOST']
+     * @magentoConfigFixture current_store web/unsecure/base_link_url http://domain.com/
+     */
     public function testSessionUrlVar()
     {
-        $this->assertEquals('<a href="http://example.com/?SID=' . session_id() . '">www.example.com</a>',
+        $sessionId = Mage::getSingleton('Mage_Core_Model_Session')->getEncryptedSessionId();
+        $this->assertEquals('<a href="http://example.com/?SID=' . $sessionId . '">www.example.com</a>',
             $this->_model->sessionUrlVar('<a href="http://example.com/?___SID=U">www.example.com</a>')
         );
     }
@@ -341,6 +361,10 @@ class Mage_Core_Model_UrlTest extends PHPUnit_Framework_TestCase
         $this->assertFalse($this->_model->useSessionIdForUrl(false));
     }
 
+    /**
+     * Note: isolation flushes the URL memory cache
+     * @magentoAppIsolation enabled
+     */
     public function testSessionVarCallback()
     {
         $this->_model->setData('use_session_id_for_url_0', false);
@@ -355,6 +379,10 @@ class Mage_Core_Model_UrlTest extends PHPUnit_Framework_TestCase
         $this->assertEquals('', $this->_model->sessionVarCallback(array('', '&amp;', '', '')));
     }
 
+    /**
+     * Note: isolation flushes the URL memory cache
+     * @magentoAppIsolation enabled
+     */
     public function testIsOwnOriginUrl()
     {
         $_SERVER['HTTP_REFERER'] = 'http://localhost/';
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/frontend/package/custom_theme/skin/theme_nested_skin/jquery/jquery-no-conflict.js b/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/frontend/package/custom_theme/skin/theme_nested_skin/mage/jquery-no-conflict.js
similarity index 100%
rename from dev/tests/integration/testsuite/Mage/Core/Model/_files/design/frontend/package/custom_theme/skin/theme_nested_skin/jquery/jquery-no-conflict.js
rename to dev/tests/integration/testsuite/Mage/Core/Model/_files/design/frontend/package/custom_theme/skin/theme_nested_skin/mage/jquery-no-conflict.js
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/frontend/test/cache_test_theme/local.xml b/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/frontend/test/cache_test_theme/local.xml
new file mode 100644
index 0000000000000000000000000000000000000000..89a9d9c3311eaada085a4ad6e0321a2b93bd914c
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/frontend/test/cache_test_theme/local.xml
@@ -0,0 +1,37 @@
+<?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     design
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<layout>
+
+    <layout_test_handle>
+        <block type="Mage_Core_Block_Text" name="sample_text_block">
+            <action method="setText"><text>Text declared in the frontend/test/cache_test_theme</text></action>
+        </block>
+    </layout_test_handle>
+
+</layout>
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/frontend/test/default/Mage_Catalog/layout.xml b/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/frontend/test/default/Mage_Catalog/layout.xml
index 9f64c8bba6331af08bc644a5f2b38bac6068aa35..3f9b80d2a4ee168b88577e045edce421f09b5373 100644
--- a/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/frontend/test/default/Mage_Catalog/layout.xml
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/frontend/test/default/Mage_Catalog/layout.xml
@@ -26,4 +26,9 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 -->
-<layout />
+<layout>
+    <catalog_product_view type="page" parent="default"></catalog_product_view>
+    <catalog_product_view_type_simple type="page" parent="catalog_product_view"></catalog_product_view_type_simple>
+    <catalog_category_view type="page" parent="default"></catalog_category_view>
+    <catalog_category_view_type_default type="page" parent="catalog_category_view"></catalog_category_view_type_default>
+</layout>
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/frontend/test/default/Mage_Core/test.phtml b/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/frontend/test/default/Mage_Core/test.phtml
new file mode 100644
index 0000000000000000000000000000000000000000..e4f3fa7cb3f2141d3534d41c4bb5dc677ba4feef
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/frontend/test/default/Mage_Core/test.phtml
@@ -0,0 +1,27 @@
+<?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    Magento
+ * @package     Magento_Core
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+echo 'Value: ' . $this->getTestValue();
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/frontend/test/test_theme/local.xml b/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/frontend/test/test_theme/local.xml
new file mode 100644
index 0000000000000000000000000000000000000000..a1fcc99f88ee54c1438c5cd0e1be34a2d90d2abc
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/_files/design/frontend/test/test_theme/local.xml
@@ -0,0 +1,37 @@
+<?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     design
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<layout>
+
+    <layout_test_handle>
+        <block type="Mage_Core_Block_Text" name="sample_text_block">
+            <action method="setText"><text>Text declared in the frontend/test/test_theme</text></action>
+        </block>
+    </layout_test_handle>
+
+</layout>
diff --git a/dev/tests/integration/testsuite/Mage/Core/Model/_files/valid_layout_updates.xml b/dev/tests/integration/testsuite/Mage/Core/Model/_files/valid_layout_updates.xml
new file mode 100644
index 0000000000000000000000000000000000000000..c87532aad9aa329a0c70cecd9e585309c794af0e
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Core/Model/_files/valid_layout_updates.xml
@@ -0,0 +1,40 @@
+<?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     Magento_Core
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<layout>
+    <a_handle>
+        <container name="container1">
+            <block type="Mage_Core_Block_Template" name="block1" template="Mage_Core::test.phtml">
+                <action method="setTestValue"><value>1</value></action>
+            </block>
+            <block type="Mage_Core_Block_Template" name="block2" template="Mage_Core::test.phtml">
+                <action method="setTestValue"><value>2</value></action>
+            </block>
+        </container>
+    </a_handle>
+</layout>
diff --git a/dev/tests/integration/testsuite/Mage/Core/Utility/Layout.php b/dev/tests/integration/testsuite/Mage/Core/Utility/Layout.php
new file mode 100644
index 0000000000000000000000000000000000000000..4e4cca41acde87967a67d71681113a982b6e7f22
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Core/Utility/Layout.php
@@ -0,0 +1,78 @@
+<?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
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Core layout utility
+ */
+class Mage_Core_Utility_Layout
+{
+    /**
+     * @var PHPUnit_Framework_TestCase
+     */
+    protected $_testCase;
+
+    public function __construct(PHPUnit_Framework_TestCase $testCase)
+    {
+        $this->_testCase = $testCase;
+    }
+
+    /**
+     * Retrieve new layout update model instance with XML data from a fixture file
+     *
+     * @param string $layoutUpdatesFile
+     * @return Mage_Core_Model_Layout_Update|PHPUnit_Framework_MockObject_MockObject
+     */
+    public function getLayoutUpdateFromFixture($layoutUpdatesFile)
+    {
+        $layoutUpdate = $this->_testCase->getMock(
+            'Mage_Core_Model_Layout_Update', array('getFileLayoutUpdatesXml')
+        );
+        $layoutUpdatesXml = simplexml_load_file($layoutUpdatesFile, $layoutUpdate->getElementClass());
+        $layoutUpdate->expects(PHPUnit_Framework_TestCase::any())
+            ->method('getFileLayoutUpdatesXml')
+            ->will(PHPUnit_Framework_TestCase::returnValue($layoutUpdatesXml));
+        return $layoutUpdate;
+    }
+
+    /**
+     * Retrieve new layout model instance with layout updates from a fixture file
+     *
+     * @param string $layoutUpdatesFile
+     * @param array $args
+     * @return Mage_Core_Model_Layout|PHPUnit_Framework_MockObject_MockObject
+     */
+    public function getLayoutFromFixture($layoutUpdatesFile, array $args = array())
+    {
+        $layout = $this->_testCase->getMock('Mage_Core_Model_Layout', array('getUpdate'), $args);
+        $layoutUpdate = $this->getLayoutUpdateFromFixture($layoutUpdatesFile);
+        $layoutUpdate->asSimplexml();
+        $layout->expects(PHPUnit_Framework_TestCase::any())
+            ->method('getUpdate')
+            ->will(PHPUnit_Framework_TestCase::returnValue($layoutUpdate));
+        return $layout;
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Core/Utility/LayoutTest.php b/dev/tests/integration/testsuite/Mage/Core/Utility/LayoutTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..22eeee07c90b5d68d6d50f9e282718e674ca2614
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Core/Utility/LayoutTest.php
@@ -0,0 +1,77 @@
+<?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
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Core
+ */
+class Mage_Core_Utility_LayoutTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Utility_Layout
+     */
+    protected $_utility;
+
+    public static function setUpBeforeClass()
+    {
+        Mage::app()->getCacheInstance()->banUse('layout');
+    }
+
+    protected function setUp()
+    {
+        $this->_utility = new Mage_Core_Utility_Layout($this);
+    }
+
+    /**
+     * Assert that the actual layout update instance represents the expected layout update file
+     *
+     * @param Mage_Core_Model_Layout_Update $actualUpdate
+     * @param string $expectedUpdateFile
+     */
+    protected function _assertLayoutUpdate($actualUpdate, $expectedUpdateFile)
+    {
+        $this->assertInstanceOf('Mage_Core_Model_Layout_Update', $actualUpdate);
+
+        $layoutUpdateXml = $actualUpdate->getFileLayoutUpdatesXml();
+        $this->assertInstanceOf('Mage_Core_Model_Layout_Element', $layoutUpdateXml);
+        $this->assertXmlStringEqualsXmlFile($expectedUpdateFile, $layoutUpdateXml->asNiceXml());
+    }
+
+    public function testGetLayoutUpdateFromFixture()
+    {
+        $layoutUpdateFile = __DIR__ . '/_files/_layout_update.xml';
+        $layoutUpdate = $this->_utility->getLayoutUpdateFromFixture($layoutUpdateFile);
+        $this->_assertLayoutUpdate($layoutUpdate, $layoutUpdateFile);
+    }
+
+    public function testGetLayoutFromFixture()
+    {
+        $layoutUpdateFile = __DIR__ . '/_files/_layout_update.xml';
+        $layout = $this->_utility->getLayoutFromFixture($layoutUpdateFile);
+        $this->assertInstanceOf('Mage_Core_Model_Layout', $layout);
+        $this->_assertLayoutUpdate($layout->getUpdate(), $layoutUpdateFile);
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Core/Utility/_files/_layout_update.xml b/dev/tests/integration/testsuite/Mage/Core/Utility/_files/_layout_update.xml
new file mode 100644
index 0000000000000000000000000000000000000000..ae21e35820de40a3197507940d5e5df6e5052cc7
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Core/Utility/_files/_layout_update.xml
@@ -0,0 +1,46 @@
+<?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     Mage_Core
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<layouts>
+    <handle_one>
+        <block type="Mage_Core_Block_Text" name="some_text_block">
+            <action method="setText"><text>Some Default Text</text></action>
+        </block>
+    </handle_one>
+    <handle_two translate="label">
+        <label>Handle Two</label>
+        <update handle="handle_one"/>
+        <reference name="some_text_block">
+            <action method="setText"><text>Some Custom Text</text></action>
+        </reference>
+    </handle_two>
+    <handle_three translate="label">
+        <label>Handle Three</label>
+        <update handle="handle_one"/>
+    </handle_three>
+</layouts>
diff --git a/dev/tests/integration/testsuite/Mage/Customer/Block/Account/LinkTest.php b/dev/tests/integration/testsuite/Mage/Customer/Block/Account/LinkTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..a9f44495443699448904eaa0434c27c0e72e0c53
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Customer/Block/Account/LinkTest.php
@@ -0,0 +1,90 @@
+<?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_Customer
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Customer
+ */
+class Mage_Customer_Block_Account_LinkTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Customer_Block_Account_Link
+     */
+    protected $_block;
+
+    /**
+     * @var Mage_Page_Block_Template_Links
+     */
+    protected $_links;
+
+    public function setUp()
+    {
+        $this->_block = new Mage_Customer_Block_Account_Link();
+        $layout = Mage::app()->getLayout();
+        $this->_block->setLayout($layout);
+        $layout->addBlock('Mage_Page_Block_Template_Links', 'links');
+        $this->_links = $layout->getBlock('links');
+    }
+
+    public function testAddAccountLink()
+    {
+        $this->assertEmpty($this->_links->getLinks());
+        $this->_block->addAccountLink('links', 1);
+
+        $links = $this->_links->getLinks();
+        $this->assertNotEmpty($links);
+        $this->assertEquals('My Account', $links[1]->getLabel());
+    }
+
+    public function testAddRegisterLink()
+    {
+        $this->assertEmpty($this->_links->getLinks());
+        $this->_block->addRegisterLink('links', 1);
+        $links = $this->_links->getLinks();
+        $this->assertEquals('register', $links[1]->getLabel());
+    }
+
+    public function testAddAuthLinkLogIn()
+    {
+        $this->assertEmpty($this->_links->getLinks());
+        $this->_block->addAuthLink('links', 1);
+
+        $links = $this->_links->getLinks();
+        $this->assertEquals('Log In', $links[1]->getLabel());
+
+    }
+
+    /**
+     * @magentoDataFixture Mage/Customer/_files/customer.php
+     */
+    public function testAddAuthLinkLogOut()
+    {
+        Mage::getSingleton('Mage_Customer_Model_Session')->login('customer@example.com', 'password');
+        $this->_block->addAuthLink('links', 1);
+        $links = $this->_links->getLinks();
+        $this->assertEquals('Log Out', $links[1]->getLabel());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Customer/_files/customer.php b/dev/tests/integration/testsuite/Mage/Customer/_files/customer.php
new file mode 100644
index 0000000000000000000000000000000000000000..dc4e5b46c5f1f3f22ce4205f16fcf0733f8a29f1
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Customer/_files/customer.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    Magento
+ * @package     Mage_Customer
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+$customer = new Mage_Customer_Model_Customer();
+$customer
+    ->setWebsiteId(1)
+    ->setEntityId(1)
+    ->setEntityTypeId(1)
+    ->setAttributeSetId(0)
+    ->setEmail('customer@example.com')
+    ->setPassword('password')
+    ->setGroupId(1)
+    ->setStoreId(1)
+    ->setIsActive(1)
+    ->setFirstname('Firstname')
+    ->setLastname('Lastname')
+    ->setDefaultBilling(1)
+    ->setDefaultShipping(1)
+;
+$customer->isObjectNew(true);
+$customer->save();
diff --git a/dev/tests/integration/testsuite/Mage/Customer/controllers/AccountControllerTest.php b/dev/tests/integration/testsuite/Mage/Customer/controllers/AccountControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..00f48b62fabe24aabe412d1d475a409e59fe3aa7
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Customer/controllers/AccountControllerTest.php
@@ -0,0 +1,40 @@
+<?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_Customer
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Customer_AccountControllerTest extends Magento_Test_TestCase_ControllerAbstract
+{
+    /**
+     * @magentoDataFixture Mage/Customer/_files/customer.php
+     */
+    public function testIndexAction()
+    {
+        $session = new Mage_Customer_Model_Session;
+        $session->login('customer@example.com', 'password');
+        $this->dispatch('customer/account/index');
+        $this->assertContains('<div class="my-account">', $this->getResponse()->getBody());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/BreadcrumbsTest.php b/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/BreadcrumbsTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..76a2518d9f68097143ae98248fe0ae385baa4579
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/BreadcrumbsTest.php
@@ -0,0 +1,110 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_DesignEditor
+ */
+class Mage_DesignEditor_Block_Toolbar_BreadcrumbsTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_DesignEditor_Block_Toolbar_Breadcrumbs
+     */
+    protected $_block;
+
+    protected function setUp()
+    {
+        $layoutUtility = new Mage_Core_Utility_Layout($this);
+        $pageTypesFixture = __DIR__ . '/../../../Core/Model/Layout/_files/_page_types.xml';
+        $this->_block = new Mage_DesignEditor_Block_Toolbar_Breadcrumbs(
+            array('template' => 'toolbar/breadcrumbs.phtml')
+        );
+        $this->_block->setLayout($layoutUtility->getLayoutFromFixture($pageTypesFixture));
+    }
+
+    /**
+     * Set the current route/controller/action
+     *
+     * @param string $routName
+     * @param string $controllerName
+     * @param string $actionName
+     */
+    protected function _setControllerAction($routName, $controllerName, $actionName)
+    {
+        /** @var $controllerAction Mage_Core_Controller_Varien_Action */
+        $controllerAction = $this->getMockForAbstractClass(
+            'Mage_Core_Controller_Varien_Action',
+            array(new Magento_Test_Request(), new Magento_Test_Response())
+        );
+        /* Note: controller action instance registers itself within the front controller immediately after creation */
+        $controllerAction->getRequest()
+            ->setRouteName($routName)
+            ->setControllerName($controllerName)
+            ->setActionName($actionName);
+    }
+
+    public function testGetBreadcrumbsFromPageHandles()
+    {
+        $this->_block->getLayout()->getUpdate()->addPageHandles(array('catalog_product_view_type_simple'));
+        $this->assertEquals(
+            require(__DIR__ . '/_files/_breadcrumbs_simple_product.php'),
+            $this->_block->getBreadcrumbs()
+        );
+    }
+
+    /**
+     * @magentoAppIsolation enabled
+     */
+    public function testGetBreadcrumbsFromDefaultLayoutHandle()
+    {
+        $this->_setControllerAction('catalog', 'product_view', 'type_simple');
+        $this->assertEquals(
+            require(__DIR__ . '/_files/_breadcrumbs_simple_product.php'),
+            $this->_block->getBreadcrumbs()
+        );
+    }
+
+    public function testToHtmlFromPageHandles()
+    {
+        $this->_block->getLayout()->getUpdate()->addPageHandles(array('catalog_product_view_type_simple'));
+        $this->assertXmlStringEqualsXmlFile(
+            __DIR__ . '/_files/_breadcrumbs_simple_product.html',
+            $this->_block->toHtml()
+        );
+    }
+
+    /**
+     * @magentoAppIsolation enabled
+     */
+    public function testToHtmlFromDefaultLayoutHandle()
+    {
+        $this->_setControllerAction('catalog', 'product_view', 'type_simple');
+        $this->assertXmlStringEqualsXmlFile(
+            __DIR__ . '/_files/_breadcrumbs_simple_product.html',
+            $this->_block->toHtml()
+        );
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/ExitTest.php b/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/ExitTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..b8676e8686bf4a80b3aee0c767027c9663c5ed07
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/ExitTest.php
@@ -0,0 +1,48 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_DesignEditor
+ */
+class Mage_DesignEditor_Block_Toolbar_ExitTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_DesignEditor_Block_Toolbar_Exit
+     */
+    protected $_block;
+
+    protected function setUp()
+    {
+        $this->_block = new Mage_DesignEditor_Block_Toolbar_Exit(array('template' => 'toolbar/exit.phtml'));
+    }
+
+    public function testGetExitUrl()
+    {
+        $expected = 'http://localhost/index.php/admin/system_design_editor/exit/';
+        $this->assertContains($expected, $this->_block->getExitUrl());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/PageTypeTest.php b/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/PageTypeTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..308cabb7067e340b4421a04c4fa4db35d6bfcab8
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/PageTypeTest.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.
+ *
+ * @category    Magento
+ * @package     Mage_DesignEditor
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_DesignEditor
+ */
+class Mage_DesignEditor_Block_Toolbar_PageTypeTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_DesignEditor_Block_Toolbar_PageType
+     */
+    protected $_block;
+
+    protected function setUp()
+    {
+        $layoutUtility = new Mage_Core_Utility_Layout($this);
+        $pageTypesFixture = __DIR__ . '/../../../Core/Model/Layout/_files/_page_types.xml';
+        $layout = $layoutUtility->getLayoutFromFixture($pageTypesFixture);
+        $layout->getUpdate()->addPageHandles(array('catalog_product_view_type_simple'));
+        $this->_block = new Mage_DesignEditor_Block_Toolbar_PageType();
+        $this->_block->setLayout($layout);
+    }
+
+    public function testRenderPageTypes()
+    {
+        $expected = __DIR__ . '/_files/_page_types_hierarchy.html';
+        $actual = $this->_block->renderPageTypes();
+        $this->assertXmlStringEqualsXmlFile($expected, $actual);
+    }
+
+    public function testGetSelectedPageType()
+    {
+        $this->assertEquals('catalog_product_view_type_simple', $this->_block->getSelectedPageType());
+        $this->_block->setSelectedPageType('catalog_product_view_type_configurable');
+        $this->assertEquals('catalog_product_view_type_configurable', $this->_block->getSelectedPageType());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/SkinTest.php b/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/SkinTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..de4c40961e2f6414c8abf244327182201422c0c1
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/SkinTest.php
@@ -0,0 +1,123 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Test for skin block functioning
+ *
+ * @group module:Mage_DesignEditor
+ */
+class Mage_DesignEditor_Block_Toolbar_SkinTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_DesignEditor_Block_Toolbar_Skin
+     */
+    protected $_block;
+
+    protected function setUp()
+    {
+        $this->_block = new Mage_DesignEditor_Block_Toolbar_Skin();
+    }
+
+    public function testGetOptions()
+    {
+        Mage::getConfig()->getOptions()->setDesignDir(__DIR__ . '/../../../Core/Model/Design/Source/_files/design');
+        $options = $this->_block->getOptions();
+
+        $this->assertInternalType('array', $options);
+        $this->assertNotEmpty($options);
+
+        foreach ($options as $optGroup) {
+            $this->assertInternalType('array', $optGroup);
+            $this->assertArrayHasKey('label', $optGroup);
+            $this->assertArrayHasKey('value', $optGroup);
+            $this->assertInternalType('array', $optGroup['value']);
+            foreach ($optGroup['value'] as $option) {
+                $this->assertInternalType('array', $option);
+                $this->assertArrayHasKey('label', $option);
+                $this->assertArrayHasKey('value', $option);
+                $this->assertInternalType('string', $option['label']);
+                $this->assertInternalType('string', $option['value']);
+            }
+        }
+    }
+
+    public function  testIsSkinSelected()
+    {
+        $oldTheme = Mage::getDesign()->getDesignTheme();
+        Mage::getDesign()->setDesignTheme('a/b/c');
+        $isSelected = $this->_block->isSkinSelected('a/b/c');
+        Mage::getDesign()->setDesignTheme($oldTheme);
+        $this->assertTrue($isSelected);
+
+        Mage::getDesign()->setDesignTheme('a/b/c');
+        $isSelected = $this->_block->isSkinSelected('c/b/a');
+        Mage::getDesign()->setDesignTheme($oldTheme);
+        $this->assertFalse($isSelected);
+    }
+
+    public function testGetJsonConfigType()
+    {
+        $jsonConfig = $this->_block->getJsonConfig();
+        $origData = json_decode($jsonConfig);
+        $this->assertInstanceOf('StdClass', $origData);
+    }
+
+    /**
+     * @param string $key
+     * @param string $valueType
+     *
+     * @dataProvider getJsonConfigKeysAndValuesDataProvider
+     */
+    public function testGetJsonConfigKeysAndValues($key, $valueType)
+    {
+        $jsonConfig = $this->_block->getJsonConfig();
+        $origData = (array) json_decode($jsonConfig);
+        $this->assertArrayHasKey($key, $origData);
+        if ($origData[$key] instanceof StdClass) {
+            $origData[$key] = (array) $origData[$key];
+        }
+        $this->assertInternalType($valueType, $origData[$key]);
+    }
+
+    /**
+     * @return array
+     */
+    public function getJsonConfigKeysAndValuesDataProvider()
+    {
+        return array(
+            array('selectId', 'string'),
+            array('changeSkinUrl', 'string'),
+            array('backParams', 'array')
+        );
+    }
+
+    public function testGetSelectHtmlId()
+    {
+        $value = $this->_block->getSelectHtmlId();
+        $this->assertNotEmpty($value);
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/_files/_breadcrumbs_simple_product.html b/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/_files/_breadcrumbs_simple_product.html
new file mode 100644
index 0000000000000000000000000000000000000000..3f556dd7f1bf638ee8db81fdf6bf131d40637996
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/_files/_breadcrumbs_simple_product.html
@@ -0,0 +1,37 @@
+<!--
+/**
+ * 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     Mage_DesignEditor
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<div>
+    <span>Current Location:</span>
+    <a href="http://localhost/index.php/design/editor/page/page_type/default/">All Pages</a>
+    <span>/</span>
+    <a href="http://localhost/index.php/design/editor/page/page_type/catalog_category_default/">Catalog Category (Non-Anchor)</a>
+    <span>/</span>
+    <a href="http://localhost/index.php/design/editor/page/page_type/catalog_product_view/">Catalog Product View (Any)</a>
+    <span>/</span>
+    <span>Catalog Product View (Simple)</span>
+</div>
diff --git a/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/_files/_breadcrumbs_simple_product.php b/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/_files/_breadcrumbs_simple_product.php
new file mode 100644
index 0000000000000000000000000000000000000000..aba451e5a212a5010ca1dc07b70732685d33191d
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/_files/_breadcrumbs_simple_product.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    Magento
+ * @package     Mage_DesignEditor
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+?>
+<?php
+return array(
+    array(
+        'label' => 'All Pages',
+        'url'   => 'http://localhost/index.php/design/editor/page/page_type/default/',
+    ),
+    array(
+        'label' => 'Catalog Category (Non-Anchor)',
+        'url'   => 'http://localhost/index.php/design/editor/page/page_type/catalog_category_default/',
+    ),
+    array(
+        'label' => 'Catalog Product View (Any)',
+        'url'   => 'http://localhost/index.php/design/editor/page/page_type/catalog_product_view/',
+    ),
+    array(
+        'label' => 'Catalog Product View (Simple)',
+        'url'   => '',
+    ),
+);
diff --git a/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/_files/_page_types_hierarchy.html b/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/_files/_page_types_hierarchy.html
new file mode 100644
index 0000000000000000000000000000000000000000..580eeef2d991f243f81a7efea809a40f7d758754
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/DesignEditor/Block/Toolbar/_files/_page_types_hierarchy.html
@@ -0,0 +1,67 @@
+<!--
+/**
+ * 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     Mage_DesignEditor
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<ul>
+    <li rel="print">
+        <a href="http://localhost/index.php/design/editor/page/page_type/print/">All Pages (Print Version)</a>
+        <ul>
+            <li rel="sales_order_print">
+                <a href="http://localhost/index.php/design/editor/page/page_type/sales_order_print/">Sales Order Print View</a>
+            </li>
+            <li rel="sales_guest_print">
+                <a href="http://localhost/index.php/design/editor/page/page_type/sales_guest_print/">Sales Order Print View (Guest)</a>
+            </li>
+        </ul>
+    </li>
+    <li rel="default">
+        <a href="http://localhost/index.php/design/editor/page/page_type/default/">All Pages</a>
+        <ul>
+            <li rel="catalog_category_default">
+                <a href="http://localhost/index.php/design/editor/page/page_type/catalog_category_default/">Catalog Category (Non-Anchor)</a>
+                <ul>
+                    <li rel="catalog_category_layered">
+                        <a href="http://localhost/index.php/design/editor/page/page_type/catalog_category_layered/">Catalog Category (Anchor)</a>
+                    </li>
+                    <li rel="catalog_product_view">
+                        <a href="http://localhost/index.php/design/editor/page/page_type/catalog_product_view/">Catalog Product View (Any)</a>
+                        <ul>
+                            <li rel="catalog_product_view_type_simple">
+                                <a href="http://localhost/index.php/design/editor/page/page_type/catalog_product_view_type_simple/">Catalog Product View (Simple)</a>
+                            </li>
+                            <li rel="catalog_product_view_type_configurable">
+                                <a href="http://localhost/index.php/design/editor/page/page_type/catalog_product_view_type_configurable/">Catalog Product View (Configurable)</a>
+                            </li>
+                            <li rel="catalog_product_view_type_grouped">
+                                <a href="http://localhost/index.php/design/editor/page/page_type/catalog_product_view_type_grouped/">Catalog Product View (Grouped)</a>
+                            </li>
+                        </ul>
+                    </li>
+                </ul>
+            </li>
+        </ul>
+    </li>
+</ul>
diff --git a/dev/tests/integration/testsuite/Mage/DesignEditor/Block/ToolbarCrosscuttingTest.php b/dev/tests/integration/testsuite/Mage/DesignEditor/Block/ToolbarCrosscuttingTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..b11981cef6441415390d37ca501d0cce9e95e8cd
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/DesignEditor/Block/ToolbarCrosscuttingTest.php
@@ -0,0 +1,82 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Test for presence of the design editor toolbar on frontend pages
+ *
+ * @group module:Mage_DesignEditor
+ * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+ * @magentoDataFixture Mage/Catalog/controllers/_files/products.php
+ */
+class Mage_DesignEditor_Block_ToolbarCrosscuttingTest extends Magento_Test_TestCase_ControllerAbstract
+{
+    /**
+     * Assert that a page content contains the design editor toolbar
+     *
+     * @param string $content
+     */
+    protected function _assertContainsToolbar($content)
+    {
+        $this->assertContains('id="vde_toolbar"', $content);
+    }
+
+    /**
+     * @group module:Mage_Cms
+     */
+    public function testCmsHomePage()
+    {
+        $this->dispatch('cms/index/index');
+        $this->_assertContainsToolbar($this->getResponse()->getBody());
+    }
+
+    /**
+     * @group module:Mage_Customer
+     */
+    public function testCustomerAccountLogin()
+    {
+        $this->dispatch('customer/account/login');
+        $this->_assertContainsToolbar($this->getResponse()->getBody());
+    }
+
+    /**
+     * @group module:Mage_Catalog
+     */
+    public function testCatalogProductView()
+    {
+        $this->dispatch('catalog/product/view/id/1');
+        $this->_assertContainsToolbar($this->getResponse()->getBody());
+    }
+
+    /**
+     * @group module:Mage_Checkout
+     */
+    public function testCheckoutCart()
+    {
+        $this->dispatch('checkout/cart/index');
+        $this->_assertContainsToolbar($this->getResponse()->getBody());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/DesignEditor/Block/ToolbarTest.php b/dev/tests/integration/testsuite/Mage/DesignEditor/Block/ToolbarTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..af2d127006724c530f8a51607fd5edb41fd07680
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/DesignEditor/Block/ToolbarTest.php
@@ -0,0 +1,89 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_DesignEditor
+ */
+class Mage_DesignEditor_Block_ToolbarTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_DesignEditor_Block_Toolbar
+     */
+    protected $_block;
+
+    protected function setUp()
+    {
+        $layout = Mage::app()->getLayout();
+        $this->_block = $layout->createBlock(
+            'Mage_DesignEditor_Block_Toolbar',
+            'block',
+            array('template' => 'toolbar.phtml')
+        );
+        $layout->insertBlock('', 'block', 'block');
+    }
+
+    /**
+     * Isolation has been raised because block pollutes the registry
+     *
+     * @magentoAppIsolation enabled
+     */
+    public function testToHtmlDesignEditorInactive()
+    {
+        $this->assertEmpty($this->_block->toHtml());
+    }
+
+    /**
+     * @magentoAppIsolation enabled
+     * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+     */
+    public function testToHtmlDesignEditorActive()
+    {
+        $this->assertNotEmpty($this->_block->toHtml());
+        $this->assertContains(' id="vde_toolbar"', $this->_block->toHtml());
+    }
+
+    public function testGetMessages()
+    {
+        /** @var $session Mage_DesignEditor_Model_Session */
+        $session = Mage::getSingleton('Mage_DesignEditor_Model_Session');
+        $this->assertEmpty($session->getMessages()->getItems());
+
+        $session->addError('test error');
+        $session->addSuccess('test success');
+
+        $blockMessages = $this->_block->getMessages();
+        $this->assertInternalType('array', $blockMessages);
+        $this->assertEquals(2, count($blockMessages));
+
+        $this->assertInstanceOf('Mage_Core_Model_Message_Error', $blockMessages[0]);
+        $this->assertEquals('test error', $blockMessages[0]->getCode());
+        $this->assertInstanceOf('Mage_Core_Model_Message_Success', $blockMessages[1]);
+        $this->assertEquals('test success', $blockMessages[1]->getCode());
+
+        $this->assertEmpty($session->getMessages()->getItems());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/DesignEditor/Model/ObserverTest.php b/dev/tests/integration/testsuite/Mage/DesignEditor/Model/ObserverTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..9fda5ab83b7103050b1ca286643010dd3bdf25bf
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/DesignEditor/Model/ObserverTest.php
@@ -0,0 +1,217 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Test for skin changing observer
+ *
+ * @group module:Mage_DesignEditor
+ */
+class Mage_DesignEditor_Model_ObserverTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_DesignEditor_Model_Observer
+     */
+    protected $_observer;
+
+    /**
+     * @var Varien_Event_Observer
+     */
+    protected $_eventObserver;
+
+    protected function setUp()
+    {
+        $this->_observer = new Mage_DesignEditor_Model_Observer;
+
+        $this->_eventObserver = new Varien_Event_Observer();
+        $this->_eventObserver->setEvent(new Varien_Event(array('layout' => Mage::app()->getLayout())));
+    }
+
+    /**
+     * @magentoAppIsolation enabled
+     * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+     * @magentoConfigFixture current_store admin/security/session_lifetime 100
+     */
+    public function testPreDispatchDeactivateDesignEditor()
+    {
+        /** @var $session Mage_DesignEditor_Model_Session */
+        $session = Mage::getSingleton('Mage_DesignEditor_Model_Session');
+        $this->assertNotEmpty($session->getData(Mage_DesignEditor_Model_Session::SESSION_DESIGN_EDITOR_ACTIVE));
+        /* active admin session */
+        $this->_observer->preDispatch($this->_eventObserver);
+        $this->assertNotEmpty($session->getData(Mage_DesignEditor_Model_Session::SESSION_DESIGN_EDITOR_ACTIVE));
+        /* expired admin session */
+        $session->setUpdatedAt(time() - 101);
+        $this->_observer->preDispatch($this->_eventObserver);
+        $this->assertEmpty($session->getData(Mage_DesignEditor_Model_Session::SESSION_DESIGN_EDITOR_ACTIVE));
+    }
+
+    /**
+     * @magentoAppIsolation enabled
+     * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+     */
+    public function testPreDispatchApplyDesign()
+    {
+        $newSkin = 'default/default/blank';
+        $this->assertNotEquals($newSkin, Mage::getDesign()->getDesignTheme());
+        Mage::getSingleton('Mage_DesignEditor_Model_Session')->setSkin($newSkin);
+        $this->_observer->preDispatch($this->_eventObserver);
+        $this->assertEquals($newSkin, Mage::getDesign()->getDesignTheme());
+    }
+
+    /**
+     * @magentoAppIsolation enabled
+     * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+     */
+    public function testPreDispatchApplyDesignIgnoreNoSkin()
+    {
+        $currentSkin = Mage::getDesign()->getDesignTheme();
+        $this->assertEmpty(Mage::getSingleton('Mage_DesignEditor_Model_Session')->getSkin());
+        $this->_observer->preDispatch($this->_eventObserver);
+        $this->assertEquals($currentSkin, Mage::getDesign()->getDesignTheme());
+    }
+
+    /**
+     * @magentoAppIsolation enabled
+     */
+    public function testPreDispatchApplyDesignInactive()
+    {
+        $newSkin = 'default/default/blank';
+        $oldSkin = Mage::getDesign()->getDesignTheme();
+        $this->assertNotEquals($newSkin, $oldSkin);
+        Mage::getSingleton('Mage_DesignEditor_Model_Session')->setSkin($newSkin);
+        $this->_observer->preDispatch($this->_eventObserver);
+        $this->assertEquals($oldSkin, Mage::getDesign()->getDesignTheme());
+    }
+
+    /**
+     * @magentoAppIsolation enabled
+     * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+     */
+    public function testAddToolbar()
+    {
+        $layoutUpdate = Mage::app()->getLayout()->getUpdate();
+        $this->assertNotContains(Mage_DesignEditor_Model_Observer::TOOLBAR_HANDLE, $layoutUpdate->getHandles());
+        $this->_observer->addToolbar($this->_eventObserver);
+        $this->assertContains(Mage_DesignEditor_Model_Observer::TOOLBAR_HANDLE, $layoutUpdate->getHandles());
+    }
+
+    /**
+     * @magentoAppIsolation enabled
+     */
+    public function testDisableBlocksOutputCachingInactive()
+    {
+        Mage::app()->getCacheInstance()->allowUse(Mage_Core_Block_Abstract::CACHE_GROUP);
+        $this->_observer->disableBlocksOutputCaching(new Varien_Event_Observer());
+        $this->assertTrue(Mage::app()->useCache(Mage_Core_Block_Abstract::CACHE_GROUP));
+    }
+
+    /**
+     * @magentoAppIsolation enabled
+     * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+     */
+    public function testDisableBlocksOutputCachingActive()
+    {
+        Mage::app()->getCacheInstance()->allowUse(Mage_Core_Block_Abstract::CACHE_GROUP);
+        $this->_observer->disableBlocksOutputCaching(new Varien_Event_Observer());
+        $this->assertFalse(Mage::app()->useCache(Mage_Core_Block_Abstract::CACHE_GROUP));
+    }
+
+    /**
+     * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+     */
+    public function testSetDesignEditorFlag()
+    {
+        $headBlock = new Mage_Page_Block_Html_Head();
+        $layout = new Mage_Core_Model_Layout();
+        $layout->addBlock($headBlock, 'head');
+        $this->assertEmpty($headBlock->getDesignEditorActive());
+        $observerData = new Varien_Event_Observer(array('event' => new Varien_Object(array('layout' => $layout))));
+        $this->_observer->setDesignEditorFlag($observerData);
+        $this->assertNotEmpty($headBlock->getDesignEditorActive());
+    }
+
+    /**
+     * @param string $elementName
+     * @param string $expectedOutput
+     * @magentoAppIsolation enabled
+     * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+     * @dataProvider wrapPageElementDataProvider
+     */
+    public function testWrapPageElement($elementName, $expectedOutput)
+    {
+        // create a layout object mock with fixture data
+        $structure = new Mage_Core_Model_Layout_Structure;
+        $utility = new Mage_Core_Utility_Layout($this);
+        $layoutMock = $utility->getLayoutFromFixture(
+            __DIR__ . '/../_files/observer_test.xml', array(array('structure' => $structure))
+        );
+
+        // load the fixture data. This will populate layout structure as well
+        $layoutMock->getUpdate()->addHandle('test_handle')->load();
+        $layoutMock->generateXml()->generateBlocks();
+
+        $expectedContent = 'test_content';
+        $transport = new Varien_Object(array('output' => $expectedContent));
+        $observer = new Varien_Event_Observer(array(
+            'event' => new Varien_Event(array(
+                'structure' => $structure,
+                'layout' => $layoutMock,
+                'element_name' => $elementName,
+                'transport' => $transport,
+            ))
+        ));
+
+        $this->_observer->wrapPageElement($observer);
+        $this->assertStringMatchesFormat(sprintf($expectedOutput, $expectedContent), $transport->getData('output'));
+    }
+
+    /**
+     * @return array
+     */
+    public function wrapPageElementDataProvider()
+    {
+        return array(
+            array('test.text',
+                '<div class="vde_element_wrapper">%%w<div class="vde_element_title">test.text</div>%%w%s%%w</div>'
+            ),
+            array('toolbar', '%s'),
+            array('test.text3', '%s'),
+        );
+    }
+
+    /**
+     * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+     */
+    public function testAdminSessionUserLogout()
+    {
+        /** @var $session Mage_DesignEditor_Model_Session */
+        $session = Mage::getSingleton('Mage_DesignEditor_Model_Session');
+        $this->assertTrue($session->isDesignEditorActive());
+        $this->_observer->adminSessionUserLogout();
+        $this->assertFalse($session->isDesignEditorActive());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/DesignEditor/Model/SessionTest.php b/dev/tests/integration/testsuite/Mage/DesignEditor/Model/SessionTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..aaacc5dbe44f60cf3d67a76d42a65530d35e902a
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/DesignEditor/Model/SessionTest.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    Magento
+ * @package     Mage_DesignEditor
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_DesignEditor
+ */
+class Mage_DesignEditor_Model_SessionTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Admin_Model_Session
+     */
+    protected static $_adminSession;
+
+    /**
+     * @var Mage_DesignEditor_Model_Session
+     */
+    protected $_model;
+
+    protected function setUp()
+    {
+        $this->_model = new Mage_DesignEditor_Model_Session();
+    }
+
+    public function testIsDesignEditorActiveFalse()
+    {
+        $this->assertFalse($this->_model->isDesignEditorActive());
+    }
+
+    /**
+     * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+     */
+    public function testIsDesignEditorActiveTrue()
+    {
+        $this->assertTrue($this->_model->isDesignEditorActive());
+    }
+
+    /**
+     * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+     * @magentoConfigFixture current_store admin/security/session_lifetime 100
+     */
+    public function testIsDesignEditorActiveAdminSessionExpired()
+    {
+        $this->assertTrue($this->_model->isDesignEditorActive());
+        $this->_model->setUpdatedAt(time() - 101);
+        $this->assertFalse($this->_model->isDesignEditorActive());
+    }
+
+    /**
+     * @magentoDataFixture loginAdmin
+     */
+    public function testActivateDesignEditor()
+    {
+        $this->assertFalse($this->_model->isDesignEditorActive());
+        $this->_model->activateDesignEditor();
+        $this->assertTrue($this->_model->isDesignEditorActive());
+    }
+
+    public static function loginAdmin()
+    {
+        Mage_Admin_Utility_User::getInstance()
+            ->createAdmin();
+        self::$_adminSession = new Mage_Admin_Model_Session();
+        self::$_adminSession->login(Mage_Admin_Utility_User::CRED_USERNAME, Mage_Admin_Utility_User::CRED_PASSWORD);
+    }
+
+    public static function loginAdminRollback()
+    {
+        self::$_adminSession->logout();
+        Mage_Admin_Utility_User::getInstance()
+            ->destroyAdmin();
+    }
+
+    /**
+     * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+     */
+    public function testDeactivateDesignEditor()
+    {
+        $this->assertTrue($this->_model->isDesignEditorActive());
+        $this->_model->deactivateDesignEditor();
+        $this->assertFalse($this->_model->isDesignEditorActive());
+    }
+
+    public function testSetSkin()
+    {
+        $this->_model->setSkin('default/default/blank');
+        $this->assertEquals('default/default/blank', $this->_model->getSkin());
+    }
+
+    /**
+     * @expectedException Mage_Core_Exception
+     */
+    public function testSetSkinWrongValue()
+    {
+        $this->_model->setSkin('wrong/skin/applied');
+    }
+}
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..61718761112b9d81fce82a72f53ca6ce1927cfe4
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/DesignEditor/_files/design_editor_active.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    Magento
+ * @package     Mage_DesignEditor
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+$utility = Mage_Admin_Utility_User::getInstance();
+$utility->createAdmin();
+
+$session = new Mage_DesignEditor_Model_Session();
+$session->login(Mage_Admin_Utility_User::CRED_USERNAME, Mage_Admin_Utility_User::CRED_PASSWORD);
+$session->activateDesignEditor();
diff --git a/dev/tests/integration/testsuite/Mage/DesignEditor/_files/design_editor_active_rollback.php b/dev/tests/integration/testsuite/Mage/DesignEditor/_files/design_editor_active_rollback.php
new file mode 100644
index 0000000000000000000000000000000000000000..c07a2c033c6bbda97388c5c74d6c6f67c196ab6b
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/DesignEditor/_files/design_editor_active_rollback.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    Magento
+ * @package     Mage_DesignEditor
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+$session = new Mage_DesignEditor_Model_Session();
+$session->deactivateDesignEditor();
+$session->logout();
+
+$utility = Mage_Admin_Utility_User::getInstance();
+$utility->destroyAdmin();
diff --git a/dev/tests/integration/testsuite/Mage/DesignEditor/_files/observer_test.xml b/dev/tests/integration/testsuite/Mage/DesignEditor/_files/observer_test.xml
new file mode 100644
index 0000000000000000000000000000000000000000..8f197c348ace71e47d81b306558416f485ae138e
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/DesignEditor/_files/observer_test.xml
@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+/**
+ * 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_DesignEditor
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<layout>
+    <test_handle>
+        <container name="root">
+            <block type="Mage_Core_Block_Text" name="test.text">
+                <action method="setText"><value>txt</value></action>
+            </block>
+            <block type="Mage_DesignEditor_Block_Toolbar" name="toolbar" template="toolbar.phtml"/>
+            <block type="Mage_Core_Block_Text" name="test.text2">
+                <block type="Mage_Core_Block_Text" name="test.text3"/>
+            </block>
+        </container>
+    </test_handle>
+</layout>
diff --git a/dev/tests/integration/testsuite/Mage/DesignEditor/controllers/Adminhtml/System/Design/EditorControllerTest.php b/dev/tests/integration/testsuite/Mage/DesignEditor/controllers/Adminhtml/System/Design/EditorControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..359b941749031bcb4f17af17180f5168b1325930
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/DesignEditor/controllers/Adminhtml/System/Design/EditorControllerTest.php
@@ -0,0 +1,121 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_DesignEditor
+ */
+class Mage_DesignEditor_Adminhtml_System_Design_EditorControllerTest extends Mage_Adminhtml_Utility_Controller
+{
+    /**
+     * Assert that a page content contains the design editor form
+     *
+     * @param string $content
+     */
+    protected function _assertContainsDesignEditor($content)
+    {
+        $expectedFormAction = 'http://localhost/index.php/admin/system_design_editor/launch/';
+        $this->assertContains('Visual Design Editor', $content);
+        $this->assertContains('<form id="edit_form" action="' . $expectedFormAction, $content);
+        $this->assertContains("editForm = new varienForm('edit_form'", $content);
+        $this->assertContains('onclick="editForm.submit();"', $content);
+    }
+
+    /**
+     * Skip the current test, if session identifier is not defined in the environment
+     */
+    public function _requireSessionId()
+    {
+        if (!$this->_session->getSessionId()) {
+            $this->markTestSkipped('Test requires environment with non-empty session identifier.');
+        }
+    }
+
+    public function testIndexActionSingleStore()
+    {
+        $this->dispatch('admin/system_design_editor/index');
+        $this->_assertContainsDesignEditor($this->getResponse()->getBody());
+    }
+
+    /**
+     * @magentoDataFixture Mage/Core/_files/store.php
+     */
+    public function testIndexActionMultipleStores()
+    {
+        $this->dispatch('admin/system_design_editor/index');
+        $responseBody = $this->getResponse()->getBody();
+        $this->_assertContainsDesignEditor($responseBody);
+        $this->assertContains('<select id="store_id" name="store_id"', $responseBody);
+        $this->assertContains('<label for="store_id">Store View', $responseBody);
+        $this->assertContains('Fixture Store</option>', $responseBody);
+    }
+
+    public function testLaunchActionSingleStore()
+    {
+        $session = new Mage_DesignEditor_Model_Session();
+        $this->assertFalse($session->isDesignEditorActive());
+        $this->dispatch('admin/system_design_editor/launch');
+        $this->assertTrue($session->isDesignEditorActive());
+
+        $this->_requireSessionId();
+        $this->assertRedirect('http://localhost/index.php/?SID=' . $this->_session->getSessionId());
+    }
+
+    /**
+     * @magentoDataFixture Mage/Core/_files/store.php
+     * @magentoConfigFixture fixturestore_store web/unsecure/base_link_url http://example.com/
+     */
+    public function testLaunchActionMultipleStores()
+    {
+        $this->getRequest()->setParam('store_id', Mage::app()->getStore('fixturestore')->getId());
+
+        $session = new Mage_DesignEditor_Model_Session();
+        $this->assertFalse($session->isDesignEditorActive());
+        $this->dispatch('admin/system_design_editor/launch');
+        $this->assertTrue($session->isDesignEditorActive());
+
+        $this->_requireSessionId();
+        $this->assertRedirect(
+            'http://example.com/index.php/?SID=' . $this->_session->getSessionId() . '&___store=fixturestore'
+        );
+    }
+
+    /**
+     * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+     */
+    public function testExitAction()
+    {
+        $session = new Mage_DesignEditor_Model_Session();
+        $this->assertTrue($session->isDesignEditorActive());
+        $this->dispatch('admin/system_design_editor/exit');
+
+        $this->assertFalse($session->isDesignEditorActive());
+        $this->assertContains(
+            '<script type="text/javascript">window.close();</script>',
+            $this->getResponse()->getBody()
+        );
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/DesignEditor/controllers/EditorControllerTest.php b/dev/tests/integration/testsuite/Mage/DesignEditor/controllers/EditorControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..2ed087737a9df6b9027bb083a85956850f56b7a2
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/DesignEditor/controllers/EditorControllerTest.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.
+ *
+ * @category    Magento
+ * @package     Mage_DesignEditor
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_DesignEditor
+ */
+class Mage_DesignEditor_EditorControllerTest extends Magento_Test_TestCase_ControllerAbstract
+{
+    public function testPreDispatchSession()
+    {
+        $this->dispatch('design/editor/page');
+        $this->assert404NotFound();
+    }
+
+    /**
+     * @param string $pageType
+     * @param string $expectedMessage
+     * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+     * @dataProvider pageActionErrorDataProvider
+     */
+    public function testPageActionError($pageType, $expectedMessage)
+    {
+        $this->getRequest()->setParam('page_type', $pageType);
+        $this->dispatch('design/editor/page');
+        $this->assertEquals(503, $this->getResponse()->getHttpResponseCode());
+        $this->assertStringMatchesFormat($expectedMessage, $this->getResponse()->getBody());
+    }
+
+    /**
+     * @return array
+     */
+    public function pageActionErrorDataProvider()
+    {
+        return array(
+            'no page type'      => array('', 'Invalid page type specified.'),
+            'invalid page type' => array('1nvalid_type', 'Invalid page type specified.'),
+            'non-existing type' => array('non_existing_type', 'Specified page type doesn\'t exist: %s'),
+        );
+    }
+
+    /**
+     * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+     * @dataProvider pageActionDataProvider
+     *
+     * @param string $pageType
+     * @param string $requiredModule
+     * @param bool $isVdeToolbarBug
+     */
+    public function testPageAction($pageType, $requiredModule)
+    {
+        if (!in_array($requiredModule, Magento_Test_Helper_Factory::getHelper('config')->getEnabledModules())) {
+            $this->markTestSkipped("Test requires the module '$requiredModule' to be enabled.");
+        }
+        $this->getRequest()->setParam('page_type', $pageType);
+        $this->dispatch('design/editor/page');
+        $this->assertEquals(200, $this->getResponse()->getHttpResponseCode());
+        $controller = Mage::app()->getFrontController()->getAction();
+        $this->assertInstanceOf('Mage_DesignEditor_EditorController', $controller);
+        $this->assertRegExp(
+            '/treeInstance\.select_node\(.*"' . preg_quote($pageType, '/') . '".*\)/U',
+            $this->getResponse()->getBody(),
+            'Page type control should maintain the selection of the current page type.'
+        );
+    }
+
+    public function pageActionDataProvider()
+    {
+        return array(
+            'Catalog Product View'             => array('catalog_product_view',            'Mage_Catalog'),
+            'One Page Checkout Overview'       => array('checkout_onepage_review',         'Mage_Checkout'),
+            'Paypal Express Review Details'    => array('paypal_express_review_details',   'Mage_Paypal'),
+            'Paypal UK Express Review Details' => array('paypaluk_express_review_details', 'Mage_PaypalUk'),
+        );
+    }
+
+    public function testGetFullActionName()
+    {
+        $this->dispatch('design/editor/page');
+        $controller = Mage::app()->getFrontController()->getAction();
+        $this->assertNotInstanceOf('Mage_DesignEditor_EditorController', $controller);
+    }
+
+    /**
+     * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+     */
+    public function testSkinAction()
+    {
+        $this->getRequest()->setParam('skin', 'default/default/blank');
+        $this->dispatch('design/editor/skin');
+        $this->assertRedirect();
+
+        $session = Mage::getSingleton('Mage_DesignEditor_Model_Session');
+        $this->assertEquals('default/default/blank', $session->getSkin());
+    }
+
+    /**
+     * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+     */
+    public function testSkinActionWrongValue()
+    {
+        $this->getRequest()->setParam('skin', 'wrong/skin/applied');
+        $this->dispatch('design/editor/skin');
+        $this->assertRedirect();
+
+        $session = Mage::getSingleton('Mage_DesignEditor_Model_Session');
+        $this->assertNotEquals('wrong/skin/applied', $session->getSkin());
+    }
+
+    public function testSkinActionNonActivatedEditor()
+    {
+        $this->getRequest()->setParam('skin', 'default/default/blank');
+        $this->dispatch('design/editor/skin');
+        $this->assert404NotFound();
+
+        $session = Mage::getSingleton('Mage_DesignEditor_Model_Session');
+        $this->assertNotEquals('default/default/blank', $session->getSkin());
+    }
+
+    /**
+     * @magentoDataFixture Mage/DesignEditor/_files/design_editor_active.php
+     */
+    public function testSkinActionRedirectUrl()
+    {
+        $expectedRedirectUrl = 'http://localhost/index.php/path/to/redirect/?value=1#anchor';
+
+        $this->getRequest()->setParam('skin', 'default/default/blank');
+        $this->getRequest()->setParam(
+            Mage_Core_Controller_Front_Action::PARAM_NAME_URL_ENCODED,
+            Mage::helper('Mage_Core_Helper_Data')->urlEncode($expectedRedirectUrl)
+        );
+        $this->dispatch('design/editor/skin');
+        $this->assertRedirect($expectedRedirectUrl);
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/PageCache/Helper/DataTest.php b/dev/tests/integration/testsuite/Mage/PageCache/Helper/DataTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..98840e8b727b87d60e224289a8eb43ee164abd96
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/PageCache/Helper/DataTest.php
@@ -0,0 +1,80 @@
+<?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_PageCache
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_PageCache
+ */
+class Mage_PageCache_Helper_DataTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_PageCache_Helper_Data
+     */
+    protected $_helper;
+
+    protected function setUp()
+    {
+        $this->_helper = new Mage_PageCache_Helper_Data;
+    }
+
+    public function testSetNoCacheCookie()
+    {
+        /** @var $cookie Mage_Core_Model_Cookie */
+        $cookie = Mage::getSingleton('Mage_Core_Model_Cookie');
+        $this->assertEmpty($cookie->get(Mage_PageCache_Helper_Data::NO_CACHE_COOKIE));
+        $this->_helper->setNoCacheCookie();
+        $this->assertNotEmpty($cookie->get(Mage_PageCache_Helper_Data::NO_CACHE_COOKIE));
+    }
+
+    public function testRemoveNoCacheCookie()
+    {
+        /** @var $cookie Mage_Core_Model_Cookie */
+        $cookie = Mage::getSingleton('Mage_Core_Model_Cookie');
+        $this->_helper->setNoCacheCookie();
+        $this->_helper->removeNoCacheCookie();
+        $this->assertEmpty($cookie->get(Mage_PageCache_Helper_Data::NO_CACHE_COOKIE));
+    }
+
+    public function testLockUnlockNoCacheCookie()
+    {
+        /** @var $cookie Mage_Core_Model_Cookie */
+        $cookie = Mage::getSingleton('Mage_Core_Model_Cookie');
+        $this->_helper->setNoCacheCookie();
+        $this->assertNotEmpty($cookie->get(Mage_PageCache_Helper_Data::NO_CACHE_COOKIE));
+
+        $this->_helper->lockNoCacheCookie();
+        $this->_helper->removeNoCacheCookie();
+        $this->assertNotEmpty($cookie->get(Mage_PageCache_Helper_Data::NO_CACHE_COOKIE));
+
+        $this->_helper->unlockNoCacheCookie();
+        $this->_helper->removeNoCacheCookie();
+        $this->assertEmpty($cookie->get(Mage_PageCache_Helper_Data::NO_CACHE_COOKIE));
+
+        $this->_helper->lockNoCacheCookie();
+        $this->_helper->setNoCacheCookie();
+        $this->assertEmpty($cookie->get(Mage_PageCache_Helper_Data::NO_CACHE_COOKIE));
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/PageCache/Model/ObserverTest.php b/dev/tests/integration/testsuite/Mage/PageCache/Model/ObserverTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..4ccdbd3e6db0dcc1954adbf6829e6810f8413e22
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/PageCache/Model/ObserverTest.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    Magento
+ * @package     Mage_PageCache
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_PageCache
+ */
+class Mage_PageCache_Model_ObserverTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_PageCache_Model_Observer
+     */
+    protected $_observer;
+
+    protected function setUp()
+    {
+        $this->_observer = new Mage_PageCache_Model_Observer;
+    }
+
+    /**
+     * @magentoConfigFixture current_store system/external_page_cache/enabled 1
+     */
+    public function testDesignEditorSessionActivate()
+    {
+        /** @var $cookie Mage_Core_Model_Cookie */
+        $cookie = Mage::getSingleton('Mage_Core_Model_Cookie');
+        $this->assertEmpty($cookie->get(Mage_PageCache_Helper_Data::NO_CACHE_COOKIE));
+        $this->_observer->designEditorSessionActivate(new Varien_Event_Observer());
+        $this->assertNotEmpty($cookie->get(Mage_PageCache_Helper_Data::NO_CACHE_COOKIE));
+    }
+
+    /**
+     * @magentoConfigFixture current_store system/external_page_cache/enabled 1
+     */
+    public function testDesignEditorSessionDeactivate()
+    {
+        /** @var $cookie Mage_Core_Model_Cookie */
+        $cookie = Mage::getSingleton('Mage_Core_Model_Cookie');
+        $cookie->set(Mage_PageCache_Helper_Data::NO_CACHE_COOKIE, '1');
+        $this->_observer->designEditorSessionDeactivate(new Varien_Event_Observer());
+        $this->assertEmpty($cookie->get(Mage_PageCache_Helper_Data::NO_CACHE_COOKIE));
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Paypal/controllers/HostedproControllerTest.php b/dev/tests/integration/testsuite/Mage/Paypal/controllers/HostedproControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..e3b9124177ec9a0232798dd4eeb759d1f2cfa1dd
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Paypal/controllers/HostedproControllerTest.php
@@ -0,0 +1,59 @@
+<?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_Paypal
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Paypal
+ * @magentoDataFixture Mage/Sales/_files/order.php
+ */
+class Mage_Paypal_HostedproControllerTest extends Magento_Test_TestCase_ControllerAbstract
+{
+    public function testCancelActionIsContentGenerated()
+    {
+        $order = new Mage_Sales_Model_Order();
+        $order->load('100000001', 'increment_id');
+        $order->getPayment()->setMethod(Mage_Paypal_Model_Config::METHOD_HOSTEDPRO);
+        $order->save();
+
+        $session = Mage::getSingleton('Mage_Checkout_Model_Session');
+        $session->setLastRealOrderId($order->getRealOrderId())
+            ->setLastQuoteId($order->getQuoteId());
+
+        $this->dispatch('paypal/hostedpro/cancel');
+        $this->assertContains(
+            'window.top.checkout.gotoSection("payment");',
+            $this->getResponse()->getBody()
+        );
+        $this->assertContains(
+            'window.top.document.getElementById(\'checkout-review-submit\').show();',
+            $this->getResponse()->getBody()
+        );
+        $this->assertContains(
+            'window.top.document.getElementById(\'iframe-warning\').hide();',
+            $this->getResponse()->getBody()
+        );
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Paypal/controllers/PayflowControllerTest.php b/dev/tests/integration/testsuite/Mage/Paypal/controllers/PayflowControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..58d8cf678ed8ec79b28e2878d16558a2cccc2319
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Paypal/controllers/PayflowControllerTest.php
@@ -0,0 +1,90 @@
+<?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_Paypal
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Paypal
+ * @magentoDataFixture Mage/Sales/_files/order.php
+ */
+class Mage_Paypal_PayflowControllerTest extends Magento_Test_TestCase_ControllerAbstract
+{
+    public function setUp()
+    {
+        parent::setUp();
+
+        $order = new Mage_Sales_Model_Order();
+        $order->load('100000001', 'increment_id');
+        $order->getPayment()->setMethod(Mage_Paypal_Model_Config::METHOD_PAYFLOWLINK);
+        $order->save();
+
+        $session = Mage::getSingleton('Mage_Checkout_Model_Session');
+        $session->setLastRealOrderId($order->getRealOrderId())
+            ->setLastQuoteId($order->getQuoteId());
+    }
+
+    public function testCancelPaymentActionIsContentGenerated()
+    {
+        $this->dispatch('paypal/payflow/cancelpayment');
+        $this->assertContains(
+            'window_top.checkout.gotoSection("payment");',
+            $this->getResponse()->getBody()
+        );
+        $this->assertContains(
+            'window_top.document.getElementById(\'checkout-review-submit\').show();',
+            $this->getResponse()->getBody()
+        );
+        $this->assertContains(
+            'window_top.document.getElementById(\'iframe-warning\').hide();',
+            $this->getResponse()->getBody()
+        );
+    }
+
+    public function testReturnurlActionIsContentGenerated()
+    {
+        $this->dispatch('paypal/payflow/returnurl');
+        $this->assertContains(
+            'window_top.checkout.gotoSection("payment");',
+            $this->getResponse()->getBody()
+        );
+        $this->assertContains(
+            'window_top.document.getElementById(\'checkout-review-submit\').show();',
+            $this->getResponse()->getBody()
+        );
+        $this->assertContains(
+            'window_top.document.getElementById(\'iframe-warning\').hide();',
+            $this->getResponse()->getBody()
+        );
+    }
+
+    public function testFormActionIsContentGenerated()
+    {
+        $this->dispatch('paypal/payflow/form');
+        $this->assertContains(
+            '<form id="token_form" method="POST" action="https://payflowlink.paypal.com/">',
+            $this->getResponse()->getBody()
+        );
+    }
+}
\ No newline at end of file
diff --git a/dev/tests/integration/testsuite/Mage/Paypal/controllers/PayflowadvancedControllerTest.php b/dev/tests/integration/testsuite/Mage/Paypal/controllers/PayflowadvancedControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..37453d0f98bf2537cfc177a7e58c5d4807cfbc06
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Paypal/controllers/PayflowadvancedControllerTest.php
@@ -0,0 +1,90 @@
+<?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_Paypal
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Paypal
+ * @magentoDataFixture Mage/Sales/_files/order.php
+ */
+class Mage_Paypal_PayflowadvancedControllerTest extends Magento_Test_TestCase_ControllerAbstract
+{
+    public function setUp()
+    {
+        parent::setUp();
+
+        $order = new Mage_Sales_Model_Order();
+        $order->load('100000001', 'increment_id');
+        $order->getPayment()->setMethod(Mage_Paypal_Model_Config::METHOD_PAYFLOWADVANCED);
+        $order->save();
+
+        $session = Mage::getSingleton('Mage_Checkout_Model_Session');
+        $session->setLastRealOrderId($order->getRealOrderId())
+            ->setLastQuoteId($order->getQuoteId());
+    }
+
+    public function testCancelPaymentActionIsContentGenerated()
+    {
+        $this->dispatch('paypal/payflowadvanced/cancelpayment');
+        $this->assertContains(
+            'window_top.checkout.gotoSection("payment");',
+            $this->getResponse()->getBody()
+        );
+        $this->assertContains(
+            'window_top.document.getElementById(\'checkout-review-submit\').show();',
+            $this->getResponse()->getBody()
+        );
+        $this->assertContains(
+            'window_top.document.getElementById(\'iframe-warning\').hide();',
+            $this->getResponse()->getBody()
+        );
+    }
+
+    public function testReturnurlActionIsContentGenerated()
+    {
+        $this->dispatch('paypal/payflowadvanced/returnurl');
+        $this->assertContains(
+            'window_top.checkout.gotoSection("payment");',
+            $this->getResponse()->getBody()
+        );
+        $this->assertContains(
+            'window_top.document.getElementById(\'checkout-review-submit\').show();',
+            $this->getResponse()->getBody()
+        );
+        $this->assertContains(
+            'window_top.document.getElementById(\'iframe-warning\').hide();',
+            $this->getResponse()->getBody()
+        );
+    }
+
+    public function testFormActionIsContentGenerated()
+    {
+        $this->dispatch('paypal/payflowadvanced/form');
+        $this->assertContains(
+            '<form id="token_form" method="POST" action="https://payflowlink.paypal.com/">',
+            $this->getResponse()->getBody()
+        );
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Paypal/controllers/StandardControllerTest.php b/dev/tests/integration/testsuite/Mage/Paypal/controllers/StandardControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..5079af801e0bcee93390614cbf51b118d55e7a89
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Paypal/controllers/StandardControllerTest.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    Magento
+ * @package     Mage_Paypal
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Paypal
+ * @magentoDataFixture Mage/Sales/_files/order.php
+ */
+class Mage_Paypal_StandardControllerTest extends Magento_Test_TestCase_ControllerAbstract
+{
+    public function testRedirectActionIsContentGenerated()
+    {
+        $order = new Mage_Sales_Model_Order();
+        $order->load('100000001', 'increment_id');
+        $order->getPayment()->setMethod(Mage_Paypal_Model_Config::METHOD_WPS);
+        $order->save();
+
+        $session = Mage::getSingleton('Mage_Checkout_Model_Session');
+        $session->setLastRealOrderId($order->getRealOrderId())
+            ->setLastQuoteId($order->getQuoteId());
+
+        $this->dispatch('paypal/standard/redirect');
+        $this->assertContains(
+            '<form action="https://www.paypal.com/webscr" id="paypal_standard_checkout"'
+                . ' name="paypal_standard_checkout" method="POST">',
+            $this->getResponse()->getBody()
+        );
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Report/WidgetTest.php b/dev/tests/integration/testsuite/Mage/Report/WidgetTest.php
index 0662245f6212978cd7fe360e352bd2de6d5ad929..0cde0581b453e0a7e2fd55f8a79aee1a436c5f11 100644
--- a/dev/tests/integration/testsuite/Mage/Report/WidgetTest.php
+++ b/dev/tests/integration/testsuite/Mage/Report/WidgetTest.php
@@ -42,7 +42,7 @@ class Mage_Report_WidgetTest extends PHPUnit_Framework_TestCase
         $this->assertArrayHasKey('list_names', $templates);
         $this->assertArrayHasKey('list_images', $templates);
 
-        $blocks = $config->xpath('supported_blocks');
+        $blocks = $config->xpath('supported_containers');
         $blocks = (array) $blocks[0]->children();
         $this->assertArrayHasKey('left_column', $blocks);
         $this->assertArrayHasKey('main_content', $blocks);
@@ -61,7 +61,7 @@ class Mage_Report_WidgetTest extends PHPUnit_Framework_TestCase
         $this->assertArrayHasKey('list_names', $templates);
         $this->assertArrayHasKey('list_images', $templates);
 
-        $blocks = $config->xpath('supported_blocks');
+        $blocks = $config->xpath('supported_containers');
         $blocks = (array) $blocks[0]->children();
         $this->assertArrayHasKey('left_column', $blocks);
         $this->assertArrayHasKey('main_content', $blocks);
diff --git a/dev/tests/integration/testsuite/Mage/Rss/Helper/DataTest.php b/dev/tests/integration/testsuite/Mage/Rss/Helper/DataTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..b57fc4b3bb28c3fd187bb4763a25601b6c368514
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Rss/Helper/DataTest.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    Magento
+ * @package     Mage_Rss
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Rss
+ */
+class Mage_Rss_Helper_DataTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Rss_Helper_Data
+     */
+    protected $_helper;
+
+    protected function setUp()
+    {
+        $this->_helper = new Mage_Rss_Helper_Data;
+    }
+
+    /**
+     * @magentoAppIsolation enabled
+     */
+    public function testAuthAdminLoggedIn()
+    {
+        $admin = new Varien_Object(array('id' => 1));
+        $session = Mage::getSingleton('Mage_Rss_Model_Session');
+        $session->setAdmin($admin);
+        $this->assertEquals($admin, $this->_helper->authAdmin(''));
+    }
+
+    public function testAuthAdminNotLogged()
+    {
+        $this->markTestIncomplete('Incomplete until helper stops exiting script for non-logged user');
+        $this->assertFalse($this->_helper->authAdmin(''));
+    }
+
+    /**
+     * @magentoDataFixture adminUserFixture
+     * @magentoAppIsolation enabled
+     */
+    public function testAuthAdminLogin()
+    {
+        $_SERVER['PHP_AUTH_USER'] = Mage_Admin_Utility_User::CRED_USERNAME;
+        $_SERVER['PHP_AUTH_PW'] = Mage_Admin_Utility_User::CRED_PASSWORD;
+        $this->assertInstanceOf('Mage_Admin_Model_User', $this->_helper->authAdmin(''));
+
+        $response = Mage::app()->getResponse();
+        $code = $response->getHttpResponseCode();
+        $this->assertFalse(($code >= 300) && ($code < 400));
+    }
+
+    public static function adminUserFixture()
+    {
+        Mage_Admin_Utility_User::getInstance()
+            ->createAdmin();
+    }
+
+    public static function adminUserFixtureRollback()
+    {
+        Mage_Admin_Utility_User::getInstance()
+            ->destroyAdmin();
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Rss/controllers/CatalogControllerTest.php b/dev/tests/integration/testsuite/Mage/Rss/controllers/CatalogControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..a5892b9e295e0ea0aad853d7462e9f1c5a1ea8b8
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Rss/controllers/CatalogControllerTest.php
@@ -0,0 +1,104 @@
+<?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_Rss
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Rss
+ */
+class Mage_Rss_CatalogControllerTest extends Magento_Test_TestCase_ControllerAbstract
+{
+    /**
+     * @dataProvider actionsDataProvider
+     */
+    public function testRssActionsNonLoggedUser($action)
+    {
+        $this->markTestIncomplete('Incomplete until Mage_Core_Helper_Http stops exiting script for non-logged user');
+        $this->dispatch('rss/catalog/' . $action . '/');
+    }
+
+    /**
+     * @dataProvider actionsDataProvider
+     * @magentoDataFixture adminUserFixture
+     */
+    public function testRssActionsLoggedUser($action)
+    {
+        $admin = new Mage_Admin_Model_User;
+        $admin->loadByUsername(Mage_Admin_Utility_User::CRED_USERNAME);
+        $session = Mage::getSingleton('Mage_Rss_Model_Session');
+        $session->setAdmin($admin);
+
+        $adminSession = Mage::getSingleton('Mage_Admin_Model_Session');
+        $adminSession->setUpdatedAt(time())
+            ->setUser($admin);
+
+        $this->dispatch('rss/catalog/' . $action . '/');
+
+        $body = $this->getResponse()->getBody();
+        $this->assertNotEmpty($body);
+
+        $response = Mage::app()->getResponse();
+        $code = $response->getHttpResponseCode();
+        $this->assertFalse(($code >= 300) && ($code < 400));
+
+        $xmlContentType = false;
+        $headers = $response->getHeaders();
+        foreach ($headers as $header) {
+            if ($header['name'] != 'Content-Type') {
+                continue;
+            }
+            if (strpos($header['value'], 'text/xml') !== false) {
+                $xmlContentType = true;
+            }
+        }
+        $this->assertTrue($xmlContentType, 'Rss document should output xml header');
+
+        $body = $response->getBody();
+        $this->assertContains('<rss', $body);
+    }
+
+    /**
+     * @return array
+     */
+    public function actionsDataProvider()
+    {
+        return array(
+            array('notifystock'),
+            array('review')
+        );
+    }
+
+    public static function adminUserFixture()
+    {
+        Mage_Admin_Utility_User::getInstance()
+            ->createAdmin();
+    }
+
+    public static function adminUserFixtureRollback()
+    {
+        Mage_Admin_Utility_User::getInstance()
+            ->destroyAdmin();
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Rss/controllers/OrderControllerTest.php b/dev/tests/integration/testsuite/Mage/Rss/controllers/OrderControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..57a2993d1b5dcee1bb5ac8885568427e9cf2bd4d
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Rss/controllers/OrderControllerTest.php
@@ -0,0 +1,89 @@
+<?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_Rss
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Rss
+ */
+class Mage_Rss_OrderControllerTest extends Magento_Test_TestCase_ControllerAbstract
+{
+    public function testNewActionNonLoggedUser()
+    {
+        $this->markTestIncomplete('Incomplete until Mage_Core_Helper_Http stops exiting script for non-logged user');
+        $this->dispatch('rss/order/new/');
+    }
+
+    /**
+     * @magentoDataFixture adminUserFixture
+     */
+    public function testNewActionLoggedUser()
+    {
+        $admin = new Mage_Admin_Model_User;
+        $admin->loadByUsername(Mage_Admin_Utility_User::CRED_USERNAME);
+        $session = Mage::getSingleton('Mage_Rss_Model_Session');
+        $session->setAdmin($admin);
+
+        $adminSession = Mage::getSingleton('Mage_Admin_Model_Session');
+        $adminSession->setUpdatedAt(time())
+            ->setUser($admin);
+
+        $this->dispatch('rss/order/new/');
+
+        $body = $this->getResponse()->getBody();
+        $this->assertNotEmpty($body);
+
+        $response = Mage::app()->getResponse();
+        $code = $response->getHttpResponseCode();
+        $this->assertFalse(($code >= 300) && ($code < 400));
+
+        $xmlContentType = false;
+        $headers = $response->getHeaders();
+        foreach ($headers as $header) {
+            if ($header['name'] != 'Content-Type') {
+                continue;
+            }
+            if (strpos($header['value'], 'text/xml') !== false) {
+                $xmlContentType = true;
+            }
+        }
+        $this->assertTrue($xmlContentType, 'Rss document should output xml header');
+
+        $body = $response->getBody();
+        $this->assertContains('<rss', $body);
+    }
+
+    public static function adminUserFixture()
+    {
+        Mage_Admin_Utility_User::getInstance()
+            ->createAdmin();
+    }
+
+    public static function adminUserFixtureRollback()
+    {
+        Mage_Admin_Utility_User::getInstance()
+            ->destroyAdmin();
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Sales/_files/order.php b/dev/tests/integration/testsuite/Mage/Sales/_files/order.php
new file mode 100644
index 0000000000000000000000000000000000000000..f71376d2c3fd56748feca0a88d673e12bd079b91
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Sales/_files/order.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.
+ *
+ * @category    Magento
+ * @package     Mage_Sales
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+$billingAddress = new Mage_Sales_Model_Order_Address();
+$billingAddress->setRegion('CA')
+    ->setPostcode('11111')
+    ->setFirstname('firstname')
+    ->setLastname('lastname')
+    ->setStreet('street')
+    ->setCity('Los Angeles')
+    ->setEmail('admin@example.com')
+    ->setTelephone('1111111111')
+    ->setCountryId('US')
+    ->setAddressType('billing');
+
+$shippingAddress = clone $billingAddress;
+$shippingAddress->setId(null)
+    ->setAddressType('shipping');
+
+$payment = new Mage_Sales_Model_Order_Payment();
+$payment->setMethod('checkmo');
+
+$order = new Mage_Sales_Model_Order();
+$order->setIncrementId('100000001')
+    ->setSubtotal(100)
+    ->setBaseSubtotal(100)
+    ->setCustomerIsGuest(true)
+    ->setBillingAddress($billingAddress)
+    ->setShippingAddress($shippingAddress)
+    ->setPayment($payment);
+$order->save();
diff --git a/dev/tests/integration/testsuite/Mage/Sales/_files/quote.php b/dev/tests/integration/testsuite/Mage/Sales/_files/quote.php
new file mode 100644
index 0000000000000000000000000000000000000000..b3d88f7e69a2e24978aacde88393ed2280cd6d0d
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Sales/_files/quote.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.
+ *
+ * @category    Magento
+ * @package     Mage_Sales
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+$product = new Mage_Catalog_Model_Product();
+$product->setTypeId('simple')
+    ->setId(1)
+    ->setAttributeSetId(4)
+    ->setName('Simple Product')
+    ->setSku('simple')
+    ->setPrice(10)
+    ->setStockData(
+        array(
+            'use_config_manage_stock'   => 1,
+            'qty'                       => 100,
+            'is_qty_decimal'            => 0,
+            'is_in_stock'               => 1,
+        )
+    )
+    ->setMetaTitle('meta title')
+    ->setMetaKeyword('meta keyword')
+    ->setMetaDescription('meta description')
+    ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
+    ->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
+    ->save();
+$product->load(1);
+
+$quote = new Mage_Sales_Model_Quote();
+$quote->setCustomerIsGuest(true)
+    ->setStoreId(Mage::app()->getStore()->getId())
+    ->setReservedOrderId('test01')
+    ->addProduct($product);
+$quote->getPayment()->setMethod('checkmo');
+$quote->save();
diff --git a/dev/tests/integration/testsuite/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/ContainerTest.php b/dev/tests/integration/testsuite/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/ContainerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..5c24b95d5a3075bba7f71b05357584cc1ca304b8
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/ContainerTest.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_Widget
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Widget
+ */
+class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_ContainerTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_Container
+     */
+    protected $_block = null;
+
+    protected function setUp()
+    {
+        $this->_block = new Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_Container;
+    }
+
+    public function testSetGetAllowedContainers()
+    {
+        $this->assertEmpty($this->_block->getAllowedContainers());
+        $containers = array('some_container', 'another_container');
+        $this->_block->setAllowedContainers($containers);
+        $this->assertEquals($containers, $this->_block->getAllowedContainers());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/LayoutTest.php b/dev/tests/integration/testsuite/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/LayoutTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..729faa365f8a49e95b994ee2f468f31f52e4cfc1
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/LayoutTest.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.
+ *
+ * @category    Magento
+ * @package     Mage_Widget
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Widget
+ */
+class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_LayoutTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_Layout|PHPUnit_Framework_MockObject_MockObject
+     */
+    protected $_block;
+
+    protected function setUp()
+    {
+        $layoutUtility = new Mage_Core_Utility_Layout($this);
+        $pageTypesFixture = __DIR__ . '/_files/_page_types_with_containers.xml';
+        $this->_block = $this->getMock(
+            'Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Chooser_Layout',
+            array('_getLayoutUpdate'),
+            array(array(
+                'name'  => 'page_type',
+                'id'    => 'page_types_select',
+                'class' => 'page-types-select',
+                'title' => 'Page Types Select',
+            ))
+        );
+        $this->_block
+            ->expects($this->any())
+            ->method('_getLayoutUpdate')
+            ->will($this->returnValue($layoutUtility->getLayoutUpdateFromFixture($pageTypesFixture)))
+        ;
+    }
+
+    public function testToHtml()
+    {
+        $this->assertXmlStringEqualsXmlFile(__DIR__ . '/_files/page_types_select.html', $this->_block->toHtml());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/_files/_page_types_with_containers.xml b/dev/tests/integration/testsuite/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/_files/_page_types_with_containers.xml
new file mode 100644
index 0000000000000000000000000000000000000000..99fe9a10f28fcddb3693053cb285b4e878441923
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/_files/_page_types_with_containers.xml
@@ -0,0 +1,62 @@
+<?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     Mage_Core
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<layouts>
+    <non_page_handle_with_own_containers>
+        <container name="container_one" label="Container One"/>
+    </non_page_handle_with_own_containers>
+
+    <root_page_without_containers type="page">
+        <label>Root Page without Containers</label>
+    </root_page_without_containers>
+    <root_page_without_own_containers type="page">
+        <label>Root Page without Own Containers</label>
+    </root_page_without_own_containers>
+    <root_page_with_own_containers type="page">
+        <label>Root Page with Own Containers</label>
+        <container name="container_two" label="Container Two"/>
+    </root_page_with_own_containers>
+    <root_page_with_imported_containers type="page">
+        <label>Root Page with Imported Containers</label>
+        <update handle="non_page_handle_with_own_containers"/>
+    </root_page_with_imported_containers>
+
+    <child_page_without_containers type="page" parent="root_page_without_own_containers">
+        <label>Child Page without Containers</label>
+    </child_page_without_containers>
+    <child_page_with_own_containers type="page" parent="root_page_without_own_containers">
+        <label>Child Page with Own Containers</label>
+        <container name="container_three" label="Container Three"/>
+    </child_page_with_own_containers>
+    <child_page_with_inherited_containers type="page" parent="root_page_with_own_containers">
+        <label>Child Page with Inherited Containers</label>
+    </child_page_with_inherited_containers>
+    <child_page_with_inherited_imported_containers type="page" parent="root_page_with_imported_containers">
+        <label>Child Page with Inherited Imported Containers</label>
+    </child_page_with_inherited_imported_containers>
+</layouts>
diff --git a/dev/tests/integration/testsuite/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/_files/page_types_select.html b/dev/tests/integration/testsuite/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/_files/page_types_select.html
new file mode 100644
index 0000000000000000000000000000000000000000..b92ab0fd3760f936cbffd2e8af005bdcd7de82a6
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Chooser/_files/page_types_select.html
@@ -0,0 +1,39 @@
+<!--
+/**
+ * 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     Mage_Widget
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<select name="page_type" id="page_types_select" class="page-types-select" title="Page Types Select">
+    <option value="">-- Please Select --</option>
+    <!--
+    <option value="root_page_without_own_containers">Root Page without Own Containers</option>
+    <option value="child_page_with_own_containers">. Child Page with Own Containers</option>
+    -->
+    <option value="root_page_with_own_containers">Root Page with Own Containers</option>
+    <option value="child_page_with_inherited_containers">. Child Page with Inherited Containers</option>
+
+    <option value="root_page_with_imported_containers">Root Page with Imported Containers</option>
+    <option value="child_page_with_inherited_imported_containers">. Child Page with Inherited Imported Containers</option>
+</select>
diff --git a/dev/tests/integration/testsuite/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main/LayoutTest.php b/dev/tests/integration/testsuite/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main/LayoutTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..b7d96b7b1936e1cc9d0291f96f2fc5d2fee6e4e5
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Widget/Block/Adminhtml/Widget/Instance/Edit/Tab/Main/LayoutTest.php
@@ -0,0 +1,56 @@
+<?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_Widget
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Widget
+ */
+class Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Main_LayoutTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Main_Layout
+     */
+    protected $_block;
+
+    protected function setUp()
+    {
+        $this->_block = new Mage_Widget_Block_Adminhtml_Widget_Instance_Edit_Tab_Main_Layout(array(
+            'widget_instance' => new Mage_Widget_Model_Widget_Instance()
+        ));
+        $this->_block->setLayout(Mage::app()->getLayout());
+    }
+
+    public function testGetLayoutsChooser()
+    {
+        $actualHtml = $this->_block->getLayoutsChooser();
+        $this->assertStringStartsWith('<select ', $actualHtml);
+        $this->assertStringEndsWith('</select>', $actualHtml);
+        $this->assertContains('id="layout_handle"', $actualHtml);
+        $optionCount = substr_count($actualHtml, '<option ');
+        $this->assertGreaterThan(1, $optionCount, 'HTML select tag must provide options to choose from.');
+        $this->assertEquals($optionCount, substr_count($actualHtml, '</option>'));
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Widget/Model/Widget/InstanceTest.php b/dev/tests/integration/testsuite/Mage/Widget/Model/Widget/InstanceTest.php
index c487fdd49c0c0513c0be36ea14df4d298def2545..fec93237803defb7c5d4c75d3e7d5c1f73dd0ad1 100644
--- a/dev/tests/integration/testsuite/Mage/Widget/Model/Widget/InstanceTest.php
+++ b/dev/tests/integration/testsuite/Mage/Widget/Model/Widget/InstanceTest.php
@@ -30,19 +30,77 @@
  */
 class Mage_Widget_Model_Widget_InstanceTest extends PHPUnit_Framework_TestCase
 {
+    /**
+     * @var Mage_Widget_Model_Widget_Instance
+     */
+    protected $_model;
+
+    protected function setUp()
+    {
+        $this->_model = new Mage_Widget_Model_Widget_Instance;
+    }
+
+    public function testSetGetType()
+    {
+        $this->assertEmpty($this->_model->getType());
+        $this->assertSame('test', $this->_model->setType('test')->getType());
+        $this->assertSame('test', $this->_model->getInstanceType());
+    }
+
+    public function testGetPackageGetThemeDefault()
+    {
+        $this->assertEquals(Mage_Core_Model_Design_Package::DEFAULT_PACKAGE, $this->_model->getPackage());
+        $this->assertEquals(Mage_Core_Model_Design_Package::DEFAULT_THEME, $this->_model->getTheme());
+    }
+
+    public function testGetPackageGetTheme()
+    {
+        $this->_model->setPackageTheme('some_package/some_theme');
+        $this->assertEquals('some_package', $this->_model->getPackage());
+        $this->assertEquals('some_theme', $this->_model->getTheme());
+    }
+
     /**
      * @return Mage_Widget_Model_Widget_Instance
      */
     public function testGetWidgetConfig()
     {
-        $model = new Mage_Widget_Model_Widget_Instance;
-        $config = $model->setType('Mage_Catalog_Block_Product_Widget_New')->getWidgetConfig();
+        $config = $this->_model->setType('Mage_Catalog_Block_Product_Widget_New')->getWidgetConfig();
         $this->assertInstanceOf('Varien_Simplexml_Element', $config);
         /** @var Varien_Simplexml_Element $config */
         $element = $config->xpath('/widgets/new_products/parameters/template/values/list');
         $this->assertArrayHasKey(0, $element);
         $this->assertInstanceOf('Varien_Simplexml_Element', $element[0]);
-        return $model;
+        return $this->_model;
+    }
+
+    /**
+     * @return Mage_Widget_Model_Widget_Instance
+     */
+    public function testGetWidgetSupportedContainers()
+    {
+        $this->_model->setType('Mage_Catalog_Block_Product_Widget_New');
+        $containers = $this->_model->getWidgetSupportedContainers();
+        $this->assertInternalType('array', $containers);
+        $this->assertContains('left', $containers);
+        $this->assertContains('content', $containers);
+        $this->assertContains('right', $containers);
+        return $this->_model;
+    }
+
+    /**
+     * @param Mage_Widget_Model_Widget_Instance $model
+     * @depends testGetWidgetSupportedContainers
+     */
+    public function testGetWidgetSupportedTemplatesByContainer($model)
+    {
+        $templates = $model->getWidgetSupportedTemplatesByContainer('content');
+        $this->assertNotEmpty($templates);
+        $this->assertInternalType('array', $templates);
+        foreach ($templates as $row) {
+            $this->assertArrayHasKey('value', $row);
+            $this->assertArrayHasKey('label', $row);
+        }
     }
 
     /**
@@ -57,16 +115,4 @@ class Mage_Widget_Model_Widget_InstanceTest extends PHPUnit_Framework_TestCase
         $this->assertContains('<reference name="content">', $result);
         $this->assertContains('<block type="' . $model->getType() . '"', $result);
     }
-
-    public function testSetGetType()
-    {
-        $model = new Mage_Widget_Model_Widget_Instance();
-        $this->assertEmpty($model->getType());
-
-        $model->setType('test-test');
-        $this->assertEquals('test/test', $model->getType());
-
-        $model->setData('instance_type', 'test-test');
-        $this->assertEquals('test/test', $model->getType());
-    }
 }
diff --git a/dev/tests/integration/testsuite/Mage/Widget/controllers/Adminhtml/Widget/InstanceControllerTest.php b/dev/tests/integration/testsuite/Mage/Widget/controllers/Adminhtml/Widget/InstanceControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..d8e497ea5878ee83f9f0434dfdd89e0fad7cfade
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Widget/controllers/Adminhtml/Widget/InstanceControllerTest.php
@@ -0,0 +1,60 @@
+<?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_Adminhtml
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Widget
+ */
+class Mage_Widget_Adminhtml_Widget_InstanceControllerTest extends Mage_Adminhtml_Utility_Controller
+{
+    protected function setUp()
+    {
+        parent::setUp();
+
+        $this->getRequest()->setParam('type', 'Mage_Cms_Block_Widget_Page_Link');
+        $this->getRequest()->setParam('package_theme', 'default-default');
+    }
+
+    public function testEditAction()
+    {
+        $this->dispatch('admin/widget_instance/edit');
+        $this->assertContains('<option value="Mage_Cms_Block_Widget_Page_Link" selected="selected">',
+            $this->getResponse()->getBody()
+        );
+    }
+
+    public function testBlocksAction()
+    {
+        $this->dispatch('admin/widget_instance/blocks');
+        $this->assertStringStartsWith('<select name="block" id=""', $this->getResponse()->getBody());
+    }
+
+    public function testTemplateAction()
+    {
+        $this->dispatch('admin/widget_instance/template');
+        $this->assertStringStartsWith('<select name="template" id=""', $this->getResponse()->getBody());
+    }
+}
diff --git a/dev/tests/integration/testsuite/Mage/Wishlist/Block/AbstractTest.php b/dev/tests/integration/testsuite/Mage/Wishlist/Block/AbstractTest.php
index 8910b52f3d2a45b8bc527986b0a55ea092d9d070..cef1cc3bcdf4032394ba910851117368f9a0b0a6 100644
--- a/dev/tests/integration/testsuite/Mage/Wishlist/Block/AbstractTest.php
+++ b/dev/tests/integration/testsuite/Mage/Wishlist/Block/AbstractTest.php
@@ -25,20 +25,16 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-class Mage_Wishlist_Block_AbstractTestAbstract extends Mage_Wishlist_Block_Abstract
-{
-}
-
 class Mage_Wishlist_Block_AbstractTest extends PHPUnit_Framework_TestCase
 {
     /**
-     * @var Mage_Wishlist_Block_AbstractTestAbstract
+     * @var Mage_Wishlist_Block_Abstract
      */
     protected $_block;
 
     protected function setUp()
     {
-        $this->_block = new Mage_Wishlist_Block_AbstractTestAbstract();
+        $this->_block = $this->getMockForAbstractClass('Mage_Wishlist_Block_Abstract');
     }
 
     /**
diff --git a/dev/tests/integration/testsuite/Mage/Wishlist/_files/wishlist.php b/dev/tests/integration/testsuite/Mage/Wishlist/_files/wishlist.php
new file mode 100644
index 0000000000000000000000000000000000000000..e0e415d536840c18e2e816eef0f8c23807f9fe2b
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Wishlist/_files/wishlist.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    Magento
+ * @package     Mage_Wishlist
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+require __DIR__ . '/../../Customer/_files/customer.php';
+require __DIR__ . '/../../Catalog/_files/product_simple.php';
+
+$wishlist = new Mage_Wishlist_Model_Wishlist;
+$wishlist->loadByCustomer($customer->getId(), true);
+$item = $wishlist->addNewItem($product, new Varien_Object(array(
+//    'product' => '1',
+//    'related_product' => '',
+//    'options' => array(
+//        1 => '1-text',
+//        2 => array('month' => 1, 'day' => 1, 'year' => 2001, 'hour' => 1, 'minute' => 1),
+//        3 => '1',
+//        4 => '1',
+//    ),
+//    'validate_datetime_2' => '',
+//    'qty' => '1',
+)));
+$wishlist->save();
diff --git a/dev/tests/integration/testsuite/Mage/Wishlist/controllers/IndexControllerTest.php b/dev/tests/integration/testsuite/Mage/Wishlist/controllers/IndexControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..499dbd65822e1d48d2e0a4e4c9e15f8a696d90ad
--- /dev/null
+++ b/dev/tests/integration/testsuite/Mage/Wishlist/controllers/IndexControllerTest.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.
+ *
+ * @category    Magento
+ * @package     Mage_Wishlist
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Mage_Wishlist_IndexControllerTest extends Magento_Test_TestCase_ControllerAbstract
+{
+    /**
+     * Verify wishlist view action
+     *
+     * The following is verified:
+     * - Mage_Wishlist_Model_Resource_Item_Collection
+     * - Mage_Wishlist_Block_Customer_Wishlist
+     * - Mage_Wishlist_Block_Customer_Wishlist_Items
+     * - Mage_Wishlist_Block_Customer_Wishlist_Item_Column
+     * - Mage_Wishlist_Block_Customer_Wishlist_Item_Column_Cart
+     * - Mage_Wishlist_Block_Customer_Wishlist_Item_Column_Comment
+     * - Mage_Wishlist_Block_Customer_Wishlist_Button
+     * - that Mage_Wishlist_Block_Customer_Wishlist_Item_Options doesn't throw a fatal error
+     *
+     * @magentoDataFixture Mage/Wishlist/_files/wishlist.php
+     */
+    public function testItemColumnBlock()
+    {
+        $session = new Mage_Customer_Model_Session;
+        $session->login('customer@example.com', 'password');
+        $this->dispatch('wishlist/index/index');
+        $body = $this->getResponse()->getBody();
+        $this->assertStringMatchesFormat('%A<img src="%Asmall_image.jpg" %A alt="Simple Product"%A/>%A', $body);
+        $this->assertStringMatchesFormat('%Afunction addWItemToCart(itemId)%A', $body);
+        $this->assertStringMatchesFormat('%Aonclick="addWItemToCart(%d);"%A', $body);
+        $this->assertStringMatchesFormat('%A<textarea name="description[%d]"%A', $body);
+        $this->assertStringMatchesFormat('%A<button%Aonclick="addAllWItemsToCart()"%A', $body);
+    }
+}
diff --git a/dev/tests/integration/testsuite/MageTest.php b/dev/tests/integration/testsuite/MageTest.php
index 62110a5c3e38f50c7961a06f795826996241dee2..33bb6371f4bf265dbde588b9f49d579b37a08a59 100644
--- a/dev/tests/integration/testsuite/MageTest.php
+++ b/dev/tests/integration/testsuite/MageTest.php
@@ -134,38 +134,4 @@ class MageTest extends PHPUnit_Framework_TestCase
             'class name'  => array('Mage_Core_Helper_Js', 'Mage_Core_Helper_Js'),
         );
     }
-
-    /**
-     * @magentoAppIsolation enabled
-     */
-    public function testSetConfigModel()
-    {
-        Mage::reset();
-        Mage::setConfigModel();
-        $config = Mage::getConfig();
-        $this->assertInstanceOf('Mage_Core_Model_Config', $config);
-
-        Mage::reset();
-        Mage::setConfigModel(array('config_model' => 'Mage_Core_Model_Config'));
-        $config = Mage::getConfig();
-        $this->assertInstanceOf('Mage_Core_Model_Config', $config);
-
-        Mage::reset();
-        Mage::setConfigModel(array('config_model' => 'ERROR_STRING'));
-        $config = Mage::getConfig();
-        $this->assertInstanceOf('Mage_Core_Model_Config', $config);
-    }
-
-    /**
-     * @magentoAppIsolation enabled
-     */
-    public function testSetIsInstalled()
-    {
-        if (!Mage::isInstalled()) {
-            $this->assertFalse(Mage::isInstalled());
-
-            Mage::setIsInstalled(array('is_installed' => true));
-            $this->assertTrue(Mage::isInstalled());
-        }
-    }
 }
diff --git a/dev/tests/integration/testsuite/Phoenix/Moneybookers/controllers/ProcessingControllerTest.php b/dev/tests/integration/testsuite/Phoenix/Moneybookers/controllers/ProcessingControllerTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..c177e94b2d1ef8cec3c801d8b958121759377064
--- /dev/null
+++ b/dev/tests/integration/testsuite/Phoenix/Moneybookers/controllers/ProcessingControllerTest.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.
+ *
+ * @category    Magento
+ * @package     Phoenix_Moneybookers
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Phoenix_Moneybookers
+ */
+class Phoenix_Moneybookers_ProcessingControllerTest extends Magento_Test_TestCase_ControllerAbstract
+{
+    public function testCancelActionRedirect()
+    {
+        $this->dispatch('moneybookers/processing/cancel');
+        $redirectUrl = Mage::getUrl('checkout/cart');
+        $this->assertContains(
+            '<script type="text/javascript">parent.location.href="' . $redirectUrl . '";</script>',
+            $this->getResponse()->getBody()
+        );
+    }
+}
diff --git a/dev/tests/integration/testsuite/Varien/Db/Adapter/InterfaceTest.php b/dev/tests/integration/testsuite/Varien/Db/Adapter/InterfaceTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..aac51225f6b808f3a38f3a070e676fbf26b6b2b0
--- /dev/null
+++ b/dev/tests/integration/testsuite/Varien/Db/Adapter/InterfaceTest.php
@@ -0,0 +1,161 @@
+<?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    Varien
+ * @package     Varien_Db
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Test for an environment-dependent DB adapter that implements Varien_Db_Adapter_Interface
+ */
+class Varien_Db_Adapter_InterfaceTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Varien_Db_Adapter_Interface
+     */
+    protected $_connection;
+
+    /**
+     * @var string
+     */
+    protected $_tableName;
+
+    /**
+     * @var string
+     */
+    protected $_oneColumnIdxName;
+
+    /**
+     * @var string
+     */
+    protected $_twoColumnIdxName;
+
+    protected function setUp()
+    {
+        $installer = new Mage_Core_Model_Resource_Setup(Mage_Core_Model_Resource_Setup::DEFAULT_SETUP_CONNECTION);
+        $this->_connection = $installer->getConnection();
+        $this->_tableName = $installer->getTable('table_two_column_idx');
+        $this->_oneColumnIdxName = $installer->getIdxName($this->_tableName, array('column1'));
+        $this->_twoColumnIdxName = $installer->getIdxName($this->_tableName, array('column1', 'column2'));
+
+        $table = $this->_connection->newTable($this->_tableName)
+            ->addColumn('column1', Varien_Db_Ddl_Table::TYPE_INTEGER)
+            ->addColumn('column2', Varien_Db_Ddl_Table::TYPE_INTEGER)
+            ->addIndex($this->_oneColumnIdxName, array('column1'))
+            ->addIndex($this->_twoColumnIdxName, array('column1', 'column2'))
+        ;
+        $this->_connection->createTable($table);
+    }
+
+    /**
+     * Cleanup DDL cache for the fixture table
+     */
+    protected function tearDown()
+    {
+        $this->_connection->dropTable($this->_tableName);
+        $this->_connection->resetDdlCache($this->_tableName);
+    }
+
+    protected function assertPreConditions()
+    {
+        $this->assertTrue(
+            $this->_connection->tableColumnExists($this->_tableName, 'column1'),
+            'Table column "column1" must be provided by the fixture.'
+        );
+        $this->assertTrue(
+            $this->_connection->tableColumnExists($this->_tableName, 'column2'),
+            'Table column "column2" must be provided by the fixture.'
+        );
+        $this->assertEquals(
+            array('column1'),
+            $this->_getIndexColumns($this->_tableName, $this->_oneColumnIdxName),
+            'Single-column index must be provided by the fixture.'
+        );
+        $this->assertEquals(
+            array('column1', 'column2'),
+            $this->_getIndexColumns($this->_tableName, $this->_twoColumnIdxName),
+            'Multiple-column index must be provided by the fixture.'
+        );
+    }
+
+    /**
+     * Retrieve list of columns used for an index or return false, if an index with a given name does not exist
+     *
+     * @param string $tableName
+     * @param string $indexName
+     * @param string|null $schemaName
+     * @return array|false
+     */
+    protected function _getIndexColumns($tableName, $indexName, $schemaName = null)
+    {
+        foreach ($this->_connection->getIndexList($tableName, $schemaName) as $idxData) {
+            if ($idxData['KEY_NAME'] == $indexName) {
+                return $idxData['COLUMNS_LIST'];
+            }
+        }
+        return false;
+    }
+
+    public function testDropColumn()
+    {
+        $this->_connection->dropColumn($this->_tableName, 'column1');
+        $this->assertFalse(
+            $this->_connection->tableColumnExists($this->_tableName, 'column1'),
+            'Table column must not exist after it has been dropped.'
+        );
+    }
+
+    /**
+     * @depends testDropColumn
+     */
+    public function testDropColumnRemoveFromIndexes()
+    {
+        $this->_connection->dropColumn($this->_tableName, 'column1');
+        $this->assertFalse(
+            $this->_getIndexColumns($this->_tableName, $this->_oneColumnIdxName),
+            'Column index must be dropped along with the column.'
+        );
+        $this->assertEquals(
+            array('column2'),
+            $this->_getIndexColumns($this->_tableName, $this->_twoColumnIdxName),
+            'References to the dropped column must be removed from the multiple-column indexes.'
+        );
+    }
+
+    /**
+     * @depends testDropColumn
+     */
+    public function testDropColumnRemoveIndexDuplicate()
+    {
+        $this->_connection->dropColumn($this->_tableName, 'column2');
+        $this->assertEquals(
+            array('column1'),
+            $this->_getIndexColumns($this->_tableName, $this->_oneColumnIdxName),
+            'Column index must be preserved.'
+        );
+        $this->assertFalse(
+            $this->_getIndexColumns($this->_tableName, $this->_twoColumnIdxName),
+            'Multiple-column index must be dropped to not duplicate existing index by indexed columns.'
+        );
+    }
+}
diff --git a/dev/tests/integration/testsuite/integrity/LayoutTest.php b/dev/tests/integration/testsuite/integrity/LayoutTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..71f3c0d40f90de900ab0448e392953a671f80828
--- /dev/null
+++ b/dev/tests/integration/testsuite/integrity/LayoutTest.php
@@ -0,0 +1,74 @@
+<?php
+/**
+ * Layout nodes integrity tests
+ *
+ * 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    tests
+ * @package     integration
+ * @subpackage  integrity
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+class Integrity_LayoutTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @param string $area
+     * @param string $package
+     * @param string $theme
+     * @dataProvider handleHierarchyDataProvider
+     */
+    public function testHandleHierarchy($area, $package, $theme)
+    {
+        $layoutUpdate = new Mage_Core_Model_Layout_Update(array(
+            'area' => $area, 'package' => $package, 'theme' => $theme
+        ));
+        $xml = $layoutUpdate->getFileLayoutUpdatesXml();
+        $handles = $xml->xpath('/layouts/*[@parent]') ?: array();
+        /** @var Mage_Core_Model_Layout_Element $node */
+        $errors = array();
+        foreach ($handles as $node) {
+            $parent = $node->getAttribute('parent');
+            if (!$xml->xpath("/layouts/{$parent}")) {
+                $errors[$node->getName()] = $parent;
+            }
+        }
+        if ($errors) {
+            $this->fail("Reference(s) to non-existing parent handle found at:\n" . var_export($errors, 1));
+        }
+    }
+
+    /**
+     * @return array
+     */
+    public function handleHierarchyDataProvider()
+    {
+        $result = array();
+        foreach (array('adminhtml', 'frontend', 'install') as $area) {
+            $result[] = array($area, false, false);
+            foreach (Mage::getDesign()->getDesignEntitiesStructure($area, false) as $package => $themes) {
+                foreach (array_keys($themes) as $theme) {
+                    $result[] = array($area, $package, $theme);
+                }
+            }
+        }
+        return $result;
+    }
+}
diff --git a/dev/tests/integration/testsuite/integrity/Mage/Payment/MethodsTest.php b/dev/tests/integration/testsuite/integrity/Mage/Payment/MethodsTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..5da1772856d96ae47a32670cc3872bb949ff1898
--- /dev/null
+++ b/dev/tests/integration/testsuite/integrity/Mage/Payment/MethodsTest.php
@@ -0,0 +1,76 @@
+<?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_Payment
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Locate all payment methods in the system and verify declaration of their blocks
+ *
+ * @group module:Mage_Payment
+ * @group integrity
+ */
+class Integrity_Mage_Payment_MethodsTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @param string $methodClass
+     * @dataProvider paymentMethodDataProvider
+     */
+    public function testFormInfoTemplates($methodClass)
+    {
+        $storeId = Mage::app()->getStore()->getId();
+        /** @var $model Mage_Payment_Model_Method_Abstract */
+        $model = new $methodClass;
+        foreach (array($model->getFormBlockType(), $model->getInfoBlockType()) as $blockClass) {
+            $message = "Block class: {$blockClass}";
+            $block = new $blockClass;
+            $block->setArea('frontend');
+            $this->assertFileExists($block->getTemplateFile(), $message);
+            if ($model->canUseInternal()) {
+                try {
+                    Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
+                    $block->setArea('adminhtml');
+                    $this->assertFileExists($block->getTemplateFile(), $message);
+                    Mage::app()->getStore()->setId($storeId);
+                } catch (Exception $e) {
+                    Mage::app()->getStore()->setId($storeId);
+                    throw $e;
+                }
+            }
+        }
+    }
+
+    /**
+     * @return array
+     */
+    public function paymentMethodDataProvider()
+    {
+        $helper = new Mage_Payment_Helper_Data;
+        $result = array();
+        foreach ($helper->getPaymentMethods() as $method) {
+            $result[] = array($method['model']);
+        }
+        return $result;
+    }
+}
diff --git a/dev/tests/integration/testsuite/integrity/modular/TemplateFilesTest.php b/dev/tests/integration/testsuite/integrity/modular/TemplateFilesTest.php
index bc123d31d2c51f0b9dd6dc26695e21d77d38c556..49e7b20c7b36cf13a6ca5e5f9757a8f34461f650 100644
--- a/dev/tests/integration/testsuite/integrity/modular/TemplateFilesTest.php
+++ b/dev/tests/integration/testsuite/integrity/modular/TemplateFilesTest.php
@@ -28,7 +28,7 @@
 /**
  * @group integrity
  */
-class Integrity_Modular_TemplateFilesTest extends Magento_Test_TestCase_IntegrityAbstract
+class Integrity_Modular_TemplateFilesTest extends PHPUnit_Framework_TestCase
 {
     /**
      * @param string $module
@@ -39,17 +39,11 @@ class Integrity_Modular_TemplateFilesTest extends Magento_Test_TestCase_Integrit
      */
     public function testAllTemplates($module, $template, $class, $area)
     {
-        if ((strpos($class, 'Enterprise') === 0 && strpos($class, '_Adminhtml') === false) || $area == 'frontend') {
-            $package = 'enterprise';
-        } else {
-            $package = 'default';
-        }
-
         $params = array(
-            '_area'     => $area,
-            '_package'  => $package,
-            '_theme'    => 'default',
-            '_module'   => $module
+            '_area'    => $area,
+            '_package' => 'nonexisting_package', // intentionally to make sure the module files will be requested
+            '_theme'   => 'nonexisting_theme',
+            '_module'  => $module
         );
         $file = Mage::getDesign()->getTemplateFilename($template, $params);
         $this->assertFileExists($file, "Block class: {$class}");
@@ -60,139 +54,26 @@ class Integrity_Modular_TemplateFilesTest extends Magento_Test_TestCase_Integrit
      */
     public function allTemplatesDataProvider()
     {
-        $excludeList = array(
-            'Mage_Checkout_Block_Onepage_Review',
-            'Enterprise_GiftRegistry_Block_Items',
-            'Enterprise_Search_Block_Catalog_Layer_View',
-            'Enterprise_Search_Block_Catalogsearch_Layer',
-        );
-
         $templates = array();
-        foreach ($this->_getEnabledModules() as $module) {
-            $blocks = $this->_getModuleBlocks($module);
-            foreach ($blocks as $blockClass) {
-                $isClassValid = strpos($blockClass, 'Abstract') === false
-                    && strpos($blockClass, 'Interface') === false
-                    && !in_array($blockClass, $excludeList);
-                if ($isClassValid) {
-                    $class = new ReflectionClass($blockClass);
-                    if ($class->isAbstract()) {
-                        continue;
-                    }
-                    $block = new $blockClass;
-                    if ($block instanceof Mage_Core_Block_Template) {
-                        $template = $block->getTemplate();
-                        if ($template && !$this->_isFileForDisabledModule($template)) {
-                            $area = $module == 'Mage_Install' ? 'install' : 'frontend';
-                            $useAdminArea = $module == 'Mage_Adminhtml' || strpos($blockClass, '_Adminhtml_')
-                                || ($block instanceof Mage_Adminhtml_Block_Template);
-                            if ($useAdminArea) {
-                                $area = 'adminhtml';
-                            }
-                            $templates[] = array($module, $template, $blockClass, $area);
-                        }
-                    }
-                }
+        foreach (Utility_Classes::collectModuleClasses('Block') as $blockClass => $module) {
+            $class = new ReflectionClass($blockClass);
+            if ($class->isAbstract() || !$class->isSubclassOf('Mage_Core_Block_Template')) {
+                continue;
             }
-        }
-        return $templates;
-    }
-
-    /**
-     * Get all block classes of specified module
-     *
-     * @param  string $module
-     * @return array
-     */
-    protected function _getModuleBlocks($module)
-    {
-        $classes = array();
-        $dir = Mage::getConfig()->getModuleDir('', $module) . DIRECTORY_SEPARATOR . 'Block';
-        if (!is_dir($dir)) {
-            return $classes;
-        }
-        $directory  = new RecursiveDirectoryIterator($dir);
-        $iterator   = new RecursiveIteratorIterator($directory);
-        $regex      = new RegexIterator($iterator, '/^.+\.php$/i', RecursiveRegexIterator::GET_MATCH);
-
-        foreach ($regex as $file) {
-            $class = str_replace($dir. DIRECTORY_SEPARATOR, '', $file[0]);
-            $class = str_replace('.php', '', $class);
-            $class = str_replace(DIRECTORY_SEPARATOR, '_', $class);
-            $class = $module . '_Block_' . $class;
-            $classes[] = $class;
-        }
-        return $classes;
-    }
-
-    /**
-     * @param string $blockClass
-     * @dataProvider blocksWithGlobalTemplatesDataProvider
-     */
-    public function testBlocksWithGlobalTemplates($blockClass)
-    {
-        $block = new $blockClass;
-        list($module) = explode('_Block_', $blockClass);
-        $file = Mage::getDesign()->getTemplateFilename($block->getTemplate(), array(
-            '_area' => 'adminhtml',
-            '_package'  => 'default',
-            '_theme'    => 'default',
-            '_module' => $module,
-        ));
-        $this->assertFileExists($file, $blockClass);
-    }
-
-    /**
-     * @return array
-     */
-    public function blocksWithGlobalTemplatesDataProvider()
-    {
-        // All possible files to test
-        $allBlocks = array(
-            array('Mage_Payment_Block_Form_Cc'),
-            array('Mage_Payment_Block_Form_Ccsave'),
-            array('Mage_Payment_Block_Form_Checkmo'),
-            array('Mage_Payment_Block_Form_Purchaseorder'),
-            array('Mage_Payment_Block_Info_Cc'),
-            array('Mage_Payment_Block_Info_Ccsave'),
-            array('Mage_Payment_Block_Info_Checkmo'),
-            array('Mage_Payment_Block_Info_Purchaseorder'),
-            array('Mage_Payment_Block_Info'),
-            array('Mage_Sales_Block_Payment_Form_Billing_Agreement'),
-            array('Mage_Sales_Block_Payment_Info_Billing_Agreement'),
-            array('Mage_Paygate_Block_Authorizenet_Form_Cc'),
-            array('Mage_Paygate_Block_Authorizenet_Info_Cc'),
-            array('Mage_Paypal_Block_Payment_Info'),
-            array('Mage_Authorizenet_Block_Directpost_Form'),
-            array('Mage_Authorizenet_Block_Directpost_Iframe'),
-            array('Mage_Ogone_Block_Info'),
-            array('Phoenix_Moneybookers_Block_Info'),
-        );
-
-        return $this->_removeDisabledModulesFiles($allBlocks);
-    }
-
-    /**
-     * Scans array of block class names and removes the ones that belong to disabled modules.
-     * Thus we won't test them.
-     *
-     * @param array $allBlocks
-     * @return array
-     */
-    protected function _removeDisabledModulesFiles($allBlocks)
-    {
-        $enabledModules = $this->_getEnabledModules();
-        $result = array();
-        foreach ($allBlocks as $blockInfo) {
-            $block = $blockInfo[0];
-            if (preg_match('/^(.*?)_Block/', $block, $matches)) {
-                $module = $matches[1];
-                if (!isset($enabledModules[$module])) {
-                    continue;
+            $block = new $blockClass;
+            $template = $block->getTemplate();
+            if ($template) {
+                $area = 'frontend';
+                if ($module == 'Mage_Install') {
+                    $area = 'install';
+                } elseif ($module == 'Mage_Adminhtml' || strpos($blockClass, '_Adminhtml_')
+                    || ($block instanceof Mage_Adminhtml_Block_Template)
+                ) {
+                    $area = 'adminhtml';
                 }
+                $templates[] = array($module, $template, $blockClass, $area);
             }
-            $result[] = $blockInfo;
         }
-        return $result;
+        return $templates;
     }
 }
diff --git a/dev/tests/integration/testsuite/integrity/theme/SkinFilesTest.php b/dev/tests/integration/testsuite/integrity/theme/SkinFilesTest.php
index 65298dd11011239acbb8583415f4f37529e5ccf9..44567c4ceb4bcd5981959636073a9a62a3412812 100644
--- a/dev/tests/integration/testsuite/integrity/theme/SkinFilesTest.php
+++ b/dev/tests/integration/testsuite/integrity/theme/SkinFilesTest.php
@@ -147,10 +147,11 @@ class Integrity_Theme_SkinFilesTest extends Magento_Test_TestCase_IntegrityAbstr
         }
 
         // Collect "addCss" and "addJs" from theme layout
-        $layout = Mage::app()->getLayout()->getUpdate()->getFileLayoutUpdatesXml(
-            $area, $package, $theme
+        $layoutUpdate = new Mage_Core_Model_Layout_Update(
+            array('area' => $area, 'package' => $package, 'theme' => $theme)
         );
-        $elements = $layout->xpath('//action[@method="addCss" or @method="addJs"]/*[1]');
+        $fileLayoutUpdates = $layoutUpdate->getFileLayoutUpdatesXml();
+        $elements = $fileLayoutUpdates->xpath('//action[@method="addCss" or @method="addJs"]/*[1]');
         if ($elements) {
             foreach ($elements as $filenameNode) {
                 $skinFile = (string)$filenameNode;
diff --git a/dev/tests/integration/testsuite/integrity/theme/TemplateFilesTest.php b/dev/tests/integration/testsuite/integrity/theme/TemplateFilesTest.php
index c46869ac8994a14e6e800852e6d22e8492a47705..aa4b9db936e56d6bf3697bf6ef7143d1d4db8034 100644
--- a/dev/tests/integration/testsuite/integrity/theme/TemplateFilesTest.php
+++ b/dev/tests/integration/testsuite/integrity/theme/TemplateFilesTest.php
@@ -63,9 +63,10 @@ class Integrity_Theme_TemplateFilesTest extends Magento_Test_TestCase_IntegrityA
         $themes = $this->_getDesignThemes();
         foreach ($themes as $view) {
             list($area, $package, $theme) = explode('/', $view);
-            $layoutUpdate = new Mage_Core_Model_Layout_Update();
-            $xml = $layoutUpdate->getFileLayoutUpdatesXml($area, $package, $theme);
-            $layoutTemplates = $this->_getLayoutTemplates($xml);
+            $layoutUpdate = new Mage_Core_Model_Layout_Update(
+                array('area' => $area, 'package' => $package, 'theme' => $theme)
+            );
+            $layoutTemplates = $this->_getLayoutTemplates($layoutUpdate->getFileLayoutUpdatesXml());
             foreach ($layoutTemplates as $templateData) {
                 $templates[] = array_merge(array($area, $package, $theme), $templateData);
             }
diff --git a/dev/tests/static/framework/bootstrap.php b/dev/tests/static/framework/bootstrap.php
index f5f9af2d0ef29a6dadc6b1f378dad61ed1dfcb03..ad63fe604919127a8e5d08ddb2b0663628988e2b 100644
--- a/dev/tests/static/framework/bootstrap.php
+++ b/dev/tests/static/framework/bootstrap.php
@@ -24,9 +24,6 @@
  * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
-if (!defined('PATH_TO_SOURCE_CODE')) {
-    define('PATH_TO_SOURCE_CODE', realpath(dirname(__FILE__) . '/../../../..'));
-}
 
 $includePath = array(
     __DIR__,
@@ -39,3 +36,5 @@ spl_autoload_register(function ($class) {
     $file = str_replace('_', '/', $class) . '.php';
     require_once $file;
 });
+
+Utility_Files::init(new Utility_Files(realpath(__DIR__ . '/../../../..')));
diff --git a/dev/tests/static/testsuite/Integrity/ClassesTest.php b/dev/tests/static/testsuite/Integrity/ClassesTest.php
index 13994e9ee65d6471741b930019a55c8e3bb38929..a6a92b42fa6a0b9ab473923000807a2cb6dff56d 100644
--- a/dev/tests/static/testsuite/Integrity/ClassesTest.php
+++ b/dev/tests/static/testsuite/Integrity/ClassesTest.php
@@ -37,13 +37,13 @@ class Integrity_ClassesTest extends PHPUnit_Framework_TestCase
 
     /**
      * @param string $file
-     * @dataProvider Util_Files::getPhpFiles
+     * @dataProvider phpFileDataProvider
      */
     public function testPhpFile($file)
     {
         self::skipBuggyFile($file);
         $contents = file_get_contents($file);
-        $classes = Util_Classes::getAllMatches($contents, '/
+        $classes = Utility_Classes::getAllMatches($contents, '/
             # ::getResourceModel ::getBlockSingleton ::getModel ::getSingleton
             \:\:get(?:ResourceModel | BlockSingleton | Model | Singleton)?\(\s*[\'"]([a-z\d_]+)[\'"]\s*[\),]
 
@@ -61,12 +61,13 @@ class Integrity_ClassesTest extends PHPUnit_Framework_TestCase
             # misc
             | function\s_getCollectionClass\(\)\s+{\s+return\s+[\'"]([a-z\d_]+)[\'"]
             | \'resource_model\'\s*=>\s*[\'"]([a-z\d_]+)[\'"]
-            | _parentResourceModelName\s*=\s*\'([a-z\d_]+)\'
+            | (?:_parentResourceModelName | _checkoutType | _apiType)\s*=\s*\'([a-z\d_]+)\'
+            | \'renderer\'\s*=>\s*\'([a-z\d_]+)\'
             /ix'
         );
 
         // without modifier "i". Starting from capital letter is a significant characteristic of a class name
-        Util_Classes::getAllMatches($contents, '/(?:\-> | parent\:\:)(?:_init | setType)\(\s*
+        Utility_Classes::getAllMatches($contents, '/(?:\-> | parent\:\:)(?:_init | setType)\(\s*
                 \'([A-Z][a-z\d][A-Za-z\d_]+)\'(?:,\s*\'([A-Z][a-z\d][A-Za-z\d_]+)\')
             \s*\)/x',
             $classes
@@ -77,6 +78,14 @@ class Integrity_ClassesTest extends PHPUnit_Framework_TestCase
         $this->_assertClassesExist($classes);
     }
 
+    /**
+     * @return array
+     */
+    public function phpFileDataProvider()
+    {
+        return Utility_Files::init()->getPhpFiles();
+    }
+
     /**
      * Special case: collect resource helper references in PHP-code
      *
@@ -85,7 +94,8 @@ class Integrity_ClassesTest extends PHPUnit_Framework_TestCase
      */
     protected function _collectResourceHelpersPhp($contents, &$classes)
     {
-        $matches = Util_Classes::getAllMatches($contents, '/(?:\:\:|\->)getResourceHelper\(\s*\'([a-z\d_]+)\'\s*\)/ix');
+        $regex = '/(?:\:\:|\->)getResourceHelper\(\s*\'([a-z\d_]+)\'\s*\)/ix';
+        $matches = Utility_Classes::getAllMatches($contents, $regex);
         foreach ($matches as $moduleName) {
             $classes[] = "{$moduleName}_Model_Resource_Helper_Mysql4";
         }
@@ -98,7 +108,7 @@ class Integrity_ClassesTest extends PHPUnit_Framework_TestCase
     public function testConfigFile($path)
     {
         self::skipBuggyFile($path);
-        $classes = Util_Classes::collectClassesInConfig(simplexml_load_file($path));
+        $classes = Utility_Classes::collectClassesInConfig(simplexml_load_file($path));
         $this->_assertClassesExist($classes);
     }
 
@@ -107,32 +117,40 @@ class Integrity_ClassesTest extends PHPUnit_Framework_TestCase
      */
     public function configFileDataProvider()
     {
-        return Util_Files::getConfigFiles();
+        return Utility_Files::init()->getConfigFiles();
     }
 
     /**
      * @param string $path
-     * @dataProvider Util_Files::getLayoutFiles
+     * @dataProvider layoutFileDataProvider
      */
     public function testLayoutFile($path)
     {
         self::skipBuggyFile($path);
         $xml = simplexml_load_file($path);
 
-        $classes = Util_Classes::getXmlNodeValues($xml,
+        $classes = Utility_Classes::getXmlNodeValues($xml,
             '/layout//*[contains(text(), "_Block_") or contains(text(), "_Model_") or contains(text(), "_Helper_")]'
         );
-        foreach (Util_Classes::getXmlAttributeValues($xml, '/layout//@helper', 'helper') as $class) {
-            $classes[] = Util_Classes::getCallbackClass($class);
+        foreach (Utility_Classes::getXmlAttributeValues($xml, '/layout//@helper', 'helper') as $class) {
+            $classes[] = Utility_Classes::getCallbackClass($class);
         }
-        foreach (Util_Classes::getXmlAttributeValues($xml, '/layout//@module', 'module') as $module) {
+        foreach (Utility_Classes::getXmlAttributeValues($xml, '/layout//@module', 'module') as $module) {
             $classes[] = "{$module}_Helper_Data";
         }
-        $classes = array_merge($classes, Util_Classes::collectLayoutClasses($xml));
+        $classes = array_merge($classes, Utility_Classes::collectLayoutClasses($xml));
 
         $this->_assertClassesExist(array_unique($classes));
     }
 
+    /**
+     * @return array
+     */
+    public function layoutFileDataProvider()
+    {
+        return Utility_Files::init()->getLayoutFiles();
+    }
+
     /**
      * Determine that some files must be skipped because implementation, broken by some bug
      *
@@ -184,12 +202,8 @@ class Integrity_ClassesTest extends PHPUnit_Framework_TestCase
                     $isBug = true;
                     continue;
                 }
-                $path = str_replace('_', DIRECTORY_SEPARATOR, $class) . '.php';
                 $this->assertTrue(isset(self::$_existingClasses[$class])
-                    || file_exists(PATH_TO_SOURCE_CODE . "/app/code/core/{$path}")
-                    || file_exists(PATH_TO_SOURCE_CODE . "/app/code/community/{$path}")
-                    || file_exists(PATH_TO_SOURCE_CODE . "/app/code/local/{$path}")
-                    || file_exists(PATH_TO_SOURCE_CODE . "/lib/{$path}")
+                    || Utility_Files::init()->codePoolClassFileExists($class)
                 );
                 self::$_existingClasses[$class] = 1;
             } catch (PHPUnit_Framework_AssertionFailedError $e) {
diff --git a/dev/tests/static/testsuite/Integrity/LayoutTest.php b/dev/tests/static/testsuite/Integrity/LayoutTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..b89126844fdce9e285c4a9ebf53bbcfdd0522b2b
--- /dev/null
+++ b/dev/tests/static/testsuite/Integrity/LayoutTest.php
@@ -0,0 +1,289 @@
+<?php
+/**
+ * Test constructions of layout 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.
+ *
+ * @category    tests
+ * @package     static
+ * @subpackage  Integrity
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Integrity_LayoutTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * Pattern for attribute elements, compatible with HTML ID
+     */
+    const HTML_ID_PATTERN = '/^[a-z][a-z\-\_\d]*$/';
+
+    /**
+     * @var array
+     */
+    protected static $_containerAliases = array();
+
+    /**
+     * @var array|bool
+     */
+    protected $_codeFrontendHandles = false;
+
+    /**
+     * @var array|bool
+     */
+    protected $_pageHandles = false;
+
+    /**
+     * Collect declarations of containers per layout file that have aliases
+     */
+    public static function setUpBeforeClass()
+    {
+        foreach (Utility_Files::init()->getLayoutFiles(array(), false) as $file) {
+            $xml = simplexml_load_file($file);
+            $containers = $xml->xpath('/layout//container[@as]') ?: array();
+            foreach ($containers as $node) {
+                $alias = (string)$node['as'];
+                self::$_containerAliases[$file][(string)$node['name']] = $alias;
+            }
+        }
+    }
+
+    /**
+     * Check count of layout handle labels that described in modules for frontend area
+     *
+     * @param string $handleName
+     * @param int $labelCount
+     *
+     * @dataProvider handleLabelCountDataProvider
+     */
+    public function testHandleLabelCount($handleName, $labelCount)
+    {
+         $this->assertSame($labelCount, 1, "Handle '{$handleName}' does not have a label or has more then one.'");
+    }
+
+    /**
+     * @return array
+     */
+    public function handleLabelCountDataProvider()
+    {
+        $handles = $this->_getCodeFrontendHandles();
+
+        $result = array();
+        foreach ($handles as $handleName => $data) {
+            $result[] = array($handleName, $data['label_count']);
+        }
+        return $result;
+    }
+
+    /**
+     * Check that all handles declared in a theme layout are declared in code
+     *
+     * @param string $handleName
+     * @dataProvider designHandlesDataProvider
+     */
+
+    public function testIsDesignHandleDeclaredInCode($handleName)
+    {
+        $this->assertArrayHasKey(
+            $handleName,
+            $this->_getCodeFrontendHandles(),
+            "Handle '{$handleName}' is not declared in any module.'"
+        );
+    }
+
+    /**
+     * @return array
+     */
+    public function designHandlesDataProvider()
+    {
+        $files = Utility_Files::init()->getLayoutFiles(array(
+            'include_code' => false,
+            'area' => 'frontend'
+        ));
+
+        $handles = array();
+        foreach (array_keys($files) as $path) {
+            $xml = simplexml_load_file($path);
+            $handleNodes = $xml->xpath('/layout/*') ?: array();
+            foreach ($handleNodes as $handleNode) {
+                $handles[] = $handleNode->getName();
+            }
+        }
+
+        $result = array();
+        foreach (array_unique($handles) as $handleName) {
+            $result[] = array($handleName);
+        }
+        return $result;
+    }
+
+    /**
+     * Returns information about handles that are declared in code for frontend
+     *
+     * @return array
+     */
+    protected function _getCodeFrontendHandles()
+    {
+        if ($this->_codeFrontendHandles) {
+            return $this->_codeFrontendHandles;
+        }
+
+        $files = Utility_Files::init()->getLayoutFiles(array(
+            'include_design' => false,
+            'area' => 'frontend'
+        ));
+        foreach (array_keys($files) as $path) {
+            $xml = simplexml_load_file($path);
+            $handleNodes = $xml->xpath('/layout/*') ?: array();
+            foreach ($handleNodes as $handleNode) {
+                $isLabel = $handleNode->xpath('label');
+                if (isset($handles[$handleNode->getName()]['label_count'])) {
+                    $handles[$handleNode->getName()]['label_count'] += (int)$isLabel;
+                } else {
+                    $handles[$handleNode->getName()]['label_count'] = (int)$isLabel;
+                }
+            }
+        }
+
+        $this->_codeFrontendHandles = $handles;
+        return $this->_codeFrontendHandles;
+    }
+
+    /**
+     * Suppressing PHPMD issues because this test is complex and it is not reasonable to separate it
+     *
+     * @param string $file
+     * @dataProvider layoutFilesDataProvider
+     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
+     * @SuppressWarnings(PHPMD.NPathComplexity)
+     * @SuppressWarnings(PHPMD.UnusedLocalVariable)
+     */
+    public function testContainerDeclaration($file)
+    {
+        $xml = simplexml_load_file($file);
+        $containers = $xml->xpath('/layout//container') ?: array();
+        $errors = array();
+        /** @var SimpleXMLElement $node */
+        foreach ($containers as $node) {
+            $nodeErrors = array();
+            $attr = $node->attributes();
+            if (!isset($attr['name'])) {
+                $nodeErrors[] = '"name" attribute is not specified';
+            } elseif (!preg_match('/^[a-z][a-z\-\_\d\.]*$/i', $attr['name'])) {
+                $nodeErrors[] = 'specified value for "name" attribute is invalid';
+            }
+            if (!isset($attr['label']) || '' == $attr['label']) {
+                $nodeErrors[] = '"label" attribute is not specified or empty';
+            }
+            if (isset($attr['as']) && !preg_match('/^[a-z\d\-\_]+$/i', $attr['as'])) {
+                $nodeErrors[] = 'specified value for "as" attribute is invalid';
+            }
+            if (isset($attr['htmlTag']) && !preg_match('/^[a-z]+$/', $attr['htmlTag'])) {
+                $nodeErrors[] = 'specified value for "htmlTag" attribute is invalid';
+            }
+            if (!isset($attr['htmlTag']) && (isset($attr['htmlId']) || isset($attr['htmlClass']))) {
+                $nodeErrors[] = 'having "htmlId" or "htmlClass" attributes don\'t make sense without "htmlTag"';
+            }
+            if (isset($attr['htmlId']) && !preg_match(self::HTML_ID_PATTERN, $attr['htmlId'])) {
+                $nodeErrors[] = 'specified value for "htmlId" attribute is invalid';
+            }
+            if (isset($attr['htmlClass']) && !preg_match(self::HTML_ID_PATTERN, $attr['htmlClass'])) {
+                $nodeErrors[] = 'specified value for "htmlClass" attribute is invalid';
+            }
+            $allowedAttributes = array('name', 'label', 'as', 'htmlTag', 'htmlId', 'htmlClass', 'module', 'output');
+            foreach ($attr as $key => $attribute) {
+                if (!in_array($key, $allowedAttributes)) {
+                    $nodeErrors[] = 'unexpected attribute "' . $key . '"';
+                }
+            }
+            if ($nodeErrors) {
+                $errors[] = "\n" . $node->asXML() . "\n - " . implode("\n - ", $nodeErrors);
+            }
+        }
+        if ($errors) {
+            $this->fail(implode("\n\n", $errors));
+        }
+    }
+
+    /**
+     * @param string $file
+     * @dataProvider layoutFilesDataProvider
+     */
+    public function testAjaxHandles($file)
+    {
+        $issues = array();
+        $xml = simplexml_load_file($file);
+        $handles = $xml->xpath('/layout//*[@parent="ajax_index"]');
+        if ($handles) {
+            foreach ($handles as $handle) {
+                if (!$handle->xpath('reference[@name="root"]')) {
+                    $issues[] = $handle->getName();
+                }
+            }
+        }
+        if (!empty($issues)) {
+            $this->fail(
+                sprintf('Hadle(s) "%s" in "%s" must contain reference to root', implode(', ', $issues), $file)
+            );
+        }
+    }
+
+    /**
+     * @return array
+     */
+    public function layoutFilesDataProvider()
+    {
+        return Utility_Files::init()->getLayoutFiles();
+    }
+
+    /**
+     * @param string $alias
+     * @dataProvider getChildBlockDataProvider
+     */
+    public function testBlocksNotContainers($alias)
+    {
+        foreach (self::$_containerAliases as $layoutFile => $containers) {
+            try {
+                $this->assertNotContains($alias, $containers,
+                    "The getChildBlock('{$alias}') is used, but this alias is declared for container in {$layoutFile}"
+                );
+            } catch (PHPUnit_Framework_ExpectationFailedException $e) {
+                $xml = simplexml_load_file($layoutFile);
+                // if there is a block with this alias, then most likely it will be used and container is ok
+                if (!$xml->xpath('/layout//block[@as="' . $alias . '"]')) {
+                    throw $e;
+                }
+            }
+        }
+    }
+
+    /**
+     * @return array
+     */
+    public function getChildBlockDataProvider()
+    {
+        $result = array();
+        foreach (Utility_Files::init()->getPhpFiles(true, false, true, false) as $file) {
+            $aliases = Utility_Classes::getAllMatches(file_get_contents($file), '/\->getChildBlock\(\'([^\']+)\'\)/x');
+            foreach ($aliases as $alias) {
+                $result[$file] = array($alias);
+            }
+        }
+        return $result;
+    }
+}
diff --git a/dev/tests/static/testsuite/Legacy/ClassesTest.php b/dev/tests/static/testsuite/Legacy/ClassesTest.php
index 392d45050ae87a33592cf9911eb96e1a889dbd22..47ce42612a377bad67062241a82c5cb26f3a3c8b 100644
--- a/dev/tests/static/testsuite/Legacy/ClassesTest.php
+++ b/dev/tests/static/testsuite/Legacy/ClassesTest.php
@@ -32,7 +32,7 @@ class Legacy_ClassesTest extends PHPUnit_Framework_TestCase
 {
     /**
      * @param string $file
-     * @dataProvider Util_Files::getPhpFiles
+     * @dataProvider phpCodeDataProvider
      */
     public function testPhpCode($file)
     {
@@ -40,6 +40,14 @@ class Legacy_ClassesTest extends PHPUnit_Framework_TestCase
         $this->_assertNonFactoryName($classes);
     }
 
+    /**
+     * @return array
+     */
+    public function phpCodeDataProvider()
+    {
+        return Utility_Files::init()->getPhpFiles();
+    }
+
     /**
      * Scan contents as PHP-code and find class name occurrences
      *
@@ -49,7 +57,7 @@ class Legacy_ClassesTest extends PHPUnit_Framework_TestCase
      */
     public static function collectPhpCodeClasses($contents, &$classes = array())
     {
-        Util_Classes::getAllMatches($contents, '/
+        Utility_Classes::getAllMatches($contents, '/
             # ::getModel ::getSingleton ::getResourceModel ::getResourceSingleton
             \:\:get(?:Resource)?(?:Model | Singleton)\(\s*[\'"]([^\'"]+)[\'"]\s*[\),]
 
@@ -74,7 +82,9 @@ class Legacy_ClassesTest extends PHPUnit_Framework_TestCase
 
             # misc
             | function\s_getCollectionClass\(\)\s+{\s+return\s+[\'"]([a-z\d_\/]+)[\'"]
-            | _parentResourceModelName\s*=\s*\'([a-z\d_\/]+)\'
+            | (?:_parentResourceModelName | _checkoutType | _apiType)\s*=\s*\'([a-z\d_\/]+)\'
+            | \'renderer\'\s*=>\s*\'([a-z\d_\/]+)\'
+            | protected\s+\$_(?:form|info)BlockType\s*=\s*[\'"]([^\'"]+)[\'"]
 
             /Uix',
             $classes
@@ -84,7 +94,7 @@ class Legacy_ClassesTest extends PHPUnit_Framework_TestCase
         $skipForInit = implode('|',
             array('id', '[\w\d_]+_id', 'pk', 'code', 'status', 'serial_number', 'entity_pk_value', 'currency_code')
         );
-        Util_Classes::getAllMatches($contents, '/
+        Utility_Classes::getAllMatches($contents, '/
             (?:parent\:\: | \->)_init\(\s*[\'"]([^\'"]+)[\'"]\s*\)
             | (?:parent\:\: | \->)_init\(\s*[\'"]([^\'"]+)[\'"]\s*,\s*[\'"]((?!(' . $skipForInit . '))[^\'"]+)[\'"]\s*\)
             /Uix',
@@ -101,10 +111,10 @@ class Legacy_ClassesTest extends PHPUnit_Framework_TestCase
     {
         $xml = simplexml_load_file($path);
 
-        $classes = Util_Classes::collectClassesInConfig($xml);
+        $classes = Utility_Classes::collectClassesInConfig($xml);
         $this->_assertNonFactoryName($classes);
 
-        $modules = Util_Classes::getXmlAttributeValues($xml, '//@module', 'module');
+        $modules = Utility_Classes::getXmlAttributeValues($xml, '//@module', 'module');
         $this->_assertNonFactoryName(array_unique($modules));
     }
 
@@ -113,7 +123,7 @@ class Legacy_ClassesTest extends PHPUnit_Framework_TestCase
      */
     public function configFileDataProvider()
     {
-        return Util_Files::getConfigFiles();
+        return Utility_Files::init()->getConfigFiles();
     }
 
     /**
@@ -123,11 +133,11 @@ class Legacy_ClassesTest extends PHPUnit_Framework_TestCase
     public function testLayouts($path)
     {
         $xml = simplexml_load_file($path);
-        $classes = Util_Classes::collectLayoutClasses($xml);
-        foreach (Util_Classes::getXmlAttributeValues($xml, '/layout//@helper', 'helper') as $class) {
-            $classes[] = Util_Classes::getCallbackClass($class);
+        $classes = Utility_Classes::collectLayoutClasses($xml);
+        foreach (Utility_Classes::getXmlAttributeValues($xml, '/layout//@helper', 'helper') as $class) {
+            $classes[] = Utility_Classes::getCallbackClass($class);
         }
-        $classes = array_merge($classes, Util_Classes::getXmlAttributeValues($xml, '/layout//@module', 'module'));
+        $classes = array_merge($classes, Utility_Classes::getXmlAttributeValues($xml, '/layout//@module', 'module'));
         $this->_assertNonFactoryName(array_unique($classes));
     }
 
@@ -136,7 +146,7 @@ class Legacy_ClassesTest extends PHPUnit_Framework_TestCase
      */
     public function layoutFileDataProvider()
     {
-        return Util_Files::getLayoutFiles();
+        return Utility_Files::init()->getLayoutFiles();
     }
 
     /**
diff --git a/dev/tests/static/testsuite/Legacy/ConfigTest.php b/dev/tests/static/testsuite/Legacy/ConfigTest.php
index a9cdb9739e11a005b3344a23626c7e573dc675ce..1944e802c07336813bdc5632ea1784e14749ee4f 100644
--- a/dev/tests/static/testsuite/Legacy/ConfigTest.php
+++ b/dev/tests/static/testsuite/Legacy/ConfigTest.php
@@ -47,6 +47,8 @@ class Legacy_ConfigTest extends PHPUnit_Framework_TestCase
             '/config/global/models/*/resourceModel'    => '',
             '/config/adminhtml/menu'                   => 'Move them to adminhtml.xml.',
             '/config/adminhtml/acl'                    => 'Move them to adminhtml.xml.',
+            '/config/*/events/core_block_abstract_to_html_after' =>
+                'Event has been replaced with "core_layout_render_element"',
         );
         $xml = simplexml_load_file($file);
         foreach ($obsoleteNodes as $xpath => $suggestion) {
@@ -62,6 +64,6 @@ class Legacy_ConfigTest extends PHPUnit_Framework_TestCase
      */
     public function configFileDataProvider()
     {
-        return Util_Files::getConfigFiles('config.xml');
+        return Utility_Files::init()->getConfigFiles('config.xml');
     }
 }
diff --git a/dev/tests/static/testsuite/Legacy/EmailTemplateTest.php b/dev/tests/static/testsuite/Legacy/EmailTemplateTest.php
index c48e9f0ca8ba53317dbb7591f112b5706696a1f4..10db55b4c3591815308e8ab627d787ce73958ef8 100644
--- a/dev/tests/static/testsuite/Legacy/EmailTemplateTest.php
+++ b/dev/tests/static/testsuite/Legacy/EmailTemplateTest.php
@@ -46,6 +46,6 @@ class Legacy_EmailTemplateTest extends PHPUnit_Framework_TestCase
 
     public function obsoleteDirectivesDataProvider()
     {
-        return Util_Files::getEmailTemplates();
+        return Utility_Files::init()->getEmailTemplates();
     }
 }
diff --git a/dev/tests/static/testsuite/Legacy/FilesystemTest.php b/dev/tests/static/testsuite/Legacy/FilesystemTest.php
index 8a9ba2a978842b012bca71b86a7c4df264bcbcdc..d36603fb91f161c1e5094eda40d2c35cdf0a98bd 100644
--- a/dev/tests/static/testsuite/Legacy/FilesystemTest.php
+++ b/dev/tests/static/testsuite/Legacy/FilesystemTest.php
@@ -36,7 +36,7 @@ class Legacy_FilesystemTest extends PHPUnit_Framework_TestCase
      */
     public function testRelocations($path)
     {
-        $this->assertFileNotExists(realpath(__DIR__ . '/../../../../..') . DIRECTORY_SEPARATOR . $path);
+        $this->assertFileNotExists(Utility_Files::init()->getPathToSource() . DIRECTORY_SEPARATOR . $path);
     }
 
     public function relocationsDataProvider()
@@ -48,6 +48,35 @@ class Legacy_FilesystemTest extends PHPUnit_Framework_TestCase
             array('Relocated to pub/media' => 'media'),
             array('Eliminated as not needed' => 'pkginfo'),
             array('Dissolved into themes under app/design ' => 'skin'),
+            array('Dissolved into different modules\' view/frontend' => 'app/design/frontend/base'),
         );
     }
+
+    public function testObsoleteDirectories()
+    {
+        $area    = '*';
+        $package = '*';
+        $theme   = '*';
+        $root = Utility_Files::init()->getPathToSource();
+        $dirs = glob("{$root}/app/design/{$area}/{$package}/{$theme}/template", GLOB_ONLYDIR);
+        $msg = array();
+        if ($dirs) {
+            $msg[] = 'Theme "template" directories are obsolete. Relocate files as follows:';
+            foreach ($dirs as $dir) {
+                $msg[] = str_replace($root, '',
+                    "{$dir} => " . realpath($dir . '/..') . '/Namespace_Module/*'
+                );
+            }
+        }
+
+        $dirs = glob("{$root}/app/design/{$area}/{$package}/{$theme}/layout", GLOB_ONLYDIR);
+        if ($dirs) {
+            $msg[] = 'Theme "layout" directories are obsolete. Relocate layout files into the root of theme directory.';
+            $msg = array_merge($msg, $dirs);
+        }
+
+        if ($msg) {
+            $this->fail(implode(PHP_EOL, $msg));
+        }
+    }
 }
diff --git a/dev/tests/static/testsuite/Legacy/LayoutTest.php b/dev/tests/static/testsuite/Legacy/LayoutTest.php
index e3e6c502cfd00dab038f6b063fd2f316a2cddceb..c64dbe6ac5b6870b605bdc3f1fcc57f978383357 100644
--- a/dev/tests/static/testsuite/Legacy/LayoutTest.php
+++ b/dev/tests/static/testsuite/Legacy/LayoutTest.php
@@ -30,7 +30,16 @@
  */
 class Legacy_LayoutTest extends PHPUnit_Framework_TestCase
 {
+    protected $_obsoleteNodes = array(
+        'PRODUCT_TYPE_simple', 'PRODUCT_TYPE_configurable', 'PRODUCT_TYPE_grouped', 'PRODUCT_TYPE_bundle',
+        'PRODUCT_TYPE_virtual', 'PRODUCT_TYPE_downloadable', 'PRODUCT_TYPE_giftcard',
+        'catalog_category_default', 'catalog_category_layered', 'catalog_category_layered_nochildren',
+        'customer_logged_in', 'customer_logged_out', 'customer_logged_in_psc_handle', 'customer_logged_out_psc_handle',
+        'cms_page',
+    );
+
     /**
+     * @param string $layoutFile
      * @dataProvider layoutFileDataProvider
      */
     public function testLayoutFile($layoutFile)
@@ -50,10 +59,31 @@ class Legacy_LayoutTest extends PHPUnit_Framework_TestCase
             ),
             "Calls addCss/addJs are allowed within the 'head' block only. Verify integrity of the nodes nesting."
         );
+        $this->assertEmpty(
+            $layoutXml->xpath('/layout/*[@output="toHtml"]'), 'output="toHtml" is obsolete. Use output="1"'
+        );
+        foreach ($layoutXml as $handle) {
+            $this->assertNotContains($handle->getName(), $this->_obsoleteNodes, 'Layout handle was removed.');
+        }
+        foreach ($layoutXml->xpath('@helper') as $action) {
+            $this->assertNotContains('/', $action->getAtrtibute('helper'));
+            $this->assertContains('::', $action->getAtrtibute('helper'));
+        }
+        if (false !== strpos($layoutFile, 'app/code/core/Mage/Adminhtml/view/adminhtml/sales.xml')) {
+            $this->markTestIncomplete("The file {$layoutFile} has to use Mage_Core_Block_Text_List, \n"
+                . 'there is no solution to get rid of it right now.'
+            );
+        }
+        $this->assertEmpty($layoutXml->xpath('/layout//block[@type="Mage_Core_Block_Text_List"]'),
+            'The class Mage_Core_Block_Text_List is not supposed to be used in layout anymore.'
+        );
     }
 
+    /**
+     * @return array
+     */
     public function layoutFileDataProvider()
     {
-        return Util_Files::getLayoutFiles();
+        return Utility_Files::init()->getLayoutFiles();
     }
 }
diff --git a/dev/tests/static/testsuite/Legacy/LicenseTest.php b/dev/tests/static/testsuite/Legacy/LicenseTest.php
index c566b01295dffc0b4a96604020c5f17c25b5ae88..1608acdd71b4cfb511e9e91a3a14dfa1261da8f3 100644
--- a/dev/tests/static/testsuite/Legacy/LicenseTest.php
+++ b/dev/tests/static/testsuite/Legacy/LicenseTest.php
@@ -53,16 +53,17 @@ class Legacy_LicenseTest extends PHPUnit_Framework_TestCase
 
     public function legacyCommentDataProvider()
     {
+        $root = Utility_Files::init()->getPathToSource();
         $recursiveIterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(
-            PATH_TO_SOURCE_CODE, FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS
+            $root, FilesystemIterator::SKIP_DOTS | FilesystemIterator::UNIX_PATHS
         ));
 
-        $rootFolderName = substr(strrchr(PATH_TO_SOURCE_CODE, DIRECTORY_SEPARATOR), 1);
+        $rootFolderName = substr(strrchr($root, DIRECTORY_SEPARATOR), 1);
         $extensions = '(xml|css|php|phtml|js|dist|sample|additional)';
         $paths =  array(
             $rootFolderName . '/[^/]+\.' . $extensions,
             $rootFolderName . '/app/.+\.' . $extensions,
-            $rootFolderName . '/dev/(?!tests/integration/tmp).+\.' . $extensions,
+            $rootFolderName . '/dev/(?!tests/integration/tmp|tests/functional).+\.' . $extensions,
             $rootFolderName . '/downloader/.+\.' . $extensions,
             $rootFolderName . '/lib/(Mage|Magento|Varien)/.+\.' . $extensions,
             $rootFolderName . '/pub/.+\.' . $extensions,
diff --git a/dev/tests/static/testsuite/Legacy/Mage/Core/Block/AbstractTest.php b/dev/tests/static/testsuite/Legacy/Mage/Core/Block/AbstractTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..d362c3b95dc8d43311eb0203a01198a5099bbb96
--- /dev/null
+++ b/dev/tests/static/testsuite/Legacy/Mage/Core/Block/AbstractTest.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.
+ *
+ * @category    tests
+ * @package     static
+ * @subpackage  Legacy
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * Tests usage of Mage_Core_Block_Abstract
+ */
+class Legacy_Mage_Core_Block_AbstractTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * Tests if methods are used with correct count of parameters
+     *
+     * @param string $file
+     * @dataProvider phpFilesDataProvider
+     */
+    public function testGetChildHtml($file)
+    {
+        $result = Utility_Classes::getAllMatches(
+            file_get_contents($file),
+            "/(->(getChildHtml|getChildChildHtml)\([^,)]+, ?[^,)]+, ?[^,)]+\))/i"
+        );
+        $this->assertEmpty(
+            $result,
+            "3rd parameter is used while calling getChildHtml() in '$file': " . print_r($result, true)
+        );
+    }
+
+    public function phpFilesDataProvider()
+    {
+        return Utility_Files::init()->getPhpFiles();
+    }
+}
diff --git a/dev/tests/static/testsuite/Legacy/Mage/Widget/XmlTest.php b/dev/tests/static/testsuite/Legacy/Mage/Widget/XmlTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..615f1ef5717bfe89a8c74c3c22a6d23d13b12431
--- /dev/null
+++ b/dev/tests/static/testsuite/Legacy/Mage/Widget/XmlTest.php
@@ -0,0 +1,72 @@
+<?php
+/**
+ * Test VS backwards-incompatible changes in widget.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.
+ *
+ * @category    tests
+ * @package     static
+ * @subpackage  Legacy
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * A test for backwards-incompatible change in widget.xml structure
+ */
+class Legacy_Mage_Widget_XmlTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @param string $file
+     * @dataProvider widgetXmlFilesDataProvider
+     */
+    public function testClassFactoryNames($file)
+    {
+        $xml = simplexml_load_file($file);
+        $nodes = $xml->xpath('/widgets/*[@type]') ?: array();
+        /** @var SimpleXMLElement $node */
+        foreach ($nodes as $node) {
+            $type = (string)$node['type'];
+            $this->assertNotRegExp('/\//', $type, "Factory name detected: {$type}.");
+        }
+    }
+
+    /**
+     * @param string $file
+     * @dataProvider widgetXmlFilesDataProvider
+     */
+    public function testBlocksIntoContainers($file)
+    {
+        $xml = simplexml_load_file($file);
+        $this->assertSame(array(), $xml->xpath('/widgets/*/supported_blocks'),
+            'Obsolete node: <supported_blocks>. To be replaced with <supported_containers>'
+        );
+        $this->assertSame(array(), $xml->xpath('/widgets/*/*/*/block_name'),
+            'Obsolete node: <block_name>. To be replaced with <container_name>'
+        );
+    }
+
+    /**
+     * @return array
+     */
+    public function widgetXmlFilesDataProvider()
+    {
+        return Utility_Files::init()->getConfigFiles('widget.xml');
+    }
+}
diff --git a/dev/tests/static/testsuite/Legacy/ObsoleteCodeTest.php b/dev/tests/static/testsuite/Legacy/ObsoleteCodeTest.php
index 7a719d40852afd5989fc0c4138c89506fd0b72c4..bba2fb96de6f10eaff2d130b12ad4d70eaab0c2f 100644
--- a/dev/tests/static/testsuite/Legacy/ObsoleteCodeTest.php
+++ b/dev/tests/static/testsuite/Legacy/ObsoleteCodeTest.php
@@ -50,12 +50,12 @@ class Legacy_ObsoleteCodeTest extends PHPUnit_Framework_TestCase
     public function testPhpFile($file)
     {
         $content = file_get_contents($file);
-        $this->_testObsoleteClasses($content);
-        $this->_testObsoleteMethods($content);
+        $this->_testObsoleteClasses($content, $file);
+        $this->_testObsoleteMethods($content, $file);
         $this->_testObsoleteMethodArguments($content);
-        $this->_testObsoleteProperties($content);
-        $this->_testObsoleteActions($content);
-        $this->_testObsoleteConstants($content);
+        $this->_testObsoleteProperties($content, $file);
+        $this->_testObsoleteActions($content, $file);
+        $this->_testObsoleteConstants($content, $file);
         $this->_testObsoletePropertySkipCalculate($content);
     }
 
@@ -64,7 +64,7 @@ class Legacy_ObsoleteCodeTest extends PHPUnit_Framework_TestCase
      */
     public function phpFileDataProvider()
     {
-        return Util_Files::getPhpFiles();
+        return Utility_Files::init()->getPhpFiles();
     }
 
     /**
@@ -74,7 +74,7 @@ class Legacy_ObsoleteCodeTest extends PHPUnit_Framework_TestCase
     public function testXmlFile($file)
     {
         $content = file_get_contents($file);
-        $this->_testObsoleteClasses($content);
+        $this->_testObsoleteClasses($content, $file);
     }
 
     /**
@@ -82,7 +82,7 @@ class Legacy_ObsoleteCodeTest extends PHPUnit_Framework_TestCase
      */
     public function xmlFileDataProvider()
     {
-        return Util_Files::getXmlFiles();
+        return Utility_Files::init()->getXmlFiles();
     }
 
     /**
@@ -100,15 +100,16 @@ class Legacy_ObsoleteCodeTest extends PHPUnit_Framework_TestCase
      */
     public function jsFileDataProvider()
     {
-        return Util_Files::getJsFiles();
+        return Utility_Files::init()->getJsFiles();
     }
 
     /**
      * @param string $content
+     * @param string $file
      */
-    protected function _testObsoleteClasses($content)
+    protected function _testObsoleteClasses($content, $file)
     {
-        $declarations = $this->_getRelevantConfigEntities('obsolete_classes*.php', $content);
+        $declarations = $this->_getRelevantConfigEntities('obsolete_classes*.php', $content, $file);
         foreach ($declarations as $entity => $suggestion) {
             $this->assertNotRegExp(
                 '/[^a-z\d_]' . preg_quote($entity, '/') . '[^a-z\d_]/iS',
@@ -120,15 +121,14 @@ class Legacy_ObsoleteCodeTest extends PHPUnit_Framework_TestCase
 
     /**
      * @param string $content
+     * @param string $file
      */
-    protected function _testObsoleteMethods($content)
+    protected function _testObsoleteMethods($content, $file)
     {
-        $declarations = $this->_getRelevantConfigEntities('obsolete_methods*.php', $content);
-        foreach ($declarations as $entity => $suggestion) {
-            $this->assertNotRegExp(
-                '/[^a-z\d_]' . preg_quote($entity, '/') . '\s*\(/iS',
-                $content,
-                "Method '$entity' is obsolete. $suggestion"
+        $declarations = $this->_getRelevantConfigEntities('obsolete_methods*.php', $content, $file);
+        foreach ($declarations as $method => $suggestion) {
+            $this->assertNotRegExp('/[^a-z\d_]' . preg_quote($method, '/') . '\s*\(/iS',
+                $content, "Method '$method' is obsolete. $suggestion"
             );
         }
     }
@@ -138,20 +138,22 @@ class Legacy_ObsoleteCodeTest extends PHPUnit_Framework_TestCase
      */
     protected function _testObsoleteMethodArguments($content)
     {
-        $suggestion = 'Remove arguments, refactor code to treat returned type instance as a singleton.';
-        $this->assertNotRegExp(
-            '/[^a-z\d_]getTypeInstance\s*\(\s*[^\)]+/iS',
-            $content,
-            "Method 'getTypeInstance' is called with obsolete arguments. $suggestion"
+        $this->assertNotRegExp('/[^a-z\d_]getTypeInstance\s*\(\s*[^\)]+/iS', $content,
+            'Backwards-incompatible change: method getTypeInstance() is not supposed to be invoked with any arguments.'
+        );
+        $this->assertNotRegExp('/\->getUsedProductIds\(([^\)]+,\s*[^\)]+)?\)/', $content,
+            'Backwards-incompatible change: method getUsedProductIds($product)'
+            . ' must be invoked with one and only one argument - product model object'
         );
     }
 
     /**
      * @param string $content
+     * @param string $file
      */
-    protected function _testObsoleteProperties($content)
+    protected function _testObsoleteProperties($content, $file)
     {
-        $declarations = $this->_getRelevantConfigEntities('obsolete_properties*.php', $content);
+        $declarations = $this->_getRelevantConfigEntities('obsolete_properties*.php', $content, $file);
         foreach ($declarations as $entity => $suggestion) {
             $this->assertNotRegExp(
                 '/[^a-z\d_]' . preg_quote($entity, '/') . '[^a-z\d_]/iS',
@@ -176,10 +178,11 @@ class Legacy_ObsoleteCodeTest extends PHPUnit_Framework_TestCase
 
     /**
      * @param string $content
+     * @param string $file
      */
-    protected function _testObsoleteConstants($content)
+    protected function _testObsoleteConstants($content, $file)
     {
-        $declarations = $this->_getRelevantConfigEntities('obsolete_constants*.php', $content);
+        $declarations = $this->_getRelevantConfigEntities('obsolete_constants*.php', $content, $file);
         foreach ($declarations as $entity => $suggestion) {
             $this->assertNotRegExp(
                 '/[^a-z\d_]' . preg_quote($entity, '/') . '[^a-z\d_]/iS',
@@ -210,9 +213,10 @@ class Legacy_ObsoleteCodeTest extends PHPUnit_Framework_TestCase
      *
      * @param string $fileNamePattern
      * @param string $content
+     * @param string $file
      * @return array
      */
-    protected function _getRelevantConfigEntities($fileNamePattern, $content)
+    protected function _getRelevantConfigEntities($fileNamePattern, $content, $file)
     {
         $result = array();
         foreach ($this->_loadConfigFiles($fileNamePattern) as $entity => $info) {
@@ -222,6 +226,11 @@ class Legacy_ObsoleteCodeTest extends PHPUnit_Framework_TestCase
             if ($class && (!strpos($content, $class) || !preg_match($regexp, $content))) {
                 continue;
             }
+            if ($info['directory']) {
+                if (0 !== strpos(str_replace('\\', '/', $file), str_replace('\\', '/', $info['directory']))) {
+                    continue;
+                }
+            }
             $result[$entity] = $info['suggestion'];
         }
         return $result;
@@ -264,21 +273,19 @@ class Legacy_ObsoleteCodeTest extends PHPUnit_Framework_TestCase
     {
         $result = array();
         foreach ($config as $key => $value) {
-            $entity = is_string($key) ? $key : $value;
-            $class = null;
-            $suggestion = null;
-            if (is_array($value)) {
-                if (isset($value['class_scope'])) {
-                    $class = $value['class_scope'];
+            $row = array('suggestion' => null, 'class_scope' => null, 'directory' => null);
+            if (is_string($key)) {
+                $row = array_merge($row, $value);
+                if ($row['suggestion']) {
+                    $row['suggestion'] = sprintf(self::SUGGESTION_MESSAGE, $row['suggestion']);
                 }
-                if (isset($value['suggestion'])) {
-                    $suggestion = sprintf(self::SUGGESTION_MESSAGE, $value['suggestion']);
+                if ($row['directory']) {
+                    $row['directory'] = Utility_Files::init()->getPathToSource() . '/' . $row['directory'];
                 }
+                $result[$key] = $row;
+            } else {
+                $result[$value] = $row;
             }
-            $result[$entity] = array(
-                'suggestion' => $suggestion,
-                'class_scope' => $class
-            );
         }
         return $result;
     }
diff --git a/dev/tests/static/testsuite/Legacy/TableTest.php b/dev/tests/static/testsuite/Legacy/TableTest.php
index 22339a457590dfee2dc8885cf242482a1332a440..e0ac0b88b04cb475dfa2693b1ccb0a38a8ea838d 100644
--- a/dev/tests/static/testsuite/Legacy/TableTest.php
+++ b/dev/tests/static/testsuite/Legacy/TableTest.php
@@ -232,6 +232,6 @@ class Legacy_TableTest extends PHPUnit_Framework_TestCase
      */
     public function tableNameDataProvider()
     {
-        return Util_Files::getPhpFiles();
+        return Utility_Files::init()->getPhpFiles();
     }
 }
diff --git a/dev/tests/static/testsuite/Legacy/_files/obsolete_classes.php b/dev/tests/static/testsuite/Legacy/_files/obsolete_classes.php
index ffbf1c92249611be64595ffd4ed5a4c71f305930..22eefd2e05d9bb951e0858c871dbe030db177645 100644
--- a/dev/tests/static/testsuite/Legacy/_files/obsolete_classes.php
+++ b/dev/tests/static/testsuite/Legacy/_files/obsolete_classes.php
@@ -25,36 +25,64 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 return array(
-    'Mage_XmlConnect_Helper_Payment',
+    'Mage_Admin_Model_Acl_Role',
+    'Mage_Admin_Model_Resource_Acl_Role',
+    'Mage_Admin_Model_Resource_Acl_Role_Collection',
+    'Mage_Adminhtml_Block_Api_Edituser',
+    'Mage_Adminhtml_Block_Api_Tab_Userroles',
+    'Mage_Adminhtml_Block_Catalog',
+    'Mage_Adminhtml_Block_Permissions_Edituser',
+    'Mage_Adminhtml_Block_Permissions_Tab_Userroles',
+    'Mage_Adminhtml_Block_Permissions_Usernroles',
+    'Mage_Adminhtml_Block_Report_Product_Ordered',
+    'Mage_Adminhtml_Block_Report_Product_Ordered_Grid',
+    'Mage_Adminhtml_Block_Sales',
+    'Mage_Adminhtml_Block_Sales_Order_Create_Search_Grid_Renderer_Giftmessage',
+    'Mage_Adminhtml_Block_Tag_Tag_Edit',
+    'Mage_Adminhtml_Block_Tag_Tag_Edit_Form',
+    'Mage_Adminhtml_Block_Tree',
+    'Mage_Adminhtml_Helper_Rss',
+    'Mage_Adminhtml_Model_System_Config_Source_Shipping_Allowedmethods',
+    'Mage_Adminhtml_Rss_CatalogController',
+    'Mage_Adminhtml_Rss_OrderController',
+    'Mage_Bundle_Product_EditController' => array('suggestion' => 'Mage_Bundle_Adminhtml_Bundle_SelectionController'),
+    'Mage_Bundle_SelectionController' => array('suggestion' => 'Mage_Bundle_Adminhtml_Bundle_SelectionController'),
     'Mage_Catalog_Model_Entity_Product_Attribute_Frontend_Image',
     'Mage_Catalog_Model_Resource_Product_Attribute_Frontend_Image',
-    'Mage_Bundle_SelectionController' => array('suggestion' => 'Mage_Bundle_Adminhtml_Bundle_SelectionController'),
-    'Mage_Bundle_Product_EditController' => array('suggestion' => 'Mage_Bundle_Adminhtml_Bundle_SelectionController'),
+    'Mage_Catalog_Model_Resource_Product_Attribute_Frontend_Tierprice',
+    'Mage_Core_Model_Design_Source_Apply',
+    'Mage_Core_Model_Language',
+    'Mage_Core_Model_Resource_Language',
+    'Mage_Core_Model_Resource_Language_Collection',
+    'Mage_Core_Model_Session_Abstract_Varien',
+    'Mage_Core_Model_Session_Abstract_Zend',
+    'Mage_Customer_Block_Account',
+    'Mage_Directory_Model_Resource_Currency_Collection',
     'Mage_Downloadable_FileController' => array(
         'suggestion' => 'Mage_Downloadable_Adminhtml_Downloadable_FileController'
     ),
     'Mage_Downloadable_Product_EditController' => array('suggestion' => 'Mage_Adminhtml_Catalog_ProductController'),
+    'Mage_GiftMessage_Block_Message_Form',
+    'Mage_GiftMessage_Block_Message_Helper',
     'Mage_GiftMessage_IndexController',
+    'Mage_GiftMessage_Model_Entity_Attribute_Backend_Boolean_Config',
+    'Mage_GiftMessage_Model_Entity_Attribute_Source_Boolean_Config',
     'Mage_GoogleOptimizer_IndexController' => array(
         'suggestion' => 'Mage_GoogleOptimizer_Adminhtml_Googleoptimizer_IndexController'
     ),
-    'Mage_Shipping_ShippingController',
+    'Mage_Ogone_Model_Api_Debug',
+    'Mage_Ogone_Model_Resource_Api_Debug',
     'Mage_Page_Block_Html_Toplinks',
+    'Mage_Page_Block_Html_Wrapper',
+    'Mage_Poll_Block_Poll',
     'Mage_ProductAlert_Block_Price',
     'Mage_ProductAlert_Block_Stock',
+    'Mage_Reports_Model_Resource_Coupons_Collection',
+    'Mage_Reports_Model_Resource_Invoiced_Collection',
+    'Mage_Reports_Model_Resource_Refunded_Collection',
+    'Mage_Reports_Model_Resource_Shipping_Collection',
     'Mage_Sales_Block_Order_Details',
     'Mage_Sales_Block_Order_Tax',
-    'Mage_Tag_Block_Customer_Edit',
-    'Mage_Sales_Model_Entity_Setup',
-    'Mage_Core_Model_Language',
-    'Mage_Core_Model_Resource_Language',
-    'Mage_Core_Model_Resource_Language_Collection',
-    'Mage_Adminhtml_Model_System_Config_Source_Shipping_Allowedmethods',
-    'Mage_Adminhtml_Block_Tag_Tag_Edit',
-    'Mage_Adminhtml_Block_Tag_Tag_Edit_Form',
-    'Mage_Adminhtml_Block_Sales_Order_Create_Search_Grid_Renderer_Giftmessage',
-    'Mage_Adminhtml_Block_Report_Product_Ordered',
-    'Mage_Adminhtml_Block_Report_Product_Ordered_Grid',
     'Mage_Sales_Model_Entity_Order',
     'Mage_Sales_Model_Entity_Order_Address',
     'Mage_Sales_Model_Entity_Order_Address_Collection',
@@ -121,21 +149,11 @@ return array(
     'Mage_Sales_Model_Entity_Quote_Payment',
     'Mage_Sales_Model_Entity_Quote_Payment_Collection',
     'Mage_Sales_Model_Entity_Sale_Collection',
-    'Mage_Reports_Model_Resource_Coupons_Collection',
-    'Mage_Reports_Model_Resource_Invoiced_Collection',
-    'Mage_Reports_Model_Resource_Refunded_Collection',
-    'Mage_Reports_Model_Resource_Shipping_Collection',
-    'Mage_Admin_Model_Acl_Role',
-    'Mage_Admin_Model_Resource_Acl_Role',
-    'Mage_Admin_Model_Resource_Acl_Role_Collection',
-    'Mage_Core_Model_Design_Source_Apply',
-    'Mage_Directory_Model_Resource_Currency_Collection',
-    'Mage_GiftMessage_Model_Entity_Attribute_Backend_Boolean_Config',
-    'Mage_GiftMessage_Model_Entity_Attribute_Source_Boolean_Config',
-    'Mage_Ogone_Model_Api_Debug',
-    'Mage_Ogone_Model_Resource_Api_Debug',
+    'Mage_Sales_Model_Entity_Setup',
+    'Mage_Shipping_ShippingController',
+    'Mage_Tag_Block_Customer_Edit',
     'Mage_Wishlist_Model_Resource_Product_Collection',
-    'Varien_File_Uploader_Image',
+    'Mage_XmlConnect_Helper_Payment',
     'Varien_Convert_Action',
     'Varien_Convert_Action_Abstract',
     'Varien_Convert_Action_Interface',
@@ -162,21 +180,9 @@ return array(
     'Varien_Convert_Profile_Abstract',
     'Varien_Convert_Profile_Collection',
     'Varien_Convert_Validator_Abstract',
-    'Varien_Convert_Validator_Dryrun',
     'Varien_Convert_Validator_Column',
+    'Varien_Convert_Validator_Dryrun',
     'Varien_Convert_Validator_Interface',
+    'Varien_File_Uploader_Image',
     'Varien_Profiler' => array('suggestion' => 'Magento_Profiler'),
-    'Mage_Catalog_Model_Resource_Product_Attribute_Frontend_Tierprice',
-    'Mage_Adminhtml_Block_Api_Tab_Userroles',
-    'Mage_Adminhtml_Block_Api_Edituser',
-    'Mage_Adminhtml_Block_Permissions_Tab_Userroles',
-    'Mage_Adminhtml_Block_Permissions_Edituser',
-    'Mage_Adminhtml_Block_Permissions_Usernroles',
-    'Mage_Adminhtml_Block_Tree',
-    'Mage_Adminhtml_Block_Catalog',
-    'Mage_Adminhtml_Block_Sales',
-    'Mage_Customer_Block_Account',
-    'Mage_GiftMessage_Block_Message_Form',
-    'Mage_GiftMessage_Block_Message_Helper',
-    'Mage_Poll_Block_Poll',
 );
diff --git a/dev/tests/static/testsuite/Legacy/_files/obsolete_constants.php b/dev/tests/static/testsuite/Legacy/_files/obsolete_constants.php
index b86e08dfe470209be0ef7458ff0fbf7322d9df57..fe78e47d9e0576138f425662c631cc7bd4d0ad64 100644
--- a/dev/tests/static/testsuite/Legacy/_files/obsolete_constants.php
+++ b/dev/tests/static/testsuite/Legacy/_files/obsolete_constants.php
@@ -57,4 +57,5 @@ return array(
     'TYPE_BINARY',
     'TYPE_LONGVARBINARY',
     'HASH_ALGO',
+    'SEESION_MAX_COOKIE_LIFETIME',
 );
diff --git a/dev/tests/static/testsuite/Legacy/_files/obsolete_methods.php b/dev/tests/static/testsuite/Legacy/_files/obsolete_methods.php
index d34c02eb67cece9bb12f97dfe1c10222f6b022a4..92fd49a05f823dc1a13a01825b2443ca36c9ddb4 100644
--- a/dev/tests/static/testsuite/Legacy/_files/obsolete_methods.php
+++ b/dev/tests/static/testsuite/Legacy/_files/obsolete_methods.php
@@ -25,299 +25,332 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 return array(
-    'htmlEscape' => array('suggestion' => 'escapeHtml'),
-    'urlEscape' => array('suggestion' => 'urlEscape'),
-    'getTrackingPopUpUrlByOrderId' => array('suggestion' => 'getTrackingPopupUrlBySalesModel'),
-    'getTrackingPopUpUrlByShipId' => array('suggestion' => 'getTrackingPopupUrlBySalesModel'),
-    'getTrackingPopUpUrlByTrackId' => array('suggestion' => 'getTrackingPopupUrlBySalesModel'),
-    'isReadablePopupObject',
-    'getOriginalHeigh' => array('suggestion' => 'getOriginalHeight'),
-    'shaCrypt' => array('suggestion' => 'Mage_Ogone_Model_Api::getHash'),
-    'shaCryptValidation' => array('suggestion' => 'Mage_Ogone_Model_Api::getHash'),
-    'getTaxRatesByProductClass' => array('suggestion' => '_getAllRatesByProductClass'),
-    'getAddToCartUrlBase64' => array('suggestion' => '_getAddToCartUrl'),
-    'isTemplateAllowedForApplication',
-    '_inludeControllerClass' => array('suggestion' => '_includeControllerClass'),
-    '_getSHAInSet' => array('suggestion' => 'Mage_Ogone_Model_Api::getHash'),
-    '_getAttributeFilterBlockName',
-    'getIsActiveAanalytics' => array('suggestion' => 'getOnsubmitJs'),
-    'setTaxGroupFilter',
-    'fetchRuleRatesForCustomerTaxClass',
-    'getValueTable',
-    'getSuggestionsByQuery',
-    'getOneBalanceTotal',
-    'shouldShowOneBalance',
-    'shouldCustomerHaveOneBalance',
-    'isFulAmountCovered',
-    'getFacets',
-    'addSearchQfFilter',
-    'addBackupedFilter',
-    'addBackupedFilter',
-    'postDispatchMyAccountSave',
-    'addCustomerToSegments',
-    'removeCustomerFromSegments',
-    'addCustomerToSegments',
-    'removeCustomerFromSegments',
-    'getSuggestionsByQuery',
-    'isLeyeredNavigationAllowed',
-    'logInvitationSave',
-    'logEncryptionKeySave',
-    'saveSegmentCustomersFromSelect',
-    'getIsEngineAvailable',
-    'getRowId' => array('class_scope' => 'Mage_Adminhtml_Block_Widget_Grid'),
-    '_escapeValue' => array('class_scope' => 'Mage_Adminhtml_Block_Widget_Grid_Column_Filter_Abstract'),
-    'getCustomerData' => array('class_scope' => 'Mage_Adminhtml_Block_Sales_Order_Create_Form_Account'),
+    '__get' => array('class_scope' => 'Varien_Object'),
+    '__set' => array('class_scope' => 'Varien_Object'),
+    '_addMinimalPrice' => array('class_scope' => 'Mage_Catalog_Model_Resource_Product_Collection'),
+    '_addTaxPercents' => array('class_scope' => 'Mage_Catalog_Model_Resource_Product_Collection'),
+    '_addToXml' => array('class_scope' => 'Mage_XmlConnect_Block_Checkout_Payment_Method_List'),
+    '_afterSaveCommit' => array('class_scope' => 'Mage_Core_Model_Abstract'),
+    '_afterSetConfig' => array('class_scope' => 'Mage_Eav_Model_Entity_Abstract'),
+    '_aggregateByOrderCreatedAt' => array('class_scope' => 'Mage_SalesRule_Model_Resource_Report_Rule'),
+    '_amountByCookies' => array('class_scope' => 'Mage_Sendfriend_Model_Sendfriend'),
+    '_amountByIp' => array('class_scope' => 'Mage_Sendfriend_Model_Sendfriend'),
+    '_applyCustomDesignSettings',
+    '_applyCustomDesignSettings',
+    '_applyDesign' => array('class_scope' => 'Mage_Catalog_Model_Design'),
+    '_applyDesignRecursively' => array('class_scope' => 'Mage_Catalog_Model_Design'),
+    '_avoidDoubleTransactionProcessing',
+    '_beforeChildToHtml',
+    '_calculatePrice' => array('class_scope' => 'Mage_Sales_Model_Quote_Item_Abstract'),
     '_checkUrlSettings' => array('class_scope' => 'Mage_Adminhtml_Controller_Action'),
-    'getProductsNotInStoreIds',
-    'addToAlersAction',
+    '_collectOrigData' => array('class_scope' => 'Mage_Catalog_Model_Resource_Abstract'),
+    '_decodeInput' => array('class_scope' => 'Mage_Adminhtml_Catalog_ProductController'),
+    '_emailOrderConfirmation' => array('class_scope' => 'Mage_Checkout_Model_Type_Abstract'),
+    '_escapeValue' => array('class_scope' => 'Mage_Adminhtml_Block_Widget_Grid_Column_Filter_Abstract'),
+    '_formatAddress' => array('class_scope' => 'Mage_XmlConnect_Block_Customer_Order_Details'),
+    '_getAddressTaxRequest' => array('class_scope' => 'Mage_Tax_Model_Sales_Total_Quote_Shipping'),
+    '_getAggregationPerStoreView',
+    '_getAttributeFilterBlockName' => array('class_scope' => 'Mage_Catalog_Block_Layer_View'),
+    '_getAttributeFilterBlockName' => array('class_scope' => 'Mage_CatalogSearch_Block_Layer'),
+    '_getAttributeFilterBlockName',
+    '_getAvailable' => array('class_scope' => 'Mage_GiftMessage_Model_Observer'),
+    '_getCacheId' => array('class_scope' => 'Mage_Core_Model_App'),
+    '_getCacheKey' => array('class_scope' => 'Mage_Catalog_Model_Layer_Filter_Price'),
+    '_getCacheTags' => array('class_scope' => 'Mage_Core_Model_App'),
+    '_getChildHtml',
+    '_getCollectionNames' => array('class_scope' => 'Mage_Adminhtml_Report_SalesController'),
+    '_getConnenctionType' => array('class_scope' => 'Mage_Install_Model_Installer_Db'),
+    '_getDateFromToHtml' => array('class_scope' => 'Mage_ImportExport_Block_Adminhtml_Export_Filter'),
+    '_getExistingBasePopularity',
+    '_getFieldTableAlias' => array('class_scope' => 'Mage_Newsletter_Model_Resource_Subscriber_Collection'),
+    '_getForeignKeyName' => array('class_scope' => 'Varien_Db_Adapter_Pdo_Mysql'),
+    '_getGiftmessageSaveModel' => array('class_scope' => 'Mage_Adminhtml_Block_Sales_Order_Create_Search_Grid'),
+    '_getGlobalAggregation',
+    '_getGroupByDateFormat' => array('class_scope' => 'Mage_Log_Model_Resource_Visitor_Collection'),
+    '_getInputHtml' => array('class_scope' => 'Mage_ImportExport_Block_Adminhtml_Export_Filter'),
+    '_getLabelForStore' => array('class_scope' => 'Mage_Catalog_Model_Resource_Eav_Attribute'),
+    '_getMultiSelectHtml' => array('class_scope' => 'Mage_ImportExport_Block_Adminhtml_Export_Filter'),
+    '_getNumberFromToHtml' => array('class_scope' => 'Mage_ImportExport_Block_Adminhtml_Export_Filter'),
+    '_getProductQtyForCheck' => array('class_scope' => 'Mage_CatalogInventory_Model_Observer'),
+    '_getRangeByType' => array('class_scope' => 'Mage_Log_Model_Resource_Visitor_Collection'),
+    '_getRecentProductsCollection',
+    '_getSelectHtml' => array('class_scope' => 'Mage_ImportExport_Block_Adminhtml_Export_Filter'),
+    '_getSetData' => array('class_scope' => 'Mage_Adminhtml_Block_Catalog_Product_Attribute_Set_Main'),
+    '_getSHAInSet' => array('suggestion' => 'Mage_Ogone_Model_Api::getHash'),
+    '_getStoreTaxRequest' => array('class_scope' => 'Mage_Tax_Model_Sales_Total_Quote_Shipping'),
+    '_importAddress' => array('class_scope' => 'Mage_Paypal_Model_Api_Nvp'),
+    '_inheritDesign' => array('class_scope' => 'Mage_Catalog_Model_Design'),
+    '_initOrder' => array('class_scope' => 'Mage_Shipping_Block_Tracking_Popup'),
+    '_initShipment' => array('class_scope' => 'Mage_Shipping_Block_Tracking_Popup'),
+    '_inludeControllerClass' => array('suggestion' => '_includeControllerClass'),
+    '_isApplyDesign' => array('class_scope' => 'Mage_Catalog_Model_Design'),
+    '_isApplyFor' => array('class_scope' => 'Mage_Catalog_Model_Design'),
+    '_isPositiveDecimalNumber' => array('class_scope' => 'Mage_Shipping_Model_Resource_Carrier_Tablerate'),
+    '_loadOldRates' => array('class_scope' => 'Mage_Tax_Model_Resource_Setup'),
+    '_needSubtractShippingTax',
+    '_needSubtractTax',
+    '_needToAddDummy',
+    '_needToAddDummyForShipment',
+    '_parseDescription' => array('class_scope' => 'Mage_Sales_Model_Order_Pdf_Items_Abstract'),
+    '_parseXmlTrackingResponse' => array('class_scope' => 'Mage_Usa_Model_Shipping_Carrier_Fedex'),
+    '_prepareCondition' => array('class_scope' => 'Mage_CatalogSearch_Model_Advanced'),
+    '_prepareConfigurableProductData' => array('class_scope' => 'Mage_ImportExport_Model_Export_Entity_Product'),
+    '_prepareConfigurableProductPrice' => array('class_scope' => 'Mage_ImportExport_Model_Export_Entity_Product'),
+    '_prepareOptionsForCart' => array('class_scope' => 'Mage_Catalog_Model_Product_Type_Abstract'),
+    '_preparePackageTheme' => array('class_scope' => 'Mage_Widget_Model_Widget_Instance'),
+    '_processItem' => array('class_scope' => 'Mage_Weee_Model_Total_Quote_Weee'),
+    '_processShippingAmount',
+    '_processValidateCustomer' => array('class_scope' => 'Mage_Checkout_Model_Type_Onepage'),
     '_putCustomerIntoQuote' => array('class_scope' => 'Mage_Adminhtml_Model_Sales_Order_Create'),
+    '_quoteRow' => array('class_scope' => 'Mage_Backup_Model_Resource_Db'),
+    '_recollectItem' => array('class_scope' => 'Mage_Tax_Model_Sales_Total_Quote_Subtotal'),
+    '_resetItemPriceInclTax',
     '_saveCustomerAfterOrder' => array('class_scope' => 'Mage_Adminhtml_Model_Sales_Order_Create'),
     '_saveCustomers' => array('class_scope' => 'Mage_Adminhtml_Model_Sales_Order_Create'),
-    '_needToAddDummy',
-    '_needToAddDummy',
-    '_needToAddDummyForShipment',
-    '_needToAddDummy',
     '_sendUploadResponse' => array('class_scope' => 'Mage_Adminhtml_CustomerController'),
     '_sendUploadResponse' => array('class_scope' => 'Mage_Adminhtml_Newsletter_SubscriberController'),
-    'getFormObject' => array('class_scope' => 'Mage_Adminhtml_Block_Widget_Form'),
-    'orderedAction' => array('class_scope' => 'Mage_Adminhtml_Report_ProductController'),
-    'exportOrderedCsvAction',
-    'exportOrderedExcelAction',
-    '_getGiftmessageSaveModel' => array('class_scope' => 'Mage_Adminhtml_Block_Sales_Order_Create_Search_Grid'),
-    'getGiftmessageHtml' => array('class_scope' => 'Mage_Adminhtml_Block_Sales_Order_View_Tab_Info'),
-    'getAddNewButtonHtml' => array('class_scope' => 'Mage_Adminhtml_Block_Catalog_Product'),
-    '_getSetData' => array('class_scope' => 'Mage_Adminhtml_Block_Catalog_Product_Attribute_Set_Main'),
-    '_decodeInput' => array('class_scope' => 'Mage_Adminhtml_Catalog_ProductController'),
-    'addCustomersToAlertQueueAction',
-    'bundlesAction' => array('class_scope' => 'Mage_Adminhtml_Catalog_ProductController'),
-    'getPriceFormatted' => array('class_scope' => 'Mage_Adminhtml_Block_Customer_Edit_Tab_View_Sales'),
-    'getRowId' => array('class_scope' => 'Mage_Adminhtml_Block_Sales_Order_Create_Customer_Grid'),
-    '_getCollectionNames' => array('class_scope' => 'Mage_Adminhtml_Report_SalesController'),
+    '_setAttribteValue',
+    'actionPreDispatchAdmin' => array('class_scope' => 'Mage_Admin_Model_Observer'),
     'actionPostDispatchAdmin' => array('class_scope' => 'Mage_Admin_Model_Observer'),
-    'sendNewPasswordEmail',
-    'getStatrupPageUrl',
-    'crear',
-    '_quoteRow' => array('class_scope' => 'Mage_Backup_Model_Resource_Db'),
-    'catalogProductLoadAfter' => array('class_scope' => 'Mage_Bundle_Model_Observer'),
-    'getPrices' => array('class_scope' => 'Mage_Bundle_Model_Product_Price'),
-    'getPricesDependingOnTax' => array('class_scope' => 'Mage_Bundle_Model_Product_Price'),
-    'getSelectionFinalPrice' => array('class_scope' => 'Mage_Bundle_Model_Product_Price'),
-    'setCustomerId' => array('class_scope' => 'Mage_Customer_Model_Resource_Address'),
-    'parse' => array('class_scope' => 'Mage_Catalog_Model_Convert_Parser_Product'),
+    'addBackupedFilter',
+    'addConfigField' => array('class_scope' => 'Mage_Core_Model_Resource_Setup'),
+    'addConstraint' => array('class_scope' => 'Varien_Db_Adapter_Pdo_Mysql'),
+    'addCustomersToAlertQueueAction',
+    'addCustomerToSegments',
+    'addGroupByTag' => array('class_scope' => 'Mage_Reports_Model_Resource_Tag_Collection'),
+    'addKey' => array('class_scope' => 'Varien_Db_Adapter_Pdo_Mysql'),
+    'addSaleableFilterToCollection' => array('class_scope' => 'Mage_Catalog_Model_Product_Status'),
+    'addSearchQfFilter',
+    'addStoresFilter' => array('class_scope' => 'Mage_Poll_Model_Resource_Poll_Collection'),
+    'addSummary' => array('class_scope' => 'Mage_Tag_Model_Resource_Tag'),
+    'addSummary' => array('class_scope' => 'Mage_Tag_Model_Tag'),
+    'addTemplateData' => array('class_scope' => 'Mage_Newsletter_Model_Queue'),
+    'addToAlersAction',
+    'addToChildGroup',
+    'addVisibleFilterToCollection' => array('class_scope' => 'Mage_Catalog_Model_Product_Status'),
+    'addVisibleInCatalogFilterToCollection' => array('suggestion' =>
+        '$collection->setVisibility(Mage_Catalog_Model_Product_Visibility->getVisibleInCatalogIds());'
+    ),
+    'addVisibleInSearchFilterToCollection' => array('suggestion' =>
+        '$collection->setVisibility(Mage_Catalog_Model_Product_Visibility->getVisibleInSearchIds());'
+    ),
+    'addVisibleInSiteFilterToCollection' => array('suggestion' =>
+        '$collection->setVisibility(Mage_Catalog_Model_Product_Visibility->getVisibleInSiteIds());'
+    ),
+    'addWishlistLink' => array('class_scope' => 'Mage_Wishlist_Block_Links'),
+    'addWishListSortOrder' => array('class_scope' => 'Mage_Wishlist_Model_Resource_Item_Collection'),
+    'aggregate' => array('class_scope' => 'Mage_Tag_Model_Resource_Tag'),
+    'aggregate' => array('class_scope' => 'Mage_Tag_Model_Tag'),
     'applyDesign' => array('class_scope' => 'Mage_Catalog_Model_Design'),
-    '_isApplyFor' => array('class_scope' => 'Mage_Catalog_Model_Design'),
-    '_isApplyDesign' => array('class_scope' => 'Mage_Catalog_Model_Design'),
-    '_inheritDesign' => array('class_scope' => 'Mage_Catalog_Model_Design'),
-    '_applyDesignRecursively' => array('class_scope' => 'Mage_Catalog_Model_Design'),
-    '_applyDesign' => array('class_scope' => 'Mage_Catalog_Model_Design'),
-    '_getCacheKey' => array('class_scope' => 'Mage_Catalog_Model_Layer_Filter_Price'),
-    'loadParentProductIds' => array('class_scope' => 'Mage_Catalog_Model_Product'),
+    'authAdmin' => array('class_scope' => 'Mage_Adminhtml_Helper_Rss'),
+    'bundlesAction' => array('class_scope' => 'Mage_Adminhtml_Catalog_ProductController'),
+    'calcTaxAmount' => array('class_scope' => 'Mage_Sales_Model_Quote_Item_Abstract'),
+    'canPrint' => array('class_scope' => 'Mage_Checkout_Block_Onepage_Success'),
     'catalogCategoryChangeProducts' => array('class_scope' => 'Mage_Catalog_Model_Product_Flat_Observer'),
-    'getQuoteItemOption' => array('class_scope' => 'Mage_Catalog_Model_Product_Option_Type_Default'),
-    'getQuoteItem' => array('class_scope' => 'Mage_Catalog_Model_Product_Option_Type_Default'),
-    'addVisibleFilterToCollection' => array('class_scope' => 'Mage_Catalog_Model_Product_Status'),
-    'addSaleableFilterToCollection' => array('class_scope' => 'Mage_Catalog_Model_Product_Status'),
-    '_prepareOptionsForCart' => array('class_scope' => 'Mage_Catalog_Model_Product_Type_Abstract'),
-    'addVisibleInCatalogFilterToCollection' => array('class_scope' => 'Mage_Catalog_Model_Product_Visibility'),
-    'addVisibleInSearchFilterToCollection' => array('class_scope' => 'Mage_Catalog_Model_Product_Visibility'),
-    'addVisibleInSiteFilterToCollection' => array('class_scope' => 'Mage_Catalog_Model_Product_Visibility'),
-    '_collectOrigData' => array('class_scope' => 'Mage_Catalog_Model_Resource_Abstract'),
-    '_getLabelForStore' => array('class_scope' => 'Mage_Catalog_Model_Resource_Eav_Attribute'),
-    'initLabels' => array('class_scope' => 'Mage_Catalog_Model_Resource_Eav_Attribute'),
-    'getParentProductIds' => array('class_scope' => 'Mage_Catalog_Model_Resource_Product'),
-    'loadProductPrices' => array('class_scope' => 'Mage_Catalog_Model_Resource_Product_Attribute_Backend_Tierprice'),
-    'deleteProductPrices' => array('class_scope' => 'Mage_Catalog_Model_Resource_Product_Attribute_Backend_Tierprice'),
-    'insertProductPrice' => array('class_scope' => 'Mage_Catalog_Model_Resource_Product_Attribute_Backend_Tierprice'),
-    '_addMinimalPrice' => array('class_scope' => 'Mage_Catalog_Model_Resource_Product_Collection'),
-    '_addTaxPercents' => array('class_scope' => 'Mage_Catalog_Model_Resource_Product_Collection'),
-    'loadLabel' => array('class_scope' => 'Mage_Catalog_Model_Resource_Product_Type_Configurable_Attribute'),
-    'loadPrices' => array('class_scope' => 'Mage_Catalog_Model_Resource_Product_Type_Configurable_Attribute'),
-    'convertOldTreeToNew' => array('class_scope' => 'Mage_Catalog_Model_Resource_Setup'),
-    'rebuildCategoryLevels' => array('class_scope' => 'Mage_Catalog_Model_Resource_Setup'),
-    '_getProductQtyForCheck' => array('class_scope' => 'Mage_CatalogInventory_Model_Observer'),
-    'lockOrderInventoryData' => array('class_scope' => 'Mage_CatalogInventory_Model_Observer'),
-    'createOrderItem' => array('class_scope' => 'Mage_CatalogInventory_Model_Observer'),
-    'refundOrderItem' => array('class_scope' => 'Mage_CatalogInventory_Model_Observer'),
-    '_prepareCondition' => array('class_scope' => 'Mage_CatalogSearch_Model_Advanced'),
-    'getMinQueryLenght',
-    'getMaxQueryLenght',
-    'salesOrderPaymentPlaceEnd',
-    '_emailOrderConfirmation' => array('class_scope' => 'Mage_Checkout_Model_Type_Abstract'),
-    'isCheckoutAvailable' => array('class_scope' => 'Mage_Checkout_Model_Type_Multishipping'),
-    'getCheckoutMehod' => array('class_scope' => 'Mage_Checkout_Model_Type_Onepage'),
-    '_processValidateCustomer' => array('class_scope' => 'Mage_Checkout_Model_Type_Onepage'),
-    'validateOrder' => array('class_scope' => 'Mage_Checkout_Model_Type_Onepage'),
-    'toOptionArray' => array('class_scope' => 'Mage_Cms_Model_Resource_Page_Collection'),
-    '_afterSaveCommit' => array('class_scope' => 'Mage_Core_Model_Abstract'),
-    '_getCacheTags' => array('class_scope' => 'Mage_Core_Model_App'),
-    'getUseCacheFilename' => array('class_scope' => 'Mage_Core_Model_App'),
-    '_getCacheId' => array('class_scope' => 'Mage_Core_Model_App'),
-    'prepareCacheId' => array('class_scope' => 'Mage_Core_Model_App'),
+    'catalogEventProductCollectionAfterLoad' => array('class_scope' => 'Mage_GiftMessage_Model_Observer'),
+    'catalogProductLoadAfter' => array('class_scope' => 'Mage_Bundle_Model_Observer'),
+    'chechAllowedExtension',
+    'checkConfigurableProducts' => array('class_scope' => 'Mage_Eav_Model_Resource_Entity_Attribute_Collection'),
+    'checkDatabase' => array('class_scope' => 'Mage_Install_Model_Installer_Db'),
     'checkDateTime' => array('class_scope' => 'Mage_Core_Model_Date'),
-    'parseDateTime' => array('class_scope' => 'Mage_Core_Model_Date'),
     'cleanDbRow' => array('class_scope' => 'Mage_Core_Model_Resource'),
-    'forsedSave',
-    'updateTable' => array('class_scope' => 'Mage_Core_Model_Resource_Setup'),
-    'addConfigField' => array('class_scope' => 'Mage_Core_Model_Resource_Setup'),
-    'revalidateCookie' => array('class_scope' => 'Mage_Core_Model_Session_Abstract_Varien'),
-    'processSubst' => array('class_scope' => 'Mage_Core_Model_Store'),
-    'getIsAjaxRequest' => array('class_scope' => 'Mage_Core_Model_Translate_Inline'),
-    'setIsAjaxRequest' => array('class_scope' => 'Mage_Core_Model_Translate_Inline'),
-    'getHtmlFormat' => array('class_scope' => 'Mage_Customer_Model_Address_Abstract'),
-    'getFormated' => array('class_scope' => 'Mage_Customer_Model_Address_Abstract'),
-    'parse' => array('class_scope' => 'Mage_Customer_Model_Convert_Parser_Customer'),
-    '_setAttribteValue',
-    '_afterSetConfig' => array('class_scope' => 'Mage_Eav_Model_Entity_Abstract'),
-    'getConfig' => array('class_scope' => 'Mage_Eav_Model_Entity_Attribute_Abstract'),
-    'getIsGlobal' => array('class_scope' => 'Mage_Eav_Model_Entity_Attribute_Abstract'),
-    'checkConfigurableProducts' => array('class_scope' => 'Mage_Eav_Model_Resource_Entity_Attribute_Collection'),
-    '_getAvailable' => array('class_scope' => 'Mage_GiftMessage_Model_Observer'),
-    'catalogEventProductCollectionAfterLoad' => array('class_scope' => 'Mage_GiftMessage_Model_Observer'),
-    'order_success_page_view' => array('class_scope' => 'Mage_GoogleAnalytics_Model_Observer'),
-    'processBeacon',
-    'prepareGoogleOptimizerScripts',
-    '_prepareConfigurableProductData' => array('class_scope' => 'Mage_ImportExport_Model_Export_Entity_Product'),
-    '_prepareConfigurableProductPrice' => array('class_scope' => 'Mage_ImportExport_Model_Export_Entity_Product'),
     'cloneIndexTable' => array('class_scope' => 'Mage_Index_Model_Resource_Abstract'),
-    '_getConnenctionType' => array('class_scope' => 'Mage_Install_Model_Installer_Db'),
-    'checkDatabase' => array('class_scope' => 'Mage_Install_Model_Installer_Db'),
-    '_getGroupByDateFormat' => array('class_scope' => 'Mage_Log_Model_Resource_Visitor_Collection'),
-    '_getRangeByType' => array('class_scope' => 'Mage_Log_Model_Resource_Visitor_Collection'),
-    'addTemplateData' => array('class_scope' => 'Mage_Newsletter_Model_Queue'),
-    'setSaveTemplateFlag' => array('class_scope' => 'Mage_Newsletter_Model_Queue'),
-    'getSaveTemplateFlag' => array('class_scope' => 'Mage_Newsletter_Model_Queue'),
-    '_getFieldTableAlias' => array('class_scope' => 'Mage_Newsletter_Model_Resource_Subscriber_Collection'),
-    'isValidForSend' => array('class_scope' => 'Mage_Newsletter_Model_Template'),
-    'getMail' => array('class_scope' => 'Mage_Newsletter_Model_Template'),
-    'send' => array('class_scope' => 'Mage_Newsletter_Model_Template'),
-    'preprocess' => array('class_scope' => 'Mage_Newsletter_Model_Template'),
-    'getDebug' => array('class_scope' => 'Mage_Ogone_Model_Api'),
-    'processBeforeVoid' => array('class_scope' => 'Mage_Payment_Model_Method_Abstract'),
-    'getDebug' => array('class_scope' => 'Mage_Paypal_Model_Api_Abstract'),
-    '_importAddress' => array('class_scope' => 'Mage_Paypal_Model_Api_Nvp'),
+    'convertOldTaxData' => array('class_scope' => 'Mage_Tax_Model_Resource_Setup'),
+    'convertOldTreeToNew' => array('class_scope' => 'Mage_Catalog_Model_Resource_Setup'),
+    'countChildren' => array('class_scope' => 'Mage_Core_Block_Abstract'),
+    'crear',
+    'createOrderItem' => array('class_scope' => 'Mage_CatalogInventory_Model_Observer'),
     'debugRequest' => array('class_scope' => 'Mage_Paypal_Model_Api_Standard'),
-    'addStoresFilter' => array('class_scope' => 'Mage_Poll_Model_Resource_Poll_Collection'),
-    'addGroupByTag' => array('class_scope' => 'Mage_Reports_Model_Resource_Tag_Collection'),
-    'getEntityTypeIdsToTypes' => array('class_scope' => 'Mage_Rss_Model_Resource_Order'),
-    'getEntityIdsToIncrementIds' => array('class_scope' => 'Mage_Rss_Model_Resource_Order'),
-    'getAllOrderEntityTypeIds' => array('class_scope' => 'Mage_Rss_Model_Resource_Order'),
-    'getAllOrderEntityIds' => array('class_scope' => 'Mage_Rss_Model_Resource_Order'),
+    'deleteProductPrices' => array('class_scope' => 'Mage_Catalog_Model_Resource_Product_Attribute_Backend_Tierprice'),
+    'displayFullSummary' => array('class_scope' => 'Mage_Tax_Model_Config'),
+    'displayTaxColumn' => array('class_scope' => 'Mage_Tax_Model_Config'),
+    'displayZeroTax' => array('class_scope' => 'Mage_Tax_Model_Config'),
+    'drawItem' => array('class_scope' => 'Mage_Catalog_Block_Navigation'),
+    'dropKey' => array('class_scope' => 'Varien_Db_Adapter_Pdo_Mysql'),
+    'editAction' => array('class_scope' => 'Mage_Tag_CustomerController'),
+    'exportOrderedCsvAction',
+    'exportOrderedExcelAction',
+    'fetchItemsCount' => array('class_scope' => 'Mage_Wishlist_Model_Resource_Wishlist'),
+    'fetchRuleRatesForCustomerTaxClass',
+    'forsedSave',
+    'getAccount' => array('class_scope' => 'Mage_GoogleAnalytics_Block_Ga'),
+    'getAddNewButtonHtml' => array('class_scope' => 'Mage_Adminhtml_Block_Catalog_Product'),
+    'getAddToCartItemUrl' => array('class_scope' => 'Mage_Wishlist_Block_Customer_Sidebar'),
+    'getAddToCartUrlBase64' => array('suggestion' => '_getAddToCartUrl'),
     'getAllEntityIds' => array('class_scope' => 'Mage_Rss_Model_Resource_Order'),
     'getAllEntityTypeCommentIds' => array('class_scope' => 'Mage_Rss_Model_Resource_Order'),
-    'getStoreCurrency' => array('class_scope' => 'Mage_Sales_Model_Order'),
-    '_avoidDoubleTransactionProcessing',
-    '_parseDescription' => array('class_scope' => 'Mage_Sales_Model_Order_Pdf_Items_Abstract'),
-    'isAllowedGuestCheckout' => array('class_scope' => 'Mage_Sales_Model_Quote'),
-    'getTotalModels' => array('class_scope' => 'Mage_Sales_Model_Quote_Address'),
-    'calcTaxAmount' => array('class_scope' => 'Mage_Sales_Model_Quote_Item_Abstract'),
-    'getTaxAmount' => array('class_scope' => 'Mage_Sales_Model_Quote_Item_Abstract'),
+    'getAllOrderEntityIds' => array('class_scope' => 'Mage_Rss_Model_Resource_Order'),
+    'getAllOrderEntityTypeIds' => array('class_scope' => 'Mage_Rss_Model_Resource_Order'),
+    'getAnonSuffix' => array('class_scope' => 'Mage_Core_Block_Abstract'),
     'getBaseTaxAmount' => array('class_scope' => 'Mage_Sales_Model_Quote_Item_Abstract'),
-    '_calculatePrice' => array('class_scope' => 'Mage_Sales_Model_Quote_Item_Abstract'),
-    'getValidator' => array('class_scope' => 'Mage_SalesRule_Model_Observer'),
-    'sales_quote_address_discount_item',
-    'sales_order_afterPlace',
-    '_aggregateByOrderCreatedAt' => array('class_scope' => 'Mage_SalesRule_Model_Resource_Report_Rule'),
-    'toOptionArray' => array('class_scope' => 'Mage_Sendfriend_Model_Sendfriend'),
-    '_amountByCookies' => array('class_scope' => 'Mage_Sendfriend_Model_Sendfriend'),
-    '_amountByIp' => array('class_scope' => 'Mage_Sendfriend_Model_Sendfriend'),
-    '_isPositiveDecimalNumber' => array('class_scope' => 'Mage_Shipping_Model_Resource_Carrier_Tablerate'),
-    'setJoinFlag' => array('class_scope' => 'Mage_Tag_Model_Resource_Customer_Collection'),
+    'getCheckoutMehod' => array('class_scope' => 'Mage_Checkout_Model_Type_Onepage'),
+    'getChild' => array('directory' => 'app', 'suggestion' => 'Mage_Core_Block_Abstract::getChildBlock()'),
+    'getChildGroup',
+    'getConfig' => array('class_scope' => 'Mage_Eav_Model_Entity_Attribute_Abstract'),
+    'getCustomerData' => array('class_scope' => 'Mage_Adminhtml_Block_Sales_Order_Create_Form_Account'),
+    'getDataForSave' => array('class_scope' => 'Mage_Wishlist_Model_Item'),
+    'getDebug' => array('class_scope' => 'Mage_Ogone_Model_Api'),
+    'getDebug' => array('class_scope' => 'Mage_Paypal_Model_Api_Abstract'),
+    'getDirectOutput' => array('class_scope' => 'Mage_Core_Model_Layout'),
+    'getEntityIdsToIncrementIds' => array('class_scope' => 'Mage_Rss_Model_Resource_Order'),
+    'getEntityTypeIdsToTypes' => array('class_scope' => 'Mage_Rss_Model_Resource_Order'),
+    'getFacets',
+    'getFallbackTheme',
+    'getFormated' => array('class_scope' => 'Mage_Customer_Model_Address_Abstract'),
+    'getFormObject' => array('class_scope' => 'Mage_Adminhtml_Block_Widget_Form'),
+    'getGiftmessageHtml' => array('class_scope' => 'Mage_Adminhtml_Block_Sales_Order_View_Tab_Info'),
+    'getHtmlFormat' => array('class_scope' => 'Mage_Customer_Model_Address_Abstract'),
+    'getIsActiveAanalytics' => array('suggestion' => 'getOnsubmitJs'),
+    'getIsAjaxRequest' => array('class_scope' => 'Mage_Core_Model_Translate_Inline'),
+    'getIsAnonymous',
+    'getIsEngineAvailable',
+    'getIsGlobal' => array('class_scope' => 'Mage_Eav_Model_Entity_Attribute_Abstract'),
+    'getIsInStock' => array('class_scope' => 'Mage_Checkout_Block_Cart_Item_Renderer'),
+    'getItemRender' => array('class_scope' => 'Mage_Checkout_Block_Cart_Abstract'),
     'getJoinFlag' => array('class_scope' => 'Mage_Tag_Model_Resource_Customer_Collection'),
-    'unsetJoinFlag' => array('class_scope' => 'Mage_Tag_Model_Resource_Customer_Collection'),
-    'setJoinFlag' => array('class_scope' => 'Mage_Tag_Model_Resource_Product_Collection'),
     'getJoinFlag' => array('class_scope' => 'Mage_Tag_Model_Resource_Product_Collection'),
-    'unsetJoinFlag' => array('class_scope' => 'Mage_Tag_Model_Resource_Product_Collection'),
-    '_getExistingBasePopularity',
-    '_getAggregationPerStoreView',
-    '_getGlobalAggregation',
-    'aggregate' => array('class_scope' => 'Mage_Tag_Model_Resource_Tag'),
-    'addSummary' => array('class_scope' => 'Mage_Tag_Model_Resource_Tag'),
-    'displayFullSummary' => array('class_scope' => 'Mage_Tax_Model_Config'),
-    'displayZeroTax' => array('class_scope' => 'Mage_Tax_Model_Config'),
-    'displayTaxColumn' => array('class_scope' => 'Mage_Tax_Model_Config'),
-    'setJoinFlag' => array('class_scope' => 'Mage_Tag_Model_Resource_Tag_Collection'),
     'getJoinFlag' => array('class_scope' => 'Mage_Tag_Model_Resource_Tag_Collection'),
-    'unsetJoinFlag' => array('class_scope' => 'Mage_Tag_Model_Resource_Tag_Collection'),
-    'aggregate' => array('class_scope' => 'Mage_Tag_Model_Tag'),
-    'addSummary' => array('class_scope' => 'Mage_Tag_Model_Tag'),
-    'convertOldTaxData' => array('class_scope' => 'Mage_Tax_Model_Resource_Setup'),
-    '_loadOldRates' => array('class_scope' => 'Mage_Tax_Model_Resource_Setup'),
-    '_getStoreTaxRequest' => array('class_scope' => 'Mage_Tax_Model_Sales_Total_Quote_Shipping'),
-    '_getAddressTaxRequest' => array('class_scope' => 'Mage_Tax_Model_Sales_Total_Quote_Shipping'),
-    '_processShippingAmount',
-    '_resetItemPriceInclTax',
-    '_recollectItem' => array('class_scope' => 'Mage_Tax_Model_Sales_Total_Quote_Subtotal'),
-    '_parseXmlTrackingResponse' => array('class_scope' => 'Mage_Usa_Model_Shipping_Carrier_Fedex'),
-    '_needSubtractTax',
-    '_needSubtractShippingTax',
-    '_processItem' => array('class_scope' => 'Mage_Weee_Model_Total_Quote_Weee'),
-    '_preparePackageTheme' => array('class_scope' => 'Mage_Widget_Model_Widget_Instance'),
-    'getDataForSave' => array('class_scope' => 'Mage_Wishlist_Model_Item'),
-    'addWishListSortOrder' => array('class_scope' => 'Mage_Wishlist_Model_Resource_Item_Collection'),
-    'fetchItemsCount' => array('class_scope' => 'Mage_Wishlist_Model_Resource_Wishlist'),
-    'getProductCollection' => array('class_scope' => 'Mage_Wishlist_Model_Wishlist'),
-    'isAutomaticCleaningAvailable' => array('class_scope' => 'Varien_Cache_Backend_Eaccelerator'),
-    'getSuggestedZeroDate',
-    'dropKey' => array('class_scope' => 'Varien_Db_Adapter_Pdo_Mysql'),
-    'addConstraint' => array('class_scope' => 'Varien_Db_Adapter_Pdo_Mysql'),
     'getKeyList' => array('class_scope' => 'Varien_Db_Adapter_Pdo_Mysql'),
-    'addKey' => array('class_scope' => 'Varien_Db_Adapter_Pdo_Mysql'),
-    'truncate' => array('class_scope' => 'Varien_Db_Adapter_Pdo_Mysql'),
-    '_getForeignKeyName' => array('class_scope' => 'Varien_Db_Adapter_Pdo_Mysql'),
-    'chechAllowedExtension',
-    '__get' => array('class_scope' => 'Varien_Object'),
-    '__set' => array('class_scope' => 'Varien_Object'),
-    'getProfile' => array('class_scope' => 'Varien_Convert_Container_Abstract'),
-    'setProfile' => array('class_scope' => 'Varien_Convert_Container_Abstract'),
-    'validateDataArray' => array('class_scope' => 'Varien_Convert_Container_Abstract'),
-    'hasItems' => array('class_scope' => 'Mage_Wishlist_Helper_Data'),
-    'getProductCollection' => array('class_scope' => 'Mage_Wishlist_Helper_Data'),
-    'imageAction' => array('class_scope' => 'Mage_Catalog_ProductController'),
-    '_applyCustomDesignSettings',
-    '_applyCustomDesignSettings',
-    'editAction' => array('class_scope' => 'Mage_Tag_CustomerController'),
-    'saveAction' => array('class_scope' => 'Mage_Tag_CustomerController'),
-    '_getAttributeFilterBlockName' => array('class_scope' => 'Mage_Catalog_Block_Layer_View'),
-    'drawItem' => array('class_scope' => 'Mage_Catalog_Block_Navigation'),
-    '_getAttributeFilterBlockName' => array('class_scope' => 'Mage_CatalogSearch_Block_Layer'),
-    'getItemRender' => array('class_scope' => 'Mage_Checkout_Block_Cart_Abstract'),
-    'getIsInStock' => array('class_scope' => 'Mage_Checkout_Block_Cart_Item_Renderer'),
+    'getLanguages' => array('class_scope' => 'Mage_Install_Block_Begin'),
+    'getLifeTime' => array('class_scope' => 'Mage_Core_Model_Resource_Session'),
+    'getLocaleBaseDir' => array('class_scope' => 'Mage_Core_Model_Design_Package'),
+    'getMail' => array('class_scope' => 'Mage_Newsletter_Model_Template'),
+    'getMaxQueryLenght',
+    'getMergedCssUrl',
+    'getMergedJsUrl',
+    'getMinQueryLenght',
+    'getOneBalanceTotal',
+    'getOrderHtml' => array('class_scope' => 'Mage_GoogleAnalytics_Block_Ga'),
     'getOrderId' => array('class_scope' => 'Mage_Checkout_Block_Onepage_Success'),
-    'canPrint' => array('class_scope' => 'Mage_Checkout_Block_Onepage_Success'),
+    'getOrderId' => array('class_scope' => 'Mage_Shipping_Block_Tracking_Popup'),
+    'getOriginalHeigh' => array('suggestion' => 'getOriginalHeight'),
+    'getParentProductIds' => array('class_scope' => 'Mage_Catalog_Model_Resource_Product'),
+    'getPriceFormatted' => array('class_scope' => 'Mage_Adminhtml_Block_Customer_Edit_Tab_View_Sales'),
+    'getPrices' => array('class_scope' => 'Mage_Bundle_Model_Product_Price'),
+    'getPricesDependingOnTax' => array('class_scope' => 'Mage_Bundle_Model_Product_Price'),
     'getPrintUrl' => array('class_scope' => 'Mage_Checkout_Block_Onepage_Success'),
-    'getViewOrderUrl' => array('class_scope' => 'Mage_Checkout_Block_Onepage_Success'),
+    'getPrintUrl' => array('class_scope' => 'Mage_Sales_Block_Order_Info'),
+    'getProductCollection' => array('class_scope' => 'Mage_Wishlist_Helper_Data'),
+    'getProductCollection' => array('class_scope' => 'Mage_Wishlist_Model_Wishlist'),
+    'getProductsNotInStoreIds',
+    'getProfile' => array('class_scope' => 'Varien_Convert_Container_Abstract'),
+    'getQuoteItem' => array('class_scope' => 'Mage_Catalog_Model_Product_Option_Type_Default'),
+    'getQuoteItemOption' => array('class_scope' => 'Mage_Catalog_Model_Product_Option_Type_Default'),
     'getQuoteOrdersHtml' => array('class_scope' => 'Mage_GoogleAnalytics_Block_Ga'),
-    'getOrderHtml' => array('class_scope' => 'Mage_GoogleAnalytics_Block_Ga'),
-    'getAccount' => array('class_scope' => 'Mage_GoogleAnalytics_Block_Ga'),
-    '_getDateFromToHtml' => array('class_scope' => 'Mage_ImportExport_Block_Adminhtml_Export_Filter'),
-    '_getInputHtml' => array('class_scope' => 'Mage_ImportExport_Block_Adminhtml_Export_Filter'),
-    '_getMultiSelectHtml' => array('class_scope' => 'Mage_ImportExport_Block_Adminhtml_Export_Filter'),
-    '_getNumberFromToHtml' => array('class_scope' => 'Mage_ImportExport_Block_Adminhtml_Export_Filter'),
-    '_getSelectHtml' => array('class_scope' => 'Mage_ImportExport_Block_Adminhtml_Export_Filter'),
-    'getLanguages' => array('class_scope' => 'Mage_Install_Block_Begin'),
-    '_getRecentProductsCollection',
+    'getRemoveItemUrl' => array('class_scope' => 'Mage_Wishlist_Block_Customer_Sidebar'),
     'getReorderUrl' => array('class_scope' => 'Mage_Sales_Block_Order_Info'),
-    'getPrintUrl' => array('class_scope' => 'Mage_Sales_Block_Order_Info'),
-    'setOrderId' => array('class_scope' => 'Mage_Shipping_Block_Tracking_Popup'),
-    'getOrderId' => array('class_scope' => 'Mage_Shipping_Block_Tracking_Popup'),
-    'setShipId' => array('class_scope' => 'Mage_Shipping_Block_Tracking_Popup'),
+    'getRowId' => array('class_scope' => 'Mage_Adminhtml_Block_Sales_Order_Create_Customer_Grid'),
+    'getRowId' => array('class_scope' => 'Mage_Adminhtml_Block_Widget_Grid'),
+    'getSaveTemplateFlag' => array('class_scope' => 'Mage_Newsletter_Model_Queue'),
+    'getSelectionFinalPrice' => array('class_scope' => 'Mage_Bundle_Model_Product_Price'),
     'getShipId' => array('class_scope' => 'Mage_Shipping_Block_Tracking_Popup'),
-    'setTrackId' => array('class_scope' => 'Mage_Shipping_Block_Tracking_Popup'),
+    'getSortedChildren' => array('suggestion' => 'getChildNames'),
+    'getSortedChildBlocks' => array('suggestion' => 'getChildNames() + $this->getLayout()->getBlock($name)'),
+    'getStatrupPageUrl',
+    'getStoreCurrency' => array('class_scope' => 'Mage_Sales_Model_Order'),
+    'getSuggestedZeroDate',
+    'getSuggestionsByQuery',
+    'getSuggestionsByQuery',
+    'getTaxAmount' => array('class_scope' => 'Mage_Sales_Model_Quote_Item_Abstract'),
+    'getTaxRatesByProductClass' => array('suggestion' => '_getAllRatesByProductClass'),
+    'getTotalModels' => array('class_scope' => 'Mage_Sales_Model_Quote_Address'),
     'getTrackId' => array('class_scope' => 'Mage_Shipping_Block_Tracking_Popup'),
-    '_initOrder' => array('class_scope' => 'Mage_Shipping_Block_Tracking_Popup'),
-    '_initShipment' => array('class_scope' => 'Mage_Shipping_Block_Tracking_Popup'),
     'getTrackingInfoByOrder' => array('class_scope' => 'Mage_Shipping_Block_Tracking_Popup'),
     'getTrackingInfoByShip' => array('class_scope' => 'Mage_Shipping_Block_Tracking_Popup'),
     'getTrackingInfoByTrackId' => array('class_scope' => 'Mage_Shipping_Block_Tracking_Popup'),
-    'getRemoveItemUrl' => array('class_scope' => 'Mage_Wishlist_Block_Customer_Sidebar'),
-    'getAddToCartItemUrl' => array('class_scope' => 'Mage_Wishlist_Block_Customer_Sidebar'),
-    'addWishlistLink' => array('class_scope' => 'Mage_Wishlist_Block_Links'),
-    '_addToXml' => array('class_scope' => 'Mage_XmlConnect_Block_Checkout_Payment_Method_List'),
-    '_formatAddress' => array('class_scope' => 'Mage_XmlConnect_Block_Customer_Order_Details'),
+    'getTrackingPopUpUrlByOrderId' => array('suggestion' => 'getTrackingPopupUrlBySalesModel'),
+    'getTrackingPopUpUrlByShipId' => array('suggestion' => 'getTrackingPopupUrlBySalesModel'),
+    'getTrackingPopUpUrlByTrackId' => array('suggestion' => 'getTrackingPopupUrlBySalesModel'),
+    'getUseCacheFilename' => array('class_scope' => 'Mage_Core_Model_App'),
+    'getValidator' => array('class_scope' => 'Mage_SalesRule_Model_Observer'),
+    'getValidatorData' => array(
+        'class_scope' => 'Mage_Core_Model_Session_Abstract',
+        'suggestion' => 'use _getSessionEnvironment method'
+    ),
+    'getValueTable',
+    'getViewOrderUrl' => array('class_scope' => 'Mage_Checkout_Block_Onepage_Success'),
+    'getWidgetSupportedBlocks' => array('class_scope' => 'Mage_Widget_Model_Widget_Instance'),
+    'getWidgetSupportedTemplatesByBlock' => array('class_scope' => 'Mage_Widget_Model_Widget_Instance'),
+    'hasItems' => array('class_scope' => 'Mage_Wishlist_Helper_Data'),
+    'htmlEscape' => array('suggestion' => 'escapeHtml'),
+    'imageAction' => array('class_scope' => 'Mage_Catalog_ProductController'),
+    'initLabels' => array('class_scope' => 'Mage_Catalog_Model_Resource_Eav_Attribute'),
+    'insertProductPrice' => array('class_scope' => 'Mage_Catalog_Model_Resource_Product_Attribute_Backend_Tierprice'),
+    'isAllowedGuestCheckout' => array('class_scope' => 'Mage_Sales_Model_Quote'),
+    'isAutomaticCleaningAvailable' => array('class_scope' => 'Varien_Cache_Backend_Eaccelerator'),
+    'isCheckoutAvailable' => array('class_scope' => 'Mage_Checkout_Model_Type_Multishipping'),
+    'isFulAmountCovered',
+    'isLeyeredNavigationAllowed',
+    'isReadablePopupObject',
+    'isTemplateAllowedForApplication',
+    'isValidForSend' => array('class_scope' => 'Mage_Newsletter_Model_Template'),
+    'loadLabel' => array('class_scope' => 'Mage_Catalog_Model_Resource_Product_Type_Configurable_Attribute'),
+    'loadParentProductIds' => array('class_scope' => 'Mage_Catalog_Model_Product'),
+    'loadPrices' => array('class_scope' => 'Mage_Catalog_Model_Resource_Product_Type_Configurable_Attribute'),
+    'loadProductPrices' => array('class_scope' => 'Mage_Catalog_Model_Resource_Product_Attribute_Backend_Tierprice'),
+    'lockOrderInventoryData' => array('class_scope' => 'Mage_CatalogInventory_Model_Observer'),
+    'logEncryptionKeySave',
+    'logInvitationSave',
     'mergeFiles' => array('class_scope' => 'Mage_Core_Helper_Data'),
-    'getLocaleBaseDir' => array('class_scope' => 'Mage_Core_Model_Design_Package'),
+    'order_success_page_view' => array('class_scope' => 'Mage_GoogleAnalytics_Model_Observer'),
+    'orderedAction' => array('class_scope' => 'Mage_Adminhtml_Report_ProductController'),
+    'parse' => array('class_scope' => 'Mage_Catalog_Model_Convert_Parser_Product'),
+    'parse' => array('class_scope' => 'Mage_Customer_Model_Convert_Parser_Customer'),
+    'parseDateTime' => array('class_scope' => 'Mage_Core_Model_Date'),
+    'postDispatchMyAccountSave',
+    'prepareCacheId' => array('class_scope' => 'Mage_Core_Model_App'),
+    'prepareGoogleOptimizerScripts',
+    'preprocess' => array('class_scope' => 'Mage_Newsletter_Model_Template'),
+    'processBeacon',
+    'processBeforeVoid' => array('class_scope' => 'Mage_Payment_Model_Method_Abstract'),
+    'processSubst' => array('class_scope' => 'Mage_Core_Model_Store'),
+    'rebuildCategoryLevels' => array('class_scope' => 'Mage_Catalog_Model_Resource_Setup'),
+    'regenerateSessionId' => array('class_scope' => 'Mage_Core_Model_Session_Abstract'),
+    'refundOrderItem' => array('class_scope' => 'Mage_CatalogInventory_Model_Observer'),
+    'removeCustomerFromSegments',
+    'removeCustomerFromSegments',
+    'revalidateCookie' => array('class_scope' => 'Mage_Core_Model_Session_Abstract_Varien'),
+    'sales_order_afterPlace',
+    'sales_quote_address_discount_item',
+    'salesOrderPaymentPlaceEnd',
+    'saveAction' => array('class_scope' => 'Mage_Tag_CustomerController'),
+    'saveSegmentCustomersFromSelect',
+    'send' => array('class_scope' => 'Mage_Newsletter_Model_Template'),
+    'sendNewPasswordEmail',
+    'setAnonSuffix' => array('class_scope' => 'Mage_Core_Block_Abstract'),
+    'setBlockAlias',
+    'setCustomerId' => array('class_scope' => 'Mage_Customer_Model_Resource_Address'),
+    'setIsAjaxRequest' => array('class_scope' => 'Mage_Core_Model_Translate_Inline'),
+    'setIsAnonymous' => array('class_scope' => 'Mage_Core_Block_Abstract'),
+    'setJoinFlag' => array('class_scope' => 'Mage_Tag_Model_Resource_Customer_Collection'),
+    'setJoinFlag' => array('class_scope' => 'Mage_Tag_Model_Resource_Product_Collection'),
+    'setJoinFlag' => array('class_scope' => 'Mage_Tag_Model_Resource_Tag_Collection'),
+    'setOrderId' => array('class_scope' => 'Mage_Shipping_Block_Tracking_Popup'),
+    'setParentBlock',
+    'setProfile' => array('class_scope' => 'Varien_Convert_Container_Abstract'),
+    'setSaveTemplateFlag' => array('class_scope' => 'Mage_Newsletter_Model_Queue'),
+    'setShipId' => array('class_scope' => 'Mage_Shipping_Block_Tracking_Popup'),
+    'setTaxGroupFilter',
+    'setTrackId' => array('class_scope' => 'Mage_Shipping_Block_Tracking_Popup'),
+    'shaCrypt' => array('suggestion' => 'Mage_Ogone_Model_Api::getHash'),
+    'shaCryptValidation' => array('suggestion' => 'Mage_Ogone_Model_Api::getHash'),
+    'shouldCustomerHaveOneBalance',
+    'shouldShowOneBalance',
+    'sortChildren',
+    'toOptionArray' => array('class_scope' => 'Mage_Cms_Model_Resource_Page_Collection'),
+    'toOptionArray' => array('class_scope' => 'Mage_Sendfriend_Model_Sendfriend'),
+    'truncate' => array('class_scope' => 'Varien_Db_Adapter_Pdo_Mysql'),
+    'unsetBlock',
+    'unsetJoinFlag' => array('class_scope' => 'Mage_Tag_Model_Resource_Customer_Collection'),
+    'unsetJoinFlag' => array('class_scope' => 'Mage_Tag_Model_Resource_Product_Collection'),
+    'unsetJoinFlag' => array('class_scope' => 'Mage_Tag_Model_Resource_Tag_Collection'),
+    'useValidateRemoteAddr' => array('class_scope' => 'Mage_Core_Model_Session_Abstract'),
+    'useValidateHttpVia' => array('class_scope' => 'Mage_Core_Model_Session_Abstract'),
+    'useValidateHttpXForwardedFor' => array('class_scope' => 'Mage_Core_Model_Session_Abstract'),
+    'useValidateHttpUserAgent' => array('class_scope' => 'Mage_Core_Model_Session_Abstract'),
+    'updateTable' => array('class_scope' => 'Mage_Core_Model_Resource_Setup'),
+    'urlEscape' => array('suggestion' => 'urlEscape'),
+    'validateDataArray' => array('class_scope' => 'Varien_Convert_Container_Abstract'),
     'validateFile' => array('class_scope' => 'Mage_Core_Model_Design_Package'),
-    'getFallbackTheme',
-    'getMergedJsUrl',
-    'getMergedCssUrl',
+    'validateOrder' => array('class_scope' => 'Mage_Checkout_Model_Type_Onepage'),
 );
diff --git a/dev/tests/static/testsuite/Legacy/_files/obsolete_properties.php b/dev/tests/static/testsuite/Legacy/_files/obsolete_properties.php
index e56d77a1e51f2bf71a58f7dc039c0634b9c66297..03b55a81888e4ae6173b2cdf15a84a07ced063cd 100644
--- a/dev/tests/static/testsuite/Legacy/_files/obsolete_properties.php
+++ b/dev/tests/static/testsuite/Legacy/_files/obsolete_properties.php
@@ -25,15 +25,23 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 return array(
+    '_anonSuffix' => array('class_scope' => 'Mage_Core_Block_Abstract'),
+    '_isAnonymous' => array('class_scope' => 'Mage_Core_Block_Abstract'),
     'decoratedIsFirst' => array('suggestion' => 'getDecoratedIsFirst'),
     'decoratedIsEven' => array('suggestion' => 'getDecoratedIsEven'),
     'decoratedIsOdd' => array('suggestion' => 'getDecoratedIsOdd'),
     'decoratedIsLast' => array('suggestion' => 'getDecoratedIsLast'),
+    '_alias' => array('class_scope' => 'Mage_Core_Block_Abstract'),
+    '_children' => array('class_scope' => 'Mage_Core_Block_Abstract'),
+    '_childrenHtmlCache' => array('class_scope' => 'Mage_Core_Block_Abstract'),
+    '_childGroups' => array('class_scope' => 'Mage_Core_Block_Abstract'),
     '_currencyNameTable',
     '_combineHistory',
     '_searchTextFields',
     '_skipFieldsByModel',
     '_imageFields' => array('class_scope' => 'Mage_Catalog_Model_Convert_Adapter_Product'),
+    '_parent' => array('class_scope' => 'Mage_Core_Block_Abstract'),
+    '_parentBlock' => array('class_scope' => 'Mage_Core_Block_Abstract'),
     '_setAttributes' => array('class_scope' => 'Mage_Catalog_Model_Product_Type_Abstract'),
     '_storeFilter' => array('class_scope' => 'Mage_Catalog_Model_Product_Type_Abstract'),
     '_addMinimalPrice' => array('class_scope' => 'Mage_Catalog_Model_Resource_Product_Collection'),
@@ -57,4 +65,6 @@ return array(
     '_track_id',
     '_order_id',
     '_ship_id',
+    '_sortedChildren' => array('class_scope' => 'Mage_Core_Block_Abstract'),
+    '_sortInstructions' => array('class_scope' => 'Mage_Core_Block_Abstract'),
 );
diff --git a/dev/tests/static/testsuite/Php/LiveCodeTest.php b/dev/tests/static/testsuite/Php/LiveCodeTest.php
index 2795c4746ffe13b37ed0507026cda336e59e35f3..0104f25b1fe3e057ad13d8c6dad7534c68a38162 100644
--- a/dev/tests/static/testsuite/Php/LiveCodeTest.php
+++ b/dev/tests/static/testsuite/Php/LiveCodeTest.php
@@ -46,7 +46,7 @@ class Php_LiveCodeTest extends PHPUnit_Framework_TestCase
 
     public static function setUpBeforeClass()
     {
-        self::$_reportDir = PATH_TO_SOURCE_CODE . '/dev/tests/static/report';
+        self::$_reportDir = Utility_Files::init()->getPathToSource() . '/dev/tests/static/report';
         if (!is_dir(self::$_reportDir)) {
             mkdir(self::$_reportDir, 0777);
         }
@@ -100,7 +100,7 @@ class Php_LiveCodeTest extends PHPUnit_Framework_TestCase
             $result = array_merge($result, file($list));
         }
         $map = function($value) {
-            return trim($value) ? PATH_TO_SOURCE_CODE . '/' . trim($value) : '';
+            return trim($value) ? Utility_Files::init()->getPathToSource() . '/' . trim($value) : '';
         };
         return array_filter(array_map($map, $result), 'file_exists');
     }
diff --git a/dev/tests/static/testsuite/Php/_files/blacklist/core.txt b/dev/tests/static/testsuite/Php/_files/blacklist/core.txt
index 9e2b97c0e79ff91410f1aba27e1b7ffa6822e777..a4807a55ae13a93533cb413dcfd3e5b61d750aa3 100644
--- a/dev/tests/static/testsuite/Php/_files/blacklist/core.txt
+++ b/dev/tests/static/testsuite/Php/_files/blacklist/core.txt
@@ -1,3 +1,4 @@
+app/code/core/Mage/DesignEditor/view
 dev/tests/integration/framework/tests/unit/testsuite/Magento/Test/TestSuite/_files
 dev/tests/integration/testsuite/integrity/modular/TemplateFilesTest.php
 dev/tests/integration/testsuite/integrity/theme/TemplateFilesTest.php
diff --git a/dev/tests/static/testsuite/Php/_files/whitelist/core.txt b/dev/tests/static/testsuite/Php/_files/whitelist/core.txt
index b4b336c448fe43a9d135a8262e0d1f518f68ee09..d9534cf54dfe0a46b56d42d293d6fa995c0b2dfd 100644
--- a/dev/tests/static/testsuite/Php/_files/whitelist/core.txt
+++ b/dev/tests/static/testsuite/Php/_files/whitelist/core.txt
@@ -1,11 +1,18 @@
 app/bootstrap.php
+app/code/core/Mage/Adminhtml/Model/Observer.php
 app/code/core/Mage/Core/Model/Design.php
 app/code/core/Mage/Core/Model/ShellAbstract.php
+app/code/core/Mage/Core/Model/Layout.php
+app/code/core/Mage/Core/Model/Layout/Structure.php
+app/code/core/Mage/Core/Model/Layout/Update.php
+app/code/core/Mage/Core/Block/Abstract.php
+app/code/core/Mage/DesignEditor
 app/code/core/Mage/Index/Model/Indexer/Abstract.php
 app/code/core/Mage/Index/Model/Shell.php
 app/code/core/Mage/Log/Model/Resource/Helper
 app/code/core/Mage/Log/Model/Resource/Shell.php
 app/code/core/Mage/Log/Model/Shell.php
+app/code/core/Mage/Rss/Controller/AdminhtmlAbstract.php
 dev/shell
 dev/tests/integration
 dev/tests/static
diff --git a/dev/tests/static/testsuite/Util/Files.php b/dev/tests/static/testsuite/Util/Files.php
deleted file mode 100644
index b3caf9ba871d561dd35a0bcd838852ee064b2cd7..0000000000000000000000000000000000000000
--- a/dev/tests/static/testsuite/Util/Files.php
+++ /dev/null
@@ -1,199 +0,0 @@
-<?php
-/**
- * A helper to gather specific kinds if files in Magento 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.
- *
- * @category    tests
- * @package     static
- * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
- * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
- */
-class Util_Files
-{
-    /**
-     * In-memory cache for the data sets
-     *
-     * @var array
-     */
-    protected static $_cache = array();
-
-    /**
-     * Compose PHPUnit's data sets that contain each file as the first argument
-     *
-     * @param array $files
-     * @return array
-     */
-    public static function composeDataSets(array $files)
-    {
-        $result = array();
-        foreach ($files as $file) {
-            /* Use filename as a data set name to not include it to every assertion message */
-            $result[$file] = array($file);
-        }
-        return $result;
-    }
-
-    /**
-     * Returns array of PHP-files, that use or declare Magento application classes and Magento libs
-     *
-     * @return array
-     */
-    public static function getPhpFiles()
-    {
-        if (isset(self::$_cache[__METHOD__])) {
-            return self::$_cache[__METHOD__];
-        }
-        $root = PATH_TO_SOURCE_CODE;
-        $pool = $namespace = $module = $area = $package = $theme = '*';
-        $files = array_merge(
-            glob($root . '/{app,pub}/*.php', GLOB_NOSORT | GLOB_BRACE),
-            self::_getFiles(array("{$root}/app/code/{$pool}/{$namespace}/{$module}"), '*.{php,phtml}'),
-            self::_getFiles(array("{$root}/app/design/{$area}/{$package}/{$theme}/{$namespace}_{$module}"), '*.phtml'),
-            self::_getFiles(array("{$root}/downloader"), '*.php'),
-            self::_getFiles(array("{$root}/lib/{Mage,Magento,Varien}"), '*.php')
-        );
-        $result = self::composeDataSets($files);
-        self::$_cache[__METHOD__] = $result;
-        return $result;
-    }
-
-    /**
-     * Returns list of xml files, used by Magento application
-     *
-     * @return array
-     */
-    public static function getXmlFiles()
-    {
-        return array_merge(
-            self::getConfigFiles(),
-            self::getLayoutFiles()
-        );
-    }
-
-    /**
-     * Returns list of configuration files, used by Magento application
-     *
-     * @param string $fileNamePattern
-     * @param array $excludedFileNames
-     * @return array
-     */
-    public static function getConfigFiles(
-        $fileNamePattern = '*.xml', $excludedFileNames = array('wsdl.xml', 'wsdl2.xml', 'wsi.xml')
-    ) {
-        $cacheKey = __METHOD__ . '|' . serialize(func_get_args());
-        if (isset(self::$_cache[$cacheKey])) {
-            return self::$_cache[$cacheKey];
-        }
-        $files = glob(PATH_TO_SOURCE_CODE . "/app/code/*/*/*/etc/$fileNamePattern", GLOB_NOSORT | GLOB_BRACE);
-        $files = array_filter($files, function ($file) use ($excludedFileNames) {
-            return !in_array(basename($file), $excludedFileNames);
-        });
-        $result = self::composeDataSets($files);
-        self::$_cache[$cacheKey] = $result;
-        return $result;
-    }
-
-    /**
-     * Returns list of layout files, used by Magento application modules
-     *
-     * @return array
-     */
-    public static function getLayoutFiles()
-    {
-        if (isset(self::$_cache[__METHOD__])) {
-            return self::$_cache[__METHOD__];
-        }
-        $root = PATH_TO_SOURCE_CODE;
-        $pool = $namespace = $module = $area = $package = $theme = '*';
-        $files = array_merge(
-            self::_getFiles(
-                array(
-                    "{$root}/app/code/{$pool}/{$namespace}/{$module}/view/{$area}",
-                    "{$root}/app/design/{$area}/{$package}/{$theme}/{$namespace}_{$module}",
-                ),
-                '*.xml'
-            ),
-            glob("{$root}/app/design/{$area}/{$package}/{$theme}/local.xml", GLOB_NOSORT)
-        );
-        $result = self::composeDataSets($files);
-        self::$_cache[__METHOD__] = $result;
-        return $result;
-    }
-
-    /**
-     * Returns list of Javascript files in Magento
-     *
-     * @return array
-     */
-    public static function getJsFiles()
-    {
-        if (isset(self::$_cache[__METHOD__])) {
-            return self::$_cache[__METHOD__];
-        }
-        $root = PATH_TO_SOURCE_CODE;
-        $pool = $namespace = $module = $area = $package = $theme = $skin = '*';
-        $files = self::_getFiles(
-            array(
-                "{$root}/app/code/{$pool}/{$namespace}/{$module}/view/{$area}",
-                "{$root}/app/design/{$area}/{$package}/{$theme}/skin/{$skin}",
-                "{$root}/pub/js/{mage,varien}"
-            ),
-            '*.js'
-        );
-        $result = self::composeDataSets($files);
-        self::$_cache[__METHOD__] = $result;
-        return $result;
-    }
-
-    /**
-     * Returns list of email template files
-     *
-     * @return array
-     */
-    public static function getEmailTemplates()
-    {
-        if (isset(self::$_cache[__METHOD__])) {
-            return self::$_cache[__METHOD__];
-        }
-        $files = self::_getFiles(array(PATH_TO_SOURCE_CODE . '/app/code/*/*/*/view/email'), '*.html');
-        $result = self::composeDataSets($files);
-        self::$_cache[__METHOD__] = $result;
-        return $result;
-    }
-
-    /**
-     * Retrieve all files in folders and sub-folders that match pattern (glob syntax)
-     *
-     * @param array $dirPatterns
-     * @param string $fileNamePattern
-     * @return array
-     */
-    protected static function _getFiles(array $dirPatterns, $fileNamePattern)
-    {
-        $result = array();
-        foreach ($dirPatterns as $oneDirPattern) {
-            $filesInDir = glob("$oneDirPattern/$fileNamePattern", GLOB_NOSORT | GLOB_BRACE);
-            $subDirs = glob("$oneDirPattern/*", GLOB_ONLYDIR | GLOB_NOSORT | GLOB_BRACE);
-            $filesInSubDir = self::_getFiles($subDirs, $fileNamePattern);
-            $result = array_merge($result, $filesInDir, $filesInSubDir);
-        }
-        return $result;
-    }
-}
diff --git a/dev/tests/static/testsuite/Util/Classes.php b/dev/tests/static/testsuite/Utility/Classes.php
similarity index 82%
rename from dev/tests/static/testsuite/Util/Classes.php
rename to dev/tests/static/testsuite/Utility/Classes.php
index b8e341538e35f50667cdefc7e9dd322ef9b1de7e..c00f0ee35a39a8e19b6e90a2b37638fa05b51e28 100644
--- a/dev/tests/static/testsuite/Util/Classes.php
+++ b/dev/tests/static/testsuite/Utility/Classes.php
@@ -26,7 +26,9 @@
  * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-class Util_Classes
+require_once __DIR__ . '/Files.php';
+
+class Utility_Classes
 {
     /**
      * Find all unique matches in specified content using specified PCRE
@@ -121,7 +123,7 @@ class Util_Classes
             $classes[] = $node->getName();
         }
 
-        $classes = array_map(array('Util_Classes', 'getCallbackClass'), $classes);
+        $classes = array_map(array('Utility_Classes', 'getCallbackClass'), $classes);
         $classes = array_map('trim', $classes);
         $classes = array_unique($classes);
         $classes = array_filter($classes, function ($value) {
@@ -151,4 +153,28 @@ class Util_Classes
         ));
         return array_unique($classes);
     }
+
+    /**
+     * Scan application source code and find classes
+     *
+     * Sub-type pattern allows to distinguish "type" of a class within a module (for example, Block, Model)
+     * Returns array(<class> => <module>)
+     *
+     * @param string $subTypePattern
+     * @return array
+     */
+    public static function collectModuleClasses($subTypePattern = '[A-Za-z]+')
+    {
+        $pattern = '/^' . preg_quote(Utility_Files::init()->getPathToSource(), '/')
+            . '\/app\/code\/[a-z]+\/([A-Za-z]+)\/([A-Za-z]+)\/(' . $subTypePattern . '\/.+)\.php$/';
+        $result = array();
+        foreach (Utility_Files::init()->getPhpFiles(true, false, false, false) as $file) {
+            if (preg_match($pattern, $file, $matches)) {
+                $module = "{$matches[1]}_{$matches[2]}";
+                $class = "{$module}_" . str_replace('/', '_', $matches[3]);
+                $result[$class] = $module;
+            }
+        }
+        return $result;
+    }
 }
diff --git a/dev/tests/static/testsuite/Utility/Files.php b/dev/tests/static/testsuite/Utility/Files.php
new file mode 100644
index 0000000000000000000000000000000000000000..50bcf87d770c8aab0d7904c8be5169dc67e577e1
--- /dev/null
+++ b/dev/tests/static/testsuite/Utility/Files.php
@@ -0,0 +1,328 @@
+<?php
+/**
+ * A helper to gather specific kinds if files in Magento 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.
+ *
+ * @category    tests
+ * @package     static
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+class Utility_Files
+{
+    /**
+     * @var Utility_Files
+     */
+    protected static $_instance = null;
+
+    /**
+     * In-memory cache for the data sets
+     *
+     * @var array
+     */
+    protected static $_cache = array();
+
+    /**
+     * @var string
+     */
+    protected $_path = '';
+
+    /**
+     * Setter/Getter for an instance of self
+     *
+     * @param Utility_Files $instance
+     * @return Utility_Files
+     * @throws Exception when there is no instance set
+     */
+    public static function init(Utility_Files $instance = null)
+    {
+        if ($instance) {
+            self::$_instance = $instance;
+        }
+        if (!self::$_instance) {
+            throw new Exception('Instance is not set yet.');
+        }
+        return self::$_instance;
+    }
+
+    /**
+     * Compose PHPUnit's data sets that contain each file as the first argument
+     *
+     * @param array $files
+     * @return array
+     */
+    public static function composeDataSets(array $files)
+    {
+        $result = array();
+        foreach ($files as $file) {
+            /* Use filename as a data set name to not include it to every assertion message */
+            $result[$file] = array($file);
+        }
+        return $result;
+    }
+
+    /**
+     * Set path to source code
+     *
+     * @param string $pathToSource
+     */
+    public function __construct($pathToSource)
+    {
+        $this->_path = $pathToSource;
+    }
+
+    /**
+     * Getter for _path
+     *
+     * @return string
+     */
+    public function getPathToSource()
+    {
+        return $this->_path;
+    }
+
+    /**
+     * Returns array of PHP-files, that use or declare Magento application classes and Magento libs
+     *
+     * @param bool $appCode   application PHP-code
+     * @param bool $otherCode non-application PHP-code (doesn't include "dev" directory)
+     * @param bool $templates application PHTML-code
+     * @param bool $asDataSet
+     * @return array
+     */
+    public function getPhpFiles($appCode = true, $otherCode = true, $templates = true, $asDataSet = true)
+    {
+        $key = __METHOD__ . "/{$this->_path}/{$appCode}/{$otherCode}/{$templates}";
+        if (!isset(self::$_cache[$key])) {
+            $pool = $namespace = $module = $area = $package = $theme = '*';
+
+            $files = array();
+            if ($appCode) {
+                $files = array_merge($files, glob($this->_path . '/app/*.php', GLOB_NOSORT | GLOB_BRACE),
+                    self::_getFiles(array("{$this->_path}/app/code/{$pool}/{$namespace}/{$module}"), '*.php')
+                );
+            }
+            if ($otherCode) {
+                $files = array_merge($files, glob($this->_path . '/pub/*.php', GLOB_NOSORT | GLOB_BRACE),
+                    self::_getFiles(array("{$this->_path}/downloader"), '*.php'),
+                    self::_getFiles(array("{$this->_path}/lib/{Mage,Magento,Varien}"), '*.php')
+                );
+            }
+            if ($templates) {
+                $files = array_merge($files,
+                    self::_getFiles(array("{$this->_path}/app/code/{$pool}/{$namespace}/{$module}"), '*.phtml'),
+                    self::_getFiles(
+                        array("{$this->_path}/app/design/{$area}/{$package}/{$theme}/{$namespace}_{$module}"), '*.phtml'
+                    )
+                );
+            }
+            self::$_cache[$key] = $files;
+        }
+
+        if ($asDataSet) {
+            return self::composeDataSets(self::$_cache[$key]);
+        }
+        return self::$_cache[$key];
+    }
+
+    /**
+     * Returns list of xml files, used by Magento application
+     *
+     * @return array
+     */
+    public function getXmlFiles()
+    {
+        return array_merge(
+            self::getConfigFiles(),
+            self::getLayoutFiles()
+        );
+    }
+
+    /**
+     * Returns list of configuration files, used by Magento application
+     *
+     * @param string $fileNamePattern
+     * @param array $excludedFileNames
+     * @return array
+     */
+    public function getConfigFiles(
+        $fileNamePattern = '*.xml', $excludedFileNames = array('wsdl.xml', 'wsdl2.xml', 'wsi.xml')
+    ) {
+        $cacheKey = __METHOD__ . '|' . $this->_path . '|' . serialize(func_get_args());
+        if (isset(self::$_cache[$cacheKey])) {
+            return self::$_cache[$cacheKey];
+        }
+        $files = glob($this->_path . "/app/code/*/*/*/etc/$fileNamePattern", GLOB_NOSORT | GLOB_BRACE);
+        $files = array_filter($files, function ($file) use ($excludedFileNames) {
+            return !in_array(basename($file), $excludedFileNames);
+        });
+        $result = self::composeDataSets($files);
+        self::$_cache[$cacheKey] = $result;
+        return $result;
+    }
+
+    /**
+     * Returns list of layout files, used by Magento application modules
+     *
+     * An incoming array can contain the following items
+     * array (
+     *     'pool'           => 'pool_name',
+     *     'namespace'      => 'namespace_name',
+     *     'module'         => 'module_name',
+     *     'area'           => 'area_name',
+     *     'package'        => 'package_name',
+     *     'theme'          => 'theme_name',
+     *     'include_code'   => true|false,
+     *     'include_design' => true|false,
+     * )
+     *
+     * @param array $incomingParams
+     * @param bool $asDataSet
+     * @return array
+     */
+    public function getLayoutFiles($incomingParams = array(), $asDataSet = true)
+    {
+         $params = array(
+            'pool' => '*',
+            'namespace' => '*',
+            'module' => '*',
+            'area' => '*',
+            'package' => '*',
+            'theme' => '*',
+            'include_code' => true,
+            'include_design' => true
+        );
+        foreach (array_keys($params) as $key) {
+            if (isset($incomingParams[$key])) {
+                $params[$key] = $incomingParams[$key];
+            }
+        }
+        $cacheKey = md5($this->_path . '|' . implode('|', $params));
+
+        if (!isset(self::$_cache[__METHOD__][$cacheKey])) {
+            $files = array();
+            if ($params['include_code']) {
+                $files = self::_getFiles(
+                    array("{$this->_path}/app/code/{$params['pool']}/{$params['namespace']}/{$params['module']}"
+                        . "/view/{$params['area']}"),
+                    '*.xml'
+                );
+            }
+            if ($params['include_design']) {
+                $files = array_merge(
+                    $files,
+                    self::_getFiles(
+                        array("{$this->_path}/app/design/{$params['area']}/{$params['package']}/{$params['theme']}"
+                            . "/{$params['namespace']}_{$params['module']}"),
+                        '*.xml'
+                    ),
+                    glob(
+                        "{$this->_path}/app/design/{$params['area']}/{$params['package']}/{$params['theme']}/local.xml",
+                        GLOB_NOSORT
+                    )
+                );
+            }
+            self::$_cache[__METHOD__][$cacheKey] = $files;
+        }
+
+        if ($asDataSet) {
+            return self::composeDataSets(self::$_cache[__METHOD__][$cacheKey]);
+        }
+        return self::$_cache[__METHOD__][$cacheKey];
+    }
+
+    /**
+     * Returns list of Javascript files in Magento
+     *
+     * @return array
+     */
+    public function getJsFiles()
+    {
+        $key = __METHOD__ . $this->_path;
+        if (isset(self::$_cache[$key])) {
+            return self::$_cache[$key];
+        }
+        $pool = $namespace = $module = $area = $package = $theme = $skin = '*';
+        $files = self::_getFiles(
+            array(
+                "{$this->_path}/app/code/{$pool}/{$namespace}/{$module}/view/{$area}",
+                "{$this->_path}/app/design/{$area}/{$package}/{$theme}/skin/{$skin}",
+                "{$this->_path}/pub/js/{mage,varien}"
+            ),
+            '*.js'
+        );
+        $result = self::composeDataSets($files);
+        self::$_cache[$key] = $result;
+        return $result;
+    }
+
+    /**
+     * Returns list of email template files
+     *
+     * @return array
+     */
+    public function getEmailTemplates()
+    {
+        $key = __METHOD__ . $this->_path;
+        if (isset(self::$_cache[$key])) {
+            return self::$_cache[$key];
+        }
+        $files = self::_getFiles(array($this->_path . '/app/code/*/*/*/view/email'), '*.html');
+        $result = self::composeDataSets($files);
+        self::$_cache[$key] = $result;
+        return $result;
+    }
+
+    /**
+     * Retrieve all files in folders and sub-folders that match pattern (glob syntax)
+     *
+     * @param array $dirPatterns
+     * @param string $fileNamePattern
+     * @return array
+     */
+    protected static function _getFiles(array $dirPatterns, $fileNamePattern)
+    {
+        $result = array();
+        foreach ($dirPatterns as $oneDirPattern) {
+            $filesInDir = glob("$oneDirPattern/$fileNamePattern", GLOB_NOSORT | GLOB_BRACE);
+            $subDirs = glob("$oneDirPattern/*", GLOB_ONLYDIR | GLOB_NOSORT | GLOB_BRACE);
+            $filesInSubDir = self::_getFiles($subDirs, $fileNamePattern);
+            $result = array_merge($result, $filesInDir, $filesInSubDir);
+        }
+        return $result;
+    }
+
+    /**
+     * Check if specified class exists within code pools
+     *
+     * @param string $class
+     * @param string &$path
+     * @return bool
+     */
+    public function codePoolClassFileExists($class, &$path = '')
+    {
+        $path = implode('/', explode('_', $class)) . '.php';
+        return file_exists($this->_path . "/app/code/core/{$path}")
+            || file_exists($this->_path . "/app/code/community/{$path}")
+            || file_exists($this->_path . "/app/code/local/{$path}")
+            || file_exists($this->_path . "/lib/{$path}")
+        ;
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Catalog/Model/Layer/Filter/Price/_files/_algorithm_data.php b/dev/tests/unit/testsuite/Mage/Catalog/Model/Layer/Filter/Price/_files/_algorithm_data.php
deleted file mode 100644
index 6e262c13a0f5b6032ffe61088c2965ea2067d0ea..0000000000000000000000000000000000000000
--- a/dev/tests/unit/testsuite/Mage/Catalog/Model/Layer/Filter/Price/_files/_algorithm_data.php
+++ /dev/null
@@ -1,412 +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_Catalog
- * @subpackage  integration_tests
- * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
- * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
- */
-
-/**
- * Test cases for pricesSegmentationDataProvider
- */
-
-$testCases = array(
-    // no products, no prices
-    array(array(), 1, array()),
-    // small prices test case
-    array(range(0.01, 0.08, 0.01), 2, array(
-        array(
-            'from'  => 0,
-            'to'    => 0.05,
-            'count' => 4,
-        ),
-        array(
-            'from'  => 0.05,
-            'to'    => '',
-            'count' => 4,
-        ),
-    )),
-    // simple test case (should skip first quantile)
-    array(
-        array(
-            0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01,
-            0.01, 0.03, 0.05, 0.05, 0.06, 0.07, 0.07, 0.08, 0.08, 0.09, 0.15
-        ), 3, array(
-            array(
-                'from'  => 0,
-                'to'    => 0.05,
-                'count' => 12,
-            ),
-            array(
-                'from'  => 0.05,
-                'to'    => '',
-                'count' => 9,
-            ),
-        )
-    ),
-    // test if best rounding factor is used
-    array(
-        array(10.19, 10.2, 10.2, 10.2, 10.21),
-        2,
-        array(
-            array(
-                'from'  => 10.19,
-                'to'    => 10.19,
-                'count' => 1,
-            ),
-            array(
-                'from'  => 10.2,
-                'to'    => '',
-                'count' => 4,
-            ),
-        )
-    ),
-    // test if best rounding factor is used
-    array(
-        array(10.18, 10.19, 10.19, 10.19, 10.2),
-        2,
-        array(
-            array(
-                'from'  => 0,
-                'to'    => 10.2,
-                'count' => 4,
-            ),
-            array(
-                'from'  => 10.2,
-                'to'    => 10.2,
-                'count' => 1,
-            ),
-        )
-    ),
-    // test preventing low count in interval and rounding factor to have lower priority
-    array(
-        array(
-            0.01, 0.01, 0.01, 0.02, 0.02, 0.03, 0.03, 0.04, 0.04, 0.04,
-            0.05, 0.05, 0.05, 0.06, 0.06, 0.06, 0.06, 0.07, 0.07, 0.08, 0.08,
-            2.99, 5.99, 5.99, 5.99, 5.99, 5.99, 5.99, 5.99, 5.99, 5.99, 13.50,
-            15.99, 41.95, 69.99, 89.99, 99.99, 99.99, 160.99, 161.94,
-            199.99, 199.99, 199.99, 239.99, 329.99, 447.98, 550.00, 599.99,
-            699.99, 750.00, 847.97, 1599.99, 2699.99, 4999.95
-        ), 7, array(
-            array(
-                'from'  => 0,
-                'to'    => 0.05,
-                'count' => 10,
-            ),
-            // this is important, that not 0.06 is used to prevent low count in interval
-            array(
-                'from'  => 0.05,
-                'to'    => 0.07,
-                'count' => 7,
-            ),
-            array(
-                'from'  => 0.07,
-                'to'    => 5,
-                'count' => 5,
-            ),
-            array(
-                'from'  => 5.99,
-                'to'    => 5.99,
-                'count' => 9,
-            ),
-            array(
-                'from'  => 10,
-                'to'    => 100,
-                'count' => 7,
-            ),
-            array(
-                'from'  => 100,
-                'to'    => 500,
-                'count' => 8,
-            ),
-            array(
-                'from'  => 500,
-                'to'    => '',
-                'count' => 8,
-            ),
-        )
-    ),
-    // test with large values (variance is near to zero)
-    array(
-        array_merge(array(9659.57), array_fill(0, 231, 9659.58), array(9659.59)),
-        10,
-        array(
-            array(
-                'from'  => 9659.57,
-                'to'    => 9659.57,
-                'count' => 1,
-            ),
-            array(
-                'from'  => 9659.58,
-                'to'    => 9659.58,
-                'count' => 231,
-            ),
-            array(
-                'from'  => 9659.59,
-                'to'    => 9659.59,
-                'count' => 1,
-            ),
-        )
-    ),
-    // another test with large values (variance is near to zero)
-    array(
-        array_merge(array(8997.71), array_fill(0, 291, 8997.72), array(8997.73)),
-        10,
-        array(
-            array(
-                'from'  => 8997.71,
-                'to'    => 8997.71,
-                'count' => 1,
-            ),
-            array(
-                'from'  => 8997.72,
-                'to'    => 8997.72,
-                'count' => 291,
-            ),
-            array(
-                'from'  => 8997.73,
-                'to'    => 8997.73,
-                'count' => 1,
-            ),
-        )
-    ),
-    // simple test
-    array(
-        array(3336.23, 3336.24, 3336.24),
-        2,
-        array(
-            array(
-                'from'  => 3336.23,
-                'to'    => 3336.23,
-                'count' => 1,
-            ),
-            array(
-                'from'  => 3336.24,
-                'to'    => 3336.24,
-                'count' => 2,
-            ),
-        )
-    ),
-    // simple test
-    array(
-        array(6323.19, 6323.2, 6323.2, 6323.2),
-        2,
-        array(
-            array(
-                'from'  => 6323.19,
-                'to'    => 6323.19,
-                'count' => 1,
-            ),
-            array(
-                'from'  => 6323.2,
-                'to'    => 6323.2,
-                'count' => 3,
-            ),
-        )
-    ),
-    // simple test
-    array(
-        array(8732.58, 8732.59, 8732.59, 8732.59),
-        2,
-        array(
-            array(
-                'from'  => 8732.58,
-                'to'    => 8732.58,
-                'count' => 1,
-            ),
-            array(
-                'from'  => 8732.59,
-                'to'    => 8732.59,
-                'count' => 3,
-            ),
-        )
-    ),
-    // simple test
-    array(
-        array(2623.35, 2623.36, 2623.36),
-        2,
-        array(
-            array(
-                'from'  => 2623.35,
-                'to'    => 2623.35,
-                'count' => 1,
-            ),
-            array(
-                'from'  => 2623.36,
-                'to'    => 2623.36,
-                'count' => 2,
-            ),
-        )
-    ),
-    // simple test
-    array(
-        array(
-            13.5, 41.95, 69.99, 89.99, 99.99, 99.99, 160.99, 161.94, 199.99, 199.99, 199.99,
-            239.99, 329.99, 447.98, 550, 599.99, 699.99, 750, 847.97, 1599.99, 2699.99, 4999.95
-        ), 4, array(
-            array(
-                'from'  => 0,
-                'to'    => 100,
-                'count' => 6,
-            ),
-            array(
-                'from'  => 100,
-                'to'    => 200,
-                'count' => 5,
-            ),
-            array(
-                'from'  => 200,
-                'to'    => 600,
-                'count' => 5,
-            ),
-            array(
-                'from'  => 600,
-                'to'    => '',
-                'count' => 6,
-            ),
-        )
-    ),
-    // simple test
-    array(
-        array(
-            5.99, 5.99, 7.99, 8.99, 8.99, 9.99, 9.99, 9.99, 9.99, 9.99,
-            14.6, 15.99, 16, 16.99, 17, 17.5, 18.99, 19, 20.99, 24.99
-        ), 3, array(
-            array(
-                'from'  => 0,
-                'to'    => 9,
-                'count' => 5,
-            ),
-            array(
-                'from'  => 9.99,
-                'to'    => 9.99,
-                'count' => 5,
-            ),
-            array(
-                'from'  => 10,
-                'to'    => '',
-                'count' => 10,
-            ),
-        )
-    ),
-);
-
-
-// generate random data
-for ($i = 0; $i < 50; ++$i) {
-    $randomPrice       = mt_rand(1, 1000000) / 100;
-    $randomCount       = mt_rand(2, 300);
-    $randomCount1      = $randomCount + 4;
-    $randomPrice1      = round(
-        $randomPrice  + Mage_Catalog_Model_Layer_Filter_Price_Algorithm::MIN_POSSIBLE_PRICE, 2
-    );
-    $randomPrice2      = round(
-        $randomPrice1 + Mage_Catalog_Model_Layer_Filter_Price_Algorithm::MIN_POSSIBLE_PRICE, 2
-    );
-
-    $testCases = array_merge($testCases, array(
-        // one product with random price
-        array(array($randomPrice), 1, array(array(
-            'from'  => $randomPrice,
-            'to'    => $randomPrice,
-            'count' => 1,
-        ))),
-        // several products with the same price
-        array(array_fill(0, $randomCount, $randomPrice), 1, array(array(
-            'from'  => $randomPrice,
-            'to'    => $randomPrice,
-            'count' => $randomCount,
-        ))),
-        // one price is less than others
-        array(
-            array_merge(array($randomPrice), array_fill(
-                0,
-                $randomCount,
-                $randomPrice1
-            )),
-            null,
-            array(
-                array(
-                    'from'  => $randomPrice,
-                    'to'    => $randomPrice,
-                    'count' => 1,
-                ),
-                array(
-                    'from'  => $randomPrice1,
-                    'to'    => $randomPrice1,
-                    'count' => $randomCount,
-                ),
-            )
-        ),
-        // one price is bigger than others
-        array(
-            array_merge(array_fill(
-                0,
-                $randomCount,
-                $randomPrice
-            ), array($randomPrice1)),
-            null,
-            array(
-                array(
-                    'from'  => $randomPrice,
-                    'to'    => $randomPrice,
-                    'count' => $randomCount,
-                ),
-                array(
-                    'from'  => $randomPrice1,
-                    'to'    => $randomPrice1,
-                    'count' => 1,
-                ),
-            )
-        ),
-        // one price is less and one is bigger than others
-        array(
-            array_merge(
-                array($randomPrice), array_fill(
-                    0,
-                    $randomCount1,
-                    $randomPrice1
-                ), array($randomPrice2)
-            ),
-            null,
-            array(
-                array(
-                    'from'  => $randomPrice,
-                    'to'    => $randomPrice,
-                    'count' => 1,
-                ),
-                array(
-                    'from'  => $randomPrice1,
-                    'to'    => $randomPrice1,
-                    'count' => $randomCount1,
-                ),
-                array(
-                    'from'  => $randomPrice2,
-                    'to'    => $randomPrice2,
-                    'count' => 1,
-                ),
-            )
-        ),
-    ));
-}
-
-return $testCases;
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Layout/ElementTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Layout/ElementTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..8f509e24031c9d8bad08d999f2b302aebf78d271
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Layout/ElementTest.php
@@ -0,0 +1,78 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Core
+ */
+/**
+ * Test class for Mage_Core_Model_Layout_Element
+ */
+class Mage_Core_Model_Layout_ElementTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @dataProvider elementNameDataProvider
+     */
+    public function testGetElementName($xml, $name)
+    {
+        $model = new Mage_Core_Model_Layout_Element($xml);
+        $this->assertEquals($name, $model->getElementName());
+    }
+
+    public function elementNameDataProvider()
+    {
+        return array(
+            array('<block name="name" />', 'name'),
+            array('<container name="name" />', 'name'),
+            array('<reference name="name" />', 'name'),
+            array('<invalid name="name" />', false),
+            array('<block />', ''),
+        );
+    }
+
+    /**
+     * @dataProvider siblingDataProvider
+     */
+    public function testGetSibling($xml, $expected)
+    {
+        $model = new Mage_Core_Model_Layout_Element($xml);
+        $this->assertEquals($expected, $model->getSibling());
+    }
+
+    public function siblingDataProvider()
+    {
+        return array(
+            array('<block name="name" before="-" />', ''),
+            array('<block name="name" before="" />', ''),
+            array('<block name="name" before="first" />', 'first'),
+            array('<block name="name" after="-" />', ''),
+            array('<block name="name" after="" />', ''),
+            array('<block name="name" after="last" />', 'last'),
+            array('<block name="name" before="first" after="last" />', 'first'),
+            array('<block name="name" after="last" before="first" />', 'first'),
+        );
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/Core/Model/Layout/StructureTest.php b/dev/tests/unit/testsuite/Mage/Core/Model/Layout/StructureTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..a1928e43b694bc621a7cb0e89c90e5a4b037effa
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/Core/Model/Layout/StructureTest.php
@@ -0,0 +1,368 @@
+<?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) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_Core
+ */
+/**
+ * Test class for Mage_Core_Model_Layout_Structure.
+ */
+class Mage_Core_Model_Layout_StructureTest extends PHPUnit_Framework_TestCase
+{
+    /**
+     * @var Mage_Core_Model_Layout_Structure
+     */
+    protected $_model;
+
+    protected function setUp()
+    {
+        $this->_model = new Mage_Core_Model_Layout_Structure;
+    }
+
+    public function testGetParentName()
+    {
+        $parent = 'parent';
+        $child = 'child';
+        $this->_model->insertElement('', $parent, 'container');
+        $this->assertEmpty($this->_model->getParentName($parent));
+
+        $this->_model->insertElement($parent, $child, 'block');
+        $parentName = $this->_model->getParentName($child);
+        $this->assertEquals($parent, $parentName);
+    }
+
+    public function testGetChildNames()
+    {
+        $parent = 'parent';
+        $children = array('child1', 'child2', 'child3');
+
+        $this->_model->insertContainer('', $parent);
+        foreach ($children as $child) {
+            $this->_model->insertElement($parent, $child, 'block');
+        }
+        $childNames = $this->_model->getChildNames($parent);
+        $this->assertEquals($children, $childNames);
+    }
+
+    public function testSetChild()
+    {
+        $parent = 'parent';
+        $child = 'child';
+        $alias = 'alias';
+        $this->_model->insertContainer('', $parent);
+        $this->assertEmpty($this->_model->getChildNames($parent));
+        $this->_model->setChild($parent, $child, $alias);
+        $this->assertEquals($child, $this->_model->getChildName($parent, $alias));
+    }
+
+    public function testGetChildBeforeParent()
+    {
+        $parent = 'parent';
+        $child = 'child';
+        $alias = 'alias';
+        $this->_model->insertBlock($parent, $child, $alias);
+        $this->assertEmpty($this->_model->getElementAttribute($parent, 'type'));
+        $this->assertEquals($parent, $this->_model->getParentName($child));
+        $this->assertEquals($child, $this->_model->getChildName($parent, $alias));
+        $this->_model->insertBlock('', $parent);
+        $result = $this->_model->getChildName($parent, $alias);
+        $this->assertEquals($child, $result);
+    }
+
+    public function testSetGetElementAlias()
+    {
+        $alias1 = 'alias1';
+        $alias2 = 'alias1';
+        $name = 'name';
+        $this->_model->insertBlock('', $name, $alias1);
+        $this->assertEquals($alias1, $this->_model->getElementAlias($name));
+        $this->_model->setElementAlias($name, $alias2);
+        $this->assertEquals($alias2, $this->_model->getElementAlias($name));
+    }
+
+    public function testRenameElement()
+    {
+        $name1 = 'name1';
+        $name2 = 'name2';
+
+        $this->assertFalse($this->_model->hasElement($name1));
+        $this->_model->insertBlock('', $name1);
+        $this->assertTrue($this->_model->hasElement($name1));
+        $this->_model->renameElement($name1, $name2);
+        $this->assertFalse($this->_model->hasElement($name1));
+        $this->assertTrue($this->_model->hasElement($name2));
+    }
+
+    public function testGetElementAttribute()
+    {
+        $name = 'name';
+        $options = array('attribute' => 'value');
+        $this->_model->insertElement('', $name, 'block', '', '', '', $options);
+        $this->assertEquals($options['attribute'], $this->_model->getElementAttribute($name, 'attribute'));
+        $this->assertFalse($this->_model->getElementAttribute($name, 'invalid_attribute'));
+    }
+
+    public function testMove()
+    {
+        $parent1 = 'parent1';
+        $parent2 = 'parent2';
+        $block1 = 'block1';
+        $block2 = 'block2';
+
+        $this->_model->insertContainer('', $parent1);
+        $this->_model->insertContainer('', $parent2);
+        $this->_model->insertBlock('', $block1);
+        $this->_model->insertBlock('', $block2);
+        $this->assertEmpty($this->_model->getChildNames($parent1));
+        $this->assertEmpty($this->_model->getChildNames($parent2));
+        $this->_model->move($block1, $parent1);
+        $this->_model->move($block2, $parent2);
+        $this->assertEquals(array($block1), $this->_model->getChildNames($parent1));
+        $this->assertEquals(array($block2), $this->_model->getChildNames($parent2));
+        $this->_model->move($block2, $parent1);
+        $this->assertEquals(array($block1, $block2), $this->_model->getChildNames($parent1));
+        $this->assertEmpty($this->_model->getChildNames($parent2));
+    }
+
+    public function testUnsetChild()
+    {
+        $parent = 'parent';
+        $child = 'child';
+        $this->_model->insertBlock($parent, $child);
+        $this->_model->unsetChild($parent, $child);
+        $this->_model->insertBlock('', $parent);
+        $this->assertEmpty($this->_model->getParentName($child));
+    }
+
+    public function testUnsetElement()
+    {
+        $name = 'name';
+        $this->_model->insertBlock('', $name);
+        $this->assertTrue($this->_model->hasElement($name));
+        $this->_model->unsetElement($name);
+        $this->assertFalse($this->_model->hasElement($name));
+    }
+
+    public function testGetChildName()
+    {
+        $parent = 'parent';
+        $child = 'child';
+        $alias = 'alias';
+        $this->_model->insertBlock('', $parent);
+        $this->assertFalse($this->_model->getChildName($parent, $alias));
+        $this->_model->insertBlock($parent, $child, $alias);
+        $result = $this->_model->getChildName($parent, $alias);
+        $this->assertEquals($child, $result);
+    }
+
+    /**
+     * @dataProvider elementsDataProvider
+     */
+    public function testInsertElement($parentName, $name, $type, $alias = '', $after = true, $sibling = '',
+        $options = array(), $expected
+    ) {
+        $this->_model->insertElement($parentName, $name, $type, $alias, $after, $sibling, $options);
+        $this->assertEquals($expected, $this->_model->hasElement($name));
+    }
+
+    public function elementsDataProvider()
+    {
+        return array(
+            array('root', 'name', 'block', 'alias', true, 'sibling', array('htmlTag' => 'div'), true),
+            array('root', 'name', 'container', 'alias', true, 'sibling', array('htmlTag' => 'div'), true),
+            array('', 'name', 'block', 'alias', true, 'sibling', array('htmlTag' => 'div'), true),
+            array('root', 'name', 'invalid_type', 'alias', true, 'sibling', array('htmlTag' => 'div'), false),
+            array('root', 'name', 'block', 'alias', false, 'sibling', array('htmlTag' => 'div'), true),
+            array('root', 'name', 'block', 'alias', true, 'sibling', array(), true),
+        );
+    }
+
+    public function testInsertElementWithoutName()
+    {
+        $name = $this->_model->insertElement('root', '', 'block');
+        $this->assertTrue($this->_model->hasElement($name));
+        $this->assertEquals(Mage_Core_Model_Layout_Structure::TMP_NAME_PREFIX . '0', $name);
+
+        $this->_model->insertElement('root', 'name', 'block');
+        $name = $this->_model->insertElement('root', '', 'block');
+        $this->assertTrue($this->_model->hasElement($name));
+        $this->assertEquals(Mage_Core_Model_Layout_Structure::TMP_NAME_PREFIX . '1', $name);
+    }
+
+    public function testInsertElementWithoutAlias()
+    {
+        $root = 'root';
+        $name = 'name';
+
+        $this->_model->insertContainer('', $root);
+        $this->_model->insertElement($root, $name, 'block');
+        $alias = $this->_model->getElementAlias($name);
+        $this->assertEquals($name, $alias);
+
+        $foundName = $this->_model->getChildName($root, $alias);
+        $this->assertEquals($name, $foundName);
+    }
+
+    public function testInsertElementOrder()
+    {
+        $root = 'root';
+        $name1 = 'name1';
+        $name2 = 'name2';
+        $name3 = 'name3';
+        $name4 = 'name4';
+        $name5 = 'name5';
+
+        $this->_model->insertElement('', $root, 'container');
+
+        $this->_model->insertElement($root, $name1, 'block');
+        $this->_model->insertElement($root, $name2, 'block', '', true, $name1);
+        $children = $this->_model->getChildNames($root);
+        $this->assertEquals(array($name1, $name2), $children);
+
+        $this->_model->insertElement($root, $name3, 'block', '', false, $name1);
+        $children = $this->_model->getChildNames($root);
+        $this->assertEquals(array($name3, $name1, $name2), $children);
+
+        $this->_model->insertElement($root, $name4, 'block');
+        $children = $this->_model->getChildNames($root);
+        $this->assertEquals(array($name3, $name1, $name2, $name4), $children);
+
+        $this->_model->insertElement($root, $name5, 'block', '', false);
+        $children = $this->_model->getChildNames($root);
+        $this->assertEquals(array($name5, $name3, $name1, $name2, $name4), $children);
+    }
+
+    public function testInsertBlock()
+    {
+        $name = 'name';
+        $this->_model->insertBlock('', $name);
+        $this->assertTrue($this->_model->hasElement($name));
+        $this->assertTrue($this->_model->isBlock($name));
+    }
+
+    public function testInsertContainer()
+    {
+        $name = 'name';
+        $this->_model->insertContainer('', $name);
+        $this->assertTrue($this->_model->hasElement($name));
+        $this->assertFalse($this->_model->isBlock($name));
+    }
+
+    /**
+     * @covers Mage_Core_Model_Layout_Structure::hasElement
+     * @covers Mage_Core_Model_Layout_Structure::unsetChild
+     */
+    public function testHasElement()
+    {
+        $parent = 'parent';
+        $child = 'name';
+        $this->_model->insertBlock('', $parent);
+        $this->assertFalse($this->_model->hasElement($child));
+        $this->_model->insertBlock($parent, $child);
+        $this->assertTrue($this->_model->hasElement($child));
+        $this->_model->unsetChild($parent, $child);
+        $this->assertFalse($this->_model->hasElement($child));
+    }
+
+    public function testGetChildrenCount()
+    {
+        $root = 'root';
+        $child = 'block';
+        $this->_model->insertBlock('', $root);
+        $this->assertEquals(0, $this->_model->getChildrenCount($root));
+        $this->_model->insertBlock($root, $child);
+        $this->assertEquals(1, $this->_model->getChildrenCount($root));
+        $this->_model->unsetChild($root, $child);
+        $this->assertEquals(0, $this->_model->getChildrenCount($root));
+    }
+
+    /**
+     * @covers Mage_Core_Model_Layout_Structure::addToParentGroup
+     * @covers Mage_Core_Model_Layout_Structure::getGroupChildNames
+     */
+    public function testAddGetGroup()
+    {
+        $parent = 'parent';
+        $child1 = 'child1';
+        $child2 = 'child2';
+        $group1 = 'group1';
+        $group2 = 'group2';
+        $this->_model->insertContainer('', $parent);
+        $this->_model->insertBlock($parent, $child1);
+        $this->assertEmpty($this->_model->getGroupChildNames($parent, $group1));
+        $this->assertEmpty($this->_model->getGroupChildNames($parent, $group2));
+        $this->_model->addToParentGroup($child1, $parent, $group1);
+        $this->_model->insertBlock($parent, $child2);
+        $this->_model->addToParentGroup($child2, $parent, $group2);
+        $this->assertEquals(array($child1), $this->_model->getGroupChildNames($parent, $group1));
+        $this->assertEquals(array($child2), $this->_model->getGroupChildNames($parent, $group2));
+    }
+
+    /**
+     * @covers Mage_Core_Model_Layout_Structure::isBlock
+     * @covers Mage_Core_Model_Layout_Structure::isContainer
+     */
+    public function testIsBlockIsContainer()
+    {
+        $block = 'block';
+        $container = 'container';
+        $invalidType = 'invalid';
+
+        $this->_model->insertBlock('', $block);
+        $this->_model->insertContainer('', $container);
+        $this->_model->insertElement('', $invalidType, $invalidType);
+
+        $this->assertTrue($this->_model->isBlock($block));
+        $this->assertFalse($this->_model->isBlock($container));
+        $this->assertFalse($this->_model->isBlock($invalidType));
+
+        $this->assertFalse($this->_model->isContainer($block));
+        $this->assertTrue($this->_model->isContainer($container));
+        $this->assertFalse($this->_model->isContainer($invalidType));
+    }
+
+    public function testIsManipulationAllowed()
+    {
+        // non-existing elements
+        $this->assertFalse($this->_model->isManipulationAllowed('block2'));
+        $this->assertFalse($this->_model->isManipulationAllowed('block3'));
+
+        // block under block
+        $this->assertEquals('block1', $this->_model->insertBlock('', 'block1'));
+        $this->assertEquals('block2', $this->_model->insertBlock('block1', 'block2'));
+        $this->assertFalse($this->_model->isManipulationAllowed('block2'));
+
+        // block under container
+        $this->assertEquals('container1', $this->_model->insertContainer('', 'container1'));
+        $this->assertEquals('block3', $this->_model->insertBlock('container1', 'block3'));
+        $this->assertTrue($this->_model->isManipulationAllowed('block3'));
+
+        // container under container
+        $this->assertEquals('container2', $this->_model->insertContainer('container1', 'container2'));
+        $this->assertTrue($this->_model->isManipulationAllowed('container2'));
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/DesignEditor/Model/LayoutTest.php b/dev/tests/unit/testsuite/Mage/DesignEditor/Model/LayoutTest.php
new file mode 100644
index 0000000000000000000000000000000000000000..2bb43481db4ff8533216733d122d75a651cd91a9
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/DesignEditor/Model/LayoutTest.php
@@ -0,0 +1,40 @@
+<?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  unit_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
+ */
+
+/**
+ * @group module:Mage_DesignEditor
+ */
+class Mage_DesignEditor_Model_LayoutTest extends PHPUnit_Framework_TestCase
+{
+    public function testSanitizeLayout()
+    {
+        $data = file_get_contents(__DIR__ . '/_files/sanitize.xml');
+        $xml = new Varien_Simplexml_Element($data);
+        Mage_DesignEditor_Model_Layout::sanitizeLayout($xml);
+        $this->assertStringMatchesFormatFile(__DIR__ . '/_files/sanitize_expected.txt', $xml->asNiceXml());
+    }
+}
diff --git a/dev/tests/unit/testsuite/Mage/DesignEditor/Model/_files/sanitize.xml b/dev/tests/unit/testsuite/Mage/DesignEditor/Model/_files/sanitize.xml
new file mode 100644
index 0000000000000000000000000000000000000000..35c14f9dbae0bbc90b2e142ed3425c352b9fff9e
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/DesignEditor/Model/_files/sanitize.xml
@@ -0,0 +1,48 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+/**
+ * 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     Mage_DesignEditor
+ * @subpackage  unit_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
+<layout>
+    <block name="root" type="Mage_Core_Block_Template" template="template.phtml">
+        <block name="head" type="Mage_Page_Block_Html_Head">
+            <action method="safeMethod"><arg>1</arg></action>
+        </block>
+        <block name="custom.safe" type="Namespace_Module_Block_Safe"/>
+        <container name="content">
+            <block name="custom.not_safe" type="Namespace_Module_Block_NotSafe">
+                <action method="setTemplate"><arg>some_template.phtml</arg></action>
+            </block>
+            <block type="Mage_Page_Block_Safe"/>
+        </container>
+    </block>
+    <reference name="head">
+        <action method="safeMethod"><arg>1</arg></action>
+    </reference>
+    <reference name="custom.not_safe">
+        <action method="rogueMethod"><block>1</block></action>
+    </reference>
+</layout>
diff --git a/dev/tests/unit/testsuite/Mage/DesignEditor/Model/_files/sanitize_expected.txt b/dev/tests/unit/testsuite/Mage/DesignEditor/Model/_files/sanitize_expected.txt
new file mode 100644
index 0000000000000000000000000000000000000000..eaab15b5fd4e8e00f5c04eb043567a8be15defa1
--- /dev/null
+++ b/dev/tests/unit/testsuite/Mage/DesignEditor/Model/_files/sanitize_expected.txt
@@ -0,0 +1,20 @@
+<layout>
+   <block name="root" type="Mage_Core_Block_Template" template="template.phtml">
+      <block name="head" type="Mage_Page_Block_Html_Head">
+         <action method="safeMethod">
+            <arg>1</arg>
+         </action>
+      </block>
+      <block name="custom.safe" type="Namespace_Module_Block_Safe"/>
+      <container name="content">
+         <block name="custom.not_safe" type="Mage_Core_Block_Template" template="Mage_DesignEditor::stub.phtml">%A</block>
+         <block type="Mage_Page_Block_Safe"/>
+      </container>
+   </block>
+   <reference name="head">
+      <action method="safeMethod">
+         <arg>1</arg>
+      </action>
+   </reference>
+   <reference name="custom.not_safe">%A</reference>
+</layout>
diff --git a/dev/tests/unit/testsuite/Magento/Profiler/Output/HtmlTest.php b/dev/tests/unit/testsuite/Magento/Profiler/Output/HtmlTest.php
index 7c821c42d86c66654d2532e1040a11458c8f2af3..1d81d1b27166726e9c97470674d0e4065fb76512 100644
--- a/dev/tests/unit/testsuite/Magento/Profiler/Output/HtmlTest.php
+++ b/dev/tests/unit/testsuite/Magento/Profiler/Output/HtmlTest.php
@@ -67,7 +67,8 @@ class Magento_Profiler_Output_HtmlTest extends PHPUnit_Framework_TestCase
         ob_start();
         $this->_object->display();
         $actualHtml = ob_get_clean();
-        $expectedHtmlFile = __DIR__ . '/../_files/output.html';
-        $this->assertStringEqualsFile($expectedHtmlFile, $actualHtml);
+        $expectedString = file_get_contents(__DIR__ . '/../_files/output.html');
+        $expectedString = ltrim(preg_replace('/^<!--.+?-->/s', '', $expectedString));
+        $this->assertEquals($expectedString, $actualHtml);
     }
 }
diff --git a/dev/tests/unit/testsuite/Magento/Profiler/_files/output.html b/dev/tests/unit/testsuite/Magento/Profiler/_files/output.html
index 1d7e94c60f465fa4ef96dccf1fbc9313d0be770f..16653805e5a14e5108571d5872e6335a498f83cf 100644
--- a/dev/tests/unit/testsuite/Magento/Profiler/_files/output.html
+++ b/dev/tests/unit/testsuite/Magento/Profiler/_files/output.html
@@ -1,3 +1,30 @@
+<!--
+/**
+ * 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     Mage_Core
+ * @subpackage  integration_tests
+ * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
+ * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
+ */
+-->
 <table border="1" cellspacing="0" cellpadding="2">
 <caption>Code Profiler Title</caption>
 <tr>
diff --git a/dev/tests/unit/testsuite/Varien/Data/Collection/DbTest.php b/dev/tests/unit/testsuite/Varien/Data/Collection/DbTest.php
index 11fa0adfcec63a61b7628e63e435b7d893e6ce0e..a12d4d8b8f68c8c88263c86f75953e4fb1f535f5 100644
--- a/dev/tests/unit/testsuite/Varien/Data/Collection/DbTest.php
+++ b/dev/tests/unit/testsuite/Varien/Data/Collection/DbTest.php
@@ -47,12 +47,16 @@ class Varien_Data_Collection_DbTest extends PHPUnit_Framework_TestCase
 
         $select = $this->_collection->getSelect();
         $this->assertEmpty($select->getPart(Zend_Db_Select::ORDER));
+
+        /* Direct access to select object is available and many places are using it for sort order declaration */
+        $select->order('select_field', Varien_Data_Collection::SORT_ORDER_ASC);
         $this->_collection->addOrder('some_field', Varien_Data_Collection::SORT_ORDER_ASC);
         $this->_collection->setOrder('other_field', Varien_Data_Collection::SORT_ORDER_ASC);
         $this->_collection->addOrder('other_field', Varien_Data_Collection::SORT_ORDER_DESC);
 
         $this->_collection->load();
         $selectOrders = $select->getPart(Zend_Db_Select::ORDER);
+        $this->assertEquals(array('select_field', 'ASC'), array_shift($selectOrders));
         $this->assertEquals('some_field ASC', (string)array_shift($selectOrders));
         $this->assertEquals('other_field DESC', (string)array_shift($selectOrders));
         $this->assertEmpty(array_shift($selectOrders));
diff --git a/dev/tests/unit/testsuite/Varien/Db/Adapter/Pdo/MysqlTest.php b/dev/tests/unit/testsuite/Varien/Db/Adapter/Pdo/MysqlTest.php
index 9a99f8135219e7ddc04312b97d0814f3f1556671..29d922a8a66464f9c3d1deaa4c1367dc3d15ae55 100644
--- a/dev/tests/unit/testsuite/Varien/Db/Adapter/Pdo/MysqlTest.php
+++ b/dev/tests/unit/testsuite/Varien/Db/Adapter/Pdo/MysqlTest.php
@@ -30,6 +30,11 @@
  */
 class Varien_Db_Adapter_Pdo_MysqlTest extends PHPUnit_Framework_TestCase
 {
+    /**
+     * Error message for DDL query in transactions
+     */
+    const ERROR_DDL_MESSAGE = 'DDL statements are not allowed in transactions';
+
     /**
      * Adapter for test
      * @var Varien_Db_Adapter_Pdo_Mysql
@@ -88,4 +93,65 @@ class Varien_Db_Adapter_Pdo_MysqlTest extends PHPUnit_Framework_TestCase
             array(0x5468792130ABCDEF, '6082244480221302255')
         );
     }
+
+    /**
+     * Test DDL query in transaction
+     */
+    public function testCheckDdlTransaction()
+    {
+        $mockAdapter = $this->getMock(
+            'Varien_Db_Adapter_Pdo_Mysql',
+            array('beginTransaction', 'getTransactionLevel'),
+            array(), '', false
+        );
+
+        $mockAdapter->expects($this->any())
+             ->method('getTransactionLevel')
+             ->will($this->returnValue(1));
+
+        $mockAdapter->beginTransaction();
+        try {
+            $mockAdapter->query("CREATE table user");
+        } catch (Zend_Db_Adapter_Exception $e) {
+            $this->assertEquals($e->getMessage(), self::ERROR_DDL_MESSAGE);
+        }
+
+        try {
+            $mockAdapter->query("ALTER table user");
+        } catch (Zend_Db_Adapter_Exception $e) {
+            $this->assertEquals($e->getMessage(), self::ERROR_DDL_MESSAGE);
+        }
+
+        try {
+            $mockAdapter->query("TRUNCATE table user");
+        } catch (Zend_Db_Adapter_Exception $e) {
+            $this->assertEquals($e->getMessage(), self::ERROR_DDL_MESSAGE);
+        }
+
+        try {
+            $mockAdapter->query("RENAME table user");
+        } catch (Zend_Db_Adapter_Exception $e) {
+            $this->assertEquals($e->getMessage(), self::ERROR_DDL_MESSAGE);
+        }
+
+        try {
+            $mockAdapter->query("DROP table user");
+        } catch (Zend_Db_Adapter_Exception $e) {
+            $this->assertEquals($e->getMessage(), self::ERROR_DDL_MESSAGE);
+        }
+
+        try {
+            $mockAdapter->query("SELECT * FROM user");
+        } catch (Exception $e) {
+            $this->assertFalse($e instanceof Zend_Db_Adapter_Exception);
+        }
+
+        $select = new Zend_Db_Select($mockAdapter);
+        $select->from('user');
+        try {
+            $mockAdapter->query($select);
+        } catch (Exception $e) {
+            $this->assertFalse($e instanceof Zend_Db_Adapter_Exception);
+        }
+    }
 }
diff --git a/dev/tools/migration/factory_names.php b/dev/tools/migration/factory_names.php
index aba70af8c58ab7b54cbda1a82c977283d2435a1a..42f2047974f7a91437289992b78985ff90730efd 100644
--- a/dev/tools/migration/factory_names.php
+++ b/dev/tools/migration/factory_names.php
@@ -40,15 +40,15 @@ foreach (Util_Files::getPhpFiles() as $file) {
     $replace = array();
     foreach ($factoryNames as $factoryName) {
         list($module, $name) = getModuleName($factoryName);
-        addReplace($factoryName, $module, $name, '::getModel(%s', '_Model_', $search, $replace);
-        addReplace($factoryName, $module, $name, '::getSingleton(%s', '_Model_', $search, $replace);
-        addReplace($factoryName, $module, $name, '::getResourceModel(%s', '_Model_Resource_', $search, $replace);
-        addReplace($factoryName, $module, $name, '::getResourceSingleton(%s', '_Model_Resource_', $search, $replace);
-        addReplace($factoryName, $module, $name, 'addBlock(%s', '_Block_', $search, $replace);
-        addReplace($factoryName, $module, $name, 'createBlock(%s', '_Block_', $search, $replace);
-        addReplace($factoryName, $module, $name, 'getBlockClassName(%s', '_Block_', $search, $replace);
-        addReplace($factoryName, $module, $name, 'getBlockSingleton(%s', '_Block_', $search, $replace);
-        addReplace($factoryName, $module, $name, 'helper(%s', '_Helper_', $search, $replace);
+        addReplace($factoryName, $module, $name, '::getModel(\'%s\'', '_Model_', $search, $replace);
+        addReplace($factoryName, $module, $name, '::getSingleton(\'%s\'', '_Model_', $search, $replace);
+        addReplace($factoryName, $module, $name, '::getResourceModel(\'%s\'', '_Model_Resource_', $search, $replace);
+        addReplace($factoryName, $module, $name, "::getResourceSingleton('%s'", '_Model_Resource_', $search, $replace);
+        addReplace($factoryName, $module, $name, 'addBlock(\'%s\'', '_Block_', $search, $replace);
+        addReplace($factoryName, $module, $name, 'createBlock(\'%s\'', '_Block_', $search, $replace);
+        addReplace($factoryName, $module, $name, 'getBlockClassName(\'%s\'', '_Block_', $search, $replace);
+        addReplace($factoryName, $module, $name, 'getBlockSingleton(\'%s\'', '_Block_', $search, $replace);
+        addReplace($factoryName, $module, $name, 'helper(\'%s\'', '_Helper_', $search, $replace);
     }
     $newContent = str_replace($search, $replace, $content);
     if ($newContent != $content) {
@@ -58,6 +58,30 @@ foreach (Util_Files::getPhpFiles() as $file) {
     }
 }
 
+// layouts
+foreach (Util_Files::getLayoutFiles() as $file) {
+    $file = array_shift($file);
+    $xml = simplexml_load_file($file);
+    $classes = Util_Classes::collectLayoutClasses($xml);
+    $factoryNames = array_filter($classes, 'isFactoryName');
+    if (!$factoryNames) {
+        continue;
+    }
+    $search = array();
+    $replace = array();
+    foreach ($factoryNames as $factoryName) {
+        list($module, $name) = getModuleName($factoryName);
+        addReplace($factoryName, $module, $name, 'type="%s"', '_Block_', $search, $replace);
+    }
+    $content = file_get_contents($file);
+    $newContent = str_replace($search, $replace, $content);
+    if ($newContent != $content) {
+        echo "{$file}\n";
+        print_r($factoryNames);
+        file_put_contents($file, $newContent);
+    }
+}
+
 /**
  * Whether the given class name is a factory name
  *
@@ -109,6 +133,6 @@ function addReplace($factoryName, $module, $name, $pattern, $suffix, &$search, &
         $name = 'data';
     }
     $realName = implode('_', array_map('ucfirst', explode('_', $module . $suffix . $name)));
-    $search[] = sprintf($pattern, "'{$factoryName}'");
-    $replace[] = sprintf($pattern, "'{$realName}'");
+    $search[] = sprintf($pattern, "{$factoryName}");
+    $replace[] = sprintf($pattern, "{$realName}");
 }
diff --git a/downloader/Maged/Controller.php b/downloader/Maged/Controller.php
index f6ea742072c02dca1f3ccaec897823ab6c6bc496..1b810f2345b656f0202cb87c92a12656d45a79c5 100755
--- a/downloader/Maged/Controller.php
+++ b/downloader/Maged/Controller.php
@@ -884,7 +884,20 @@ final class Maged_Controller
         }
 
         if (!empty($_GET['archive_type'])) {
-            $isSuccess = $this->_createBackup($_GET['archive_type'], $_GET['backup_name']);
+
+            $backupName = $_GET['backup_name'];
+            $connect = $this->model('connect', true)->connect();
+            $isSuccess = true;
+
+            if (!preg_match('/^[a-zA-Z0-9\ ]{0,50}$/', $backupName)) {
+                $connect->runHtmlConsole('Please use only letters (a-z or A-Z), numbers (0-9) or space in '
+                    . 'Backup Name field. Other characters are not allowed.');
+                $isSuccess = false;
+            }
+
+            if ($isSuccess) {
+                $isSuccess = $this->_createBackup($_GET['archive_type'], $_GET['backup_name']);
+            }
 
             if (!$isSuccess) {
                 $this->endInstall();
@@ -995,7 +1008,7 @@ final class Maged_Controller
     protected function _createBackup($archiveType, $archiveName){
         /** @var $connect Maged_Connect */
         $connect = $this->model('connect', true)->connect();
-        $connect->runHtmlConsole('Creating data backup...');
+        $connect->runHtmlConsole('Creating backup...');
 
         $isSuccess = false;
 
@@ -1065,7 +1078,7 @@ final class Maged_Controller
     {
         $messagesMap = array(
             Mage_Backup_Helper_Data::TYPE_SYSTEM_SNAPSHOT => 'System backup has been created',
-            Mage_Backup_Helper_Data::TYPE_SNAPSHOT_WITHOUT_MEDIA => 'System backup has been created',
+            Mage_Backup_Helper_Data::TYPE_SNAPSHOT_WITHOUT_MEDIA => 'System (excluding Media) backup has been created',
             Mage_Backup_Helper_Data::TYPE_MEDIA => 'Database and media backup has been created',
             Mage_Backup_Helper_Data::TYPE_DB => 'Database backup has been created'
         );
diff --git a/downloader/template/connect/packages.phtml b/downloader/template/connect/packages.phtml
index a0a3d812d9eb890d267366316f653eea721ef395..92e6ea8ba599362e881dc4147dfc17d03e121fd9 100644
--- a/downloader/template/connect/packages.phtml
+++ b/downloader/template/connect/packages.phtml
@@ -32,7 +32,7 @@
 <ul class="bare-list">
     <li>
         <input type="checkbox" id="maintenance" value="1" checked="checked" /> &nbsp;
-        <label for="maintenance">Put store on the maintenance mode while installing/upgrading/backup creating</label>
+        <label for="maintenance">Put store on the maintenance mode while installing/upgrading/backup creation</label>
     </li>
     <li>
         <table cellpadding="0" cellspacing="0">
@@ -53,11 +53,16 @@
                 </td>
             </tr>
             <tr id="backup-name-container" style="display: none; margin-top: 5px;">
-                <td>
-                    <label for="backup_name">Backup Name</label>
+                <td valign="top">
+                    <div style="margin: 6px 0 0 5px;">
+                        <label for="backup_name">Backup Name</label>
+                    </div>
                 </td>
                 <td>
-                    &nbsp;<input type="text" name="backup_name" id="backup_name" style="width: 320px; margin-top:8px;"/>
+                    <div style="margin: 6px 0 0 4px;">
+                        <input type="text" name="backup_name" id="backup_name" style="width: 318px;" maxlength="50"/>
+                        <div class="notice-msg">Please use only letters (a-z or A-Z), numbers (0-9) or<br/> space in this field. Other characters are not allowed.</div>
+                    </div>
                 </td>
             </tr>
         </table>
diff --git a/lib/Varien/Data/Collection.php b/lib/Varien/Data/Collection.php
index c4b3a0dd354e23511112f30ea13ffa572751b1cf..f8041eaf2a794703467cb8fd4634bcd0b52e89c6 100644
--- a/lib/Varien/Data/Collection.php
+++ b/lib/Varien/Data/Collection.php
@@ -145,7 +145,7 @@ class Varien_Data_Collection implements IteratorAggregate, Countable
      * - 'foo' -- get the first filter with field name 'foo'
      * - array('foo') -- get all filters with field name 'foo'
      * - array('foo', 'bar') -- get all filters with field name 'foo' or 'bar'
-     * - array() -- get all filters 
+     * - array() -- get all filters
      *
      * @param string|array $field
      * @return Varien_Object|array|null
@@ -164,7 +164,7 @@ class Varien_Data_Collection implements IteratorAggregate, Countable
                     $result[] = $filter;
                 }
             }
-            return $result; 
+            return $result;
         }
 
         // get a first filter by specified name
@@ -374,11 +374,23 @@ class Varien_Data_Collection implements IteratorAggregate, Countable
             }
             $this->_items[$itemId] = $item;
         } else {
-            $this->_items[] = $item;
+            $this->_addItem($item);
         }
         return $this;
     }
 
+    /**
+     * Add item that has no id to collection
+     *
+     * @param Varien_Object $item
+     * @return Varien_Data_Collection
+     */
+    protected function _addItem($item)
+    {
+        $this->_items[] = $item;
+        return $this;
+    }
+
     /**
      * Retrieve item id
      *
diff --git a/lib/Varien/Data/Collection/Db.php b/lib/Varien/Data/Collection/Db.php
index 0ac9545b3f3bcf45b070a2b97bc9b28b6580f7e9..0906ba8dd4f3a11b86b776d9eadd1200b2493b6d 100644
--- a/lib/Varien/Data/Collection/Db.php
+++ b/lib/Varien/Data/Collection/Db.php
@@ -496,7 +496,6 @@ class Varien_Data_Collection_Db extends Varien_Data_Collection
     protected function _renderOrders()
     {
         if (!$this->_isOrdersRendered) {
-            $this->_select->reset(Zend_Db_Select::ORDER);
             foreach ($this->_orders as $field => $direction) {
                 $this->_select->order(new Zend_Db_Expr($field . ' ' . $direction));
              }
diff --git a/lib/Varien/Data/Form.php b/lib/Varien/Data/Form.php
index 0d4de443344272dbf1a14eefc28c89691d17f4fa..b13d4bae6e3cd882f5d89b4cf35ec26e3cf3061b 100644
--- a/lib/Varien/Data/Form.php
+++ b/lib/Varien/Data/Form.php
@@ -93,7 +93,7 @@ class Varien_Data_Form extends Varien_Data_Form_Abstract
      */
     public function getHtmlAttributes()
     {
-        return array('id', 'name', 'method', 'action', 'enctype', 'class', 'onsubmit');
+        return array('id', 'name', 'method', 'action', 'enctype', 'class', 'onsubmit', 'target');
     }
 
     /**
diff --git a/lib/Varien/Data/Form/Element/Image.php b/lib/Varien/Data/Form/Element/Image.php
index 4e5fe23f3f8e4cdd0553ead06d3495b1e4968bb1..705b1f7dd079475d8a3fbee5c2c15c6ae6df312a 100644
--- a/lib/Varien/Data/Form/Element/Image.php
+++ b/lib/Varien/Data/Form/Element/Image.php
@@ -24,19 +24,17 @@
  * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
  */
 
-
 /**
  * Category form input image element
  *
  * @category   Varien
  * @package    Varien_Data
- * @author      Magento Core Team <core@magentocommerce.com>
+ * @author     Magento Core Team <core@magentocommerce.com>
  */
 class Varien_Data_Form_Element_Image extends Varien_Data_Form_Element_Abstract
 {
-
     /**
-     * Enter description here...
+     * Constructor
      *
      * @param array $data
      */
@@ -47,7 +45,7 @@ class Varien_Data_Form_Element_Image extends Varien_Data_Form_Element_Abstract
     }
 
     /**
-     * Enter description here...
+     * Return element html code
      *
      * @return string
      */
@@ -55,24 +53,28 @@ class Varien_Data_Form_Element_Image extends Varien_Data_Form_Element_Abstract
     {
         $html = '';
 
-        if ($this->getValue()) {
+        if ((string)$this->getValue()) {
             $url = $this->_getUrl();
 
             if( !preg_match("/^http\:\/\/|https\:\/\//", $url) ) {
                 $url = Mage::getBaseUrl('media') . $url;
             }
 
-            $html = '<a href="'.$url.'" onclick="imagePreview(\''.$this->getHtmlId().'_image\'); return false;"><img src="'.$url.'" id="'.$this->getHtmlId().'_image" title="'.$this->getValue().'" alt="'.$this->getValue().'" height="22" width="22" class="small-image-preview v-middle" /></a> ';
+            $html = '<a href="' . $url . '"'
+                . ' onclick="imagePreview(\'' . $this->getHtmlId() . '_image\'); return false;">'
+                . '<img src="' . $url . '" id="' . $this->getHtmlId() . '_image" title="' . $this->getValue() . '"'
+                . ' alt="' . $this->getValue() . '" height="22" width="22" class="small-image-preview v-middle" />'
+                . '</a> ';
         }
         $this->setClass('input-file');
-        $html.= parent::getElementHtml();
-        $html.= $this->_getDeleteCheckbox();
+        $html .= parent::getElementHtml();
+        $html .= $this->_getDeleteCheckbox();
 
         return $html;
     }
 
     /**
-     * Enter description here...
+     * Return html code of delete checkbox element
      *
      * @return string
      */
@@ -82,8 +84,12 @@ class Varien_Data_Form_Element_Image extends Varien_Data_Form_Element_Abstract
         if ($this->getValue()) {
             $label = Mage::helper('Mage_Core_Helper_Data')->__('Delete Image');
             $html .= '<span class="delete-image">';
-            $html .= '<input type="checkbox" name="'.parent::getName().'[delete]" value="1" class="checkbox" id="'.$this->getHtmlId().'_delete"'.($this->getDisabled() ? ' disabled="disabled"': '').'/>';
-            $html .= '<label for="'.$this->getHtmlId().'_delete"'.($this->getDisabled() ? ' class="disabled"' : '').'> '.$label.'</label>';
+            $html .= '<input type="checkbox"'
+                . ' name="' . parent::getName() . '[delete]" value="1" class="checkbox"'
+                . ' id="' . $this->getHtmlId() . '_delete"' . ($this->getDisabled() ? ' disabled="disabled"': '')
+                . '/>';
+            $html .= '<label for="' . $this->getHtmlId() . '_delete"'
+                . ($this->getDisabled() ? ' class="disabled"' : '') . '> ' . $label . '</label>';
             $html .= $this->_getHiddenInput();
             $html .= '</span>';
         }
@@ -92,13 +98,13 @@ class Varien_Data_Form_Element_Image extends Varien_Data_Form_Element_Abstract
     }
 
     /**
-     * Enter description here...
+     * Return html code of hidden element
      *
      * @return string
      */
     protected function _getHiddenInput()
     {
-        return '<input type="hidden" name="'.parent::getName().'[value]" value="'.$this->getValue().'" />';
+        return '<input type="hidden" name="' . parent::getName() . '[value]" value="' . $this->getValue() . '" />';
     }
 
     /**
@@ -112,7 +118,7 @@ class Varien_Data_Form_Element_Image extends Varien_Data_Form_Element_Abstract
     }
 
     /**
-     * Enter description here...
+     * Return name
      *
      * @return string
      */
@@ -120,5 +126,4 @@ class Varien_Data_Form_Element_Image extends Varien_Data_Form_Element_Abstract
     {
         return  $this->getData('name');
     }
-
 }
diff --git a/lib/Varien/Db/Adapter/Interface.php b/lib/Varien/Db/Adapter/Interface.php
index 85af7e2f0ad2dcc4ab12ea756b5dc3801428e75d..a29fe9b0b09a964fe25cf8091663653ca6420257 100644
--- a/lib/Varien/Db/Adapter/Interface.php
+++ b/lib/Varien/Db/Adapter/Interface.php
@@ -831,6 +831,14 @@ interface Varien_Db_Adapter_Interface
      */
     public function getSubstringSql($stringExpression, $pos, $len = null);
 
+    /**
+     * Prepare standard deviation sql function
+     *
+     * @param Zend_Db_Expr|string $expressionField   quoted field name or SQL statement
+     * @return Zend_Db_Expr
+     */
+    public function getStandardDeviationSql($expressionField);
+
     /**
      * Extract part of a date
      *
diff --git a/lib/Varien/Db/Adapter/Pdo/Mysql.php b/lib/Varien/Db/Adapter/Pdo/Mysql.php
index 035e2ce1a404bf705d12595f2e1a46c36860b005..e762f5a64e97cc5ffd48b230112bd3f227e118e1 100644
--- a/lib/Varien/Db/Adapter/Pdo/Mysql.php
+++ b/lib/Varien/Db/Adapter/Pdo/Mysql.php
@@ -178,6 +178,14 @@ class Varien_Db_Adapter_Pdo_Mysql extends Zend_Db_Adapter_Pdo_Mysql implements V
         Varien_Db_Ddl_Table::TYPE_VARBINARY     => 'blob'
     );
 
+    /**
+     * All possible DDL statements
+     * First 3 symbols for each statement
+     *
+     * @var array
+     */
+    protected $_ddlRoutines = array('alt', 'cre', 'ren', 'dro', 'tru');
+
     /**
      * Allowed interval units array
      *
@@ -381,6 +389,22 @@ class Varien_Db_Adapter_Pdo_Mysql extends Zend_Db_Adapter_Pdo_Mysql implements V
         }
     }
 
+    /**
+     * Check transaction level in case of DDL query
+     *
+     * @param string|Zend_Db_Select $sql
+     * @throws Zend_Db_Adapter_Exception
+     */
+    protected function _checkDdlTransaction($sql)
+    {
+        if (is_string($sql) && $this->getTransactionLevel() > 0) {
+            $startSql = strtolower(substr(ltrim($sql), 0, 3));
+            if (in_array($startSql, $this->_ddlRoutines)) {
+                throw new Zend_Db_Adapter_Exception('DDL statements are not allowed in transactions');
+            }
+        }
+    }
+
     /**
      * Special handling for PDO query().
      * All bind parameter names must begin with ':'.
@@ -394,6 +418,7 @@ class Varien_Db_Adapter_Pdo_Mysql extends Zend_Db_Adapter_Pdo_Mysql implements V
     {
         $this->_debugTimer();
         try {
+            $this->_checkDdlTransaction($sql);
             $this->_prepareQuery($sql, $bind);
             $result = parent::query($sql, $bind);
         } catch (Exception $e) {
@@ -605,7 +630,9 @@ class Varien_Db_Adapter_Pdo_Mysql extends Zend_Db_Adapter_Pdo_Mysql implements V
      */
     protected function _splitMultiQuery($sql)
     {
-        $parts = preg_split('#(;|\'|"|\\\\|//|--|\n|/\*|\*/)#', $sql, null, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
+        $parts = preg_split('#(;|\'|"|\\\\|//|--|\n|/\*|\*/)#', $sql, null,
+            PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
+        );
 
         $q      = false;
         $c      = false;
@@ -807,6 +834,18 @@ class Varien_Db_Adapter_Pdo_Mysql extends Zend_Db_Adapter_Pdo_Mysql implements V
             }
         }
 
+        /* drop index that after column removal would coincide with the existing index by indexed columns */
+        foreach ($this->getIndexList($tableName, $schemaName) as $idxData) {
+            $idxColumns = $idxData['COLUMNS_LIST'];
+            $idxColumnKey = array_search($columnName, $idxColumns);
+            if ($idxColumnKey !== false) {
+                unset($idxColumns[$idxColumnKey]);
+                if ($idxColumns && $this->_getIndexByColumns($tableName, $idxColumns, $schemaName)) {
+                    $this->dropIndex($tableName, $idxData['KEY_NAME'], $schemaName);
+                }
+            }
+        }
+
         $alterDrop[] = 'DROP COLUMN ' . $this->quoteIdentifier($columnName);
         $sql = sprintf('ALTER TABLE %s %s',
             $this->quoteIdentifier($this->_getTableName($tableName, $schemaName)),
@@ -818,6 +857,24 @@ class Varien_Db_Adapter_Pdo_Mysql extends Zend_Db_Adapter_Pdo_Mysql implements V
         return $result;
     }
 
+    /**
+     * Retrieve index information by indexed columns or return NULL, if there is no index for a column list
+     *
+     * @param string $tableName
+     * @param array $columns
+     * @param string|null $schemaName
+     * @return array|null
+     */
+    protected function _getIndexByColumns($tableName, array $columns, $schemaName)
+    {
+        foreach ($this->getIndexList($tableName, $schemaName) as $idxData) {
+            if ($idxData['COLUMNS_LIST'] === $columns) {
+                return $idxData;
+            }
+        }
+        return null;
+    }
+
     /**
      * Change the column name and definition
      *
@@ -836,7 +893,11 @@ class Varien_Db_Adapter_Pdo_Mysql extends Zend_Db_Adapter_Pdo_Mysql implements V
         $schemaName = null)
     {
         if (!$this->tableColumnExists($tableName, $oldColumnName, $schemaName)) {
-            throw new Zend_Db_Exception(sprintf('Column "%s" does not exists on table "%s"', $oldColumnName, $tableName));
+            throw new Zend_Db_Exception(sprintf(
+                'Column "%s" does not exists on table "%s"',
+                $oldColumnName,
+                $tableName
+            ));
         }
 
         if (is_array($definition)) {
@@ -2924,6 +2985,17 @@ class Varien_Db_Adapter_Pdo_Mysql extends Zend_Db_Adapter_Pdo_Mysql implements V
         return new Zend_Db_Expr(sprintf('SUBSTRING(%s, %s, %s)', $stringExpression, $pos, $len));
     }
 
+    /**
+     * Prepare standard deviation sql function
+     *
+     * @param Zend_Db_Expr|string $expressionField   quoted field name or SQL statement
+     * @return Zend_Db_Expr
+     */
+    public function getStandardDeviationSql($expressionField)
+    {
+        return new Zend_Db_Expr(sprintf('STDDEV_SAMP(%s)', $expressionField));
+    }
+
     /**
      * Extract part of a date
      *
@@ -3476,4 +3548,14 @@ class Varien_Db_Adapter_Pdo_Mysql extends Zend_Db_Adapter_Pdo_Mysql implements V
     {
         return $value;
     }
+
+    /**
+     * Check if all transactions have been committed
+     */
+    public function __destruct()
+    {
+        if ($this->_transactionLevel > 0) {
+            trigger_error('Some transactions have not been committed or rolled back', E_USER_ERROR);
+        }
+    }
 }
diff --git a/lib/Varien/File/Uploader.php b/lib/Varien/File/Uploader.php
index bbf34ce47be9a8ac1511150a1a754fd726b55cef..6de43ce897905f49ec3af9cbc0c130f3cedcd6fc 100644
--- a/lib/Varien/File/Uploader.php
+++ b/lib/Varien/File/Uploader.php
@@ -147,7 +147,7 @@ class Varien_File_Uploader
     function __construct($fileId)
     {
         $this->_setUploadFileId($fileId);
-        if( !file_exists($this->_file['tmp_name']) ) {
+        if(!file_exists($this->_file['tmp_name'])) {
             $code = empty($this->_file['tmp_name']) ? self::TMP_NAME_EMPTY : 0;
             throw new Exception('File was not uploaded.', $code);
         } else {
@@ -245,26 +245,32 @@ class Varien_File_Uploader
      */
     protected function _validateFile()
     {
-        if( $this->_fileExists === false ) {
+        if ($this->_fileExists === false) {
             return;
         }
 
-        $filePath = $this->_file['tmp_name'];
-        $fileName = $this->_file['name'];
-
         //is file extension allowed
-        $fileExtension = substr($fileName, strrpos($fileName, '.')+1);
-        if (!$this->checkAllowedExtension($fileExtension)) {
+        if (!$this->checkAllowedExtension($this->getFileExtension())) {
             throw new Exception('Disallowed file type.');
         }
         //run validate callbacks
         foreach ($this->_validateCallbacks as $params) {
             if (is_object($params['object']) && method_exists($params['object'], $params['method'])) {
-                $params['object']->$params['method']($filePath);
+                $params['object']->$params['method']($this->_file['tmp_name']);
             }
         }
     }
 
+    /**
+     * Returns extension of the uploaded file
+     *
+     * @return string
+     */
+    public function getFileExtension()
+    {
+        return $this->_fileExists ? pathinfo($this->_file['name'], PATHINFO_EXTENSION) : '';
+    }
+
     /**
      * Add validation callback model for us in self::_validateFile()
      *
diff --git a/lib/Varien/Http/Adapter/Curl.php b/lib/Varien/Http/Adapter/Curl.php
index f88a6143a88ca1e5983105ccc0e55ce7a097494e..e9946ff0b35b974bbed17754f7e3e383acfccf14 100644
--- a/lib/Varien/Http/Adapter/Curl.php
+++ b/lib/Varien/Http/Adapter/Curl.php
@@ -52,8 +52,20 @@ class Varien_Http_Adapter_Curl implements Zend_Http_Client_Adapter_Interface
      *
      * @var array
      */
-    protected $_allowedParams = array('timeout' => CURLOPT_TIMEOUT, 'maxredirects' => CURLOPT_MAXREDIRS,
-        'proxy' => CURLOPT_PROXY, 'ssl_cert' => CURLOPT_SSLCERT, 'userpwd' => CURLOPT_USERPWD);
+    protected $_allowedParams = array(
+        'timeout' => CURLOPT_TIMEOUT,
+        'maxredirects' => CURLOPT_MAXREDIRS,
+        'proxy' => CURLOPT_PROXY,
+        'ssl_cert' => CURLOPT_SSLCERT,
+        'userpwd' => CURLOPT_USERPWD
+    );
+
+    /**
+     * Array of CURL options
+     *
+     * @var array
+     */
+    protected $_options = array();
 
     /**
      * Apply current configuration array to transport resource
@@ -66,6 +78,17 @@ class Varien_Http_Adapter_Curl implements Zend_Http_Client_Adapter_Interface
             return $this;
         }
 
+        // apply additional options to cURL
+        foreach ($this->_options as $option => $value) {
+            curl_setopt($this->_getResource(), $option, $value);
+        }
+
+        $verifyPeer = isset($this->_config['verifypeer']) ? $this->_config['verifypeer'] : 0;
+        curl_setopt($this->_getResource(), CURLOPT_SSL_VERIFYPEER, $verifyPeer);
+
+        $verifyHost = isset($this->_config['verifyhost']) ? $this->_config['verifyhost'] : 0;
+        curl_setopt($this->_getResource(), CURLOPT_SSL_VERIFYHOST, $verifyHost);
+
         foreach ($this->_config as $param => $curlOption) {
             if (array_key_exists($param, $this->_allowedParams)) {
                 curl_setopt($this->_getResource(), $this->_allowedParams[$param], $this->_config[$param]);
@@ -74,6 +97,31 @@ class Varien_Http_Adapter_Curl implements Zend_Http_Client_Adapter_Interface
         return $this;
     }
 
+    /**
+     * Set array of additional cURL options
+     *
+     * @param array $options
+     * @return Varien_Http_Adapter_Curl
+     */
+    public function setOptions(array $options = array())
+    {
+        $this->_options = $options;
+        return $this;
+    }
+
+    /**
+     * Add additional option to cURL
+     *
+     * @param  int $option      the CURLOPT_* constants
+     * @param  mixed $value
+     * @return Varien_Http_Adapter_Curl
+     */
+    public function addOption($option, $value)
+    {
+        $this->_options[$option] = $value;
+        return $this;
+    }
+
     /**
      * Set the configuration array for the adapter
      *
@@ -97,18 +145,7 @@ class Varien_Http_Adapter_Curl implements Zend_Http_Client_Adapter_Interface
      */
     public function connect($host, $port = 80, $secure = false)
     {
-        //curl_setopt();
-        if (isset($this->_config['timeout'])) {
-            curl_setopt($this->_getResource(), CURLOPT_TIMEOUT, $this->_config['timeout']);
-        }
-        if (isset($this->_config['maxredirects'])) {
-            curl_setopt($this->_getResource(), CURLOPT_MAXREDIRS, $this->_config['maxredirects']);
-        }
-        if (isset($this->_config['proxy'])) {
-            curl_setopt($this->_getResource(), CURLOPT_PROXY, $this->_config['proxy']);
-        }
-
-        return $this;
+        return $this->_applyConfig();
     }
 
     /**
@@ -149,12 +186,6 @@ class Varien_Http_Adapter_Curl implements Zend_Http_Client_Adapter_Interface
         $header = isset($this->_config['header']) ? $this->_config['header'] : true;
         curl_setopt($this->_getResource(), CURLOPT_HEADER, $header);
 
-        $verifyPeer = isset($this->_config['verifypeer']) ? $this->_config['verifypeer'] : 0;
-        curl_setopt($this->_getResource(), CURLOPT_SSL_VERIFYPEER, $verifyPeer);
-
-        $verifyHost = isset($this->_config['verifyhost']) ? $this->_config['verifyhost'] : 0;
-        curl_setopt($this->_getResource(), CURLOPT_SSL_VERIFYHOST, $verifyHost);
-
         return $body;
     }
 
@@ -269,4 +300,4 @@ class Varien_Http_Adapter_Curl implements Zend_Http_Client_Adapter_Interface
         curl_multi_close($multihandle);
         return $result;
     }
-}
\ No newline at end of file
+}
diff --git a/pub/.htaccess b/pub/.htaccess
index c152dccc72caf11b28125e9fef5374dd4e92cbe1..742e08c830b07d926d870a411b6555c2c3c8e5e8 100644
--- a/pub/.htaccess
+++ b/pub/.htaccess
@@ -128,6 +128,12 @@
 
     RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
 
+############################################
+## TRACE and TRACK HTTP methods disabled to prevent XSS attacks
+
+    RewriteCond %{REQUEST_METHOD} ^TRAC[EK]
+    RewriteRule .* - [L,R=405]
+
 ############################################
 ## always send 404 on missing files in these folders
 
diff --git a/pub/js/calendar/calendar.js b/pub/js/calendar/calendar.js
index 9b2aa86f8f2cfd111ca34bf4902d3b136990d48d..310d2e301a70901a8c0754fe10c55a29007fd0ad 100644
--- a/pub/js/calendar/calendar.js
+++ b/pub/js/calendar/calendar.js
@@ -1,4 +1,4 @@
-/*  Copyright Mihai Bazon, 2002-2005  |  www.bazon.net/mishoo
+/*  Copyright Mihai Bazon, 2002-2005 | www.bazon.net/mishoo
  * -----------------------------------------------------------
  *
  * The DHTML Calendar, version 1.0 "It is happening again"
@@ -16,66 +16,66 @@
 
 /** The Calendar object constructor. */
 Calendar = function (firstDayOfWeek, dateStr, onSelected, onClose) {
-	// member variables
-	this.activeDiv = null;
-	this.currentDateEl = null;
-	this.getDateStatus = null;
-	this.getDateToolTip = null;
-	this.getDateText = null;
-	this.timeout = null;
-	this.onSelected = onSelected || null;
-	this.onClose = onClose || null;
-	this.dragging = false;
-	this.hidden = false;
-	this.minYear = 1970;
-	this.maxYear = 2050;
-	this.dateFormat = Calendar._TT["DEF_DATE_FORMAT"];
-	this.ttDateFormat = Calendar._TT["TT_DATE_FORMAT"];
-	this.isPopup = true;
-	this.weekNumbers = true;
-	this.firstDayOfWeek = typeof firstDayOfWeek == "number" ? firstDayOfWeek : Calendar._FD; // 0 for Sunday, 1 for Monday, etc.
-	this.showsOtherMonths = false;
-	this.dateStr = dateStr;
-	this.ar_days = null;
-	this.showsTime = false;
-	this.time24 = true;
-	this.yearStep = 2;
-	this.hiliteToday = true;
-	this.multiple = null;
-	// HTML elements
-	this.table = null;
-	this.element = null;
-	this.tbody = null;
-	this.firstdayname = null;
-	// Combo boxes
-	this.monthsCombo = null;
-	this.yearsCombo = null;
-	this.hilitedMonth = null;
-	this.activeMonth = null;
-	this.hilitedYear = null;
-	this.activeYear = null;
-	// Information
-	this.dateClicked = false;
-
-	// one-time initializations
-	if (typeof Calendar._SDN == "undefined") {
-		// table of short day names
-		if (typeof Calendar._SDN_len == "undefined")
-			Calendar._SDN_len = 3;
-		var ar = new Array();
-		for (var i = 8; i > 0;) {
-			ar[--i] = Calendar._DN[i].substr(0, Calendar._SDN_len);
-		}
-		Calendar._SDN = ar;
-		// table of short month names
-		if (typeof Calendar._SMN_len == "undefined")
-			Calendar._SMN_len = 3;
-		ar = new Array();
-		for (var i = 12; i > 0;) {
-			ar[--i] = Calendar._MN[i].substr(0, Calendar._SMN_len);
-		}
-		Calendar._SMN = ar;
-	}
+    // member variables
+    this.activeDiv = null;
+    this.currentDateEl = null;
+    this.getDateStatus = null;
+    this.getDateToolTip = null;
+    this.getDateText = null;
+    this.timeout = null;
+    this.onSelected = onSelected || null;
+    this.onClose = onClose || null;
+    this.dragging = false;
+    this.hidden = false;
+    this.minYear = 1970;
+    this.maxYear = 2050;
+    this.dateFormat = Calendar._TT["DEF_DATE_FORMAT"];
+    this.ttDateFormat = Calendar._TT["TT_DATE_FORMAT"];
+    this.isPopup = true;
+    this.weekNumbers = true;
+    this.firstDayOfWeek = typeof firstDayOfWeek == "number" ? firstDayOfWeek : Calendar._FD; // 0 for Sunday, 1 for Monday, etc.
+    this.showsOtherMonths = false;
+    this.dateStr = dateStr;
+    this.ar_days = null;
+    this.showsTime = false;
+    this.time24 = true;
+    this.yearStep = 2;
+    this.hiliteToday = true;
+    this.multiple = null;
+    // HTML elements
+    this.table = null;
+    this.element = null;
+    this.tbody = null;
+    this.firstdayname = null;
+    // Combo boxes
+    this.monthsCombo = null;
+    this.yearsCombo = null;
+    this.hilitedMonth = null;
+    this.activeMonth = null;
+    this.hilitedYear = null;
+    this.activeYear = null;
+    // Information
+    this.dateClicked = false;
+
+    // one-time initializations
+    if (typeof Calendar._SDN == "undefined") {
+        // table of short day names
+        if (typeof Calendar._SDN_len == "undefined")
+            Calendar._SDN_len = 3;
+        var ar = new Array();
+        for (var i = 8; i > 0;) {
+            ar[--i] = Calendar._DN[i].substr(0, Calendar._SDN_len);
+        }
+        Calendar._SDN = ar;
+        // table of short month names
+        if (typeof Calendar._SMN_len == "undefined")
+            Calendar._SMN_len = 3;
+        ar = new Array();
+        for (var i = 12; i > 0;) {
+            ar[--i] = Calendar._MN[i].substr(0, Calendar._SMN_len);
+        }
+        Calendar._SMN = ar;
+    }
 };
 
 // ** constants
@@ -85,7 +85,7 @@ Calendar._C = null;
 
 /// detect a special case of "web browser"
 Calendar.is_ie = ( /msie/i.test(navigator.userAgent) &&
-		   !/opera/i.test(navigator.userAgent) );
+           !/opera/i.test(navigator.userAgent) );
 
 Calendar.is_ie5 = ( Calendar.is_ie && /msie 5\.0/i.test(navigator.userAgent) );
 
@@ -166,119 +166,119 @@ Calendar.getAbsolutePos = function(element) {
 
     // variant 2 (not working)
 
-//	var SL = 0, ST = 0;
-//	var is_div = /^div$/i.test(el.tagName);
-//	if (is_div && el.scrollLeft)
-//		SL = el.scrollLeft;
-//	if (is_div && el.scrollTop)
-//		ST = el.scrollTop;
-//	var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
-//	if (el.offsetParent) {
-//		var tmp = this.getAbsolutePos(el.offsetParent);
-//		r.x += tmp.x;
-//		r.y += tmp.y;
-//	}
-//	return r;
+//    var SL = 0, ST = 0;
+//    var is_div = /^div$/i.test(el.tagName);
+//    if (is_div && el.scrollLeft)
+//        SL = el.scrollLeft;
+//    if (is_div && el.scrollTop)
+//        ST = el.scrollTop;
+//    var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
+//    if (el.offsetParent) {
+//        var tmp = this.getAbsolutePos(el.offsetParent);
+//        r.x += tmp.x;
+//        r.y += tmp.y;
+//    }
+//    return r;
 };
 
 Calendar.isRelated = function (el, evt) {
-	var related = evt.relatedTarget;
-	if (!related) {
-		var type = evt.type;
-		if (type == "mouseover") {
-			related = evt.fromElement;
-		} else if (type == "mouseout") {
-			related = evt.toElement;
-		}
-	}
-	while (related) {
-		if (related == el) {
-			return true;
-		}
-		related = related.parentNode;
-	}
-	return false;
+    var related = evt.relatedTarget;
+    if (!related) {
+        var type = evt.type;
+        if (type == "mouseover") {
+            related = evt.fromElement;
+        } else if (type == "mouseout") {
+            related = evt.toElement;
+        }
+    }
+    while (related) {
+        if (related == el) {
+            return true;
+        }
+        related = related.parentNode;
+    }
+    return false;
 };
 
 Calendar.removeClass = function(el, className) {
-	if (!(el && el.className)) {
-		return;
-	}
-	var cls = el.className.split(" ");
-	var ar = new Array();
-	for (var i = cls.length; i > 0;) {
-		if (cls[--i] != className) {
-			ar[ar.length] = cls[i];
-		}
-	}
-	el.className = ar.join(" ");
+    if (!(el && el.className)) {
+        return;
+    }
+    var cls = el.className.split(" ");
+    var ar = new Array();
+    for (var i = cls.length; i > 0;) {
+        if (cls[--i] != className) {
+            ar[ar.length] = cls[i];
+        }
+    }
+    el.className = ar.join(" ");
 };
 
 Calendar.addClass = function(el, className) {
-	Calendar.removeClass(el, className);
-	el.className += " " + className;
+    Calendar.removeClass(el, className);
+    el.className += " " + className;
 };
 
 // FIXME: the following 2 functions totally suck, are useless and should be replaced immediately.
 Calendar.getElement = function(ev) {
-	var f = Calendar.is_ie ? window.event.srcElement : ev.currentTarget;
-	while (f.nodeType != 1 || /^div$/i.test(f.tagName))
-		f = f.parentNode;
-	return f;
+    var f = Calendar.is_ie ? window.event.srcElement : ev.currentTarget;
+    while (f.nodeType != 1 || /^div$/i.test(f.tagName))
+        f = f.parentNode;
+    return f;
 };
 
 Calendar.getTargetElement = function(ev) {
-	var f = Calendar.is_ie ? window.event.srcElement : ev.target;
-	while (f.nodeType != 1)
-		f = f.parentNode;
-	return f;
+    var f = Calendar.is_ie ? window.event.srcElement : ev.target;
+    while (f.nodeType != 1)
+        f = f.parentNode;
+    return f;
 };
 
 Calendar.stopEvent = function(ev) {
-	ev || (ev = window.event);
-	if (Calendar.is_ie) {
-		ev.cancelBubble = true;
-		ev.returnValue = false;
-	} else {
-		ev.preventDefault();
-		ev.stopPropagation();
-	}
-	return false;
+    ev || (ev = window.event);
+    if (Calendar.is_ie) {
+        ev.cancelBubble = true;
+        ev.returnValue = false;
+    } else {
+        ev.preventDefault();
+        ev.stopPropagation();
+    }
+    return false;
 };
 
 Calendar.addEvent = function(el, evname, func) {
-	if (el.attachEvent) { // IE
-		el.attachEvent("on" + evname, func);
-	} else if (el.addEventListener) { // Gecko / W3C
-		el.addEventListener(evname, func, true);
-	} else {
-		el["on" + evname] = func;
-	}
+    if (el.attachEvent) { // IE
+        el.attachEvent("on" + evname, func);
+    } else if (el.addEventListener) { // Gecko / W3C
+        el.addEventListener(evname, func, true);
+    } else {
+        el["on" + evname] = func;
+    }
 };
 
 Calendar.removeEvent = function(el, evname, func) {
-	if (el.detachEvent) { // IE
-		el.detachEvent("on" + evname, func);
-	} else if (el.removeEventListener) { // Gecko / W3C
-		el.removeEventListener(evname, func, true);
-	} else {
-		el["on" + evname] = null;
-	}
+    if (el.detachEvent) { // IE
+        el.detachEvent("on" + evname, func);
+    } else if (el.removeEventListener) { // Gecko / W3C
+        el.removeEventListener(evname, func, true);
+    } else {
+        el["on" + evname] = null;
+    }
 };
 
 Calendar.createElement = function(type, parent) {
-	var el = null;
-	if (document.createElementNS) {
-		// use the XHTML namespace; IE won't normally get here unless
-		// _they_ "fix" the DOM2 implementation.
-		el = document.createElementNS("http://www.w3.org/1999/xhtml", type);
-	} else {
-		el = document.createElement(type);
-	}
-	if (typeof parent != "undefined") {
-		parent.appendChild(el);
-	}
-	return el;
+    var el = null;
+    if (document.createElementNS) {
+        // use the XHTML namespace; IE won't normally get here unless
+        // _they_ "fix" the DOM2 implementation.
+        el = document.createElementNS("http://www.w3.org/1999/xhtml", type);
+    } else {
+        el = document.createElement(type);
+    }
+    if (typeof parent != "undefined") {
+        parent.appendChild(el);
+    }
+    return el;
 };
 
 // END: UTILITY FUNCTIONS
@@ -287,355 +287,355 @@ Calendar.createElement = function(type, parent) {
 
 /** Internal -- adds a set of events to make some element behave like a button. */
 Calendar._add_evs = function(el) {
-	with (Calendar) {
-		addEvent(el, "mouseover", dayMouseOver);
-		addEvent(el, "mousedown", dayMouseDown);
-		addEvent(el, "mouseout", dayMouseOut);
-		if (is_ie) {
-			addEvent(el, "dblclick", dayMouseDblClick);
-			el.setAttribute("unselectable", true);
-		}
-	}
+    with (Calendar) {
+        addEvent(el, "mouseover", dayMouseOver);
+        addEvent(el, "mousedown", dayMouseDown);
+        addEvent(el, "mouseout", dayMouseOut);
+        if (is_ie) {
+            addEvent(el, "dblclick", dayMouseDblClick);
+            el.setAttribute("unselectable", true);
+        }
+    }
 };
 
 Calendar.findMonth = function(el) {
-	if (typeof el.month != "undefined") {
-		return el;
-	} else if (typeof el.parentNode.month != "undefined") {
-		return el.parentNode;
-	}
-	return null;
+    if (typeof el.month != "undefined") {
+        return el;
+    } else if (typeof el.parentNode.month != "undefined") {
+        return el.parentNode;
+    }
+    return null;
 };
 
 Calendar.findYear = function(el) {
-	if (typeof el.year != "undefined") {
-		return el;
-	} else if (typeof el.parentNode.year != "undefined") {
-		return el.parentNode;
-	}
-	return null;
+    if (typeof el.year != "undefined") {
+        return el;
+    } else if (typeof el.parentNode.year != "undefined") {
+        return el.parentNode;
+    }
+    return null;
 };
 
 Calendar.showMonthsCombo = function () {
-	var cal = Calendar._C;
-	if (!cal) {
-		return false;
-	}
-	var cal = cal;
-	var cd = cal.activeDiv;
-	var mc = cal.monthsCombo;
-	if (cal.hilitedMonth) {
-		Calendar.removeClass(cal.hilitedMonth, "hilite");
-	}
-	if (cal.activeMonth) {
-		Calendar.removeClass(cal.activeMonth, "active");
-	}
-	var mon = cal.monthsCombo.getElementsByTagName("div")[cal.date.getMonth()];
-	Calendar.addClass(mon, "active");
-	cal.activeMonth = mon;
-	var s = mc.style;
-	s.display = "block";
-	if (cd.navtype < 0)
-		s.left = cd.offsetLeft + "px";
-	else {
-		var mcw = mc.offsetWidth;
-		if (typeof mcw == "undefined")
-			// Konqueror brain-dead techniques
-			mcw = 50;
-		s.left = (cd.offsetLeft + cd.offsetWidth - mcw) + "px";
-	}
-	s.top = (cd.offsetTop + cd.offsetHeight) + "px";
+    var cal = Calendar._C;
+    if (!cal) {
+        return false;
+    }
+    var cal = cal;
+    var cd = cal.activeDiv;
+    var mc = cal.monthsCombo;
+    if (cal.hilitedMonth) {
+        Calendar.removeClass(cal.hilitedMonth, "hilite");
+    }
+    if (cal.activeMonth) {
+        Calendar.removeClass(cal.activeMonth, "active");
+    }
+    var mon = cal.monthsCombo.getElementsByTagName("div")[cal.date.getMonth()];
+    Calendar.addClass(mon, "active");
+    cal.activeMonth = mon;
+    var s = mc.style;
+    s.display = "block";
+    if (cd.navtype < 0)
+        s.left = cd.offsetLeft + "px";
+    else {
+        var mcw = mc.offsetWidth;
+        if (typeof mcw == "undefined")
+            // Konqueror brain-dead techniques
+            mcw = 50;
+        s.left = (cd.offsetLeft + cd.offsetWidth - mcw) + "px";
+    }
+    s.top = (cd.offsetTop + cd.offsetHeight) + "px";
 };
 
 Calendar.showYearsCombo = function (fwd) {
-	var cal = Calendar._C;
-	if (!cal) {
-		return false;
-	}
-	var cal = cal;
-	var cd = cal.activeDiv;
-	var yc = cal.yearsCombo;
-	if (cal.hilitedYear) {
-		Calendar.removeClass(cal.hilitedYear, "hilite");
-	}
-	if (cal.activeYear) {
-		Calendar.removeClass(cal.activeYear, "active");
-	}
-	cal.activeYear = null;
-	var Y = cal.date.getFullYear() + (fwd ? 1 : -1);
-	var yr = yc.firstChild;
-	var show = false;
-	for (var i = 12; i > 0; --i) {
-		if (Y >= cal.minYear && Y <= cal.maxYear) {
-			yr.innerHTML = Y;
-			yr.year = Y;
-			yr.style.display = "block";
-			show = true;
-		} else {
-			yr.style.display = "none";
-		}
-		yr = yr.nextSibling;
-		Y += fwd ? cal.yearStep : -cal.yearStep;
-	}
-	if (show) {
-		var s = yc.style;
-		s.display = "block";
-		if (cd.navtype < 0)
-			s.left = cd.offsetLeft + "px";
-		else {
-			var ycw = yc.offsetWidth;
-			if (typeof ycw == "undefined")
-				// Konqueror brain-dead techniques
-				ycw = 50;
-			s.left = (cd.offsetLeft + cd.offsetWidth - ycw) + "px";
-		}
-		s.top = (cd.offsetTop + cd.offsetHeight) + "px";
-	}
+    var cal = Calendar._C;
+    if (!cal) {
+        return false;
+    }
+    var cal = cal;
+    var cd = cal.activeDiv;
+    var yc = cal.yearsCombo;
+    if (cal.hilitedYear) {
+        Calendar.removeClass(cal.hilitedYear, "hilite");
+    }
+    if (cal.activeYear) {
+        Calendar.removeClass(cal.activeYear, "active");
+    }
+    cal.activeYear = null;
+    var Y = cal.date.getFullYear() + (fwd ? 1 : -1);
+    var yr = yc.firstChild;
+    var show = false;
+    for (var i = 12; i > 0; --i) {
+        if (Y >= cal.minYear && Y <= cal.maxYear) {
+            yr.innerHTML = Y;
+            yr.year = Y;
+            yr.style.display = "block";
+            show = true;
+        } else {
+            yr.style.display = "none";
+        }
+        yr = yr.nextSibling;
+        Y += fwd ? cal.yearStep : -cal.yearStep;
+    }
+    if (show) {
+        var s = yc.style;
+        s.display = "block";
+        if (cd.navtype < 0)
+            s.left = cd.offsetLeft + "px";
+        else {
+            var ycw = yc.offsetWidth;
+            if (typeof ycw == "undefined")
+                // Konqueror brain-dead techniques
+                ycw = 50;
+            s.left = (cd.offsetLeft + cd.offsetWidth - ycw) + "px";
+        }
+        s.top = (cd.offsetTop + cd.offsetHeight) + "px";
+    }
 };
 
 // event handlers
 
 Calendar.tableMouseUp = function(ev) {
-	var cal = Calendar._C;
-	if (!cal) {
-		return false;
-	}
-	if (cal.timeout) {
-		clearTimeout(cal.timeout);
-	}
-	var el = cal.activeDiv;
-	if (!el) {
-		return false;
-	}
-	var target = Calendar.getTargetElement(ev);
-	ev || (ev = window.event);
-	Calendar.removeClass(el, "active");
-	if (target == el || target.parentNode == el) {
-		Calendar.cellClick(el, ev);
-	}
-	var mon = Calendar.findMonth(target);
-	var date = null;
-	if (mon) {
-		date = new CalendarDateObject(cal.date);
-		if (mon.month != date.getMonth()) {
-			date.setMonth(mon.month);
-			cal.setDate(date);
-			cal.dateClicked = false;
-			cal.callHandler();
-		}
-	} else {
-		var year = Calendar.findYear(target);
-		if (year) {
-			date = new CalendarDateObject(cal.date);
-			if (year.year != date.getFullYear()) {
-				date.setFullYear(year.year);
-				cal.setDate(date);
-				cal.dateClicked = false;
-				cal.callHandler();
-			}
-		}
-	}
-	with (Calendar) {
-		removeEvent(document, "mouseup", tableMouseUp);
-		removeEvent(document, "mouseover", tableMouseOver);
-		removeEvent(document, "mousemove", tableMouseOver);
-		cal._hideCombos();
-		_C = null;
-		return stopEvent(ev);
-	}
+    var cal = Calendar._C;
+    if (!cal) {
+        return false;
+    }
+    if (cal.timeout) {
+        clearTimeout(cal.timeout);
+    }
+    var el = cal.activeDiv;
+    if (!el) {
+        return false;
+    }
+    var target = Calendar.getTargetElement(ev);
+    ev || (ev = window.event);
+    Calendar.removeClass(el, "active");
+    if (target == el || target.parentNode == el) {
+        Calendar.cellClick(el, ev);
+    }
+    var mon = Calendar.findMonth(target);
+    var date = null;
+    if (mon) {
+        date = new CalendarDateObject(cal.date);
+        if (mon.month != date.getMonth()) {
+            date.setMonth(mon.month);
+            cal.setDate(date);
+            cal.dateClicked = false;
+            cal.callHandler();
+        }
+    } else {
+        var year = Calendar.findYear(target);
+        if (year) {
+            date = new CalendarDateObject(cal.date);
+            if (year.year != date.getFullYear()) {
+                date.setFullYear(year.year);
+                cal.setDate(date);
+                cal.dateClicked = false;
+                cal.callHandler();
+            }
+        }
+    }
+    with (Calendar) {
+        removeEvent(document, "mouseup", tableMouseUp);
+        removeEvent(document, "mouseover", tableMouseOver);
+        removeEvent(document, "mousemove", tableMouseOver);
+        cal._hideCombos();
+        _C = null;
+        return stopEvent(ev);
+    }
 };
 
 Calendar.tableMouseOver = function (ev) {
-	var cal = Calendar._C;
-	if (!cal) {
-		return;
-	}
-	var el = cal.activeDiv;
-	var target = Calendar.getTargetElement(ev);
-	if (target == el || target.parentNode == el) {
-		Calendar.addClass(el, "hilite active");
-		Calendar.addClass(el.parentNode, "rowhilite");
-	} else {
-		if (typeof el.navtype == "undefined" || (el.navtype != 50 && (el.navtype == 0 || Math.abs(el.navtype) > 2)))
-			Calendar.removeClass(el, "active");
-		Calendar.removeClass(el, "hilite");
-		Calendar.removeClass(el.parentNode, "rowhilite");
-	}
-	ev || (ev = window.event);
-	if (el.navtype == 50 && target != el) {
-		var pos = Calendar.getAbsolutePos(el);
-		var w = el.offsetWidth;
-		var x = ev.clientX;
-		var dx;
-		var decrease = true;
-		if (x > pos.x + w) {
-			dx = x - pos.x - w;
-			decrease = false;
-		} else
-			dx = pos.x - x;
-
-		if (dx < 0) dx = 0;
-		var range = el._range;
-		var current = el._current;
-		var count = Math.floor(dx / 10) % range.length;
-		for (var i = range.length; --i >= 0;)
-			if (range[i] == current)
-				break;
-		while (count-- > 0)
-			if (decrease) {
-				if (--i < 0)
-					i = range.length - 1;
-			} else if ( ++i >= range.length )
-				i = 0;
-		var newval = range[i];
-		el.innerHTML = newval;
-
-		cal.onUpdateTime();
-	}
-	var mon = Calendar.findMonth(target);
-	if (mon) {
-		if (mon.month != cal.date.getMonth()) {
-			if (cal.hilitedMonth) {
-				Calendar.removeClass(cal.hilitedMonth, "hilite");
-			}
-			Calendar.addClass(mon, "hilite");
-			cal.hilitedMonth = mon;
-		} else if (cal.hilitedMonth) {
-			Calendar.removeClass(cal.hilitedMonth, "hilite");
-		}
-	} else {
-		if (cal.hilitedMonth) {
-			Calendar.removeClass(cal.hilitedMonth, "hilite");
-		}
-		var year = Calendar.findYear(target);
-		if (year) {
-			if (year.year != cal.date.getFullYear()) {
-				if (cal.hilitedYear) {
-					Calendar.removeClass(cal.hilitedYear, "hilite");
-				}
-				Calendar.addClass(year, "hilite");
-				cal.hilitedYear = year;
-			} else if (cal.hilitedYear) {
-				Calendar.removeClass(cal.hilitedYear, "hilite");
-			}
-		} else if (cal.hilitedYear) {
-			Calendar.removeClass(cal.hilitedYear, "hilite");
-		}
-	}
-	return Calendar.stopEvent(ev);
+    var cal = Calendar._C;
+    if (!cal) {
+        return;
+    }
+    var el = cal.activeDiv;
+    var target = Calendar.getTargetElement(ev);
+    if (target == el || target.parentNode == el) {
+        Calendar.addClass(el, "hilite active");
+        Calendar.addClass(el.parentNode, "rowhilite");
+    } else {
+        if (typeof el.navtype == "undefined" || (el.navtype != 50 && (el.navtype == 0 || Math.abs(el.navtype) > 2)))
+            Calendar.removeClass(el, "active");
+        Calendar.removeClass(el, "hilite");
+        Calendar.removeClass(el.parentNode, "rowhilite");
+    }
+    ev || (ev = window.event);
+    if (el.navtype == 50 && target != el) {
+        var pos = Calendar.getAbsolutePos(el);
+        var w = el.offsetWidth;
+        var x = ev.clientX;
+        var dx;
+        var decrease = true;
+        if (x > pos.x + w) {
+            dx = x - pos.x - w;
+            decrease = false;
+        } else
+            dx = pos.x - x;
+
+        if (dx < 0) dx = 0;
+        var range = el._range;
+        var current = el._current;
+        var count = Math.floor(dx / 10) % range.length;
+        for (var i = range.length; --i >= 0;)
+            if (range[i] == current)
+                break;
+        while (count-- > 0)
+            if (decrease) {
+                if (--i < 0)
+                    i = range.length - 1;
+            } else if ( ++i >= range.length )
+                i = 0;
+        var newval = range[i];
+        el.innerHTML = newval;
+
+        cal.onUpdateTime();
+    }
+    var mon = Calendar.findMonth(target);
+    if (mon) {
+        if (mon.month != cal.date.getMonth()) {
+            if (cal.hilitedMonth) {
+                Calendar.removeClass(cal.hilitedMonth, "hilite");
+            }
+            Calendar.addClass(mon, "hilite");
+            cal.hilitedMonth = mon;
+        } else if (cal.hilitedMonth) {
+            Calendar.removeClass(cal.hilitedMonth, "hilite");
+        }
+    } else {
+        if (cal.hilitedMonth) {
+            Calendar.removeClass(cal.hilitedMonth, "hilite");
+        }
+        var year = Calendar.findYear(target);
+        if (year) {
+            if (year.year != cal.date.getFullYear()) {
+                if (cal.hilitedYear) {
+                    Calendar.removeClass(cal.hilitedYear, "hilite");
+                }
+                Calendar.addClass(year, "hilite");
+                cal.hilitedYear = year;
+            } else if (cal.hilitedYear) {
+                Calendar.removeClass(cal.hilitedYear, "hilite");
+            }
+        } else if (cal.hilitedYear) {
+            Calendar.removeClass(cal.hilitedYear, "hilite");
+        }
+    }
+    return Calendar.stopEvent(ev);
 };
 
 Calendar.tableMouseDown = function (ev) {
-	if (Calendar.getTargetElement(ev) == Calendar.getElement(ev)) {
-		return Calendar.stopEvent(ev);
-	}
+    if (Calendar.getTargetElement(ev) == Calendar.getElement(ev)) {
+        return Calendar.stopEvent(ev);
+    }
 };
 
 Calendar.calDragIt = function (ev) {
-	var cal = Calendar._C;
-	if (!(cal && cal.dragging)) {
-		return false;
-	}
-	var posX;
-	var posY;
-	if (Calendar.is_ie) {
-		posY = window.event.clientY + document.body.scrollTop;
-		posX = window.event.clientX + document.body.scrollLeft;
-	} else {
-		posX = ev.pageX;
-		posY = ev.pageY;
-	}
-	cal.hideShowCovered();
-	var st = cal.element.style;
-	st.left = (posX - cal.xOffs) + "px";
-	st.top = (posY - cal.yOffs) + "px";
-	return Calendar.stopEvent(ev);
+    var cal = Calendar._C;
+    if (!(cal && cal.dragging)) {
+        return false;
+    }
+    var posX;
+    var posY;
+    if (Calendar.is_ie) {
+        posY = window.event.clientY + document.body.scrollTop;
+        posX = window.event.clientX + document.body.scrollLeft;
+    } else {
+        posX = ev.pageX;
+        posY = ev.pageY;
+    }
+    cal.hideShowCovered();
+    var st = cal.element.style;
+    st.left = (posX - cal.xOffs) + "px";
+    st.top = (posY - cal.yOffs) + "px";
+    return Calendar.stopEvent(ev);
 };
 
 Calendar.calDragEnd = function (ev) {
-	var cal = Calendar._C;
-	if (!cal) {
-		return false;
-	}
-	cal.dragging = false;
-	with (Calendar) {
-		removeEvent(document, "mousemove", calDragIt);
-		removeEvent(document, "mouseup", calDragEnd);
-		tableMouseUp(ev);
-	}
-	cal.hideShowCovered();
+    var cal = Calendar._C;
+    if (!cal) {
+        return false;
+    }
+    cal.dragging = false;
+    with (Calendar) {
+        removeEvent(document, "mousemove", calDragIt);
+        removeEvent(document, "mouseup", calDragEnd);
+        tableMouseUp(ev);
+    }
+    cal.hideShowCovered();
 };
 
 Calendar.dayMouseDown = function(ev) {
-	var el = Calendar.getElement(ev);
-	if (el.disabled) {
-		return false;
-	}
-	var cal = el.calendar;
-	cal.activeDiv = el;
-	Calendar._C = cal;
-	if (el.navtype != 300) with (Calendar) {
-		if (el.navtype == 50) {
-			el._current = el.innerHTML;
-			addEvent(document, "mousemove", tableMouseOver);
-		} else
-			addEvent(document, Calendar.is_ie5 ? "mousemove" : "mouseover", tableMouseOver);
-		addClass(el, "hilite active");
-		addEvent(document, "mouseup", tableMouseUp);
-	} else if (cal.isPopup) {
-		cal._dragStart(ev);
-	}
-	if (el.navtype == -1 || el.navtype == 1) {
-		if (cal.timeout) clearTimeout(cal.timeout);
-		cal.timeout = setTimeout("Calendar.showMonthsCombo()", 250);
-	} else if (el.navtype == -2 || el.navtype == 2) {
-		if (cal.timeout) clearTimeout(cal.timeout);
-		cal.timeout = setTimeout((el.navtype > 0) ? "Calendar.showYearsCombo(true)" : "Calendar.showYearsCombo(false)", 250);
-	} else {
-		cal.timeout = null;
-	}
-	return Calendar.stopEvent(ev);
+    var el = Calendar.getElement(ev);
+    if (el.disabled) {
+        return false;
+    }
+    var cal = el.calendar;
+    cal.activeDiv = el;
+    Calendar._C = cal;
+    if (el.navtype != 300) with (Calendar) {
+        if (el.navtype == 50) {
+            el._current = el.innerHTML;
+            addEvent(document, "mousemove", tableMouseOver);
+        } else
+            addEvent(document, Calendar.is_ie5 ? "mousemove" : "mouseover", tableMouseOver);
+        addClass(el, "hilite active");
+        addEvent(document, "mouseup", tableMouseUp);
+    } else if (cal.isPopup) {
+        cal._dragStart(ev);
+    }
+    if (el.navtype == -1 || el.navtype == 1) {
+        if (cal.timeout) clearTimeout(cal.timeout);
+        cal.timeout = setTimeout("Calendar.showMonthsCombo()", 250);
+    } else if (el.navtype == -2 || el.navtype == 2) {
+        if (cal.timeout) clearTimeout(cal.timeout);
+        cal.timeout = setTimeout((el.navtype > 0) ? "Calendar.showYearsCombo(true)" : "Calendar.showYearsCombo(false)", 250);
+    } else {
+        cal.timeout = null;
+    }
+    return Calendar.stopEvent(ev);
 };
 
 Calendar.dayMouseDblClick = function(ev) {
-	Calendar.cellClick(Calendar.getElement(ev), ev || window.event);
-	if (Calendar.is_ie) {
-		document.selection.empty();
-	}
+    Calendar.cellClick(Calendar.getElement(ev), ev || window.event);
+    if (Calendar.is_ie) {
+        document.selection.empty();
+    }
 };
 
 Calendar.dayMouseOver = function(ev) {
-	var el = Calendar.getElement(ev);
-	if (Calendar.isRelated(el, ev) || Calendar._C || el.disabled) {
-		return false;
-	}
-	if (el.ttip) {
-		if (el.ttip.substr(0, 1) == "_") {
-			el.ttip = el.caldate.print(el.calendar.ttDateFormat) + el.ttip.substr(1);
-		}
-		el.calendar.tooltips.innerHTML = el.ttip;
-	}
-	if (el.navtype != 300) {
-		Calendar.addClass(el, "hilite");
-		if (el.caldate) {
-			Calendar.addClass(el.parentNode, "rowhilite");
-		}
-	}
-	return Calendar.stopEvent(ev);
+    var el = Calendar.getElement(ev);
+    if (Calendar.isRelated(el, ev) || Calendar._C || el.disabled) {
+        return false;
+    }
+    if (el.ttip) {
+        if (el.ttip.substr(0, 1) == "_") {
+            el.ttip = el.caldate.print(el.calendar.ttDateFormat) + el.ttip.substr(1);
+        }
+        el.calendar.tooltips.innerHTML = el.ttip;
+    }
+    if (el.navtype != 300) {
+        Calendar.addClass(el, "hilite");
+        if (el.caldate) {
+            Calendar.addClass(el.parentNode, "rowhilite");
+        }
+    }
+    return Calendar.stopEvent(ev);
 };
 
 Calendar.dayMouseOut = function(ev) {
-	with (Calendar) {
-		var el = getElement(ev);
-		if (isRelated(el, ev) || _C || el.disabled)
-			return false;
-		removeClass(el, "hilite");
-		if (el.caldate)
-			removeClass(el.parentNode, "rowhilite");
-		if (el.calendar)
-			el.calendar.tooltips.innerHTML = _TT["SEL_DATE"];
-		return stopEvent(ev);
-	}
+    with (Calendar) {
+        var el = getElement(ev);
+        if (isRelated(el, ev) || _C || el.disabled)
+            return false;
+        removeClass(el, "hilite");
+        if (el.caldate)
+            removeClass(el.parentNode, "rowhilite");
+        if (el.calendar)
+            el.calendar.tooltips.innerHTML = _TT["SEL_DATE"];
+        return stopEvent(ev);
+    }
 };
 
 /**
@@ -643,135 +643,135 @@ Calendar.dayMouseOut = function(ev) {
  *  calendar.
  */
 Calendar.cellClick = function(el, ev) {
-	var cal = el.calendar;
-	var closing = false;
-	var newdate = false;
-	var date = null;
-	if (typeof el.navtype == "undefined") {
-		if (cal.currentDateEl) {
-			Calendar.removeClass(cal.currentDateEl, "selected");
-			Calendar.addClass(el, "selected");
-			closing = (cal.currentDateEl == el);
-			if (!closing) {
-				cal.currentDateEl = el;
-			}
-		}
-		cal.date.setDateOnly(el.caldate);
-		date = cal.date;
-		var other_month = !(cal.dateClicked = !el.otherMonth);
-		if (!other_month && !cal.currentDateEl)
-			cal._toggleMultipleDate(new CalendarDateObject(date));
-		else
-			newdate = !el.disabled;
-		// a date was clicked
-		if (other_month)
-			cal._init(cal.firstDayOfWeek, date);
-	} else {
-		if (el.navtype == 200) {
-			Calendar.removeClass(el, "hilite");
-			cal.callCloseHandler();
-			return;
-		}
-		date = new CalendarDateObject(cal.date);
-		if (el.navtype == 0)
-			date.setDateOnly(new CalendarDateObject()); // TODAY
-		// unless "today" was clicked, we assume no date was clicked so
-		// the selected handler will know not to close the calenar when
-		// in single-click mode.
-		// cal.dateClicked = (el.navtype == 0);
-		cal.dateClicked = false;
-		var year = date.getFullYear();
-		var mon = date.getMonth();
-		function setMonth(m) {
-			var day = date.getDate();
-			var max = date.getMonthDays(m);
-			if (day > max) {
-				date.setDate(max);
-			}
-			date.setMonth(m);
-		};
-		switch (el.navtype) {
-		    case 400:
-			Calendar.removeClass(el, "hilite");
-			var text = Calendar._TT["ABOUT"];
-			if (typeof text != "undefined") {
-				text += cal.showsTime ? Calendar._TT["ABOUT_TIME"] : "";
-			} else {
-				// FIXME: this should be removed as soon as lang files get updated!
-				text = "Help and about box text is not translated into this language.\n" +
-					"If you know this language and you feel generous please update\n" +
-					"the corresponding file in \"lang\" subdir to match calendar-en.js\n" +
-					"and send it back to <mihai_bazon@yahoo.com> to get it into the distribution  ;-)\n\n" +
-					"Thank you!\n" +
-					"http://dynarch.com/mishoo/calendar.epl\n";
-			}
-			alert(text);
-			return;
-		    case -2:
-			if (year > cal.minYear) {
-				date.setFullYear(year - 1);
-			}
-			break;
-		    case -1:
-			if (mon > 0) {
-				setMonth(mon - 1);
-			} else if (year-- > cal.minYear) {
-				date.setFullYear(year);
-				setMonth(11);
-			}
-			break;
-		    case 1:
-			if (mon < 11) {
-				setMonth(mon + 1);
-			} else if (year < cal.maxYear) {
-				date.setFullYear(year + 1);
-				setMonth(0);
-			}
-			break;
-		    case 2:
-			if (year < cal.maxYear) {
-				date.setFullYear(year + 1);
-			}
-			break;
-		    case 100:
-			cal.setFirstDayOfWeek(el.fdow);
-			return;
-		    case 50:
-			var range = el._range;
-			var current = el.innerHTML;
-			for (var i = range.length; --i >= 0;)
-				if (range[i] == current)
-					break;
-			if (ev && ev.shiftKey) {
-				if (--i < 0)
-					i = range.length - 1;
-			} else if ( ++i >= range.length )
-				i = 0;
-			var newval = range[i];
-			el.innerHTML = newval;
-			cal.onUpdateTime();
-			return;
-		    case 0:
-			// TODAY will bring us here
-			if ((typeof cal.getDateStatus == "function") &&
-			    cal.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate())) {
-				return false;
-			}
-			break;
-		}
-		if (!date.equalsTo(cal.date)) {
-			cal.setDate(date);
-			newdate = true;
-		} else if (el.navtype == 0)
-			newdate = closing = true;
-	}
-	if (newdate) {
-		ev && cal.callHandler();
-	}
-	if (closing) {
-		Calendar.removeClass(el, "hilite");
-		ev && cal.callCloseHandler();
-	}
+    var cal = el.calendar;
+    var closing = false;
+    var newdate = false;
+    var date = null;
+    if (typeof el.navtype == "undefined") {
+        if (cal.currentDateEl) {
+            Calendar.removeClass(cal.currentDateEl, "selected");
+            Calendar.addClass(el, "selected");
+            closing = (cal.currentDateEl == el);
+            if (!closing) {
+                cal.currentDateEl = el;
+            }
+        }
+        cal.date.setDateOnly(el.caldate);
+        date = cal.date;
+        var other_month = !(cal.dateClicked = !el.otherMonth);
+        if (!other_month && !cal.currentDateEl)
+            cal._toggleMultipleDate(new CalendarDateObject(date));
+        else
+            newdate = !el.disabled;
+        // a date was clicked
+        if (other_month)
+            cal._init(cal.firstDayOfWeek, date);
+    } else {
+        if (el.navtype == 200) {
+            Calendar.removeClass(el, "hilite");
+            cal.callCloseHandler();
+            return;
+        }
+        date = new CalendarDateObject(cal.date);
+        if (el.navtype == 0)
+            date.setDateOnly(new CalendarDateObject()); // TODAY
+        // unless "today" was clicked, we assume no date was clicked so
+        // the selected handler will know not to close the calenar when
+        // in single-click mode.
+        // cal.dateClicked = (el.navtype == 0);
+        cal.dateClicked = false;
+        var year = date.getFullYear();
+        var mon = date.getMonth();
+        function setMonth(m) {
+            var day = date.getDate();
+            var max = date.getMonthDays(m);
+            if (day > max) {
+                date.setDate(max);
+            }
+            date.setMonth(m);
+        };
+        switch (el.navtype) {
+            case 400:
+            Calendar.removeClass(el, "hilite");
+            var text = Calendar._TT["ABOUT"];
+            if (typeof text != "undefined") {
+                text += cal.showsTime ? Calendar._TT["ABOUT_TIME"] : "";
+            } else {
+                // FIXME: this should be removed as soon as lang files get updated!
+                text = "Help and about box text is not translated into this language.\n" +
+                    "If you know this language and you feel generous please update\n" +
+                    "the corresponding file in \"lang\" subdir to match calendar-en.js\n" +
+                    "and send it back to <mihai_bazon@yahoo.com> to get it into the distribution  ;-)\n\n" +
+                    "Thank you!\n" +
+                    "http://dynarch.com/mishoo/calendar.epl\n";
+            }
+            alert(text);
+            return;
+            case -2:
+            if (year > cal.minYear) {
+                date.setFullYear(year - 1);
+            }
+            break;
+            case -1:
+            if (mon > 0) {
+                setMonth(mon - 1);
+            } else if (year-- > cal.minYear) {
+                date.setFullYear(year);
+                setMonth(11);
+            }
+            break;
+            case 1:
+            if (mon < 11) {
+                setMonth(mon + 1);
+            } else if (year < cal.maxYear) {
+                date.setFullYear(year + 1);
+                setMonth(0);
+            }
+            break;
+            case 2:
+            if (year < cal.maxYear) {
+                date.setFullYear(year + 1);
+            }
+            break;
+            case 100:
+            cal.setFirstDayOfWeek(el.fdow);
+            return;
+            case 50:
+            var range = el._range;
+            var current = el.innerHTML;
+            for (var i = range.length; --i >= 0;)
+                if (range[i] == current)
+                    break;
+            if (ev && ev.shiftKey) {
+                if (--i < 0)
+                    i = range.length - 1;
+            } else if ( ++i >= range.length )
+                i = 0;
+            var newval = range[i];
+            el.innerHTML = newval;
+            cal.onUpdateTime();
+            return;
+            case 0:
+            // TODAY will bring us here
+            if ((typeof cal.getDateStatus == "function") &&
+                cal.getDateStatus(date, date.getFullYear(), date.getMonth(), date.getDate())) {
+                return false;
+            }
+            break;
+        }
+        if (!date.equalsTo(cal.date)) {
+            cal.setDate(date);
+            newdate = true;
+        } else if (el.navtype == 0)
+            newdate = closing = true;
+    }
+    if (newdate) {
+        ev && cal.callHandler();
+    }
+    if (closing) {
+        Calendar.removeClass(el, "hilite");
+        ev && cal.callCloseHandler();
+    }
 };
 
 // END: CALENDAR STATIC FUNCTIONS
@@ -785,512 +785,512 @@ Calendar.cellClick = function(el, ev) {
  *  hidden).  Some properties need to be set before calling this function.
  */
 Calendar.prototype.create = function (_par) {
-	var parent = null;
-	if (! _par) {
-		// default parent is the document body, in which case we create
-		// a popup calendar.
-		parent = document.getElementsByTagName("body")[0];
-		this.isPopup = true;
-	} else {
-		parent = _par;
-		this.isPopup = false;
-	}
-	this.date = this.dateStr ? new CalendarDateObject(this.dateStr) : new CalendarDateObject();
-
-	var table = Calendar.createElement("table");
-	this.table = table;
-	table.cellSpacing = 0;
-	table.cellPadding = 0;
-	table.calendar = this;
-	Calendar.addEvent(table, "mousedown", Calendar.tableMouseDown);
-
-	var div = Calendar.createElement("div");
-	this.element = div;
-	div.className = "calendar";
-	if (this.isPopup) {
-		div.style.position = "absolute";
-		div.style.display = "none";
-	}
-	div.appendChild(table);
-
-	var thead = Calendar.createElement("thead", table);
-	var cell = null;
-	var row = null;
-
-	var cal = this;
-	var hh = function (text, cs, navtype) {
-		cell = Calendar.createElement("td", row);
-		cell.colSpan = cs;
-		cell.className = "button";
-		if (navtype != 0 && Math.abs(navtype) <= 2)
-			cell.className += " nav";
-		Calendar._add_evs(cell);
-		cell.calendar = cal;
-		cell.navtype = navtype;
-		cell.innerHTML = "<div unselectable='on'>" + text + "</div>";
-		return cell;
-	};
-
-	row = Calendar.createElement("tr", thead);
-	var title_length = 6;
-	(this.isPopup) && --title_length;
-	(this.weekNumbers) && ++title_length;
-
-	hh("?", 1, 400).ttip = Calendar._TT["INFO"];
-	this.title = hh("", title_length, 300);
-	this.title.className = "title";
-	if (this.isPopup) {
-		this.title.ttip = Calendar._TT["DRAG_TO_MOVE"];
-		this.title.style.cursor = "move";
-		hh("&#x00d7;", 1, 200).ttip = Calendar._TT["CLOSE"];
-	}
-
-	row = Calendar.createElement("tr", thead);
-	row.className = "headrow";
-
-	this._nav_py = hh("&#x00ab;", 1, -2);
-	this._nav_py.ttip = Calendar._TT["PREV_YEAR"];
-
-	this._nav_pm = hh("&#x2039;", 1, -1);
-	this._nav_pm.ttip = Calendar._TT["PREV_MONTH"];
-
-	this._nav_now = hh(Calendar._TT["TODAY"], this.weekNumbers ? 4 : 3, 0);
-	this._nav_now.ttip = Calendar._TT["GO_TODAY"];
-
-	this._nav_nm = hh("&#x203a;", 1, 1);
-	this._nav_nm.ttip = Calendar._TT["NEXT_MONTH"];
-
-	this._nav_ny = hh("&#x00bb;", 1, 2);
-	this._nav_ny.ttip = Calendar._TT["NEXT_YEAR"];
-
-	// day names
-	row = Calendar.createElement("tr", thead);
-	row.className = "daynames";
-	if (this.weekNumbers) {
-		cell = Calendar.createElement("td", row);
-		cell.className = "name wn";
-		cell.innerHTML = Calendar._TT["WK"];
-	}
-	for (var i = 7; i > 0; --i) {
-		cell = Calendar.createElement("td", row);
-		if (!i) {
-			cell.navtype = 100;
-			cell.calendar = this;
-			Calendar._add_evs(cell);
-		}
-	}
-	this.firstdayname = (this.weekNumbers) ? row.firstChild.nextSibling : row.firstChild;
-	this._displayWeekdays();
-
-	var tbody = Calendar.createElement("tbody", table);
-	this.tbody = tbody;
-
-	for (i = 6; i > 0; --i) {
-		row = Calendar.createElement("tr", tbody);
-		if (this.weekNumbers) {
-			cell = Calendar.createElement("td", row);
-		}
-		for (var j = 7; j > 0; --j) {
-			cell = Calendar.createElement("td", row);
-			cell.calendar = this;
-			Calendar._add_evs(cell);
-		}
-	}
-
-	if (this.showsTime) {
-		row = Calendar.createElement("tr", tbody);
-		row.className = "time";
-
-		cell = Calendar.createElement("td", row);
-		cell.className = "time";
-		cell.colSpan = 2;
-		cell.innerHTML = Calendar._TT["TIME"] || "&nbsp;";
-
-		cell = Calendar.createElement("td", row);
-		cell.className = "time";
-		cell.colSpan = this.weekNumbers ? 4 : 3;
-
-		(function(){
-			function makeTimePart(className, init, range_start, range_end) {
-				var part = Calendar.createElement("span", cell);
-				part.className = className;
-				part.innerHTML = init;
-				part.calendar = cal;
-				part.ttip = Calendar._TT["TIME_PART"];
-				part.navtype = 50;
-				part._range = [];
-				if (typeof range_start != "number")
-					part._range = range_start;
-				else {
-					for (var i = range_start; i <= range_end; ++i) {
-						var txt;
-						if (i < 10 && range_end >= 10) txt = '0' + i;
-						else txt = '' + i;
-						part._range[part._range.length] = txt;
-					}
-				}
-				Calendar._add_evs(part);
-				return part;
-			};
-			var hrs = cal.date.getHours();
-			var mins = cal.date.getMinutes();
-			var t12 = !cal.time24;
-			var pm = (hrs > 12);
-			if (t12 && pm) hrs -= 12;
-			var H = makeTimePart("hour", hrs, t12 ? 1 : 0, t12 ? 12 : 23);
-			var span = Calendar.createElement("span", cell);
-			span.innerHTML = ":";
-			span.className = "colon";
-			var M = makeTimePart("minute", mins, 0, 59);
-			var AP = null;
-			cell = Calendar.createElement("td", row);
-			cell.className = "time";
-			cell.colSpan = 2;
-			if (t12)
-				AP = makeTimePart("ampm", pm ? "pm" : "am", ["am", "pm"]);
-			else
-				cell.innerHTML = "&nbsp;";
-
-			cal.onSetTime = function() {
-				var pm, hrs = this.date.getHours(),
-					mins = this.date.getMinutes();
-				if (t12) {
-					pm = (hrs >= 12);
-					if (pm) hrs -= 12;
-					if (hrs == 0) hrs = 12;
-					AP.innerHTML = pm ? "pm" : "am";
-				}
-				H.innerHTML = (hrs < 10) ? ("0" + hrs) : hrs;
-				M.innerHTML = (mins < 10) ? ("0" + mins) : mins;
-			};
-
-			cal.onUpdateTime = function() {
-				var date = this.date;
-				var h = parseInt(H.innerHTML, 10);
-				if (t12) {
-					if (/pm/i.test(AP.innerHTML) && h < 12)
-						h += 12;
-					else if (/am/i.test(AP.innerHTML) && h == 12)
-						h = 0;
-				}
-				var d = date.getDate();
-				var m = date.getMonth();
-				var y = date.getFullYear();
-				date.setHours(h);
-				date.setMinutes(parseInt(M.innerHTML, 10));
-				date.setFullYear(y);
-				date.setMonth(m);
-				date.setDate(d);
-				this.dateClicked = false;
-				this.callHandler();
-			};
-		})();
-	} else {
-		this.onSetTime = this.onUpdateTime = function() {};
-	}
-
-	var tfoot = Calendar.createElement("tfoot", table);
-
-	row = Calendar.createElement("tr", tfoot);
-	row.className = "footrow";
-
-	cell = hh(Calendar._TT["SEL_DATE"], this.weekNumbers ? 8 : 7, 300);
-	cell.className = "ttip";
-	if (this.isPopup) {
-		cell.ttip = Calendar._TT["DRAG_TO_MOVE"];
-		cell.style.cursor = "move";
-	}
-	this.tooltips = cell;
-
-	div = Calendar.createElement("div", this.element);
-	this.monthsCombo = div;
-	div.className = "combo";
-	for (i = 0; i < Calendar._MN.length; ++i) {
-		var mn = Calendar.createElement("div");
-		mn.className = Calendar.is_ie ? "label-IEfix" : "label";
-		mn.month = i;
-		mn.innerHTML = Calendar._SMN[i];
-		div.appendChild(mn);
-	}
-
-	div = Calendar.createElement("div", this.element);
-	this.yearsCombo = div;
-	div.className = "combo";
-	for (i = 12; i > 0; --i) {
-		var yr = Calendar.createElement("div");
-		yr.className = Calendar.is_ie ? "label-IEfix" : "label";
-		div.appendChild(yr);
-	}
-
-	this._init(this.firstDayOfWeek, this.date);
-	parent.appendChild(this.element);
+    var parent = null;
+    if (! _par) {
+        // default parent is the document body, in which case we create
+        // a popup calendar.
+        parent = document.getElementsByTagName("body")[0];
+        this.isPopup = true;
+    } else {
+        parent = _par;
+        this.isPopup = false;
+    }
+    this.date = this.dateStr ? new CalendarDateObject(this.dateStr) : new CalendarDateObject();
+
+    var table = Calendar.createElement("table");
+    this.table = table;
+    table.cellSpacing = 0;
+    table.cellPadding = 0;
+    table.calendar = this;
+    Calendar.addEvent(table, "mousedown", Calendar.tableMouseDown);
+
+    var div = Calendar.createElement("div");
+    this.element = div;
+    div.className = "calendar";
+    if (this.isPopup) {
+        div.style.position = "absolute";
+        div.style.display = "none";
+    }
+    div.appendChild(table);
+
+    var thead = Calendar.createElement("thead", table);
+    var cell = null;
+    var row = null;
+
+    var cal = this;
+    var hh = function (text, cs, navtype) {
+        cell = Calendar.createElement("td", row);
+        cell.colSpan = cs;
+        cell.className = "button";
+        if (navtype != 0 && Math.abs(navtype) <= 2)
+            cell.className += " nav";
+        Calendar._add_evs(cell);
+        cell.calendar = cal;
+        cell.navtype = navtype;
+        cell.innerHTML = "<div unselectable='on'>" + text + "</div>";
+        return cell;
+    };
+
+    row = Calendar.createElement("tr", thead);
+    var title_length = 6;
+    (this.isPopup) && --title_length;
+    (this.weekNumbers) && ++title_length;
+
+    hh("?", 1, 400).ttip = Calendar._TT["INFO"];
+    this.title = hh("", title_length, 300);
+    this.title.className = "title";
+    if (this.isPopup) {
+        this.title.ttip = Calendar._TT["DRAG_TO_MOVE"];
+        this.title.style.cursor = "move";
+        hh("&#x00d7;", 1, 200).ttip = Calendar._TT["CLOSE"];
+    }
+
+    row = Calendar.createElement("tr", thead);
+    row.className = "headrow";
+
+    this._nav_py = hh("&#x00ab;", 1, -2);
+    this._nav_py.ttip = Calendar._TT["PREV_YEAR"];
+
+    this._nav_pm = hh("&#x2039;", 1, -1);
+    this._nav_pm.ttip = Calendar._TT["PREV_MONTH"];
+
+    this._nav_now = hh(Calendar._TT["TODAY"], this.weekNumbers ? 4 : 3, 0);
+    this._nav_now.ttip = Calendar._TT["GO_TODAY"];
+
+    this._nav_nm = hh("&#x203a;", 1, 1);
+    this._nav_nm.ttip = Calendar._TT["NEXT_MONTH"];
+
+    this._nav_ny = hh("&#x00bb;", 1, 2);
+    this._nav_ny.ttip = Calendar._TT["NEXT_YEAR"];
+
+    // day names
+    row = Calendar.createElement("tr", thead);
+    row.className = "daynames";
+    if (this.weekNumbers) {
+        cell = Calendar.createElement("td", row);
+        cell.className = "name wn";
+        cell.innerHTML = Calendar._TT["WK"];
+    }
+    for (var i = 7; i > 0; --i) {
+        cell = Calendar.createElement("td", row);
+        if (!i) {
+            cell.navtype = 100;
+            cell.calendar = this;
+            Calendar._add_evs(cell);
+        }
+    }
+    this.firstdayname = (this.weekNumbers) ? row.firstChild.nextSibling : row.firstChild;
+    this._displayWeekdays();
+
+    var tbody = Calendar.createElement("tbody", table);
+    this.tbody = tbody;
+
+    for (i = 6; i > 0; --i) {
+        row = Calendar.createElement("tr", tbody);
+        if (this.weekNumbers) {
+            cell = Calendar.createElement("td", row);
+        }
+        for (var j = 7; j > 0; --j) {
+            cell = Calendar.createElement("td", row);
+            cell.calendar = this;
+            Calendar._add_evs(cell);
+        }
+    }
+
+    if (this.showsTime) {
+        row = Calendar.createElement("tr", tbody);
+        row.className = "time";
+
+        cell = Calendar.createElement("td", row);
+        cell.className = "time";
+        cell.colSpan = 2;
+        cell.innerHTML = Calendar._TT["TIME"] || "&nbsp;";
+
+        cell = Calendar.createElement("td", row);
+        cell.className = "time";
+        cell.colSpan = this.weekNumbers ? 4 : 3;
+
+        (function(){
+            function makeTimePart(className, init, range_start, range_end) {
+                var part = Calendar.createElement("span", cell);
+                part.className = className;
+                part.innerHTML = init;
+                part.calendar = cal;
+                part.ttip = Calendar._TT["TIME_PART"];
+                part.navtype = 50;
+                part._range = [];
+                if (typeof range_start != "number")
+                    part._range = range_start;
+                else {
+                    for (var i = range_start; i <= range_end; ++i) {
+                        var txt;
+                        if (i < 10 && range_end >= 10) txt = '0' + i;
+                        else txt = '' + i;
+                        part._range[part._range.length] = txt;
+                    }
+                }
+                Calendar._add_evs(part);
+                return part;
+            };
+            var hrs = cal.date.getHours();
+            var mins = cal.date.getMinutes();
+            var t12 = !cal.time24;
+            var pm = (hrs > 12);
+            if (t12 && pm) hrs -= 12;
+            var H = makeTimePart("hour", hrs, t12 ? 1 : 0, t12 ? 12 : 23);
+            var span = Calendar.createElement("span", cell);
+            span.innerHTML = ":";
+            span.className = "colon";
+            var M = makeTimePart("minute", mins, 0, 59);
+            var AP = null;
+            cell = Calendar.createElement("td", row);
+            cell.className = "time";
+            cell.colSpan = 2;
+            if (t12)
+                AP = makeTimePart("ampm", pm ? "pm" : "am", ["am", "pm"]);
+            else
+                cell.innerHTML = "&nbsp;";
+
+            cal.onSetTime = function() {
+                var pm, hrs = this.date.getHours(),
+                    mins = this.date.getMinutes();
+                if (t12) {
+                    pm = (hrs >= 12);
+                    if (pm) hrs -= 12;
+                    if (hrs == 0) hrs = 12;
+                    AP.innerHTML = pm ? "pm" : "am";
+                }
+                H.innerHTML = (hrs < 10) ? ("0" + hrs) : hrs;
+                M.innerHTML = (mins < 10) ? ("0" + mins) : mins;
+            };
+
+            cal.onUpdateTime = function() {
+                var date = this.date;
+                var h = parseInt(H.innerHTML, 10);
+                if (t12) {
+                    if (/pm/i.test(AP.innerHTML) && h < 12)
+                        h += 12;
+                    else if (/am/i.test(AP.innerHTML) && h == 12)
+                        h = 0;
+                }
+                var d = date.getDate();
+                var m = date.getMonth();
+                var y = date.getFullYear();
+                date.setHours(h);
+                date.setMinutes(parseInt(M.innerHTML, 10));
+                date.setFullYear(y);
+                date.setMonth(m);
+                date.setDate(d);
+                this.dateClicked = false;
+                this.callHandler();
+            };
+        })();
+    } else {
+        this.onSetTime = this.onUpdateTime = function() {};
+    }
+
+    var tfoot = Calendar.createElement("tfoot", table);
+
+    row = Calendar.createElement("tr", tfoot);
+    row.className = "footrow";
+
+    cell = hh(Calendar._TT["SEL_DATE"], this.weekNumbers ? 8 : 7, 300);
+    cell.className = "ttip";
+    if (this.isPopup) {
+        cell.ttip = Calendar._TT["DRAG_TO_MOVE"];
+        cell.style.cursor = "move";
+    }
+    this.tooltips = cell;
+
+    div = Calendar.createElement("div", this.element);
+    this.monthsCombo = div;
+    div.className = "combo";
+    for (i = 0; i < Calendar._MN.length; ++i) {
+        var mn = Calendar.createElement("div");
+        mn.className = Calendar.is_ie ? "label-IEfix" : "label";
+        mn.month = i;
+        mn.innerHTML = Calendar._SMN[i];
+        div.appendChild(mn);
+    }
+
+    div = Calendar.createElement("div", this.element);
+    this.yearsCombo = div;
+    div.className = "combo";
+    for (i = 12; i > 0; --i) {
+        var yr = Calendar.createElement("div");
+        yr.className = Calendar.is_ie ? "label-IEfix" : "label";
+        div.appendChild(yr);
+    }
+
+    this._init(this.firstDayOfWeek, this.date);
+    parent.appendChild(this.element);
 };
 
 /** keyboard navigation, only for popup calendars */
 Calendar._keyEvent = function(ev) {
-	var cal = window._dynarch_popupCalendar;
-	if (!cal || cal.multiple)
-		return false;
-	(Calendar.is_ie) && (ev = window.event);
-	var act = (Calendar.is_ie || ev.type == "keypress"),
-		K = ev.keyCode;
-	if (ev.ctrlKey) {
-		switch (K) {
-		    case 37: // KEY left
-			act && Calendar.cellClick(cal._nav_pm);
-			break;
-		    case 38: // KEY up
-			act && Calendar.cellClick(cal._nav_py);
-			break;
-		    case 39: // KEY right
-			act && Calendar.cellClick(cal._nav_nm);
-			break;
-		    case 40: // KEY down
-			act && Calendar.cellClick(cal._nav_ny);
-			break;
-		    default:
-			return false;
-		}
-	} else switch (K) {
-	    case 32: // KEY space (now)
-		Calendar.cellClick(cal._nav_now);
-		break;
-	    case 27: // KEY esc
-		act && cal.callCloseHandler();
-		break;
-	    case 37: // KEY left
-	    case 38: // KEY up
-	    case 39: // KEY right
-	    case 40: // KEY down
-		if (act) {
-			var prev, x, y, ne, el, step;
-			prev = K == 37 || K == 38;
-			step = (K == 37 || K == 39) ? 1 : 7;
-			function setVars() {
-				el = cal.currentDateEl;
-				var p = el.pos;
-				x = p & 15;
-				y = p >> 4;
-				ne = cal.ar_days[y][x];
-			};setVars();
-			function prevMonth() {
-				var date = new CalendarDateObject(cal.date);
-				date.setDate(date.getDate() - step);
-				cal.setDate(date);
-			};
-			function nextMonth() {
-				var date = new CalendarDateObject(cal.date);
-				date.setDate(date.getDate() + step);
-				cal.setDate(date);
-			};
-			while (1) {
-				switch (K) {
-				    case 37: // KEY left
-					if (--x >= 0)
-						ne = cal.ar_days[y][x];
-					else {
-						x = 6;
-						K = 38;
-						continue;
-					}
-					break;
-				    case 38: // KEY up
-					if (--y >= 0)
-						ne = cal.ar_days[y][x];
-					else {
-						prevMonth();
-						setVars();
-					}
-					break;
-				    case 39: // KEY right
-					if (++x < 7)
-						ne = cal.ar_days[y][x];
-					else {
-						x = 0;
-						K = 40;
-						continue;
-					}
-					break;
-				    case 40: // KEY down
-					if (++y < cal.ar_days.length)
-						ne = cal.ar_days[y][x];
-					else {
-						nextMonth();
-						setVars();
-					}
-					break;
-				}
-				break;
-			}
-			if (ne) {
-				if (!ne.disabled)
-					Calendar.cellClick(ne);
-				else if (prev)
-					prevMonth();
-				else
-					nextMonth();
-			}
-		}
-		break;
-	    case 13: // KEY enter
-		if (act)
-			Calendar.cellClick(cal.currentDateEl, ev);
-		break;
-	    default:
-		return false;
-	}
-	return Calendar.stopEvent(ev);
+    var cal = window._dynarch_popupCalendar;
+    if (!cal || cal.multiple)
+        return false;
+    (Calendar.is_ie) && (ev = window.event);
+    var act = (Calendar.is_ie || ev.type == "keypress"),
+        K = ev.keyCode;
+    if (ev.ctrlKey) {
+        switch (K) {
+            case 37: // KEY left
+            act && Calendar.cellClick(cal._nav_pm);
+            break;
+            case 38: // KEY up
+            act && Calendar.cellClick(cal._nav_py);
+            break;
+            case 39: // KEY right
+            act && Calendar.cellClick(cal._nav_nm);
+            break;
+            case 40: // KEY down
+            act && Calendar.cellClick(cal._nav_ny);
+            break;
+            default:
+            return false;
+        }
+    } else switch (K) {
+        case 32: // KEY space (now)
+        Calendar.cellClick(cal._nav_now);
+        break;
+        case 27: // KEY esc
+        act && cal.callCloseHandler();
+        break;
+        case 37: // KEY left
+        case 38: // KEY up
+        case 39: // KEY right
+        case 40: // KEY down
+        if (act) {
+            var prev, x, y, ne, el, step;
+            prev = K == 37 || K == 38;
+            step = (K == 37 || K == 39) ? 1 : 7;
+            function setVars() {
+                el = cal.currentDateEl;
+                var p = el.pos;
+                x = p & 15;
+                y = p >> 4;
+                ne = cal.ar_days[y][x];
+            };setVars();
+            function prevMonth() {
+                var date = new CalendarDateObject(cal.date);
+                date.setDate(date.getDate() - step);
+                cal.setDate(date);
+            };
+            function nextMonth() {
+                var date = new CalendarDateObject(cal.date);
+                date.setDate(date.getDate() + step);
+                cal.setDate(date);
+            };
+            while (1) {
+                switch (K) {
+                    case 37: // KEY left
+                    if (--x >= 0)
+                        ne = cal.ar_days[y][x];
+                    else {
+                        x = 6;
+                        K = 38;
+                        continue;
+                    }
+                    break;
+                    case 38: // KEY up
+                    if (--y >= 0)
+                        ne = cal.ar_days[y][x];
+                    else {
+                        prevMonth();
+                        setVars();
+                    }
+                    break;
+                    case 39: // KEY right
+                    if (++x < 7)
+                        ne = cal.ar_days[y][x];
+                    else {
+                        x = 0;
+                        K = 40;
+                        continue;
+                    }
+                    break;
+                    case 40: // KEY down
+                    if (++y < cal.ar_days.length)
+                        ne = cal.ar_days[y][x];
+                    else {
+                        nextMonth();
+                        setVars();
+                    }
+                    break;
+                }
+                break;
+            }
+            if (ne) {
+                if (!ne.disabled)
+                    Calendar.cellClick(ne);
+                else if (prev)
+                    prevMonth();
+                else
+                    nextMonth();
+            }
+        }
+        break;
+        case 13: // KEY enter
+        if (act)
+            Calendar.cellClick(cal.currentDateEl, ev);
+        break;
+        default:
+        return false;
+    }
+    return Calendar.stopEvent(ev);
 };
 
 /**
  *  (RE)Initializes the calendar to the given date and firstDayOfWeek
  */
 Calendar.prototype._init = function (firstDayOfWeek, date) {
-	var today = new CalendarDateObject(),
-		TY = today.getFullYear(),
-		TM = today.getMonth(),
-		TD = today.getDate();
-	this.table.style.visibility = "hidden";
-	var year = date.getFullYear();
-	if (year < this.minYear) {
-		year = this.minYear;
-		date.setFullYear(year);
-	} else if (year > this.maxYear) {
-		year = this.maxYear;
-		date.setFullYear(year);
-	}
-	this.firstDayOfWeek = firstDayOfWeek;
-	this.date = new CalendarDateObject(date);
-	var month = date.getMonth();
-	var mday = date.getDate();
-	var no_days = date.getMonthDays();
-
-	// calendar voodoo for computing the first day that would actually be
-	// displayed in the calendar, even if it's from the previous month.
-	// WARNING: this is magic. ;-)
-	date.setDate(1);
-	var day1 = (date.getDay() - this.firstDayOfWeek) % 7;
-	if (day1 < 0)
-		day1 += 7;
-	date.setDate(-day1);
-	date.setDate(date.getDate() + 1);
-
-	var row = this.tbody.firstChild;
-	var MN = Calendar._SMN[month];
-	var ar_days = this.ar_days = new Array();
-	var weekend = Calendar._TT["WEEKEND"];
-	var dates = this.multiple ? (this.datesCells = {}) : null;
-	for (var i = 0; i < 6; ++i, row = row.nextSibling) {
-		var cell = row.firstChild;
-		if (this.weekNumbers) {
-			cell.className = "day wn";
-			cell.innerHTML = date.getWeekNumber();
-			cell = cell.nextSibling;
-		}
-		row.className = "daysrow";
-		var hasdays = false, iday, dpos = ar_days[i] = [];
-		for (var j = 0; j < 7; ++j, cell = cell.nextSibling, date.setDate(iday + 1)) {
-			iday = date.getDate();
-			var wday = date.getDay();
-			cell.className = "day";
-			cell.pos = i << 4 | j;
-			dpos[j] = cell;
-			var current_month = (date.getMonth() == month);
-			if (!current_month) {
-				if (this.showsOtherMonths) {
-					cell.className += " othermonth";
-					cell.otherMonth = true;
-				} else {
-					cell.className = "emptycell";
-					cell.innerHTML = "&nbsp;";
-					cell.disabled = true;
-					continue;
-				}
-			} else {
-				cell.otherMonth = false;
-				hasdays = true;
-			}
-			cell.disabled = false;
-			cell.innerHTML = this.getDateText ? this.getDateText(date, iday) : iday;
-			if (dates)
-				dates[date.print("%Y%m%d")] = cell;
-			if (this.getDateStatus) {
-				var status = this.getDateStatus(date, year, month, iday);
-				if (this.getDateToolTip) {
-					var toolTip = this.getDateToolTip(date, year, month, iday);
-					if (toolTip)
-						cell.title = toolTip;
-				}
-				if (status === true) {
-					cell.className += " disabled";
-					cell.disabled = true;
-				} else {
-					if (/disabled/i.test(status))
-						cell.disabled = true;
-					cell.className += " " + status;
-				}
-			}
-			if (!cell.disabled) {
-				cell.caldate = new CalendarDateObject(date);
-				cell.ttip = "_";
-				if (!this.multiple && current_month
-				    && iday == mday && this.hiliteToday) {
-					cell.className += " selected";
-					this.currentDateEl = cell;
-				}
-				if (date.getFullYear() == TY &&
-				    date.getMonth() == TM &&
-				    iday == TD) {
-					cell.className += " today";
-					cell.ttip += Calendar._TT["PART_TODAY"];
-				}
-				if (weekend.indexOf(wday.toString()) != -1)
-					cell.className += cell.otherMonth ? " oweekend" : " weekend";
-			}
-		}
-		if (!(hasdays || this.showsOtherMonths))
-			row.className = "emptyrow";
-	}
-	this.title.innerHTML = Calendar._MN[month] + ", " + year;
-	this.onSetTime();
-	this.table.style.visibility = "visible";
-	this._initMultipleDates();
-	// PROFILE
-	// this.tooltips.innerHTML = "Generated in " + ((new CalendarDateObject()) - today) + " ms";
+    var today = new CalendarDateObject(),
+        TY = today.getFullYear(),
+        TM = today.getMonth(),
+        TD = today.getDate();
+    this.table.style.visibility = "hidden";
+    var year = date.getFullYear();
+    if (year < this.minYear) {
+        year = this.minYear;
+        date.setFullYear(year);
+    } else if (year > this.maxYear) {
+        year = this.maxYear;
+        date.setFullYear(year);
+    }
+    this.firstDayOfWeek = firstDayOfWeek;
+    this.date = new CalendarDateObject(date);
+    var month = date.getMonth();
+    var mday = date.getDate();
+    var no_days = date.getMonthDays();
+
+    // calendar voodoo for computing the first day that would actually be
+    // displayed in the calendar, even if it's from the previous month.
+    // WARNING: this is magic. ;-)
+    date.setDate(1);
+    var day1 = (date.getDay() - this.firstDayOfWeek) % 7;
+    if (day1 < 0)
+        day1 += 7;
+    date.setDate(-day1);
+    date.setDate(date.getDate() + 1);
+
+    var row = this.tbody.firstChild;
+    var MN = Calendar._SMN[month];
+    var ar_days = this.ar_days = new Array();
+    var weekend = Calendar._TT["WEEKEND"];
+    var dates = this.multiple ? (this.datesCells = {}) : null;
+    for (var i = 0; i < 6; ++i, row = row.nextSibling) {
+        var cell = row.firstChild;
+        if (this.weekNumbers) {
+            cell.className = "day wn";
+            cell.innerHTML = date.getWeekNumber();
+            cell = cell.nextSibling;
+        }
+        row.className = "daysrow";
+        var hasdays = false, iday, dpos = ar_days[i] = [];
+        for (var j = 0; j < 7; ++j, cell = cell.nextSibling, date.setDate(iday + 1)) {
+            iday = date.getDate();
+            var wday = date.getDay();
+            cell.className = "day";
+            cell.pos = i << 4 | j;
+            dpos[j] = cell;
+            var current_month = (date.getMonth() == month);
+            if (!current_month) {
+                if (this.showsOtherMonths) {
+                    cell.className += " othermonth";
+                    cell.otherMonth = true;
+                } else {
+                    cell.className = "emptycell";
+                    cell.innerHTML = "&nbsp;";
+                    cell.disabled = true;
+                    continue;
+                }
+            } else {
+                cell.otherMonth = false;
+                hasdays = true;
+            }
+            cell.disabled = false;
+            cell.innerHTML = this.getDateText ? this.getDateText(date, iday) : iday;
+            if (dates)
+                dates[date.print("%Y%m%d")] = cell;
+            if (this.getDateStatus) {
+                var status = this.getDateStatus(date, year, month, iday);
+                if (this.getDateToolTip) {
+                    var toolTip = this.getDateToolTip(date, year, month, iday);
+                    if (toolTip)
+                        cell.title = toolTip;
+                }
+                if (status === true) {
+                    cell.className += " disabled";
+                    cell.disabled = true;
+                } else {
+                    if (/disabled/i.test(status))
+                        cell.disabled = true;
+                    cell.className += " " + status;
+                }
+            }
+            if (!cell.disabled) {
+                cell.caldate = new CalendarDateObject(date);
+                cell.ttip = "_";
+                if (!this.multiple && current_month
+                    && iday == mday && this.hiliteToday) {
+                    cell.className += " selected";
+                    this.currentDateEl = cell;
+                }
+                if (date.getFullYear() == TY &&
+                    date.getMonth() == TM &&
+                    iday == TD) {
+                    cell.className += " today";
+                    cell.ttip += Calendar._TT["PART_TODAY"];
+                }
+                if (weekend.indexOf(wday.toString()) != -1)
+                    cell.className += cell.otherMonth ? " oweekend" : " weekend";
+            }
+        }
+        if (!(hasdays || this.showsOtherMonths))
+            row.className = "emptyrow";
+    }
+    this.title.innerHTML = Calendar._MN[month] + ", " + year;
+    this.onSetTime();
+    this.table.style.visibility = "visible";
+    this._initMultipleDates();
+    // PROFILE
+    // this.tooltips.innerHTML = "Generated in " + ((new CalendarDateObject()) - today) + " ms";
 };
 
 Calendar.prototype._initMultipleDates = function() {
-	if (this.multiple) {
-		for (var i in this.multiple) {
-			var cell = this.datesCells[i];
-			var d = this.multiple[i];
-			if (!d)
-				continue;
-			if (cell)
-				cell.className += " selected";
-		}
-	}
+    if (this.multiple) {
+        for (var i in this.multiple) {
+            var cell = this.datesCells[i];
+            var d = this.multiple[i];
+            if (!d)
+                continue;
+            if (cell)
+                cell.className += " selected";
+        }
+    }
 };
 
 Calendar.prototype._toggleMultipleDate = function(date) {
-	if (this.multiple) {
-		var ds = date.print("%Y%m%d");
-		var cell = this.datesCells[ds];
-		if (cell) {
-			var d = this.multiple[ds];
-			if (!d) {
-				Calendar.addClass(cell, "selected");
-				this.multiple[ds] = date;
-			} else {
-				Calendar.removeClass(cell, "selected");
-				delete this.multiple[ds];
-			}
-		}
-	}
+    if (this.multiple) {
+        var ds = date.print("%Y%m%d");
+        var cell = this.datesCells[ds];
+        if (cell) {
+            var d = this.multiple[ds];
+            if (!d) {
+                Calendar.addClass(cell, "selected");
+                this.multiple[ds] = date;
+            } else {
+                Calendar.removeClass(cell, "selected");
+                delete this.multiple[ds];
+            }
+        }
+    }
 };
 
 Calendar.prototype.setDateToolTipHandler = function (unaryFunction) {
-	this.getDateToolTip = unaryFunction;
+    this.getDateToolTip = unaryFunction;
 };
 
 /**
@@ -1298,9 +1298,9 @@ Calendar.prototype.setDateToolTipHandler = function (unaryFunction) {
  *  date is different than the currently selected one).
  */
 Calendar.prototype.setDate = function (date) {
-	if (!date.equalsTo(this.date)) {
-		this._init(this.firstDayOfWeek, date);
-	}
+    if (!date.equalsTo(this.date)) {
+        this._init(this.firstDayOfWeek, date);
+    }
 };
 
 /**
@@ -1310,13 +1310,13 @@ Calendar.prototype.setDate = function (date) {
  *  should * change.
  */
 Calendar.prototype.refresh = function () {
-	this._init(this.firstDayOfWeek, this.date);
+    this._init(this.firstDayOfWeek, this.date);
 };
 
 /** Modifies the "firstDayOfWeek" parameter (pass 0 for Synday, 1 for Monday, etc.). */
 Calendar.prototype.setFirstDayOfWeek = function (firstDayOfWeek) {
-	this._init(firstDayOfWeek, this.date);
-	this._displayWeekdays();
+    this._init(firstDayOfWeek, this.date);
+    this._displayWeekdays();
 };
 
 /**
@@ -1326,36 +1326,36 @@ Calendar.prototype.setFirstDayOfWeek = function (firstDayOfWeek) {
  *  the passed date will be marked as disabled.
  */
 Calendar.prototype.setDateStatusHandler = Calendar.prototype.setDisabledHandler = function (unaryFunction) {
-	this.getDateStatus = unaryFunction;
+    this.getDateStatus = unaryFunction;
 };
 
 /** Customization of allowed year range for the calendar. */
 Calendar.prototype.setRange = function (a, z) {
-	this.minYear = a;
-	this.maxYear = z;
+    this.minYear = a;
+    this.maxYear = z;
 };
 
 /** Calls the first user handler (selectedHandler). */
 Calendar.prototype.callHandler = function () {
-	if (this.onSelected) {
-		this.onSelected(this, this.date.print(this.dateFormat));
-	}
+    if (this.onSelected) {
+        this.onSelected(this, this.date.print(this.dateFormat));
+    }
 };
 
 /** Calls the second user handler (closeHandler). */
 Calendar.prototype.callCloseHandler = function () {
-	if (this.onClose) {
-		this.onClose(this);
-	}
-	this.hideShowCovered();
+    if (this.onClose) {
+        this.onClose(this);
+    }
+    this.hideShowCovered();
 };
 
 /** Removes the calendar object from the DOM tree and destroys it. */
 Calendar.prototype.destroy = function () {
-	var el = this.element.parentNode;
-	el.removeChild(this.element);
-	Calendar._C = null;
-	window._dynarch_popupCalendar = null;
+    var el = this.element.parentNode;
+    el.removeChild(this.element);
+    Calendar._C = null;
+    window._dynarch_popupCalendar = null;
 };
 
 /**
@@ -1363,50 +1363,50 @@ Calendar.prototype.destroy = function () {
  *  its parent).
  */
 Calendar.prototype.reparent = function (new_parent) {
-	var el = this.element;
-	el.parentNode.removeChild(el);
-	new_parent.appendChild(el);
+    var el = this.element;
+    el.parentNode.removeChild(el);
+    new_parent.appendChild(el);
 };
 
 // This gets called when the user presses a mouse button anywhere in the
 // document, if the calendar is shown.  If the click was outside the open
 // calendar this function closes it.
 Calendar._checkCalendar = function(ev) {
-	var calendar = window._dynarch_popupCalendar;
-	if (!calendar) {
-		return false;
-	}
-	var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev);
-	for (; el != null && el != calendar.element; el = el.parentNode);
-	if (el == null) {
-		// calls closeHandler which should hide the calendar.
-		window._dynarch_popupCalendar.callCloseHandler();
-		return Calendar.stopEvent(ev);
-	}
+    var calendar = window._dynarch_popupCalendar;
+    if (!calendar) {
+        return false;
+    }
+    var el = Calendar.is_ie ? Calendar.getElement(ev) : Calendar.getTargetElement(ev);
+    for (; el != null && el != calendar.element; el = el.parentNode);
+    if (el == null) {
+        // calls closeHandler which should hide the calendar.
+        window._dynarch_popupCalendar.callCloseHandler();
+        return Calendar.stopEvent(ev);
+    }
 };
 
 /** Shows the calendar. */
 Calendar.prototype.show = function () {
-	var rows = this.table.getElementsByTagName("tr");
-	for (var i = rows.length; i > 0;) {
-		var row = rows[--i];
-		Calendar.removeClass(row, "rowhilite");
-		var cells = row.getElementsByTagName("td");
-		for (var j = cells.length; j > 0;) {
-			var cell = cells[--j];
-			Calendar.removeClass(cell, "hilite");
-			Calendar.removeClass(cell, "active");
-		}
-	}
-	this.element.style.display = "block";
-	this.hidden = false;
-	if (this.isPopup) {
-		window._dynarch_popupCalendar = this;
-		Calendar.addEvent(document, "keydown", Calendar._keyEvent);
-		Calendar.addEvent(document, "keypress", Calendar._keyEvent);
-		Calendar.addEvent(document, "mousedown", Calendar._checkCalendar);
-	}
-	this.hideShowCovered();
+    var rows = this.table.getElementsByTagName("tr");
+    for (var i = rows.length; i > 0;) {
+        var row = rows[--i];
+        Calendar.removeClass(row, "rowhilite");
+        var cells = row.getElementsByTagName("td");
+        for (var j = cells.length; j > 0;) {
+            var cell = cells[--j];
+            Calendar.removeClass(cell, "hilite");
+            Calendar.removeClass(cell, "active");
+        }
+    }
+    this.element.style.display = "block";
+    this.hidden = false;
+    if (this.isPopup) {
+        window._dynarch_popupCalendar = this;
+        Calendar.addEvent(document, "keydown", Calendar._keyEvent);
+        Calendar.addEvent(document, "keypress", Calendar._keyEvent);
+        Calendar.addEvent(document, "mousedown", Calendar._checkCalendar);
+    }
+    this.hideShowCovered();
 };
 
 /**
@@ -1414,14 +1414,14 @@ Calendar.prototype.show = function () {
  *  element.
  */
 Calendar.prototype.hide = function () {
-	if (this.isPopup) {
-		Calendar.removeEvent(document, "keydown", Calendar._keyEvent);
-		Calendar.removeEvent(document, "keypress", Calendar._keyEvent);
-		Calendar.removeEvent(document, "mousedown", Calendar._checkCalendar);
-	}
-	this.element.style.display = "none";
-	this.hidden = true;
-	this.hideShowCovered();
+    if (this.isPopup) {
+        Calendar.removeEvent(document, "keydown", Calendar._keyEvent);
+        Calendar.removeEvent(document, "keypress", Calendar._keyEvent);
+        Calendar.removeEvent(document, "mousedown", Calendar._checkCalendar);
+    }
+    this.element.style.display = "none";
+    this.hidden = true;
+    this.hideShowCovered();
 };
 
 /**
@@ -1430,90 +1430,90 @@ Calendar.prototype.hide = function () {
  *  to the parent's containing rectangle).
  */
 Calendar.prototype.showAt = function (x, y) {
-	var s = this.element.style;
-	s.left = x + "px";
-	s.top = y + "px";
-	this.show();
+    var s = this.element.style;
+    s.left = x + "px";
+    s.top = y + "px";
+    this.show();
 };
 
 /** Shows the calendar near a given element. */
 Calendar.prototype.showAtElement = function (el, opts) {
-	var self = this;
-	var p = Calendar.getAbsolutePos(el);
-	if (!opts || typeof opts != "string") {
-		this.showAt(p.x, p.y + el.offsetHeight);
-		return true;
-	}
-	function fixPosition(box) {
-		if (box.x < 0)
-			box.x = 0;
-		if (box.y < 0)
-			box.y = 0;
-		var cp = document.createElement("div");
-		var s = cp.style;
-		s.position = "absolute";
-		s.right = s.bottom = s.width = s.height = "0px";
-		document.body.appendChild(cp);
-		var br = Calendar.getAbsolutePos(cp);
-		document.body.removeChild(cp);
-		if (Calendar.is_ie) {
-			br.y += document.body.scrollTop;
-			br.x += document.body.scrollLeft;
-		} else {
-			br.y += window.scrollY;
-			br.x += window.scrollX;
-		}
-		var tmp = box.x + box.width - br.x;
-		if (tmp > 0) box.x -= tmp;
-		tmp = box.y + box.height - br.y;
-		if (tmp > 0) box.y -= tmp;
-	};
-	this.element.style.display = "block";
-	Calendar.continuation_for_the_fucking_khtml_browser = function() {
-		var w = self.element.offsetWidth;
-		var h = self.element.offsetHeight;
-		self.element.style.display = "none";
-		var valign = opts.substr(0, 1);
-		var halign = "l";
-		if (opts.length > 1) {
-			halign = opts.substr(1, 1);
-		}
-		// vertical alignment
-		switch (valign) {
-		    case "T": p.y -= h; break;
-		    case "B": p.y += el.offsetHeight; break;
-		    case "C": p.y += (el.offsetHeight - h) / 2; break;
-		    case "t": p.y += el.offsetHeight - h; break;
-		    case "b": break; // already there
-		}
-		// horizontal alignment
-		switch (halign) {
-		    case "L": p.x -= w; break;
-		    case "R": p.x += el.offsetWidth; break;
-		    case "C": p.x += (el.offsetWidth - w) / 2; break;
-		    case "l": p.x += el.offsetWidth - w; break;
-		    case "r": break; // already there
-		}
-		p.width = w;
-		p.height = h + 40;
-		self.monthsCombo.style.display = "none";
-		fixPosition(p);
-		self.showAt(p.x, p.y);
-	};
-	if (Calendar.is_khtml)
-		setTimeout("Calendar.continuation_for_the_fucking_khtml_browser()", 10);
-	else
-		Calendar.continuation_for_the_fucking_khtml_browser();
+    var self = this;
+    var p = Calendar.getAbsolutePos(el);
+    if (!opts || typeof opts != "string") {
+        this.showAt(p.x, p.y + el.offsetHeight);
+        return true;
+    }
+    function fixPosition(box) {
+        if (box.x < 0)
+            box.x = 0;
+        if (box.y < 0)
+            box.y = 0;
+        var cp = document.createElement("div");
+        var s = cp.style;
+        s.position = "absolute";
+        s.right = s.bottom = s.width = s.height = "0px";
+        document.body.appendChild(cp);
+        var br = Calendar.getAbsolutePos(cp);
+        document.body.removeChild(cp);
+        if (Calendar.is_ie) {
+            br.y += document.documentElement.scrollTop;
+            br.x += document.documentElement.scrollLeft;
+        } else {
+            br.y += window.scrollY;
+            br.x += window.scrollX;
+        }
+        var tmp = box.x + box.width - br.x;
+        if (tmp > 0) box.x -= tmp;
+        tmp = box.y + box.height - br.y;
+        if (tmp > 0) box.y -= tmp;
+    };
+    this.element.style.display = "block";
+    Calendar.continuation_for_the_fucking_khtml_browser = function() {
+        var w = self.element.offsetWidth;
+        var h = self.element.offsetHeight;
+        self.element.style.display = "none";
+        var valign = opts.substr(0, 1);
+        var halign = "l";
+        if (opts.length > 1) {
+            halign = opts.substr(1, 1);
+        }
+        // vertical alignment
+        switch (valign) {
+            case "T": p.y -= h; break;
+            case "B": p.y += el.offsetHeight; break;
+            case "C": p.y += (el.offsetHeight - h) / 2; break;
+            case "t": p.y += el.offsetHeight - h; break;
+            case "b": break; // already there
+        }
+        // horizontal alignment
+        switch (halign) {
+            case "L": p.x -= w; break;
+            case "R": p.x += el.offsetWidth; break;
+            case "C": p.x += (el.offsetWidth - w) / 2; break;
+            case "l": p.x += el.offsetWidth - w; break;
+            case "r": break; // already there
+        }
+        p.width = w;
+        p.height = h + 40;
+        self.monthsCombo.style.display = "none";
+        fixPosition(p);
+        self.showAt(p.x, p.y);
+    };
+    if (Calendar.is_khtml)
+        setTimeout("Calendar.continuation_for_the_fucking_khtml_browser()", 10);
+    else
+        Calendar.continuation_for_the_fucking_khtml_browser();
 };
 
 /** Customizes the date format. */
 Calendar.prototype.setDateFormat = function (str) {
-	this.dateFormat = str;
+    this.dateFormat = str;
 };
 
 /** Customizes the tooltip date format. */
 Calendar.prototype.setTtDateFormat = function (str) {
-	this.ttDateFormat = str;
+    this.ttDateFormat = str;
 };
 
 /**
@@ -1521,119 +1521,119 @@ Calendar.prototype.setTtDateFormat = function (str) {
  *  calls this.setDate which moves the calendar to the given date.
  */
 Calendar.prototype.parseDate = function(str, fmt) {
-	if (!fmt)
-		fmt = this.dateFormat;
-	this.setDate(Date.parseDate(str, fmt));
+    if (!fmt)
+        fmt = this.dateFormat;
+    this.setDate(Date.parseDate(str, fmt));
 };
 
 Calendar.prototype.hideShowCovered = function () {
-	if (!Calendar.is_ie && !Calendar.is_opera)
-		return;
-	function getVisib(obj){
-		var value = obj.style.visibility;
-		if (!value) {
-			if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") { // Gecko, W3C
-				if (!Calendar.is_khtml)
-					value = document.defaultView.
-						getComputedStyle(obj, "").getPropertyValue("visibility");
-				else
-					value = '';
-			} else if (obj.currentStyle) { // IE
-				value = obj.currentStyle.visibility;
-			} else
-				value = '';
-		}
-		return value;
-	};
-
-	var tags = new Array("applet", "iframe", "select");
-	var el = this.element;
-
-	var p = Calendar.getAbsolutePos(el);
-	var EX1 = p.x;
-	var EX2 = el.offsetWidth + EX1;
-	var EY1 = p.y;
-	var EY2 = el.offsetHeight + EY1;
-
-	for (var k = tags.length; k > 0; ) {
-		var ar = document.getElementsByTagName(tags[--k]);
-		var cc = null;
-
-		for (var i = ar.length; i > 0;) {
-			cc = ar[--i];
-
-			p = Calendar.getAbsolutePos(cc);
-			var CX1 = p.x;
-			var CX2 = cc.offsetWidth + CX1;
-			var CY1 = p.y;
-			var CY2 = cc.offsetHeight + CY1;
-
-			if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
-				if (!cc.__msh_save_visibility) {
-					cc.__msh_save_visibility = getVisib(cc);
-				}
-				cc.style.visibility = cc.__msh_save_visibility;
-			} else {
-				if (!cc.__msh_save_visibility) {
-					cc.__msh_save_visibility = getVisib(cc);
-				}
-				cc.style.visibility = "hidden";
-			}
-		}
-	}
+    if (!Calendar.is_ie && !Calendar.is_opera)
+        return;
+    function getVisib(obj){
+        var value = obj.style.visibility;
+        if (!value) {
+            if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function") { // Gecko, W3C
+                if (!Calendar.is_khtml)
+                    value = document.defaultView.
+                        getComputedStyle(obj, "").getPropertyValue("visibility");
+                else
+                    value = '';
+            } else if (obj.currentStyle) { // IE
+                value = obj.currentStyle.visibility;
+            } else
+                value = '';
+        }
+        return value;
+    };
+
+    var tags = new Array("applet", "iframe", "select");
+    var el = this.element;
+
+    var p = Calendar.getAbsolutePos(el);
+    var EX1 = p.x;
+    var EX2 = el.offsetWidth + EX1;
+    var EY1 = p.y;
+    var EY2 = el.offsetHeight + EY1;
+
+    for (var k = tags.length; k > 0; ) {
+        var ar = document.getElementsByTagName(tags[--k]);
+        var cc = null;
+
+        for (var i = ar.length; i > 0;) {
+            cc = ar[--i];
+
+            p = Calendar.getAbsolutePos(cc);
+            var CX1 = p.x;
+            var CX2 = cc.offsetWidth + CX1;
+            var CY1 = p.y;
+            var CY2 = cc.offsetHeight + CY1;
+
+            if (this.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1)) {
+                if (!cc.__msh_save_visibility) {
+                    cc.__msh_save_visibility = getVisib(cc);
+                }
+                cc.style.visibility = cc.__msh_save_visibility;
+            } else {
+                if (!cc.__msh_save_visibility) {
+                    cc.__msh_save_visibility = getVisib(cc);
+                }
+                cc.style.visibility = "hidden";
+            }
+        }
+    }
 };
 
 /** Internal function; it displays the bar with the names of the weekday. */
 Calendar.prototype._displayWeekdays = function () {
-	var fdow = this.firstDayOfWeek;
-	var cell = this.firstdayname;
-	var weekend = Calendar._TT["WEEKEND"];
-	for (var i = 0; i < 7; ++i) {
-		cell.className = "day name";
-		var realday = (i + fdow) % 7;
-		if (i) {
-			cell.ttip = Calendar._TT["DAY_FIRST"].replace("%s", Calendar._DN[realday]);
-			cell.navtype = 100;
-			cell.calendar = this;
-			cell.fdow = realday;
-			Calendar._add_evs(cell);
-		}
-		if (weekend.indexOf(realday.toString()) != -1) {
-			Calendar.addClass(cell, "weekend");
-		}
-		cell.innerHTML = Calendar._SDN[(i + fdow) % 7];
-		cell = cell.nextSibling;
-	}
+    var fdow = this.firstDayOfWeek;
+    var cell = this.firstdayname;
+    var weekend = Calendar._TT["WEEKEND"];
+    for (var i = 0; i < 7; ++i) {
+        cell.className = "day name";
+        var realday = (i + fdow) % 7;
+        if (i) {
+            cell.ttip = Calendar._TT["DAY_FIRST"].replace("%s", Calendar._DN[realday]);
+            cell.navtype = 100;
+            cell.calendar = this;
+            cell.fdow = realday;
+            Calendar._add_evs(cell);
+        }
+        if (weekend.indexOf(realday.toString()) != -1) {
+            Calendar.addClass(cell, "weekend");
+        }
+        cell.innerHTML = Calendar._SDN[(i + fdow) % 7];
+        cell = cell.nextSibling;
+    }
 };
 
 /** Internal function.  Hides all combo boxes that might be displayed. */
 Calendar.prototype._hideCombos = function () {
-	this.monthsCombo.style.display = "none";
-	this.yearsCombo.style.display = "none";
+    this.monthsCombo.style.display = "none";
+    this.yearsCombo.style.display = "none";
 };
 
 /** Internal function.  Starts dragging the element. */
 Calendar.prototype._dragStart = function (ev) {
-	if (this.dragging) {
-		return;
-	}
-	this.dragging = true;
-	var posX;
-	var posY;
-	if (Calendar.is_ie) {
-		posY = window.event.clientY + document.body.scrollTop;
-		posX = window.event.clientX + document.body.scrollLeft;
-	} else {
-		posY = ev.clientY + window.scrollY;
-		posX = ev.clientX + window.scrollX;
-	}
-	var st = this.element.style;
-	this.xOffs = posX - parseInt(st.left);
-	this.yOffs = posY - parseInt(st.top);
-	with (Calendar) {
-		addEvent(document, "mousemove", calDragIt);
-		addEvent(document, "mouseup", calDragEnd);
-	}
+    if (this.dragging) {
+        return;
+    }
+    this.dragging = true;
+    var posX;
+    var posY;
+    if (Calendar.is_ie) {
+        posY = window.event.clientY + document.body.scrollTop;
+        posX = window.event.clientX + document.body.scrollLeft;
+    } else {
+        posY = ev.clientY + window.scrollY;
+        posX = ev.clientX + window.scrollX;
+    }
+    var st = this.element.style;
+    this.xOffs = posX - parseInt(st.left);
+    this.yOffs = posY - parseInt(st.top);
+    with (Calendar) {
+        addEvent(document, "mousemove", calDragIt);
+        addEvent(document, "mouseup", calDragEnd);
+    }
 };
 
 // BEGIN: DATE OBJECT PATCHES
@@ -1649,242 +1649,242 @@ Date.DAY    = 24 * Date.HOUR;
 Date.WEEK   =  7 * Date.DAY;
 
 Date.parseDate = function(str, fmt) {
-	var today = new CalendarDateObject();
-	var y = 0;
-	var m = -1;
-	var d = 0;
-
-	// translate date into en_US, because split() cannot parse non-latin stuff
-	var a = str;
-	var i;
-	for (i = 0; i < Calendar._MN.length; i++) {
-		a = a.replace(Calendar._MN[i], enUS.m.wide[i]);
-	}
-	for (i = 0; i < Calendar._SMN.length; i++) {
-		a = a.replace(Calendar._SMN[i], enUS.m.abbr[i]);
-	}
-	a = a.replace(Calendar._am, 'am');
-	a = a.replace(Calendar._am.toLowerCase(), 'am');
-	a = a.replace(Calendar._pm, 'pm');
-	a = a.replace(Calendar._pm.toLowerCase(), 'pm');
-
-	a = a.split(/\W+/);
-
-	var b = fmt.match(/%./g);
-	var i = 0, j = 0;
-	var hr = 0;
-	var min = 0;
-	for (i = 0; i < a.length; ++i) {
-		if (!a[i])
-			continue;
-		switch (b[i]) {
-		    case "%d":
-		    case "%e":
-			d = parseInt(a[i], 10);
-			break;
-
-		    case "%m":
-			m = parseInt(a[i], 10) - 1;
-			break;
-
-		    case "%Y":
-		    case "%y":
-			y = parseInt(a[i], 10);
-			(y < 100) && (y += (y > 29) ? 1900 : 2000);
-			break;
-
-		    case "%b":
-			for (j = 0; j < 12; ++j) {
-				if (enUS.m.abbr[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; }
-			}
-			break;
-
-		    case "%B":
-			for (j = 0; j < 12; ++j) {
-				if (enUS.m.wide[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; }
-			}
-			break;
-
-		    case "%H":
-		    case "%I":
-		    case "%k":
-		    case "%l":
-			hr = parseInt(a[i], 10);
-			break;
-
-		    case "%P":
-		    case "%p":
-			if (/pm/i.test(a[i]) && hr < 12)
-				hr += 12;
-			else if (/am/i.test(a[i]) && hr >= 12)
-				hr -= 12;
-			break;
-
-		    case "%M":
-			min = parseInt(a[i], 10);
-			break;
-		}
-	}
-	if (isNaN(y)) y = today.getFullYear();
-	if (isNaN(m)) m = today.getMonth();
-	if (isNaN(d)) d = today.getDate();
-	if (isNaN(hr)) hr = today.getHours();
-	if (isNaN(min)) min = today.getMinutes();
-	if (y != 0 && m != -1 && d != 0)
-		return new CalendarDateObject(y, m, d, hr, min, 0);
-	y = 0; m = -1; d = 0;
-	for (i = 0; i < a.length; ++i) {
-		if (a[i].search(/[a-zA-Z]+/) != -1) {
-			var t = -1;
-			for (j = 0; j < 12; ++j) {
-				if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; }
-			}
-			if (t != -1) {
-				if (m != -1) {
-					d = m+1;
-				}
-				m = t;
-			}
-		} else if (parseInt(a[i], 10) <= 12 && m == -1) {
-			m = a[i]-1;
-		} else if (parseInt(a[i], 10) > 31 && y == 0) {
-			y = parseInt(a[i], 10);
-			(y < 100) && (y += (y > 29) ? 1900 : 2000);
-		} else if (d == 0) {
-			d = a[i];
-		}
-	}
-	if (y == 0)
-		y = today.getFullYear();
-	if (m != -1 && d != 0)
-		return new CalendarDateObject(y, m, d, hr, min, 0);
-	return today;
+    var today = new CalendarDateObject();
+    var y = 0;
+    var m = -1;
+    var d = 0;
+
+    // translate date into en_US, because split() cannot parse non-latin stuff
+    var a = str;
+    var i;
+    for (i = 0; i < Calendar._MN.length; i++) {
+        a = a.replace(Calendar._MN[i], enUS.m.wide[i]);
+    }
+    for (i = 0; i < Calendar._SMN.length; i++) {
+        a = a.replace(Calendar._SMN[i], enUS.m.abbr[i]);
+    }
+    a = a.replace(Calendar._am, 'am');
+    a = a.replace(Calendar._am.toLowerCase(), 'am');
+    a = a.replace(Calendar._pm, 'pm');
+    a = a.replace(Calendar._pm.toLowerCase(), 'pm');
+
+    a = a.split(/\W+/);
+
+    var b = fmt.match(/%./g);
+    var i = 0, j = 0;
+    var hr = 0;
+    var min = 0;
+    for (i = 0; i < a.length; ++i) {
+        if (!a[i])
+            continue;
+        switch (b[i]) {
+            case "%d":
+            case "%e":
+            d = parseInt(a[i], 10);
+            break;
+
+            case "%m":
+            m = parseInt(a[i], 10) - 1;
+            break;
+
+            case "%Y":
+            case "%y":
+            y = parseInt(a[i], 10);
+            (y < 100) && (y += (y > 29) ? 1900 : 2000);
+            break;
+
+            case "%b":
+            for (j = 0; j < 12; ++j) {
+                if (enUS.m.abbr[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; }
+            }
+            break;
+
+            case "%B":
+            for (j = 0; j < 12; ++j) {
+                if (enUS.m.wide[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; }
+            }
+            break;
+
+            case "%H":
+            case "%I":
+            case "%k":
+            case "%l":
+            hr = parseInt(a[i], 10);
+            break;
+
+            case "%P":
+            case "%p":
+            if (/pm/i.test(a[i]) && hr < 12)
+                hr += 12;
+            else if (/am/i.test(a[i]) && hr >= 12)
+                hr -= 12;
+            break;
+
+            case "%M":
+            min = parseInt(a[i], 10);
+            break;
+        }
+    }
+    if (isNaN(y)) y = today.getFullYear();
+    if (isNaN(m)) m = today.getMonth();
+    if (isNaN(d)) d = today.getDate();
+    if (isNaN(hr)) hr = today.getHours();
+    if (isNaN(min)) min = today.getMinutes();
+    if (y != 0 && m != -1 && d != 0)
+        return new CalendarDateObject(y, m, d, hr, min, 0);
+    y = 0; m = -1; d = 0;
+    for (i = 0; i < a.length; ++i) {
+        if (a[i].search(/[a-zA-Z]+/) != -1) {
+            var t = -1;
+            for (j = 0; j < 12; ++j) {
+                if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; }
+            }
+            if (t != -1) {
+                if (m != -1) {
+                    d = m+1;
+                }
+                m = t;
+            }
+        } else if (parseInt(a[i], 10) <= 12 && m == -1) {
+            m = a[i]-1;
+        } else if (parseInt(a[i], 10) > 31 && y == 0) {
+            y = parseInt(a[i], 10);
+            (y < 100) && (y += (y > 29) ? 1900 : 2000);
+        } else if (d == 0) {
+            d = a[i];
+        }
+    }
+    if (y == 0)
+        y = today.getFullYear();
+    if (m != -1 && d != 0)
+        return new CalendarDateObject(y, m, d, hr, min, 0);
+    return today;
 };
 
 /** Returns the number of days in the current month */
 Date.prototype.getMonthDays = function(month) {
-	var year = this.getFullYear();
-	if (typeof month == "undefined") {
-		month = this.getMonth();
-	}
-	if (((0 == (year%4)) && ( (0 != (year%100)) || (0 == (year%400)))) && month == 1) {
-		return 29;
-	} else {
-		return Date._MD[month];
-	}
+    var year = this.getFullYear();
+    if (typeof month == "undefined") {
+        month = this.getMonth();
+    }
+    if (((0 == (year%4)) && ( (0 != (year%100)) || (0 == (year%400)))) && month == 1) {
+        return 29;
+    } else {
+        return Date._MD[month];
+    }
 };
 
 /** Returns the number of day in the year. */
 Date.prototype.getDayOfYear = function() {
-	var now = new CalendarDateObject(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
-	var then = new CalendarDateObject(this.getFullYear(), 0, 0, 0, 0, 0);
-	var time = now - then;
-	return Math.floor(time / Date.DAY);
+    var now = new CalendarDateObject(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
+    var then = new CalendarDateObject(this.getFullYear(), 0, 0, 0, 0, 0);
+    var time = now - then;
+    return Math.floor(time / Date.DAY);
 };
 
 /** Returns the number of the week in year, as defined in ISO 8601. */
 Date.prototype.getWeekNumber = function() {
-	var d = new CalendarDateObject(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
-	var DoW = d.getDay();
-	d.setDate(d.getDate() - (DoW + 6) % 7 + 3); // Nearest Thu
-	var ms = d.valueOf(); // GMT
-	d.setMonth(0);
-	d.setDate(4); // Thu in Week 1
-	return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
+    var d = new CalendarDateObject(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
+    var DoW = d.getDay();
+    d.setDate(d.getDate() - (DoW + 6) % 7 + 3); // Nearest Thu
+    var ms = d.valueOf(); // GMT
+    d.setMonth(0);
+    d.setDate(4); // Thu in Week 1
+    return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
 };
 
 /** Checks date and time equality */
 Date.prototype.equalsTo = function(date) {
-	return ((this.getFullYear() == date.getFullYear()) &&
-		(this.getMonth() == date.getMonth()) &&
-		(this.getDate() == date.getDate()) &&
-		(this.getHours() == date.getHours()) &&
-		(this.getMinutes() == date.getMinutes()));
+    return ((this.getFullYear() == date.getFullYear()) &&
+        (this.getMonth() == date.getMonth()) &&
+        (this.getDate() == date.getDate()) &&
+        (this.getHours() == date.getHours()) &&
+        (this.getMinutes() == date.getMinutes()));
 };
 
 /** Set only the year, month, date parts (keep existing time) */
 Date.prototype.setDateOnly = function(date) {
-	var tmp = new CalendarDateObject(date);
-	this.setDate(1);
-	this.setFullYear(tmp.getFullYear());
-	this.setMonth(tmp.getMonth());
-	this.setDate(tmp.getDate());
+    var tmp = new CalendarDateObject(date);
+    this.setDate(1);
+    this.setFullYear(tmp.getFullYear());
+    this.setMonth(tmp.getMonth());
+    this.setDate(tmp.getDate());
 };
 
 /** Prints the date in a string according to the given format. */
 Date.prototype.print = function (str) {
-	var m = this.getMonth();
-	var d = this.getDate();
-	var y = this.getFullYear();
-	var wn = this.getWeekNumber();
-	var w = this.getDay();
-	var s = {};
-	var hr = this.getHours();
-	var pm = (hr >= 12);
-	var ir = (pm) ? (hr - 12) : hr;
-	var dy = this.getDayOfYear();
-	if (ir == 0)
-		ir = 12;
-	var min = this.getMinutes();
-	var sec = this.getSeconds();
-	s["%a"] = Calendar._SDN[w]; // abbreviated weekday name [FIXME: I18N]
-	s["%A"] = Calendar._DN[w]; // full weekday name
-	s["%b"] = Calendar._SMN[m]; // abbreviated month name [FIXME: I18N]
-	s["%B"] = Calendar._MN[m]; // full month name
-	// FIXME: %c : preferred date and time representation for the current locale
-	s["%C"] = 1 + Math.floor(y / 100); // the century number
-	s["%d"] = (d < 10) ? ("0" + d) : d; // the day of the month (range 01 to 31)
-	s["%e"] = d; // the day of the month (range 1 to 31)
-	// FIXME: %D : american date style: %m/%d/%y
-	// FIXME: %E, %F, %G, %g, %h (man strftime)
-	s["%H"] = (hr < 10) ? ("0" + hr) : hr; // hour, range 00 to 23 (24h format)
-	s["%I"] = (ir < 10) ? ("0" + ir) : ir; // hour, range 01 to 12 (12h format)
-	s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; // day of the year (range 001 to 366)
-	s["%k"] = hr;		// hour, range 0 to 23 (24h format)
-	s["%l"] = ir;		// hour, range 1 to 12 (12h format)
-	s["%m"] = (m < 9) ? ("0" + (1+m)) : (1+m); // month, range 01 to 12
-	s["%M"] = (min < 10) ? ("0" + min) : min; // minute, range 00 to 59
-	s["%n"] = "\n";		// a newline character
-	s["%p"] = pm ? Calendar._pm.toUpperCase() : Calendar._am.toUpperCase();
-	s["%P"] = pm ? Calendar._pm.toLowerCase() : Calendar._am.toLowerCase();
-	// FIXME: %r : the time in am/pm notation %I:%M:%S %p
-	// FIXME: %R : the time in 24-hour notation %H:%M
-	s["%s"] = Math.floor(this.getTime() / 1000);
-	s["%S"] = (sec < 10) ? ("0" + sec) : sec; // seconds, range 00 to 59
-	s["%t"] = "\t";		// a tab character
-	// FIXME: %T : the time in 24-hour notation (%H:%M:%S)
-	s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn;
-	s["%u"] = w + 1;	// the day of the week (range 1 to 7, 1 = MON)
-	s["%w"] = w;		// the day of the week (range 0 to 6, 0 = SUN)
-	// FIXME: %x : preferred date representation for the current locale without the time
-	// FIXME: %X : preferred time representation for the current locale without the date
-	s["%y"] = ('' + y).substr(2, 2); // year without the century (range 00 to 99)
-	s["%Y"] = y;		// year with the century
-	s["%%"] = "%";		// a literal '%' character
-
-	var re = /%./g;
-	if (!Calendar.is_ie5 && !Calendar.is_khtml)
-		return str.replace(re, function (par) { return s[par] || par; });
-
-	var a = str.match(re);
-	for (var i = 0; i < a.length; i++) {
-		var tmp = s[a[i]];
-		if (tmp) {
-			re = new RegExp(a[i], 'g');
-			str = str.replace(re, tmp);
-		}
-	}
-
-	return str;
+    var m = this.getMonth();
+    var d = this.getDate();
+    var y = this.getFullYear();
+    var wn = this.getWeekNumber();
+    var w = this.getDay();
+    var s = {};
+    var hr = this.getHours();
+    var pm = (hr >= 12);
+    var ir = (pm) ? (hr - 12) : hr;
+    var dy = this.getDayOfYear();
+    if (ir == 0)
+        ir = 12;
+    var min = this.getMinutes();
+    var sec = this.getSeconds();
+    s["%a"] = Calendar._SDN[w]; // abbreviated weekday name [FIXME: I18N]
+    s["%A"] = Calendar._DN[w]; // full weekday name
+    s["%b"] = Calendar._SMN[m]; // abbreviated month name [FIXME: I18N]
+    s["%B"] = Calendar._MN[m]; // full month name
+    // FIXME: %c : preferred date and time representation for the current locale
+    s["%C"] = 1 + Math.floor(y / 100); // the century number
+    s["%d"] = (d < 10) ? ("0" + d) : d; // the day of the month (range 01 to 31)
+    s["%e"] = d; // the day of the month (range 1 to 31)
+    // FIXME: %D : american date style: %m/%d/%y
+    // FIXME: %E, %F, %G, %g, %h (man strftime)
+    s["%H"] = (hr < 10) ? ("0" + hr) : hr; // hour, range 00 to 23 (24h format)
+    s["%I"] = (ir < 10) ? ("0" + ir) : ir; // hour, range 01 to 12 (12h format)
+    s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; // day of the year (range 001 to 366)
+    s["%k"] = hr;        // hour, range 0 to 23 (24h format)
+    s["%l"] = ir;        // hour, range 1 to 12 (12h format)
+    s["%m"] = (m < 9) ? ("0" + (1+m)) : (1+m); // month, range 01 to 12
+    s["%M"] = (min < 10) ? ("0" + min) : min; // minute, range 00 to 59
+    s["%n"] = "\n";        // a newline character
+    s["%p"] = pm ? Calendar._pm.toUpperCase() : Calendar._am.toUpperCase();
+    s["%P"] = pm ? Calendar._pm.toLowerCase() : Calendar._am.toLowerCase();
+    // FIXME: %r : the time in am/pm notation %I:%M:%S %p
+    // FIXME: %R : the time in 24-hour notation %H:%M
+    s["%s"] = Math.floor(this.getTime() / 1000);
+    s["%S"] = (sec < 10) ? ("0" + sec) : sec; // seconds, range 00 to 59
+    s["%t"] = "\t";        // a tab character
+    // FIXME: %T : the time in 24-hour notation (%H:%M:%S)
+    s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn;
+    s["%u"] = w + 1;    // the day of the week (range 1 to 7, 1 = MON)
+    s["%w"] = w;        // the day of the week (range 0 to 6, 0 = SUN)
+    // FIXME: %x : preferred date representation for the current locale without the time
+    // FIXME: %X : preferred time representation for the current locale without the date
+    s["%y"] = ('' + y).substr(2, 2); // year without the century (range 00 to 99)
+    s["%Y"] = y;        // year with the century
+    s["%%"] = "%";        // a literal '%' character
+
+    var re = /%./g;
+    if (!Calendar.is_ie5 && !Calendar.is_khtml)
+        return str.replace(re, function (par) { return s[par] || par; });
+
+    var a = str.match(re);
+    for (var i = 0; i < a.length; i++) {
+        var tmp = s[a[i]];
+        if (tmp) {
+            re = new RegExp(a[i], 'g');
+            str = str.replace(re, tmp);
+        }
+    }
+
+    return str;
 };
 
 Date.prototype.__msh_oldSetFullYear = Date.prototype.setFullYear;
 Date.prototype.setFullYear = function(y) {
-	var d = new CalendarDateObject(this);
-	d.__msh_oldSetFullYear(y);
-	if (d.getMonth() != this.getMonth())
-		this.setDate(28);
-	this.__msh_oldSetFullYear(y);
+    var d = new CalendarDateObject(this);
+    d.__msh_oldSetFullYear(y);
+    if (d.getMonth() != this.getMonth())
+        this.setDate(28);
+    this.__msh_oldSetFullYear(y);
 };
 
 CalendarDateObject.prototype = new Date();
diff --git a/pub/js/jquery/jquery-ui-1.8.17.custom.min.js b/pub/js/jquery/jquery-ui-1.8.17.custom.min.js
new file mode 100644
index 0000000000000000000000000000000000000000..7cd230b984ee884be3dfe98fed3feca7740495ed
--- /dev/null
+++ b/pub/js/jquery/jquery-ui-1.8.17.custom.min.js
@@ -0,0 +1,63 @@
+/*!
+ * jQuery UI 1.8.17
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI
+ */(function(a,b){function d(b){return!a(b).parents().andSelf().filter(function(){return a.curCSS(this,"visibility")==="hidden"||a.expr.filters.hidden(this)}).length}function c(b,c){var e=b.nodeName.toLowerCase();if("area"===e){var f=b.parentNode,g=f.name,h;if(!b.href||!g||f.nodeName.toLowerCase()!=="map")return!1;h=a("img[usemap=#"+g+"]")[0];return!!h&&d(h)}return(/input|select|textarea|button|object/.test(e)?!b.disabled:"a"==e?b.href||c:c)&&d(b)}a.ui=a.ui||{};a.ui.version||(a.extend(a.ui,{version:"1.8.17",keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,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,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}}),a.fn.extend({propAttr:a.fn.prop||a.fn.attr,_focus:a.fn.focus,focus:function(b,c){return typeof b=="number"?this.each(function(){var d=this;setTimeout(function(){a(d).focus(),c&&c.call(d)},b)}):this._focus.apply(this,arguments)},scrollParent:function(){var b;a.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?b=this.parents().filter(function(){return/(relative|absolute|fixed)/.test(a.curCSS(this,"position",1))&&/(auto|scroll)/.test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0):b=this.parents().filter(function(){return/(auto|scroll)/.test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0);return/fixed/.test(this.css("position"))||!b.length?a(document):b},zIndex:function(c){if(c!==b)return this.css("zIndex",c);if(this.length){var d=a(this[0]),e,f;while(d.length&&d[0]!==document){e=d.css("position");if(e==="absolute"||e==="relative"||e==="fixed"){f=parseInt(d.css("zIndex"),10);if(!isNaN(f)&&f!==0)return f}d=d.parent()}}return 0},disableSelection:function(){return this.bind((a.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(a){a.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),a.each(["Width","Height"],function(c,d){function h(b,c,d,f){a.each(e,function(){c-=parseFloat(a.curCSS(b,"padding"+this,!0))||0,d&&(c-=parseFloat(a.curCSS(b,"border"+this+"Width",!0))||0),f&&(c-=parseFloat(a.curCSS(b,"margin"+this,!0))||0)});return c}var e=d==="Width"?["Left","Right"]:["Top","Bottom"],f=d.toLowerCase(),g={innerWidth:a.fn.innerWidth,innerHeight:a.fn.innerHeight,outerWidth:a.fn.outerWidth,outerHeight:a.fn.outerHeight};a.fn["inner"+d]=function(c){if(c===b)return g["inner"+d].call(this);return this.each(function(){a(this).css(f,h(this,c)+"px")})},a.fn["outer"+d]=function(b,c){if(typeof b!="number")return g["outer"+d].call(this,b);return this.each(function(){a(this).css(f,h(this,b,!0,c)+"px")})}}),a.extend(a.expr[":"],{data:function(b,c,d){return!!a.data(b,d[3])},focusable:function(b){return c(b,!isNaN(a.attr(b,"tabindex")))},tabbable:function(b){var d=a.attr(b,"tabindex"),e=isNaN(d);return(e||d>=0)&&c(b,!e)}}),a(function(){var b=document.body,c=b.appendChild(c=document.createElement("div"));a.extend(c.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0}),a.support.minHeight=c.offsetHeight===100,a.support.selectstart="onselectstart"in c,b.removeChild(c).style.display="none"}),a.extend(a.ui,{plugin:{add:function(b,c,d){var e=a.ui[b].prototype;for(var f in d)e.plugins[f]=e.plugins[f]||[],e.plugins[f].push([c,d[f]])},call:function(a,b,c){var d=a.plugins[b];if(!!d&&!!a.element[0].parentNode)for(var e=0;e<d.length;e++)a.options[d[e][0]]&&d[e][1].apply(a.element,c)}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(b,c){if(a(b).css("overflow")==="hidden")return!1;var d=c&&c==="left"?"scrollLeft":"scrollTop",e=!1;if(b[d]>0)return!0;b[d]=1,e=b[d]>0,b[d]=0;return e},isOverAxis:function(a,b,c){return a>b&&a<b+c},isOver:function(b,c,d,e,f,g){return a.ui.isOverAxis(b,d,f)&&a.ui.isOverAxis(c,e,g)}}))})(jQuery);/*!
+ * jQuery UI Widget 1.8.17
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Widget
+ */(function(a,b){if(a.cleanData){var c=a.cleanData;a.cleanData=function(b){for(var d=0,e;(e=b[d])!=null;d++)try{a(e).triggerHandler("remove")}catch(f){}c(b)}}else{var d=a.fn.remove;a.fn.remove=function(b,c){return this.each(function(){c||(!b||a.filter(b,[this]).length)&&a("*",this).add([this]).each(function(){try{a(this).triggerHandler("remove")}catch(b){}});return d.call(a(this),b,c)})}}a.widget=function(b,c,d){var e=b.split(".")[0],f;b=b.split(".")[1],f=e+"-"+b,d||(d=c,c=a.Widget),a.expr[":"][f]=function(c){return!!a.data(c,b)},a[e]=a[e]||{},a[e][b]=function(a,b){arguments.length&&this._createWidget(a,b)};var g=new c;g.options=a.extend(!0,{},g.options),a[e][b].prototype=a.extend(!0,g,{namespace:e,widgetName:b,widgetEventPrefix:a[e][b].prototype.widgetEventPrefix||b,widgetBaseClass:f},d),a.widget.bridge(b,a[e][b])},a.widget.bridge=function(c,d){a.fn[c]=function(e){var f=typeof e=="string",g=Array.prototype.slice.call(arguments,1),h=this;e=!f&&g.length?a.extend.apply(null,[!0,e].concat(g)):e;if(f&&e.charAt(0)==="_")return h;f?this.each(function(){var d=a.data(this,c),f=d&&a.isFunction(d[e])?d[e].apply(d,g):d;if(f!==d&&f!==b){h=f;return!1}}):this.each(function(){var b=a.data(this,c);b?b.option(e||{})._init():a.data(this,c,new d(e,this))});return h}},a.Widget=function(a,b){arguments.length&&this._createWidget(a,b)},a.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:!1},_createWidget:function(b,c){a.data(c,this.widgetName,this),this.element=a(c),this.options=a.extend(!0,{},this.options,this._getCreateOptions(),b);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()}),this._create(),this._trigger("create"),this._init()},_getCreateOptions:function(){return a.metadata&&a.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName),this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled "+"ui-state-disabled")},widget:function(){return this.element},option:function(c,d){var e=c;if(arguments.length===0)return a.extend({},this.options);if(typeof c=="string"){if(d===b)return this.options[c];e={},e[c]=d}this._setOptions(e);return this},_setOptions:function(b){var c=this;a.each(b,function(a,b){c._setOption(a,b)});return this},_setOption:function(a,b){this.options[a]=b,a==="disabled"&&this.widget()[b?"addClass":"removeClass"](this.widgetBaseClass+"-disabled"+" "+"ui-state-disabled").attr("aria-disabled",b);return this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_trigger:function(b,c,d){var e,f,g=this.options[b];d=d||{},c=a.Event(c),c.type=(b===this.widgetEventPrefix?b:this.widgetEventPrefix+b).toLowerCase(),c.target=this.element[0],f=c.originalEvent;if(f)for(e in f)e in c||(c[e]=f[e]);this.element.trigger(c,d);return!(a.isFunction(g)&&g.call(this.element[0],c,d)===!1||c.isDefaultPrevented())}}})(jQuery);/*!
+ * jQuery UI Mouse 1.8.17
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Mouse
+ *
+ * Depends:
+ *	jquery.ui.widget.js
+ */(function(a,b){var c=!1;a(document).mouseup(function(a){c=!1}),a.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var b=this;this.element.bind("mousedown."+this.widgetName,function(a){return b._mouseDown(a)}).bind("click."+this.widgetName,function(c){if(!0===a.data(c.target,b.widgetName+".preventClickEvent")){a.removeData(c.target,b.widgetName+".preventClickEvent"),c.stopImmediatePropagation();return!1}}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName)},_mouseDown:function(b){if(!c){this._mouseStarted&&this._mouseUp(b),this._mouseDownEvent=b;var d=this,e=b.which==1,f=typeof this.options.cancel=="string"&&b.target.nodeName?a(b.target).closest(this.options.cancel).length:!1;if(!e||f||!this._mouseCapture(b))return!0;this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){d.mouseDelayMet=!0},this.options.delay));if(this._mouseDistanceMet(b)&&this._mouseDelayMet(b)){this._mouseStarted=this._mouseStart(b)!==!1;if(!this._mouseStarted){b.preventDefault();return!0}}!0===a.data(b.target,this.widgetName+".preventClickEvent")&&a.removeData(b.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(a){return d._mouseMove(a)},this._mouseUpDelegate=function(a){return d._mouseUp(a)},a(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),b.preventDefault(),c=!0;return!0}},_mouseMove:function(b){if(a.browser.msie&&!(document.documentMode>=9)&&!b.button)return this._mouseUp(b);if(this._mouseStarted){this._mouseDrag(b);return b.preventDefault()}this._mouseDistanceMet(b)&&this._mouseDelayMet(b)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,b)!==!1,this._mouseStarted?this._mouseDrag(b):this._mouseUp(b));return!this._mouseStarted},_mouseUp:function(b){a(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,b.target==this._mouseDownEvent.target&&a.data(b.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(b));return!1},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(a){return this.mouseDelayMet},_mouseStart:function(a){},_mouseDrag:function(a){},_mouseStop:function(a){},_mouseCapture:function(a){return!0}})})(jQuery);/*
+ * jQuery UI Position 1.8.17
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Position
+ */(function(a,b){a.ui=a.ui||{};var c=/left|center|right/,d=/top|center|bottom/,e="center",f={},g=a.fn.position,h=a.fn.offset;a.fn.position=function(b){if(!b||!b.of)return g.apply(this,arguments);b=a.extend({},b);var h=a(b.of),i=h[0],j=(b.collision||"flip").split(" "),k=b.offset?b.offset.split(" "):[0,0],l,m,n;i.nodeType===9?(l=h.width(),m=h.height(),n={top:0,left:0}):i.setTimeout?(l=h.width(),m=h.height(),n={top:h.scrollTop(),left:h.scrollLeft()}):i.preventDefault?(b.at="left top",l=m=0,n={top:b.of.pageY,left:b.of.pageX}):(l=h.outerWidth(),m=h.outerHeight(),n=h.offset()),a.each(["my","at"],function(){var a=(b[this]||"").split(" ");a.length===1&&(a=c.test(a[0])?a.concat([e]):d.test(a[0])?[e].concat(a):[e,e]),a[0]=c.test(a[0])?a[0]:e,a[1]=d.test(a[1])?a[1]:e,b[this]=a}),j.length===1&&(j[1]=j[0]),k[0]=parseInt(k[0],10)||0,k.length===1&&(k[1]=k[0]),k[1]=parseInt(k[1],10)||0,b.at[0]==="right"?n.left+=l:b.at[0]===e&&(n.left+=l/2),b.at[1]==="bottom"?n.top+=m:b.at[1]===e&&(n.top+=m/2),n.left+=k[0],n.top+=k[1];return this.each(function(){var c=a(this),d=c.outerWidth(),g=c.outerHeight(),h=parseInt(a.curCSS(this,"marginLeft",!0))||0,i=parseInt(a.curCSS(this,"marginTop",!0))||0,o=d+h+(parseInt(a.curCSS(this,"marginRight",!0))||0),p=g+i+(parseInt(a.curCSS(this,"marginBottom",!0))||0),q=a.extend({},n),r;b.my[0]==="right"?q.left-=d:b.my[0]===e&&(q.left-=d/2),b.my[1]==="bottom"?q.top-=g:b.my[1]===e&&(q.top-=g/2),f.fractions||(q.left=Math.round(q.left),q.top=Math.round(q.top)),r={left:q.left-h,top:q.top-i},a.each(["left","top"],function(c,e){a.ui.position[j[c]]&&a.ui.position[j[c]][e](q,{targetWidth:l,targetHeight:m,elemWidth:d,elemHeight:g,collisionPosition:r,collisionWidth:o,collisionHeight:p,offset:k,my:b.my,at:b.at})}),a.fn.bgiframe&&c.bgiframe(),c.offset(a.extend(q,{using:b.using}))})},a.ui.position={fit:{left:function(b,c){var d=a(window),e=c.collisionPosition.left+c.collisionWidth-d.width()-d.scrollLeft();b.left=e>0?b.left-e:Math.max(b.left-c.collisionPosition.left,b.left)},top:function(b,c){var d=a(window),e=c.collisionPosition.top+c.collisionHeight-d.height()-d.scrollTop();b.top=e>0?b.top-e:Math.max(b.top-c.collisionPosition.top,b.top)}},flip:{left:function(b,c){if(c.at[0]!==e){var d=a(window),f=c.collisionPosition.left+c.collisionWidth-d.width()-d.scrollLeft(),g=c.my[0]==="left"?-c.elemWidth:c.my[0]==="right"?c.elemWidth:0,h=c.at[0]==="left"?c.targetWidth:-c.targetWidth,i=-2*c.offset[0];b.left+=c.collisionPosition.left<0?g+h+i:f>0?g+h+i:0}},top:function(b,c){if(c.at[1]!==e){var d=a(window),f=c.collisionPosition.top+c.collisionHeight-d.height()-d.scrollTop(),g=c.my[1]==="top"?-c.elemHeight:c.my[1]==="bottom"?c.elemHeight:0,h=c.at[1]==="top"?c.targetHeight:-c.targetHeight,i=-2*c.offset[1];b.top+=c.collisionPosition.top<0?g+h+i:f>0?g+h+i:0}}}},a.offset.setOffset||(a.offset.setOffset=function(b,c){/static/.test(a.curCSS(b,"position"))&&(b.style.position="relative");var d=a(b),e=d.offset(),f=parseInt(a.curCSS(b,"top",!0),10)||0,g=parseInt(a.curCSS(b,"left",!0),10)||0,h={top:c.top-e.top+f,left:c.left-e.left+g};"using"in c?c.using.call(b,h):d.css(h)},a.fn.offset=function(b){var c=this[0];if(!c||!c.ownerDocument)return null;if(b)return this.each(function(){a.offset.setOffset(this,b)});return h.call(this)}),function(){var b=document.getElementsByTagName("body")[0],c=document.createElement("div"),d,e,g,h,i;d=document.createElement(b?"div":"body"),g={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},b&&jQuery.extend(g,{position:"absolute",left:"-1000px",top:"-1000px"});for(var j in g)d.style[j]=g[j];d.appendChild(c),e=b||document.documentElement,e.insertBefore(d,e.firstChild),c.style.cssText="position: absolute; left: 10.7432222px; top: 10.432325px; height: 30px; width: 201px;",h=a(c).offset(function(a,b){return b}).offset(),d.innerHTML="",e.removeChild(d),i=h.top+h.left+(b?2e3:0),f.fractions=i>21&&i<22}()})(jQuery);/*
+ * jQuery UI Draggable 1.8.17
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Draggables
+ *
+ * Depends:
+ *	jquery.ui.core.js
+ *	jquery.ui.mouse.js
+ *	jquery.ui.widget.js
+ */(function(a,b){a.widget("ui.draggable",a.ui.mouse,{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(){if(!!this.element.data("draggable")){this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy();return this}},_mouseCapture:function(b){var c=this.options;if(this.helper||c.disabled||a(b.target).is(".ui-resizable-handle"))return!1;this.handle=this._getHandle(b);if(!this.handle)return!1;c.iframeFix&&a(c.iframeFix===!0?"iframe":c.iframeFix).each(function(){a('<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(a(this).offset()).appendTo("body")});return!0},_mouseStart:function(b){var c=this.options;this.helper=this._createHelper(b),this._cacheHelperProportions(),a.ui.ddmanager&&(a.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},a.extend(this.offset,{click:{left:b.pageX-this.offset.left,top:b.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(b),this.originalPageX=b.pageX,this.originalPageY=b.pageY,c.cursorAt&&this._adjustOffsetFromHelper(c.cursorAt),c.containment&&this._setContainment();if(this._trigger("start",b)===!1){this._clear();return!1}this._cacheHelperProportions(),a.ui.ddmanager&&!c.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b),this.helper.addClass("ui-draggable-dragging"),this._mouseDrag(b,!0),a.ui.ddmanager&&a.ui.ddmanager.dragStart(this,b);return!0},_mouseDrag:function(b,c){this.position=this._generatePosition(b),this.positionAbs=this._convertPositionTo("absolute");if(!c){var d=this._uiHash();if(this._trigger("drag",b,d)===!1){this._mouseUp({});return!1}this.position=d.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";a.ui.ddmanager&&a.ui.ddmanager.drag(this,b);return!1},_mouseStop:function(b){var c=!1;a.ui.ddmanager&&!this.options.dropBehaviour&&(c=a.ui.ddmanager.drop(this,b)),this.dropped&&(c=this.dropped,this.dropped=!1);if((!this.element[0]||!this.element[0].parentNode)&&this.options.helper=="original")return!1;if(this.options.revert=="invalid"&&!c||this.options.revert=="valid"&&c||this.options.revert===!0||a.isFunction(this.options.revert)&&this.options.revert.call(this.element,c)){var d=this;a(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){d._trigger("stop",b)!==!1&&d._clear()})}else this._trigger("stop",b)!==!1&&this._clear();return!1},_mouseUp:function(b){this.options.iframeFix===!0&&a("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),a.ui.ddmanager&&a.ui.ddmanager.dragStop(this,b);return a.ui.mouse.prototype._mouseUp.call(this,b)},cancel:function(){this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear();return this},_getHandle:function(b){var c=!this.options.handle||!a(this.options.handle,this.element).length?!0:!1;a(this.options.handle,this.element).find("*").andSelf().each(function(){this==b.target&&(c=!0)});return c},_createHelper:function(b){var c=this.options,d=a.isFunction(c.helper)?a(c.helper.apply(this.element[0],[b])):c.helper=="clone"?this.element.clone().removeAttr("id"):this.element;d.parents("body").length||d.appendTo(c.appendTo=="parent"?this.element[0].parentNode:c.appendTo),d[0]!=this.element[0]&&!/(fixed|absolute)/.test(d.css("position"))&&d.css("position","absolute");return d},_adjustOffsetFromHelper:function(b){typeof b=="string"&&(b=b.split(" ")),a.isArray(b)&&(b={left:+b[0],top:+b[1]||0}),"left"in b&&(this.offset.click.left=b.left+this.margins.left),"right"in b&&(this.offset.click.left=this.helperProportions.width-b.right+this.margins.left),"top"in b&&(this.offset.click.top=b.top+this.margins.top),"bottom"in b&&(this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])&&(b.left+=this.scrollParent.scrollLeft(),b.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)b={top:0,left:0};return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.element.position();return{top:a.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.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 b=this.options;b.containment=="parent"&&(b.containment=this.helper[0].parentNode);if(b.containment=="document"||b.containment=="window")this.containment=[b.containment=="document"?0:a(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,b.containment=="document"?0:a(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(b.containment=="document"?0:a(window).scrollLeft())+a(b.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(b.containment=="document"?0:a(window).scrollTop())+(a(b.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(b.containment)&&b.containment.constructor!=Array){var c=a(b.containment),d=c[0];if(!d)return;var e=c.offset(),f=a(d).css("overflow")!="hidden";this.containment=[(parseInt(a(d).css("borderLeftWidth"),10)||0)+(parseInt(a(d).css("paddingLeft"),10)||0),(parseInt(a(d).css("borderTopWidth"),10)||0)+(parseInt(a(d).css("paddingTop"),10)||0),(f?Math.max(d.scrollWidth,d.offsetWidth):d.offsetWidth)-(parseInt(a(d).css("borderLeftWidth"),10)||0)-(parseInt(a(d).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(f?Math.max(d.scrollHeight,d.offsetHeight):d.offsetHeight)-(parseInt(a(d).css("borderTopWidth"),10)||0)-(parseInt(a(d).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=c}else b.containment.constructor==Array&&(this.containment=b.containment)},_convertPositionTo:function(b,c){c||(c=this.position);var d=b=="absolute"?1:-1,e=this.options,f=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,g=/(html|body)/i.test(f[0].tagName);return{top:c.top+this.offset.relative.top*d+this.offset.parent.top*d-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():g?0:f.scrollTop())*d),left:c.left+this.offset.relative.left*d+this.offset.parent.left*d-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:f.scrollLeft())*d)}},_generatePosition:function(b){var c=this.options,d=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(d[0].tagName),f=b.pageX,g=b.pageY;if(this.originalPosition){var h;if(this.containment){if(this.relative_container){var i=this.relative_container.offset();h=[this.containment[0]+i.left,this.containment[1]+i.top,this.containment[2]+i.left,this.containment[3]+i.top]}else h=this.containment;b.pageX-this.offset.click.left<h[0]&&(f=h[0]+this.offset.click.left),b.pageY-this.offset.click.top<h[1]&&(g=h[1]+this.offset.click.top),b.pageX-this.offset.click.left>h[2]&&(f=h[2]+this.offset.click.left),b.pageY-this.offset.click.top>h[3]&&(g=h[3]+this.offset.click.top)}if(c.grid){var j=c.grid[1]?this.originalPageY+Math.round((g-this.originalPageY)/c.grid[1])*c.grid[1]:this.originalPageY;g=h?j-this.offset.click.top<h[1]||j-this.offset.click.top>h[3]?j-this.offset.click.top<h[1]?j+c.grid[1]:j-c.grid[1]:j:j;var k=c.grid[0]?this.originalPageX+Math.round((f-this.originalPageX)/c.grid[0])*c.grid[0]:this.originalPageX;f=h?k-this.offset.click.left<h[0]||k-this.offset.click.left>h[2]?k-this.offset.click.left<h[0]?k+c.grid[0]:k-c.grid[0]:k:k}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:d.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():e?0:d.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(b,c,d){d=d||this._uiHash(),a.ui.plugin.call(this,b,[c,d]),b=="drag"&&(this.positionAbs=this._convertPositionTo("absolute"));return a.Widget.prototype._trigger.call(this,b,c,d)},plugins:{},_uiHash:function(a){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),a.extend(a.ui.draggable,{version:"1.8.17"}),a.ui.plugin.add("draggable","connectToSortable",{start:function(b,c){var d=a(this).data("draggable"),e=d.options,f=a.extend({},c,{item:d.element});d.sortables=[],a(e.connectToSortable).each(function(){var c=a.data(this,"sortable");c&&!c.options.disabled&&(d.sortables.push({instance:c,shouldRevert:c.options.revert}),c.refreshPositions(),c._trigger("activate",b,f))})},stop:function(b,c){var d=a(this).data("draggable"),e=a.extend({},c,{item:d.element});a.each(d.sortables,function(){this.instance.isOver?(this.instance.isOver=0,d.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=!0),this.instance._mouseStop(b),this.instance.options.helper=this.instance.options._helper,d.options.helper=="original"&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",b,e))})},drag:function(b,c){var d=a(this).data("draggable"),e=this,f=function(b){var c=this.offset.click.top,d=this.offset.click.left,e=this.positionAbs.top,f=this.positionAbs.left,g=b.height,h=b.width,i=b.top,j=b.left;return a.ui.isOver(e+c,f+d,i,j,g,h)};a.each(d.sortables,function(f){this.instance.positionAbs=d.positionAbs,this.instance.helperProportions=d.helperProportions,this.instance.offset.click=d.offset.click,this.instance._intersectsWith(this.instance.containerCache)?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=a(e).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 c.helper[0]},b.target=this.instance.currentItem[0],this.instance._mouseCapture(b,!0),this.instance._mouseStart(b,!0,!0),this.instance.offset.click.top=d.offset.click.top,this.instance.offset.click.left=d.offset.click.left,this.instance.offset.parent.left-=d.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=d.offset.parent.top-this.instance.offset.parent.top,d._trigger("toSortable",b),d.dropped=this.instance.element,d.currentItem=d.element,this.instance.fromOutside=d),this.instance.currentItem&&this.instance._mouseDrag(b)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",b,this.instance._uiHash(this.instance)),this.instance._mouseStop(b,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),d._trigger("fromSortable",b),d.dropped=!1)})}}),a.ui.plugin.add("draggable","cursor",{start:function(b,c){var d=a("body"),e=a(this).data("draggable").options;d.css("cursor")&&(e._cursor=d.css("cursor")),d.css("cursor",e.cursor)},stop:function(b,c){var d=a(this).data("draggable").options;d._cursor&&a("body").css("cursor",d._cursor)}}),a.ui.plugin.add("draggable","opacity",{start:function(b,c){var d=a(c.helper),e=a(this).data("draggable").options;d.css("opacity")&&(e._opacity=d.css("opacity")),d.css("opacity",e.opacity)},stop:function(b,c){var d=a(this).data("draggable").options;d._opacity&&a(c.helper).css("opacity",d._opacity)}}),a.ui.plugin.add("draggable","scroll",{start:function(b,c){var d=a(this).data("draggable");d.scrollParent[0]!=document&&d.scrollParent[0].tagName!="HTML"&&(d.overflowOffset=d.scrollParent.offset())},drag:function(b,c){var d=a(this).data("draggable"),e=d.options,f=!1;if(d.scrollParent[0]!=document&&d.scrollParent[0].tagName!="HTML"){if(!e.axis||e.axis!="x")d.overflowOffset.top+d.scrollParent[0].offsetHeight-b.pageY<e.scrollSensitivity?d.scrollParent[0].scrollTop=f=d.scrollParent[0].scrollTop+e.scrollSpeed:b.pageY-d.overflowOffset.top<e.scrollSensitivity&&(d.scrollParent[0].scrollTop=f=d.scrollParent[0].scrollTop-e.scrollSpeed);if(!e.axis||e.axis!="y")d.overflowOffset.left+d.scrollParent[0].offsetWidth-b.pageX<e.scrollSensitivity?d.scrollParent[0].scrollLeft=f=d.scrollParent[0].scrollLeft+e.scrollSpeed:b.pageX-d.overflowOffset.left<e.scrollSensitivity&&(d.scrollParent[0].scrollLeft=f=d.scrollParent[0].scrollLeft-e.scrollSpeed)}else{if(!e.axis||e.axis!="x")b.pageY-a(document).scrollTop()<e.scrollSensitivity?f=a(document).scrollTop(a(document).scrollTop()-e.scrollSpeed):a(window).height()-(b.pageY-a(document).scrollTop())<e.scrollSensitivity&&(f=a(document).scrollTop(a(document).scrollTop()+e.scrollSpeed));if(!e.axis||e.axis!="y")b.pageX-a(document).scrollLeft()<e.scrollSensitivity?f=a(document).scrollLeft(a(document).scrollLeft()-e.scrollSpeed):a(window).width()-(b.pageX-a(document).scrollLeft())<e.scrollSensitivity&&(f=a(document).scrollLeft(a(document).scrollLeft()+e.scrollSpeed))}f!==!1&&a.ui.ddmanager&&!e.dropBehaviour&&a.ui.ddmanager.prepareOffsets(d,b)}}),a.ui.plugin.add("draggable","snap",{start:function(b,c){var d=a(this).data("draggable"),e=d.options;d.snapElements=[],a(e.snap.constructor!=String?e.snap.items||":data(draggable)":e.snap).each(function(){var b=a(this),c=b.offset();this!=d.element[0]&&d.snapElements.push({item:this,width:b.outerWidth(),height:b.outerHeight(),top:c.top,left:c.left})})},drag:function(b,c){var d=a(this).data("draggable"),e=d.options,f=e.snapTolerance,g=c.offset.left,h=g+d.helperProportions.width,i=c.offset.top,j=i+d.helperProportions.height;for(var k=d.snapElements.length-1;k>=0;k--){var l=d.snapElements[k].left,m=l+d.snapElements[k].width,n=d.snapElements[k].top,o=n+d.snapElements[k].height;if(!(l-f<g&&g<m+f&&n-f<i&&i<o+f||l-f<g&&g<m+f&&n-f<j&&j<o+f||l-f<h&&h<m+f&&n-f<i&&i<o+f||l-f<h&&h<m+f&&n-f<j&&j<o+f)){d.snapElements[k].snapping&&d.options.snap.release&&d.options.snap.release.call(d.element,b,a.extend(d._uiHash(),{snapItem:d.snapElements[k].item})),d.snapElements[k].snapping=!1;continue}if(e.snapMode!="inner"){var p=Math.abs(n-j)<=f,q=Math.abs(o-i)<=f,r=Math.abs(l-h)<=f,s=Math.abs(m-g)<=f;p&&(c.position.top=d._convertPositionTo("relative",{top:n-d.helperProportions.height,left:0}).top-d.margins.top),q&&(c.position.top=d._convertPositionTo("relative",{top:o,left:0}).top-d.margins.top),r&&(c.position.left=d._convertPositionTo("relative",{top:0,left:l-d.helperProportions.width}).left-d.margins.left),s&&(c.position.left=d._convertPositionTo("relative",{top:0,left:m}).left-d.margins.left)}var t=p||q||r||s;if(e.snapMode!="outer"){var p=Math.abs(n-i)<=f,q=Math.abs(o-j)<=f,r=Math.abs(l-g)<=f,s=Math.abs(m-h)<=f;p&&(c.position.top=d._convertPositionTo("relative",{top:n,left:0}).top-d.margins.top),q&&(c.position.top=d._convertPositionTo("relative",{top:o-d.helperProportions.height,left:0}).top-d.margins.top),r&&(c.position.left=d._convertPositionTo("relative",{top:0,left:l}).left-d.margins.left),s&&(c.position.left=d._convertPositionTo("relative",{top:0,left:m-d.helperProportions.width}).left-d.margins.left)}!d.snapElements[k].snapping&&(p||q||r||s||t)&&d.options.snap.snap&&d.options.snap.snap.call(d.element,b,a.extend(d._uiHash(),{snapItem:d.snapElements[k].item})),d.snapElements[k].snapping=p||q||r||s||t}}}),a.ui.plugin.add("draggable","stack",{start:function(b,c){var d=a(this).data("draggable").options,e=a.makeArray(a(d.stack)).sort(function(b,c){return(parseInt(a(b).css("zIndex"),10)||0)-(parseInt(a(c).css("zIndex"),10)||0)});if(!!e.length){var f=parseInt(e[0].style.zIndex)||0;a(e).each(function(a){this.style.zIndex=f+a}),this[0].style.zIndex=f+e.length}}}),a.ui.plugin.add("draggable","zIndex",{start:function(b,c){var d=a(c.helper),e=a(this).data("draggable").options;d.css("zIndex")&&(e._zIndex=d.css("zIndex")),d.css("zIndex",e.zIndex)},stop:function(b,c){var d=a(this).data("draggable").options;d._zIndex&&a(c.helper).css("zIndex",d._zIndex)}})})(jQuery);/*
+ * jQuery UI Droppable 1.8.17
+ *
+ * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * http://docs.jquery.com/UI/Droppables
+ *
+ * Depends:
+ *	jquery.ui.core.js
+ *	jquery.ui.widget.js
+ *	jquery.ui.mouse.js
+ *	jquery.ui.draggable.js
+ */(function(a,b){a.widget("ui.droppable",{widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect"},_create:function(){var b=this.options,c=b.accept;this.isover=0,this.isout=1,this.accept=a.isFunction(c)?c:function(a){return a.is(c)},this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight},a.ui.ddmanager.droppables[b.scope]=a.ui.ddmanager.droppables[b.scope]||[],a.ui.ddmanager.droppables[b.scope].push(this),b.addClasses&&this.element.addClass("ui-droppable")},destroy:function(){var b=a.ui.ddmanager.droppables[this.options.scope];for(var c=0;c<b.length;c++)b[c]==this&&b.splice(c,1);this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable");return this},_setOption:function(b,c){b=="accept"&&(this.accept=a.isFunction(c)?c:function(a){return a.is(c)}),a.Widget.prototype._setOption.apply(this,arguments)},_activate:function(b){var c=a.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass),c&&this._trigger("activate",b,this.ui(c))},_deactivate:function(b){var c=a.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass),c&&this._trigger("deactivate",b,this.ui(c))},_over:function(b){var c=a.ui.ddmanager.current;!!c&&(c.currentItem||c.element)[0]!=this.element[0]&&this.accept.call(this.element[0],c.currentItem||c.element)&&(this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",b,this.ui(c)))},_out:function(b){var c=a.ui.ddmanager.current;!!c&&(c.currentItem||c.element)[0]!=this.element[0]&&this.accept.call(this.element[0],c.currentItem||c.element)&&(this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",b,this.ui(c)))},_drop:function(b,c){var d=c||a.ui.ddmanager.current;if(!d||(d.currentItem||d.element)[0]==this.element[0])return!1;var e=!1;this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var b=a.data(this,"droppable");if(b.options.greedy&&!b.options.disabled&&b.options.scope==d.options.scope&&b.accept.call(b.element[0],d.currentItem||d.element)&&a.ui.intersect(d,a.extend(b,{offset:b.element.offset()}),b.options.tolerance)){e=!0;return!1}});if(e)return!1;if(this.accept.call(this.element[0],d.currentItem||d.element)){this.options.activeClass&&this.element.removeClass(this.options.activeClass),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("drop",b,this.ui(d));return this.element}return!1},ui:function(a){return{draggable:a.currentItem||a.element,helper:a.helper,position:a.position,offset:a.positionAbs}}}),a.extend(a.ui.droppable,{version:"1.8.17"}),a.ui.intersect=function(b,c,d){if(!c.offset)return!1;var e=(b.positionAbs||b.position.absolute).left,f=e+b.helperProportions.width,g=(b.positionAbs||b.position.absolute).top,h=g+b.helperProportions.height,i=c.offset.left,j=i+c.proportions.width,k=c.offset.top,l=k+c.proportions.height;switch(d){case"fit":return i<=e&&f<=j&&k<=g&&h<=l;case"intersect":return i<e+b.helperProportions.width/2&&f-b.helperProportions.width/2<j&&k<g+b.helperProportions.height/2&&h-b.helperProportions.height/2<l;case"pointer":var m=(b.positionAbs||b.position.absolute).left+(b.clickOffset||b.offset.click).left,n=(b.positionAbs||b.position.absolute).top+(b.clickOffset||b.offset.click).top,o=a.ui.isOver(n,m,k,i,c.proportions.height,c.proportions.width);return o;case"touch":return(g>=k&&g<=l||h>=k&&h<=l||g<k&&h>l)&&(e>=i&&e<=j||f>=i&&f<=j||e<i&&f>j);default:return!1}},a.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(b,c){var d=a.ui.ddmanager.droppables[b.options.scope]||[],e=c?c.type:null,f=(b.currentItem||b.element).find(":data(droppable)").andSelf();droppablesLoop:for(var g=0;g<d.length;g++){if(d[g].options.disabled||b&&!d[g].accept.call(d[g].element[0],b.currentItem||b.element))continue;for(var h=0;h<f.length;h++)if(f[h]==d[g].element[0]){d[g].proportions.height=0;continue droppablesLoop}d[g].visible=d[g].element.css("display")!="none";if(!d[g].visible)continue;e=="mousedown"&&d[g]._activate.call(d[g],c),d[g].offset=d[g].element.offset(),d[g].proportions={width:d[g].element[0].offsetWidth,height:d[g].element[0].offsetHeight}}},drop:function(b,c){var d=!1;a.each(a.ui.ddmanager.droppables[b.options.scope]||[],function(){!this.options||(!this.options.disabled&&this.visible&&a.ui.intersect(b,this,this.options.tolerance)&&(d=this._drop.call(this,c)||d),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],b.currentItem||b.element)&&(this.isout=1,this.isover=0,this._deactivate.call(this,c)))});return d},dragStart:function(b,c){b.element.parents(":not(body,html)").bind("scroll.droppable",function(){b.options.refreshPositions||a.ui.ddmanager.prepareOffsets(b,c)})},drag:function(b,c){b.options.refreshPositions&&a.ui.ddmanager.prepareOffsets(b,c),a.each(a.ui.ddmanager.droppables[b.options.scope]||[],function(){if(!(this.options.disabled||this.greedyChild||!this.visible)){var d=a.ui.intersect(b,this,this.options.tolerance),e=!d&&this.isover==1?"isout":d&&this.isover==0?"isover":null;if(!e)return;var f;if(this.options.greedy){var g=this.element.parents(":data(droppable):eq(0)");g.length&&(f=a.data(g[0],"droppable"),f.greedyChild=e=="isover"?1:0)}f&&e=="isover"&&(f.isover=0,f.isout=1,f._out.call(f,c)),this[e]=1,this[e=="isout"?"isover":"isout"]=0,this[e=="isover"?"_over":"_out"].call(this,c),f&&e=="isout"&&(f.isout=0,f.isover=1,f._over.call(f,c))}})},dragStop:function(b,c){b.element.parents(":not(body,html)").unbind("scroll.droppable"),b.options.refreshPositions||a.ui.ddmanager.prepareOffsets(b,c)}}})(jQuery);
\ No newline at end of file
diff --git a/pub/js/jquery/jstree/jquery.jstree.js b/pub/js/jquery/jstree/jquery.jstree.js
new file mode 100644
index 0000000000000000000000000000000000000000..2f7618c66d32baf113cacd22843431b3c0846135
--- /dev/null
+++ b/pub/js/jquery/jstree/jquery.jstree.js
@@ -0,0 +1,4551 @@
+/*
+ * jsTree 1.0-rc3
+ * http://jstree.com/
+ *
+ * Copyright (c) 2010 Ivan Bozhanov (vakata.com)
+ *
+ * Licensed same as jquery - under the terms of either the MIT License or the GPL Version 2 License
+ *   http://www.opensource.org/licenses/mit-license.php
+ *   http://www.gnu.org/licenses/gpl.html
+ *
+ * $Date: 2011-02-09 01:17:14 +0200 (ср, 09 февр 2011) $
+ * $Revision: 236 $
+ */
+
+/*jslint browser: true, onevar: true, undef: true, bitwise: true, strict: true */
+/*global window : false, clearInterval: false, clearTimeout: false, document: false, setInterval: false, setTimeout: false, jQuery: false, navigator: false, XSLTProcessor: false, DOMParser: false, XMLSerializer: false*/
+
+"use strict";
+
+// top wrapper to prevent multiple inclusion (is this OK?)
+(function () { if(jQuery && jQuery.jstree) { return; }
+	var is_ie6 = false, is_ie7 = false, is_ff2 = false;
+
+/* 
+ * jsTree core
+ */
+(function ($) {
+	// Common functions not related to jsTree 
+	// decided to move them to a `vakata` "namespace"
+	$.vakata = {};
+	// CSS related functions
+	$.vakata.css = {
+		get_css : function(rule_name, delete_flag, sheet) {
+			rule_name = rule_name.toLowerCase();
+			var css_rules = sheet.cssRules || sheet.rules,
+				j = 0;
+			do {
+				if(css_rules.length && j > css_rules.length + 5) { return false; }
+				if(css_rules[j].selectorText && css_rules[j].selectorText.toLowerCase() == rule_name) {
+					if(delete_flag === true) {
+						if(sheet.removeRule) { sheet.removeRule(j); }
+						if(sheet.deleteRule) { sheet.deleteRule(j); }
+						return true;
+					}
+					else { return css_rules[j]; }
+				}
+			}
+			while (css_rules[++j]);
+			return false;
+		},
+		add_css : function(rule_name, sheet) {
+			if($.jstree.css.get_css(rule_name, false, sheet)) { return false; }
+			if(sheet.insertRule) { sheet.insertRule(rule_name + ' { }', 0); } else { sheet.addRule(rule_name, null, 0); }
+			return $.vakata.css.get_css(rule_name);
+		},
+		remove_css : function(rule_name, sheet) { 
+			return $.vakata.css.get_css(rule_name, true, sheet); 
+		},
+		add_sheet : function(opts) {
+			var tmp = false, is_new = true;
+			if(opts.str) {
+				if(opts.title) { tmp = $("style[id='" + opts.title + "-stylesheet']")[0]; }
+				if(tmp) { is_new = false; }
+				else {
+					tmp = document.createElement("style");
+					tmp.setAttribute('type',"text/css");
+					if(opts.title) { tmp.setAttribute("id", opts.title + "-stylesheet"); }
+				}
+				if(tmp.styleSheet) {
+					if(is_new) { 
+						document.getElementsByTagName("head")[0].appendChild(tmp); 
+						tmp.styleSheet.cssText = opts.str; 
+					}
+					else {
+						tmp.styleSheet.cssText = tmp.styleSheet.cssText + " " + opts.str; 
+					}
+				}
+				else {
+					tmp.appendChild(document.createTextNode(opts.str));
+					document.getElementsByTagName("head")[0].appendChild(tmp);
+				}
+				return tmp.sheet || tmp.styleSheet;
+			}
+			if(opts.url) {
+				if(document.createStyleSheet) {
+					try { tmp = document.createStyleSheet(opts.url); } catch (e) { }
+				}
+				else {
+					tmp			= document.createElement('link');
+					tmp.rel		= 'stylesheet';
+					tmp.type	= 'text/css';
+					tmp.media	= "all";
+					tmp.href	= opts.url;
+					document.getElementsByTagName("head")[0].appendChild(tmp);
+					return tmp.styleSheet;
+				}
+			}
+		}
+	};
+
+	// private variables 
+	var instances = [],			// instance array (used by $.jstree.reference/create/focused)
+		focused_instance = -1,	// the index in the instance array of the currently focused instance
+		plugins = {},			// list of included plugins
+		prepared_move = {};		// for the move_node function
+
+	// jQuery plugin wrapper (thanks to jquery UI widget function)
+	$.fn.jstree = function (settings) {
+		var isMethodCall = (typeof settings == 'string'), // is this a method call like $().jstree("open_node")
+			args = Array.prototype.slice.call(arguments, 1), 
+			returnValue = this;
+
+		// if a method call execute the method on all selected instances
+		if(isMethodCall) {
+			if(settings.substring(0, 1) == '_') { return returnValue; }
+			this.each(function() {
+				var instance = instances[$.data(this, "jstree_instance_id")],
+					methodValue = (instance && $.isFunction(instance[settings])) ? instance[settings].apply(instance, args) : instance;
+					if(typeof methodValue !== "undefined" && (settings.indexOf("is_") === 0 || (methodValue !== true && methodValue !== false))) { returnValue = methodValue; return false; }
+			});
+		}
+		else {
+			this.each(function() {
+				// extend settings and allow for multiple hashes and $.data
+				var instance_id = $.data(this, "jstree_instance_id"),
+					a = [],
+					b = settings ? $.extend({}, true, settings) : {},
+					c = $(this), 
+					s = false, 
+					t = [];
+				a = a.concat(args);
+				if(c.data("jstree")) { a.push(c.data("jstree")); }
+				b = a.length ? $.extend.apply(null, [true, b].concat(a)) : b;
+
+				// if an instance already exists, destroy it first
+				if(typeof instance_id !== "undefined" && instances[instance_id]) { instances[instance_id].destroy(); }
+				// push a new empty object to the instances array
+				instance_id = parseInt(instances.push({}),10) - 1;
+				// store the jstree instance id to the container element
+				$.data(this, "jstree_instance_id", instance_id);
+				// clean up all plugins
+				b.plugins = $.isArray(b.plugins) ? b.plugins : $.jstree.defaults.plugins.slice();
+				b.plugins.unshift("core");
+				// only unique plugins
+				b.plugins = b.plugins.sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(",");
+
+				// extend defaults with passed data
+				s = $.extend(true, {}, $.jstree.defaults, b);
+				s.plugins = b.plugins;
+				$.each(plugins, function (i, val) { 
+					if($.inArray(i, s.plugins) === -1) { s[i] = null; delete s[i]; } 
+					else { t.push(i); }
+				});
+				s.plugins = t;
+
+				// push the new object to the instances array (at the same time set the default classes to the container) and init
+				instances[instance_id] = new $.jstree._instance(instance_id, $(this).addClass("jstree jstree-" + instance_id), s); 
+				// init all activated plugins for this instance
+				$.each(instances[instance_id]._get_settings().plugins, function (i, val) { instances[instance_id].data[val] = {}; });
+				$.each(instances[instance_id]._get_settings().plugins, function (i, val) { if(plugins[val]) { plugins[val].__init.apply(instances[instance_id]); } });
+				// initialize the instance
+				setTimeout(function() { if(instances[instance_id]) { instances[instance_id].init(); } }, 0);
+			});
+		}
+		// return the jquery selection (or if it was a method call that returned a value - the returned value)
+		return returnValue;
+	};
+	// object to store exposed functions and objects
+	$.jstree = {
+		defaults : {
+			plugins : []
+		},
+		_focused : function () { return instances[focused_instance] || null; },
+		_reference : function (needle) { 
+			// get by instance id
+			if(instances[needle]) { return instances[needle]; }
+			// get by DOM (if still no luck - return null
+			var o = $(needle); 
+			if(!o.length && typeof needle === "string") { o = $("#" + needle); }
+			if(!o.length) { return null; }
+			return instances[o.closest(".jstree").data("jstree_instance_id")] || null; 
+		},
+		_instance : function (index, container, settings) { 
+			// for plugins to store data in
+			this.data = { core : {} };
+			this.get_settings	= function () { return $.extend(true, {}, settings); };
+			this._get_settings	= function () { return settings; };
+			this.get_index		= function () { return index; };
+			this.get_container	= function () { return container; };
+			this.get_container_ul = function () { return container.children("ul:eq(0)"); };
+			this._set_settings	= function (s) { 
+				settings = $.extend(true, {}, settings, s);
+			};
+		},
+		_fn : { },
+		plugin : function (pname, pdata) {
+			pdata = $.extend({}, {
+				__init		: $.noop, 
+				__destroy	: $.noop,
+				_fn			: {},
+				defaults	: false
+			}, pdata);
+			plugins[pname] = pdata;
+
+			$.jstree.defaults[pname] = pdata.defaults;
+			$.each(pdata._fn, function (i, val) {
+				val.plugin		= pname;
+				val.old			= $.jstree._fn[i];
+				$.jstree._fn[i] = function () {
+					var rslt,
+						func = val,
+						args = Array.prototype.slice.call(arguments),
+						evnt = new $.Event("before.jstree"),
+						rlbk = false;
+
+					if(this.data.core.locked === true && i !== "unlock" && i !== "is_locked") { return; }
+
+					// Check if function belongs to the included plugins of this instance
+					do {
+						if(func && func.plugin && $.inArray(func.plugin, this._get_settings().plugins) !== -1) { break; }
+						func = func.old;
+					} while(func);
+					if(!func) { return; }
+
+					// context and function to trigger events, then finally call the function
+					if(i.indexOf("_") === 0) {
+						rslt = func.apply(this, args);
+					}
+					else {
+						rslt = this.get_container().triggerHandler(evnt, { "func" : i, "inst" : this, "args" : args, "plugin" : func.plugin });
+						if(rslt === false) { return; }
+						if(typeof rslt !== "undefined") { args = rslt; }
+
+						rslt = func.apply(
+							$.extend({}, this, { 
+								__callback : function (data) { 
+									this.get_container().triggerHandler( i + '.jstree', { "inst" : this, "args" : args, "rslt" : data, "rlbk" : rlbk });
+								},
+								__rollback : function () { 
+									rlbk = this.get_rollback();
+									return rlbk;
+								},
+								__call_old : function (replace_arguments) {
+									return func.old.apply(this, (replace_arguments ? Array.prototype.slice.call(arguments, 1) : args ) );
+								}
+							}), args);
+					}
+
+					// return the result
+					return rslt;
+				};
+				$.jstree._fn[i].old = val.old;
+				$.jstree._fn[i].plugin = pname;
+			});
+		},
+		rollback : function (rb) {
+			if(rb) {
+				if(!$.isArray(rb)) { rb = [ rb ]; }
+				$.each(rb, function (i, val) {
+					instances[val.i].set_rollback(val.h, val.d);
+				});
+			}
+		}
+	};
+	// set the prototype for all instances
+	$.jstree._fn = $.jstree._instance.prototype = {};
+
+	// load the css when DOM is ready
+	$(function() {
+		// code is copied from jQuery ($.browser is deprecated + there is a bug in IE)
+		var u = navigator.userAgent.toLowerCase(),
+			v = (u.match( /.+?(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
+			css_string = '' + 
+				'.jstree ul, .jstree li { display:block; margin:0 0 0 0; padding:0 0 0 0; list-style-type:none; } ' + 
+				'.jstree li { display:block; min-height:18px; line-height:18px; white-space:nowrap; margin-left:18px; min-width:18px; } ' + 
+				'.jstree-rtl li { margin-left:0; margin-right:18px; } ' + 
+				'.jstree > ul > li { margin-left:0px; } ' + 
+				'.jstree-rtl > ul > li { margin-right:0px; } ' + 
+				'.jstree ins { display:inline-block; text-decoration:none; width:18px; height:18px; margin:0 0 0 0; padding:0; } ' + 
+				'.jstree a { display:inline-block; line-height:16px; height:16px; color:black; white-space:nowrap; text-decoration:none; padding:1px 2px; margin:0; } ' + 
+				'.jstree a:focus { outline: none; } ' + 
+				'.jstree a > ins { height:16px; width:16px; } ' + 
+				'.jstree a > .jstree-icon { margin-right:3px; } ' + 
+				'.jstree-rtl a > .jstree-icon { margin-left:3px; margin-right:0; } ' + 
+				'li.jstree-open > ul { display:block; } ' + 
+				'li.jstree-closed > ul { display:none; } ';
+		// Correct IE 6 (does not support the > CSS selector)
+		if(/msie/.test(u) && parseInt(v, 10) == 6) { 
+			is_ie6 = true;
+
+			// fix image flicker and lack of caching
+			try {
+				document.execCommand("BackgroundImageCache", false, true);
+			} catch (err) { }
+
+			css_string += '' + 
+				'.jstree li { height:18px; margin-left:0; margin-right:0; } ' + 
+				'.jstree li li { margin-left:18px; } ' + 
+				'.jstree-rtl li li { margin-left:0px; margin-right:18px; } ' + 
+				'li.jstree-open ul { display:block; } ' + 
+				'li.jstree-closed ul { display:none !important; } ' + 
+				'.jstree li a { display:inline; border-width:0 !important; padding:0px 2px !important; } ' + 
+				'.jstree li a ins { height:16px; width:16px; margin-right:3px; } ' + 
+				'.jstree-rtl li a ins { margin-right:0px; margin-left:3px; } ';
+		}
+		// Correct IE 7 (shifts anchor nodes onhover)
+		if(/msie/.test(u) && parseInt(v, 10) == 7) { 
+			is_ie7 = true;
+			css_string += '.jstree li a { border-width:0 !important; padding:0px 2px !important; } ';
+		}
+		// correct ff2 lack of display:inline-block
+		if(!/compatible/.test(u) && /mozilla/.test(u) && parseFloat(v, 10) < 1.9) {
+			is_ff2 = true;
+			css_string += '' + 
+				'.jstree ins { display:-moz-inline-box; } ' + 
+				'.jstree li { line-height:12px; } ' + // WHY??
+				'.jstree a { display:-moz-inline-box; } ' + 
+				'.jstree .jstree-no-icons .jstree-checkbox { display:-moz-inline-stack !important; } ';
+				/* this shouldn't be here as it is theme specific */
+		}
+		// the default stylesheet
+		$.vakata.css.add_sheet({ str : css_string, title : "jstree" });
+	});
+
+	// core functions (open, close, create, update, delete)
+	$.jstree.plugin("core", {
+		__init : function () {
+			this.data.core.locked = false;
+			this.data.core.to_open = this.get_settings().core.initially_open;
+			this.data.core.to_load = this.get_settings().core.initially_load;
+		},
+		defaults : { 
+			html_titles	: false,
+			animation	: 500,
+			initially_open : [],
+			initially_load : [],
+			open_parents : true,
+			notify_plugins : true,
+			rtl			: false,
+			load_open	: false,
+			strings		: {
+				loading		: "Loading ...",
+				new_node	: "New node",
+				multiple_selection : "Multiple selection"
+			}
+		},
+		_fn : { 
+			init	: function () { 
+				this.set_focus(); 
+				if(this._get_settings().core.rtl) {
+					this.get_container().addClass("jstree-rtl").css("direction", "rtl");
+				}
+				this.get_container().html("<ul><li class='jstree-last jstree-leaf'><ins>&#160;</ins><a class='jstree-loading' href='#'><ins class='jstree-icon'>&#160;</ins>" + this._get_string("loading") + "</a></li></ul>");
+				this.data.core.li_height = this.get_container_ul().find("li.jstree-closed, li.jstree-leaf").eq(0).height() || 18;
+
+				this.get_container()
+					.delegate("li > ins", "click.jstree", $.proxy(function (event) {
+							var trgt = $(event.target);
+							// if(trgt.is("ins") && event.pageY - trgt.offset().top < this.data.core.li_height) { this.toggle_node(trgt); }
+							this.toggle_node(trgt);
+						}, this))
+					.bind("mousedown.jstree", $.proxy(function () { 
+							this.set_focus(); // This used to be setTimeout(set_focus,0) - why?
+						}, this))
+					.bind("dblclick.jstree", function (event) { 
+						var sel;
+						if(document.selection && document.selection.empty) { document.selection.empty(); }
+						else {
+							if(window.getSelection) {
+								sel = window.getSelection();
+								try { 
+									sel.removeAllRanges();
+									sel.collapse();
+								} catch (err) { }
+							}
+						}
+					});
+				if(this._get_settings().core.notify_plugins) {
+					this.get_container()
+						.bind("load_node.jstree", $.proxy(function (e, data) { 
+								var o = this._get_node(data.rslt.obj),
+									t = this;
+								if(o === -1) { o = this.get_container_ul(); }
+								if(!o.length) { return; }
+								o.find("li").each(function () {
+									var th = $(this);
+									if(th.data("jstree")) {
+										$.each(th.data("jstree"), function (plugin, values) {
+											if(t.data[plugin] && $.isFunction(t["_" + plugin + "_notify"])) {
+												t["_" + plugin + "_notify"].call(t, th, values);
+											}
+										});
+									}
+								});
+							}, this));
+				}
+				if(this._get_settings().core.load_open) {
+					this.get_container()
+						.bind("load_node.jstree", $.proxy(function (e, data) { 
+								var o = this._get_node(data.rslt.obj),
+									t = this;
+								if(o === -1) { o = this.get_container_ul(); }
+								if(!o.length) { return; }
+								o.find("li.jstree-open:not(:has(ul))").each(function () {
+									t.load_node(this, $.noop, $.noop);
+								});
+							}, this));
+				}
+				this.__callback();
+				this.load_node(-1, function () { this.loaded(); this.reload_nodes(); });
+			},
+			destroy	: function () { 
+				var i,
+					n = this.get_index(),
+					s = this._get_settings(),
+					_this = this;
+
+				$.each(s.plugins, function (i, val) {
+					try { plugins[val].__destroy.apply(_this); } catch(err) { }
+				});
+				this.__callback();
+				// set focus to another instance if this one is focused
+				if(this.is_focused()) { 
+					for(i in instances) { 
+						if(instances.hasOwnProperty(i) && i != n) { 
+							instances[i].set_focus(); 
+							break; 
+						} 
+					}
+				}
+				// if no other instance found
+				if(n === focused_instance) { focused_instance = -1; }
+				// remove all traces of jstree in the DOM (only the ones set using jstree*) and cleans all events
+				this.get_container()
+					.unbind(".jstree")
+					.undelegate(".jstree")
+					.removeData("jstree_instance_id")
+					.find("[class^='jstree']")
+						.andSelf()
+						.attr("class", function () { return this.className.replace(/jstree[^ ]*|$/ig,''); });
+				$(document)
+					.unbind(".jstree-" + n)
+					.undelegate(".jstree-" + n);
+				// remove the actual data
+				instances[n] = null;
+				delete instances[n];
+			},
+
+			_core_notify : function (n, data) {
+				if(data.opened) {
+					this.open_node(n, false, true);
+				}
+			},
+
+			lock : function () {
+				this.data.core.locked = true;
+				this.get_container().children("ul").addClass("jstree-locked").css("opacity","0.7");
+				this.__callback({});
+			},
+			unlock : function () {
+				this.data.core.locked = false;
+				this.get_container().children("ul").removeClass("jstree-locked").css("opacity","1");
+				this.__callback({});
+			},
+			is_locked : function () { return this.data.core.locked; },
+			save_opened : function () {
+				var _this = this;
+				this.data.core.to_open = [];
+				this.get_container_ul().find("li.jstree-open").each(function () { 
+					if(this.id) { _this.data.core.to_open.push("#" + this.id.toString().replace(/^#/,"").replace(/\\\//g,"/").replace(/\//g,"\\\/").replace(/\\\./g,".").replace(/\./g,"\\.").replace(/\:/g,"\\:")); }
+				});
+				this.__callback(_this.data.core.to_open);
+			},
+			save_loaded : function () { },
+			reload_nodes : function (is_callback) {
+				var _this = this,
+					done = true,
+					current = [],
+					remaining = [];
+				if(!is_callback) { 
+					this.data.core.reopen = false; 
+					this.data.core.refreshing = true; 
+					this.data.core.to_open = $.map($.makeArray(this.data.core.to_open), function (n) { return "#" + n.toString().replace(/^#/,"").replace(/\\\//g,"/").replace(/\//g,"\\\/").replace(/\\\./g,".").replace(/\./g,"\\.").replace(/\:/g,"\\:"); });
+					this.data.core.to_load = $.map($.makeArray(this.data.core.to_load), function (n) { return "#" + n.toString().replace(/^#/,"").replace(/\\\//g,"/").replace(/\//g,"\\\/").replace(/\\\./g,".").replace(/\./g,"\\.").replace(/\:/g,"\\:"); });
+					if(this.data.core.to_open.length) {
+						this.data.core.to_load = this.data.core.to_load.concat(this.data.core.to_open);
+					}
+				}
+				if(this.data.core.to_load.length) {
+					$.each(this.data.core.to_load, function (i, val) {
+						if(val == "#") { return true; }
+						if($(val).length) { current.push(val); }
+						else { remaining.push(val); }
+					});
+					if(current.length) {
+						this.data.core.to_load = remaining;
+						$.each(current, function (i, val) { 
+							if(!_this._is_loaded(val)) {
+								_this.load_node(val, function () { _this.reload_nodes(true); }, function () { _this.reload_nodes(true); });
+								done = false;
+							}
+						});
+					}
+				}
+				if(this.data.core.to_open.length) {
+					$.each(this.data.core.to_open, function (i, val) {
+						_this.open_node(val, false, true); 
+					});
+				}
+				if(done) { 
+					// TODO: find a more elegant approach to syncronizing returning requests
+					if(this.data.core.reopen) { clearTimeout(this.data.core.reopen); }
+					this.data.core.reopen = setTimeout(function () { _this.__callback({}, _this); }, 50);
+					this.data.core.refreshing = false;
+					this.reopen();
+				}
+			},
+			reopen : function () {
+				var _this = this;
+				if(this.data.core.to_open.length) {
+					$.each(this.data.core.to_open, function (i, val) {
+						_this.open_node(val, false, true); 
+					});
+				}
+				this.__callback({});
+			},
+			refresh : function (obj) {
+				var _this = this;
+				this.save_opened();
+				if(!obj) { obj = -1; }
+				obj = this._get_node(obj);
+				if(!obj) { obj = -1; }
+				if(obj !== -1) { obj.children("UL").remove(); }
+				else { this.get_container_ul().empty(); }
+				this.load_node(obj, function () { _this.__callback({ "obj" : obj}); _this.reload_nodes(); });
+			},
+			// Dummy function to fire after the first load (so that there is a jstree.loaded event)
+			loaded	: function () { 
+				this.__callback(); 
+			},
+			// deal with focus
+			set_focus	: function () { 
+				if(this.is_focused()) { return; }
+				var f = $.jstree._focused();
+				if(f) { f.unset_focus(); }
+
+				this.get_container().addClass("jstree-focused"); 
+				focused_instance = this.get_index(); 
+				this.__callback();
+			},
+			is_focused	: function () { 
+				return focused_instance == this.get_index(); 
+			},
+			unset_focus	: function () {
+				if(this.is_focused()) {
+					this.get_container().removeClass("jstree-focused"); 
+					focused_instance = -1; 
+				}
+				this.__callback();
+			},
+
+			// traverse
+			_get_node		: function (obj) { 
+				var $obj = $(obj, this.get_container()); 
+				if($obj.is(".jstree") || obj == -1) { return -1; } 
+				$obj = $obj.closest("li", this.get_container()); 
+				return $obj.length ? $obj : false; 
+			},
+			_get_next		: function (obj, strict) {
+				obj = this._get_node(obj);
+				if(obj === -1) { return this.get_container().find("> ul > li:first-child"); }
+				if(!obj.length) { return false; }
+				if(strict) { return (obj.nextAll("li").size() > 0) ? obj.nextAll("li:eq(0)") : false; }
+
+				if(obj.hasClass("jstree-open")) { return obj.find("li:eq(0)"); }
+				else if(obj.nextAll("li").size() > 0) { return obj.nextAll("li:eq(0)"); }
+				else { return obj.parentsUntil(".jstree","li").next("li").eq(0); }
+			},
+			_get_prev		: function (obj, strict) {
+				obj = this._get_node(obj);
+				if(obj === -1) { return this.get_container().find("> ul > li:last-child"); }
+				if(!obj.length) { return false; }
+				if(strict) { return (obj.prevAll("li").length > 0) ? obj.prevAll("li:eq(0)") : false; }
+
+				if(obj.prev("li").length) {
+					obj = obj.prev("li").eq(0);
+					while(obj.hasClass("jstree-open")) { obj = obj.children("ul:eq(0)").children("li:last"); }
+					return obj;
+				}
+				else { var o = obj.parentsUntil(".jstree","li:eq(0)"); return o.length ? o : false; }
+			},
+			_get_parent		: function (obj) {
+				obj = this._get_node(obj);
+				if(obj == -1 || !obj.length) { return false; }
+				var o = obj.parentsUntil(".jstree", "li:eq(0)");
+				return o.length ? o : -1;
+			},
+			_get_children	: function (obj) {
+				obj = this._get_node(obj);
+				if(obj === -1) { return this.get_container().children("ul:eq(0)").children("li"); }
+				if(!obj.length) { return false; }
+				return obj.children("ul:eq(0)").children("li");
+			},
+			get_path		: function (obj, id_mode) {
+				var p = [],
+					_this = this;
+				obj = this._get_node(obj);
+				if(obj === -1 || !obj || !obj.length) { return false; }
+				obj.parentsUntil(".jstree", "li").each(function () {
+					p.push( id_mode ? this.id : _this.get_text(this) );
+				});
+				p.reverse();
+				p.push( id_mode ? obj.attr("id") : this.get_text(obj) );
+				return p;
+			},
+
+			// string functions
+			_get_string : function (key) {
+				return this._get_settings().core.strings[key] || key;
+			},
+
+			is_open		: function (obj) { obj = this._get_node(obj); return obj && obj !== -1 && obj.hasClass("jstree-open"); },
+			is_closed	: function (obj) { obj = this._get_node(obj); return obj && obj !== -1 && obj.hasClass("jstree-closed"); },
+			is_leaf		: function (obj) { obj = this._get_node(obj); return obj && obj !== -1 && obj.hasClass("jstree-leaf"); },
+			correct_state	: function (obj) {
+				obj = this._get_node(obj);
+				if(!obj || obj === -1) { return false; }
+				obj.removeClass("jstree-closed jstree-open").addClass("jstree-leaf").children("ul").remove();
+				this.__callback({ "obj" : obj });
+			},
+			// open/close
+			open_node	: function (obj, callback, skip_animation) {
+				obj = this._get_node(obj);
+				if(!obj.length) { return false; }
+				if(!obj.hasClass("jstree-closed")) { if(callback) { callback.call(); } return false; }
+				var s = skip_animation || is_ie6 ? 0 : this._get_settings().core.animation,
+					t = this;
+				if(!this._is_loaded(obj)) {
+					obj.children("a").addClass("jstree-loading");
+					this.load_node(obj, function () { t.open_node(obj, callback, skip_animation); }, callback);
+				}
+				else {
+					if(this._get_settings().core.open_parents) {
+						obj.parentsUntil(".jstree",".jstree-closed").each(function () {
+							t.open_node(this, false, true);
+						});
+					}
+					if(s) { obj.children("ul").css("display","none"); }
+					obj.removeClass("jstree-closed").addClass("jstree-open").children("a").removeClass("jstree-loading");
+					if(s) { obj.children("ul").stop(true, true).slideDown(s, function () { this.style.display = ""; t.after_open(obj); }); }
+					else { t.after_open(obj); }
+					this.__callback({ "obj" : obj });
+					if(callback) { callback.call(); }
+				}
+			},
+			after_open	: function (obj) { this.__callback({ "obj" : obj }); },
+			close_node	: function (obj, skip_animation) {
+				obj = this._get_node(obj);
+				var s = skip_animation || is_ie6 ? 0 : this._get_settings().core.animation,
+					t = this;
+				if(!obj.length || !obj.hasClass("jstree-open")) { return false; }
+				if(s) { obj.children("ul").attr("style","display:block !important"); }
+				obj.removeClass("jstree-open").addClass("jstree-closed");
+				if(s) { obj.children("ul").stop(true, true).slideUp(s, function () { this.style.display = ""; t.after_close(obj); }); }
+				else { t.after_close(obj); }
+				this.__callback({ "obj" : obj });
+			},
+			after_close	: function (obj) { this.__callback({ "obj" : obj }); },
+			toggle_node	: function (obj) {
+				obj = this._get_node(obj);
+				if(obj.hasClass("jstree-closed")) { return this.open_node(obj); }
+				if(obj.hasClass("jstree-open")) { return this.close_node(obj); }
+			},
+			open_all	: function (obj, do_animation, original_obj) {
+				obj = obj ? this._get_node(obj) : -1;
+				if(!obj || obj === -1) { obj = this.get_container_ul(); }
+				if(original_obj) { 
+					obj = obj.find("li.jstree-closed");
+				}
+				else {
+					original_obj = obj;
+					if(obj.is(".jstree-closed")) { obj = obj.find("li.jstree-closed").andSelf(); }
+					else { obj = obj.find("li.jstree-closed"); }
+				}
+				var _this = this;
+				obj.each(function () { 
+					var __this = this; 
+					if(!_this._is_loaded(this)) { _this.open_node(this, function() { _this.open_all(__this, do_animation, original_obj); }, !do_animation); }
+					else { _this.open_node(this, false, !do_animation); }
+				});
+				// so that callback is fired AFTER all nodes are open
+				if(original_obj.find('li.jstree-closed').length === 0) { this.__callback({ "obj" : original_obj }); }
+			},
+			close_all	: function (obj, do_animation) {
+				var _this = this;
+				obj = obj ? this._get_node(obj) : this.get_container();
+				if(!obj || obj === -1) { obj = this.get_container_ul(); }
+				obj.find("li.jstree-open").andSelf().each(function () { _this.close_node(this, !do_animation); });
+				this.__callback({ "obj" : obj });
+			},
+			clean_node	: function (obj) {
+				obj = obj && obj != -1 ? $(obj) : this.get_container_ul();
+				obj = obj.is("li") ? obj.find("li").andSelf() : obj.find("li");
+				obj.removeClass("jstree-last")
+					.filter("li:last-child").addClass("jstree-last").end()
+					.filter(":has(li)")
+						.not(".jstree-open").removeClass("jstree-leaf").addClass("jstree-closed");
+				obj.not(".jstree-open, .jstree-closed").addClass("jstree-leaf").children("ul").remove();
+				this.__callback({ "obj" : obj });
+			},
+			// rollback
+			get_rollback : function () { 
+				this.__callback();
+				return { i : this.get_index(), h : this.get_container().children("ul").clone(true), d : this.data }; 
+			},
+			set_rollback : function (html, data) {
+				this.get_container().empty().append(html);
+				this.data = data;
+				this.__callback();
+			},
+			// Dummy functions to be overwritten by any datastore plugin included
+			load_node	: function (obj, s_call, e_call) { this.__callback({ "obj" : obj }); },
+			_is_loaded	: function (obj) { return true; },
+
+			// Basic operations: create
+			create_node	: function (obj, position, js, callback, is_loaded) {
+				obj = this._get_node(obj);
+				position = typeof position === "undefined" ? "last" : position;
+				var d = $("<li />"),
+					s = this._get_settings().core,
+					tmp;
+
+				if(obj !== -1 && !obj.length) { return false; }
+				if(!is_loaded && !this._is_loaded(obj)) { this.load_node(obj, function () { this.create_node(obj, position, js, callback, true); }); return false; }
+
+				this.__rollback();
+
+				if(typeof js === "string") { js = { "data" : js }; }
+				if(!js) { js = {}; }
+				if(js.attr) { d.attr(js.attr); }
+				if(js.metadata) { d.data(js.metadata); }
+				if(js.state) { d.addClass("jstree-" + js.state); }
+				if(!js.data) { js.data = this._get_string("new_node"); }
+				if(!$.isArray(js.data)) { tmp = js.data; js.data = []; js.data.push(tmp); }
+				$.each(js.data, function (i, m) {
+					tmp = $("<a />");
+					if($.isFunction(m)) { m = m.call(this, js); }
+					if(typeof m == "string") { tmp.attr('href','#')[ s.html_titles ? "html" : "text" ](m); }
+					else {
+						if(!m.attr) { m.attr = {}; }
+						if(!m.attr.href) { m.attr.href = '#'; }
+						tmp.attr(m.attr)[ s.html_titles ? "html" : "text" ](m.title);
+						if(m.language) { tmp.addClass(m.language); }
+					}
+					tmp.prepend("<ins class='jstree-icon'>&#160;</ins>");
+					if(!m.icon && js.icon) { m.icon = js.icon; }
+					if(m.icon) { 
+						if(m.icon.indexOf("/") === -1) { tmp.children("ins").addClass(m.icon); }
+						else { tmp.children("ins").css("background","url('" + m.icon + "') center center no-repeat"); }
+					}
+					d.append(tmp);
+				});
+				d.prepend("<ins class='jstree-icon'>&#160;</ins>");
+				if(obj === -1) {
+					obj = this.get_container();
+					if(position === "before") { position = "first"; }
+					if(position === "after") { position = "last"; }
+				}
+				switch(position) {
+					case "before": obj.before(d); tmp = this._get_parent(obj); break;
+					case "after" : obj.after(d);  tmp = this._get_parent(obj); break;
+					case "inside":
+					case "first" :
+						if(!obj.children("ul").length) { obj.append("<ul />"); }
+						obj.children("ul").prepend(d);
+						tmp = obj;
+						break;
+					case "last":
+						if(!obj.children("ul").length) { obj.append("<ul />"); }
+						obj.children("ul").append(d);
+						tmp = obj;
+						break;
+					default:
+						if(!obj.children("ul").length) { obj.append("<ul />"); }
+						if(!position) { position = 0; }
+						tmp = obj.children("ul").children("li").eq(position);
+						if(tmp.length) { tmp.before(d); }
+						else { obj.children("ul").append(d); }
+						tmp = obj;
+						break;
+				}
+				if(tmp === -1 || tmp.get(0) === this.get_container().get(0)) { tmp = -1; }
+				this.clean_node(tmp);
+				this.__callback({ "obj" : d, "parent" : tmp });
+				if(callback) { callback.call(this, d); }
+				return d;
+			},
+			// Basic operations: rename (deal with text)
+			get_text	: function (obj) {
+				obj = this._get_node(obj);
+				if(!obj.length) { return false; }
+				var s = this._get_settings().core.html_titles;
+				obj = obj.children("a:eq(0)");
+				if(s) {
+					obj = obj.clone();
+					obj.children("INS").remove();
+					return obj.html();
+				}
+				else {
+					obj = obj.contents().filter(function() { return this.nodeType == 3; })[0];
+					return obj.nodeValue;
+				}
+			},
+			set_text	: function (obj, val) {
+				obj = this._get_node(obj);
+				if(!obj.length) { return false; }
+				obj = obj.children("a:eq(0)");
+				if(this._get_settings().core.html_titles) {
+					var tmp = obj.children("INS").clone();
+					obj.html(val).prepend(tmp);
+					this.__callback({ "obj" : obj, "name" : val });
+					return true;
+				}
+				else {
+					obj = obj.contents().filter(function() { return this.nodeType == 3; })[0];
+					this.__callback({ "obj" : obj, "name" : val });
+					return (obj.nodeValue = val);
+				}
+			},
+			rename_node : function (obj, val) {
+				obj = this._get_node(obj);
+				this.__rollback();
+				if(obj && obj.length && this.set_text.apply(this, Array.prototype.slice.call(arguments))) { this.__callback({ "obj" : obj, "name" : val }); }
+			},
+			// Basic operations: deleting nodes
+			delete_node : function (obj) {
+				obj = this._get_node(obj);
+				if(!obj.length) { return false; }
+				this.__rollback();
+				var p = this._get_parent(obj), prev = $([]), t = this;
+				obj.each(function () {
+					prev = prev.add(t._get_prev(this));
+				});
+				obj = obj.detach();
+				if(p !== -1 && p.find("> ul > li").length === 0) {
+					p.removeClass("jstree-open jstree-closed").addClass("jstree-leaf");
+				}
+				this.clean_node(p);
+				this.__callback({ "obj" : obj, "prev" : prev, "parent" : p });
+				return obj;
+			},
+			prepare_move : function (o, r, pos, cb, is_cb) {
+				var p = {};
+
+				p.ot = $.jstree._reference(o) || this;
+				p.o = p.ot._get_node(o);
+				p.r = r === - 1 ? -1 : this._get_node(r);
+				p.p = (typeof pos === "undefined" || pos === false) ? "last" : pos; // TODO: move to a setting
+				if(!is_cb && prepared_move.o && prepared_move.o[0] === p.o[0] && prepared_move.r[0] === p.r[0] && prepared_move.p === p.p) {
+					this.__callback(prepared_move);
+					if(cb) { cb.call(this, prepared_move); }
+					return;
+				}
+				p.ot = $.jstree._reference(p.o) || this;
+				p.rt = $.jstree._reference(p.r) || this; // r === -1 ? p.ot : $.jstree._reference(p.r) || this
+				if(p.r === -1 || !p.r) {
+					p.cr = -1;
+					switch(p.p) {
+						case "first":
+						case "before":
+						case "inside":
+							p.cp = 0; 
+							break;
+						case "after":
+						case "last":
+							p.cp = p.rt.get_container().find(" > ul > li").length; 
+							break;
+						default:
+							p.cp = p.p;
+							break;
+					}
+				}
+				else {
+					if(!/^(before|after)$/.test(p.p) && !this._is_loaded(p.r)) {
+						return this.load_node(p.r, function () { this.prepare_move(o, r, pos, cb, true); });
+					}
+					switch(p.p) {
+						case "before":
+							p.cp = p.r.index();
+							p.cr = p.rt._get_parent(p.r);
+							break;
+						case "after":
+							p.cp = p.r.index() + 1;
+							p.cr = p.rt._get_parent(p.r);
+							break;
+						case "inside":
+						case "first":
+							p.cp = 0;
+							p.cr = p.r;
+							break;
+						case "last":
+							p.cp = p.r.find(" > ul > li").length; 
+							p.cr = p.r;
+							break;
+						default: 
+							p.cp = p.p;
+							p.cr = p.r;
+							break;
+					}
+				}
+				p.np = p.cr == -1 ? p.rt.get_container() : p.cr;
+				p.op = p.ot._get_parent(p.o);
+				p.cop = p.o.index();
+				if(p.op === -1) { p.op = p.ot ? p.ot.get_container() : this.get_container(); }
+				if(!/^(before|after)$/.test(p.p) && p.op && p.np && p.op[0] === p.np[0] && p.o.index() < p.cp) { p.cp++; }
+				//if(p.p === "before" && p.op && p.np && p.op[0] === p.np[0] && p.o.index() < p.cp) { p.cp--; }
+				p.or = p.np.find(" > ul > li:nth-child(" + (p.cp + 1) + ")");
+				prepared_move = p;
+				this.__callback(prepared_move);
+				if(cb) { cb.call(this, prepared_move); }
+			},
+			check_move : function () {
+				var obj = prepared_move, ret = true, r = obj.r === -1 ? this.get_container() : obj.r;
+				if(!obj || !obj.o || obj.or[0] === obj.o[0]) { return false; }
+				if(obj.op && obj.np && obj.op[0] === obj.np[0] && obj.cp - 1 === obj.o.index()) { return false; }
+				obj.o.each(function () { 
+					if(r.parentsUntil(".jstree", "li").andSelf().index(this) !== -1) { ret = false; return false; }
+				});
+				return ret;
+			},
+			move_node : function (obj, ref, position, is_copy, is_prepared, skip_check) {
+				if(!is_prepared) { 
+					return this.prepare_move(obj, ref, position, function (p) {
+						this.move_node(p, false, false, is_copy, true, skip_check);
+					});
+				}
+				if(is_copy) { 
+					prepared_move.cy = true;
+				}
+				if(!skip_check && !this.check_move()) { return false; }
+
+				this.__rollback();
+				var o = false;
+				if(is_copy) {
+					o = obj.o.clone(true);
+					o.find("*[id]").andSelf().each(function () {
+						if(this.id) { this.id = "copy_" + this.id; }
+					});
+				}
+				else { o = obj.o; }
+
+				if(obj.or.length) { obj.or.before(o); }
+				else { 
+					if(!obj.np.children("ul").length) { $("<ul />").appendTo(obj.np); }
+					obj.np.children("ul:eq(0)").append(o); 
+				}
+
+				try { 
+					obj.ot.clean_node(obj.op);
+					obj.rt.clean_node(obj.np);
+					if(!obj.op.find("> ul > li").length) {
+						obj.op.removeClass("jstree-open jstree-closed").addClass("jstree-leaf").children("ul").remove();
+					}
+				} catch (e) { }
+
+				if(is_copy) { 
+					prepared_move.cy = true;
+					prepared_move.oc = o; 
+				}
+				this.__callback(prepared_move);
+				return prepared_move;
+			},
+			_get_move : function () { return prepared_move; }
+		}
+	});
+})(jQuery);
+//*/
+
+/* 
+ * jsTree ui plugin
+ * This plugins handles selecting/deselecting/hovering/dehovering nodes
+ */
+(function ($) {
+	var scrollbar_width, e1, e2;
+	$(function() {
+		if (/msie/.test(navigator.userAgent.toLowerCase())) {
+			e1 = $('<textarea cols="10" rows="2"></textarea>').css({ position: 'absolute', top: -1000, left: 0 }).appendTo('body');
+			e2 = $('<textarea cols="10" rows="2" style="overflow: hidden;"></textarea>').css({ position: 'absolute', top: -1000, left: 0 }).appendTo('body');
+			scrollbar_width = e1.width() - e2.width();
+			e1.add(e2).remove();
+		} 
+		else {
+			e1 = $('<div />').css({ width: 100, height: 100, overflow: 'auto', position: 'absolute', top: -1000, left: 0 })
+					.prependTo('body').append('<div />').find('div').css({ width: '100%', height: 200 });
+			scrollbar_width = 100 - e1.width();
+			e1.parent().remove();
+		}
+	});
+	$.jstree.plugin("ui", {
+		__init : function () { 
+			this.data.ui.selected = $(); 
+			this.data.ui.last_selected = false; 
+			this.data.ui.hovered = null;
+			this.data.ui.to_select = this.get_settings().ui.initially_select;
+
+			this.get_container()
+				.delegate("a", "click.jstree", $.proxy(function (event) {
+						event.preventDefault();
+						event.currentTarget.blur();
+						if(!$(event.currentTarget).hasClass("jstree-loading")) {
+							this.select_node(event.currentTarget, true, event);
+						}
+					}, this))
+				.delegate("a", "mouseenter.jstree", $.proxy(function (event) {
+						if(!$(event.currentTarget).hasClass("jstree-loading")) {
+							this.hover_node(event.target);
+						}
+					}, this))
+				.delegate("a", "mouseleave.jstree", $.proxy(function (event) {
+						if(!$(event.currentTarget).hasClass("jstree-loading")) {
+							this.dehover_node(event.target);
+						}
+					}, this))
+				.bind("reopen.jstree", $.proxy(function () { 
+						this.reselect();
+					}, this))
+				.bind("get_rollback.jstree", $.proxy(function () { 
+						this.dehover_node();
+						this.save_selected();
+					}, this))
+				.bind("set_rollback.jstree", $.proxy(function () { 
+						this.reselect();
+					}, this))
+				.bind("close_node.jstree", $.proxy(function (event, data) { 
+						var s = this._get_settings().ui,
+							obj = this._get_node(data.rslt.obj),
+							clk = (obj && obj.length) ? obj.children("ul").find("a.jstree-clicked") : $(),
+							_this = this;
+						if(s.selected_parent_close === false || !clk.length) { return; }
+						clk.each(function () { 
+							_this.deselect_node(this);
+							if(s.selected_parent_close === "select_parent") { _this.select_node(obj); }
+						});
+					}, this))
+				.bind("delete_node.jstree", $.proxy(function (event, data) { 
+						var s = this._get_settings().ui.select_prev_on_delete,
+							obj = this._get_node(data.rslt.obj),
+							clk = (obj && obj.length) ? obj.find("a.jstree-clicked") : [],
+							_this = this;
+						clk.each(function () { _this.deselect_node(this); });
+						if(s && clk.length) { 
+							data.rslt.prev.each(function () { 
+								if(this.parentNode) { _this.select_node(this); return false; /* if return false is removed all prev nodes will be selected */}
+							});
+						}
+					}, this))
+				.bind("move_node.jstree", $.proxy(function (event, data) { 
+						if(data.rslt.cy) { 
+							data.rslt.oc.find("a.jstree-clicked").removeClass("jstree-clicked");
+						}
+					}, this));
+		},
+		defaults : {
+			select_limit : -1, // 0, 1, 2 ... or -1 for unlimited
+			select_multiple_modifier : "ctrl", // on, or ctrl, shift, alt
+			select_range_modifier : "shift",
+			selected_parent_close : "select_parent", // false, "deselect", "select_parent"
+			selected_parent_open : true,
+			select_prev_on_delete : true,
+			disable_selecting_children : false,
+			initially_select : []
+		},
+		_fn : { 
+			_get_node : function (obj, allow_multiple) {
+				if(typeof obj === "undefined" || obj === null) { return allow_multiple ? this.data.ui.selected : this.data.ui.last_selected; }
+				var $obj = $(obj, this.get_container()); 
+				if($obj.is(".jstree") || obj == -1) { return -1; } 
+				$obj = $obj.closest("li", this.get_container()); 
+				return $obj.length ? $obj : false; 
+			},
+			_ui_notify : function (n, data) {
+				if(data.selected) {
+					this.select_node(n, false);
+				}
+			},
+			save_selected : function () {
+				var _this = this;
+				this.data.ui.to_select = [];
+				this.data.ui.selected.each(function () { if(this.id) { _this.data.ui.to_select.push("#" + this.id.toString().replace(/^#/,"").replace(/\\\//g,"/").replace(/\//g,"\\\/").replace(/\\\./g,".").replace(/\./g,"\\.").replace(/\:/g,"\\:")); } });
+				this.__callback(this.data.ui.to_select);
+			},
+			reselect : function () {
+				var _this = this,
+					s = this.data.ui.to_select;
+				s = $.map($.makeArray(s), function (n) { return "#" + n.toString().replace(/^#/,"").replace(/\\\//g,"/").replace(/\//g,"\\\/").replace(/\\\./g,".").replace(/\./g,"\\.").replace(/\:/g,"\\:"); });
+				// this.deselect_all(); WHY deselect, breaks plugin state notifier?
+				$.each(s, function (i, val) { if(val && val !== "#") { _this.select_node(val); } });
+				this.data.ui.selected = this.data.ui.selected.filter(function () { return this.parentNode; });
+				this.__callback();
+			},
+			refresh : function (obj) {
+				this.save_selected();
+				return this.__call_old();
+			},
+			hover_node : function (obj) {
+				obj = this._get_node(obj);
+				if(!obj.length) { return false; }
+				//if(this.data.ui.hovered && obj.get(0) === this.data.ui.hovered.get(0)) { return; }
+				if(!obj.hasClass("jstree-hovered")) { this.dehover_node(); }
+				this.data.ui.hovered = obj.children("a").addClass("jstree-hovered").parent();
+				this._fix_scroll(obj);
+				this.__callback({ "obj" : obj });
+			},
+			dehover_node : function () {
+				var obj = this.data.ui.hovered, p;
+				if(!obj || !obj.length) { return false; }
+				p = obj.children("a").removeClass("jstree-hovered").parent();
+				if(this.data.ui.hovered[0] === p[0]) { this.data.ui.hovered = null; }
+				this.__callback({ "obj" : obj });
+			},
+			select_node : function (obj, check, e) {
+				obj = this._get_node(obj);
+				if(obj == -1 || !obj || !obj.length) { return false; }
+				var s = this._get_settings().ui,
+					is_multiple = (s.select_multiple_modifier == "on" || (s.select_multiple_modifier !== false && e && e[s.select_multiple_modifier + "Key"])),
+					is_range = (s.select_range_modifier !== false && e && e[s.select_range_modifier + "Key"] && this.data.ui.last_selected && this.data.ui.last_selected[0] !== obj[0] && this.data.ui.last_selected.parent()[0] === obj.parent()[0]),
+					is_selected = this.is_selected(obj),
+					proceed = true,
+					t = this;
+				if(check) {
+					if(s.disable_selecting_children && is_multiple && 
+						(
+							(obj.parentsUntil(".jstree","li").children("a.jstree-clicked").length) ||
+							(obj.children("ul").find("a.jstree-clicked:eq(0)").length)
+						)
+					) {
+						return false;
+					}
+					proceed = false;
+					switch(!0) {
+						case (is_range):
+							this.data.ui.last_selected.addClass("jstree-last-selected");
+							obj = obj[ obj.index() < this.data.ui.last_selected.index() ? "nextUntil" : "prevUntil" ](".jstree-last-selected").andSelf();
+							if(s.select_limit == -1 || obj.length < s.select_limit) {
+								this.data.ui.last_selected.removeClass("jstree-last-selected");
+								this.data.ui.selected.each(function () {
+									if(this !== t.data.ui.last_selected[0]) { t.deselect_node(this); }
+								});
+								is_selected = false;
+								proceed = true;
+							}
+							else {
+								proceed = false;
+							}
+							break;
+						case (is_selected && !is_multiple): 
+							this.deselect_all();
+							is_selected = false;
+							proceed = true;
+							break;
+						case (!is_selected && !is_multiple): 
+							if(s.select_limit == -1 || s.select_limit > 0) {
+								this.deselect_all();
+								proceed = true;
+							}
+							break;
+						case (is_selected && is_multiple): 
+							this.deselect_node(obj);
+							break;
+						case (!is_selected && is_multiple): 
+							if(s.select_limit == -1 || this.data.ui.selected.length + 1 <= s.select_limit) { 
+								proceed = true;
+							}
+							break;
+					}
+				}
+				if(proceed && !is_selected) {
+					if(!is_range) { this.data.ui.last_selected = obj; }
+					obj.children("a").addClass("jstree-clicked");
+					if(s.selected_parent_open) {
+						obj.parents(".jstree-closed").each(function () { t.open_node(this, false, true); });
+					}
+					this.data.ui.selected = this.data.ui.selected.add(obj);
+					this._fix_scroll(obj.eq(0));
+					this.__callback({ "obj" : obj, "e" : e });
+				}
+			},
+			_fix_scroll : function (obj) {
+				var c = this.get_container()[0], t;
+				if(c.scrollHeight > c.offsetHeight) {
+					obj = this._get_node(obj);
+					if(!obj || obj === -1 || !obj.length || !obj.is(":visible")) { return; }
+					t = obj.offset().top - this.get_container().offset().top;
+					if(t < 0) { 
+						c.scrollTop = c.scrollTop + t - 1; 
+					}
+					if(t + this.data.core.li_height + (c.scrollWidth > c.offsetWidth ? scrollbar_width : 0) > c.offsetHeight) { 
+						c.scrollTop = c.scrollTop + (t - c.offsetHeight + this.data.core.li_height + 1 + (c.scrollWidth > c.offsetWidth ? scrollbar_width : 0)); 
+					}
+				}
+			},
+			deselect_node : function (obj) {
+				obj = this._get_node(obj);
+				if(!obj.length) { return false; }
+				if(this.is_selected(obj)) {
+					obj.children("a").removeClass("jstree-clicked");
+					this.data.ui.selected = this.data.ui.selected.not(obj);
+					if(this.data.ui.last_selected.get(0) === obj.get(0)) { this.data.ui.last_selected = this.data.ui.selected.eq(0); }
+					this.__callback({ "obj" : obj });
+				}
+			},
+			toggle_select : function (obj) {
+				obj = this._get_node(obj);
+				if(!obj.length) { return false; }
+				if(this.is_selected(obj)) { this.deselect_node(obj); }
+				else { this.select_node(obj); }
+			},
+			is_selected : function (obj) { return this.data.ui.selected.index(this._get_node(obj)) >= 0; },
+			get_selected : function (context) { 
+				return context ? $(context).find("a.jstree-clicked").parent() : this.data.ui.selected; 
+			},
+			deselect_all : function (context) {
+				var ret = context ? $(context).find("a.jstree-clicked").parent() : this.get_container().find("a.jstree-clicked").parent();
+				ret.children("a.jstree-clicked").removeClass("jstree-clicked");
+				this.data.ui.selected = $([]);
+				this.data.ui.last_selected = false;
+				this.__callback({ "obj" : ret });
+			}
+		}
+	});
+	// include the selection plugin by default
+	$.jstree.defaults.plugins.push("ui");
+})(jQuery);
+//*/
+
+/* 
+ * jsTree CRRM plugin
+ * Handles creating/renaming/removing/moving nodes by user interaction.
+ */
+(function ($) {
+	$.jstree.plugin("crrm", { 
+		__init : function () {
+			this.get_container()
+				.bind("move_node.jstree", $.proxy(function (e, data) {
+					if(this._get_settings().crrm.move.open_onmove) {
+						var t = this;
+						data.rslt.np.parentsUntil(".jstree").andSelf().filter(".jstree-closed").each(function () {
+							t.open_node(this, false, true);
+						});
+					}
+				}, this));
+		},
+		defaults : {
+			input_width_limit : 200,
+			move : {
+				always_copy			: false, // false, true or "multitree"
+				open_onmove			: true,
+				default_position	: "last",
+				check_move			: function (m) { return true; }
+			}
+		},
+		_fn : {
+			_show_input : function (obj, callback) {
+				obj = this._get_node(obj);
+				var rtl = this._get_settings().core.rtl,
+					w = this._get_settings().crrm.input_width_limit,
+					w1 = obj.children("ins").width(),
+					w2 = obj.find("> a:visible > ins").width() * obj.find("> a:visible > ins").length,
+					t = this.get_text(obj),
+					h1 = $("<div />", { css : { "position" : "absolute", "top" : "-200px", "left" : (rtl ? "0px" : "-1000px"), "visibility" : "hidden" } }).appendTo("body"),
+					h2 = obj.css("position","relative").append(
+					$("<input />", { 
+						"value" : t,
+						"class" : "jstree-rename-input",
+						// "size" : t.length,
+						"css" : {
+							"padding" : "0",
+							"border" : "1px solid silver",
+							"position" : "absolute",
+							"left"  : (rtl ? "auto" : (w1 + w2 + 4) + "px"),
+							"right" : (rtl ? (w1 + w2 + 4) + "px" : "auto"),
+							"top" : "0px",
+							"height" : (this.data.core.li_height - 2) + "px",
+							"lineHeight" : (this.data.core.li_height - 2) + "px",
+							"width" : "150px" // will be set a bit further down
+						},
+						"blur" : $.proxy(function () {
+							var i = obj.children(".jstree-rename-input"),
+								v = i.val();
+							if(v === "") { v = t; }
+							h1.remove();
+							i.remove(); // rollback purposes
+							this.set_text(obj,t); // rollback purposes
+							this.rename_node(obj, v);
+							callback.call(this, obj, v, t);
+							obj.css("position","");
+						}, this),
+						"keyup" : function (event) {
+							var key = event.keyCode || event.which;
+							if(key == 27) { this.value = t; this.blur(); return; }
+							else if(key == 13) { this.blur(); return; }
+							else {
+								h2.width(Math.min(h1.text("pW" + this.value).width(),w));
+							}
+						},
+						"keypress" : function(event) {
+							var key = event.keyCode || event.which;
+							if(key == 13) { return false; }
+						}
+					})
+				).children(".jstree-rename-input"); 
+				this.set_text(obj, "");
+				h1.css({
+						fontFamily		: h2.css('fontFamily')		|| '',
+						fontSize		: h2.css('fontSize')		|| '',
+						fontWeight		: h2.css('fontWeight')		|| '',
+						fontStyle		: h2.css('fontStyle')		|| '',
+						fontStretch		: h2.css('fontStretch')		|| '',
+						fontVariant		: h2.css('fontVariant')		|| '',
+						letterSpacing	: h2.css('letterSpacing')	|| '',
+						wordSpacing		: h2.css('wordSpacing')		|| ''
+				});
+				h2.width(Math.min(h1.text("pW" + h2[0].value).width(),w))[0].select();
+			},
+			rename : function (obj) {
+				obj = this._get_node(obj);
+				this.__rollback();
+				var f = this.__callback;
+				this._show_input(obj, function (obj, new_name, old_name) { 
+					f.call(this, { "obj" : obj, "new_name" : new_name, "old_name" : old_name });
+				});
+			},
+			create : function (obj, position, js, callback, skip_rename) {
+				var t, _this = this;
+				obj = this._get_node(obj);
+				if(!obj) { obj = -1; }
+				this.__rollback();
+				t = this.create_node(obj, position, js, function (t) {
+					var p = this._get_parent(t),
+						pos = $(t).index();
+					if(callback) { callback.call(this, t); }
+					if(p.length && p.hasClass("jstree-closed")) { this.open_node(p, false, true); }
+					if(!skip_rename) { 
+						this._show_input(t, function (obj, new_name, old_name) { 
+							_this.__callback({ "obj" : obj, "name" : new_name, "parent" : p, "position" : pos });
+						});
+					}
+					else { _this.__callback({ "obj" : t, "name" : this.get_text(t), "parent" : p, "position" : pos }); }
+				});
+				return t;
+			},
+			remove : function (obj) {
+				obj = this._get_node(obj, true);
+				var p = this._get_parent(obj), prev = this._get_prev(obj);
+				this.__rollback();
+				obj = this.delete_node(obj);
+				if(obj !== false) { this.__callback({ "obj" : obj, "prev" : prev, "parent" : p }); }
+			},
+			check_move : function () {
+				if(!this.__call_old()) { return false; }
+				var s = this._get_settings().crrm.move;
+				if(!s.check_move.call(this, this._get_move())) { return false; }
+				return true;
+			},
+			move_node : function (obj, ref, position, is_copy, is_prepared, skip_check) {
+				var s = this._get_settings().crrm.move;
+				if(!is_prepared) { 
+					if(typeof position === "undefined") { position = s.default_position; }
+					if(position === "inside" && !s.default_position.match(/^(before|after)$/)) { position = s.default_position; }
+					return this.__call_old(true, obj, ref, position, is_copy, false, skip_check);
+				}
+				// if the move is already prepared
+				if(s.always_copy === true || (s.always_copy === "multitree" && obj.rt.get_index() !== obj.ot.get_index() )) {
+					is_copy = true;
+				}
+				this.__call_old(true, obj, ref, position, is_copy, true, skip_check);
+			},
+
+			cut : function (obj) {
+				obj = this._get_node(obj, true);
+				if(!obj || !obj.length) { return false; }
+				this.data.crrm.cp_nodes = false;
+				this.data.crrm.ct_nodes = obj;
+				this.__callback({ "obj" : obj });
+			},
+			copy : function (obj) {
+				obj = this._get_node(obj, true);
+				if(!obj || !obj.length) { return false; }
+				this.data.crrm.ct_nodes = false;
+				this.data.crrm.cp_nodes = obj;
+				this.__callback({ "obj" : obj });
+			},
+			paste : function (obj) { 
+				obj = this._get_node(obj);
+				if(!obj || !obj.length) { return false; }
+				var nodes = this.data.crrm.ct_nodes ? this.data.crrm.ct_nodes : this.data.crrm.cp_nodes;
+				if(!this.data.crrm.ct_nodes && !this.data.crrm.cp_nodes) { return false; }
+				if(this.data.crrm.ct_nodes) { this.move_node(this.data.crrm.ct_nodes, obj); this.data.crrm.ct_nodes = false; }
+				if(this.data.crrm.cp_nodes) { this.move_node(this.data.crrm.cp_nodes, obj, false, true); }
+				this.__callback({ "obj" : obj, "nodes" : nodes });
+			}
+		}
+	});
+	// include the crr plugin by default
+	// $.jstree.defaults.plugins.push("crrm");
+})(jQuery);
+//*/
+
+/* 
+ * jsTree themes plugin
+ * Handles loading and setting themes, as well as detecting path to themes, etc.
+ */
+(function ($) {
+	var themes_loaded = [];
+	// this variable stores the path to the themes folder - if left as false - it will be autodetected
+	$.jstree._themes = false;
+	$.jstree.plugin("themes", {
+		__init : function () { 
+			this.get_container()
+				.bind("init.jstree", $.proxy(function () {
+						var s = this._get_settings().themes;
+						this.data.themes.dots = s.dots; 
+						this.data.themes.icons = s.icons; 
+						this.set_theme(s.theme, s.url);
+					}, this))
+				.bind("loaded.jstree", $.proxy(function () {
+						// bound here too, as simple HTML tree's won't honor dots & icons otherwise
+						if(!this.data.themes.dots) { this.hide_dots(); }
+						else { this.show_dots(); }
+						if(!this.data.themes.icons) { this.hide_icons(); }
+						else { this.show_icons(); }
+					}, this));
+		},
+		defaults : { 
+			theme : "default", 
+			url : false,
+			dots : true,
+			icons : true
+		},
+		_fn : {
+			set_theme : function (theme_name, theme_url) {
+				if(!theme_name) { return false; }
+				if(!theme_url) { theme_url = $.jstree._themes + theme_name + '/style.css'; }
+				if($.inArray(theme_url, themes_loaded) == -1) {
+					$.vakata.css.add_sheet({ "url" : theme_url });
+					themes_loaded.push(theme_url);
+				}
+				if(this.data.themes.theme != theme_name) {
+					this.get_container().removeClass('jstree-' + this.data.themes.theme);
+					this.data.themes.theme = theme_name;
+				}
+				this.get_container().addClass('jstree-' + theme_name);
+				if(!this.data.themes.dots) { this.hide_dots(); }
+				else { this.show_dots(); }
+				if(!this.data.themes.icons) { this.hide_icons(); }
+				else { this.show_icons(); }
+				this.__callback();
+			},
+			get_theme	: function () { return this.data.themes.theme; },
+
+			show_dots	: function () { this.data.themes.dots = true; this.get_container().children("ul").removeClass("jstree-no-dots"); },
+			hide_dots	: function () { this.data.themes.dots = false; this.get_container().children("ul").addClass("jstree-no-dots"); },
+			toggle_dots	: function () { if(this.data.themes.dots) { this.hide_dots(); } else { this.show_dots(); } },
+
+			show_icons	: function () { this.data.themes.icons = true; this.get_container().children("ul").removeClass("jstree-no-icons"); },
+			hide_icons	: function () { this.data.themes.icons = false; this.get_container().children("ul").addClass("jstree-no-icons"); },
+			toggle_icons: function () { if(this.data.themes.icons) { this.hide_icons(); } else { this.show_icons(); } }
+		}
+	});
+	// autodetect themes path
+	$(function () {
+		if($.jstree._themes === false) {
+			$("script").each(function () { 
+				if(this.src.toString().match(/jquery\.jstree[^\/]*?\.js(\?.*)?$/)) { 
+					$.jstree._themes = this.src.toString().replace(/jquery\.jstree[^\/]*?\.js(\?.*)?$/, "") + 'themes/'; 
+					return false; 
+				}
+			});
+		}
+		if($.jstree._themes === false) { $.jstree._themes = "themes/"; }
+	});
+	// include the themes plugin by default
+	$.jstree.defaults.plugins.push("themes");
+})(jQuery);
+//*/
+
+/*
+ * jsTree hotkeys plugin
+ * Enables keyboard navigation for all tree instances
+ * Depends on the jstree ui & jquery hotkeys plugins
+ */
+(function ($) {
+	var bound = [];
+	function exec(i, event) {
+		var f = $.jstree._focused(), tmp;
+		if(f && f.data && f.data.hotkeys && f.data.hotkeys.enabled) { 
+			tmp = f._get_settings().hotkeys[i];
+			if(tmp) { return tmp.call(f, event); }
+		}
+	}
+	$.jstree.plugin("hotkeys", {
+		__init : function () {
+			if(typeof $.hotkeys === "undefined") { throw "jsTree hotkeys: jQuery hotkeys plugin not included."; }
+			if(!this.data.ui) { throw "jsTree hotkeys: jsTree UI plugin not included."; }
+			$.each(this._get_settings().hotkeys, function (i, v) {
+				if(v !== false && $.inArray(i, bound) == -1) {
+					$(document).bind("keydown", i, function (event) { return exec(i, event); });
+					bound.push(i);
+				}
+			});
+			this.get_container()
+				.bind("lock.jstree", $.proxy(function () {
+						if(this.data.hotkeys.enabled) { this.data.hotkeys.enabled = false; this.data.hotkeys.revert = true; }
+					}, this))
+				.bind("unlock.jstree", $.proxy(function () {
+						if(this.data.hotkeys.revert) { this.data.hotkeys.enabled = true; }
+					}, this));
+			this.enable_hotkeys();
+		},
+		defaults : {
+			"up" : function () { 
+				var o = this.data.ui.hovered || this.data.ui.last_selected || -1;
+				this.hover_node(this._get_prev(o));
+				return false; 
+			},
+			"ctrl+up" : function () { 
+				var o = this.data.ui.hovered || this.data.ui.last_selected || -1;
+				this.hover_node(this._get_prev(o));
+				return false; 
+			},
+			"shift+up" : function () { 
+				var o = this.data.ui.hovered || this.data.ui.last_selected || -1;
+				this.hover_node(this._get_prev(o));
+				return false; 
+			},
+			"down" : function () { 
+				var o = this.data.ui.hovered || this.data.ui.last_selected || -1;
+				this.hover_node(this._get_next(o));
+				return false;
+			},
+			"ctrl+down" : function () { 
+				var o = this.data.ui.hovered || this.data.ui.last_selected || -1;
+				this.hover_node(this._get_next(o));
+				return false;
+			},
+			"shift+down" : function () { 
+				var o = this.data.ui.hovered || this.data.ui.last_selected || -1;
+				this.hover_node(this._get_next(o));
+				return false;
+			},
+			"left" : function () { 
+				var o = this.data.ui.hovered || this.data.ui.last_selected;
+				if(o) {
+					if(o.hasClass("jstree-open")) { this.close_node(o); }
+					else { this.hover_node(this._get_prev(o)); }
+				}
+				return false;
+			},
+			"ctrl+left" : function () { 
+				var o = this.data.ui.hovered || this.data.ui.last_selected;
+				if(o) {
+					if(o.hasClass("jstree-open")) { this.close_node(o); }
+					else { this.hover_node(this._get_prev(o)); }
+				}
+				return false;
+			},
+			"shift+left" : function () { 
+				var o = this.data.ui.hovered || this.data.ui.last_selected;
+				if(o) {
+					if(o.hasClass("jstree-open")) { this.close_node(o); }
+					else { this.hover_node(this._get_prev(o)); }
+				}
+				return false;
+			},
+			"right" : function () { 
+				var o = this.data.ui.hovered || this.data.ui.last_selected;
+				if(o && o.length) {
+					if(o.hasClass("jstree-closed")) { this.open_node(o); }
+					else { this.hover_node(this._get_next(o)); }
+				}
+				return false;
+			},
+			"ctrl+right" : function () { 
+				var o = this.data.ui.hovered || this.data.ui.last_selected;
+				if(o && o.length) {
+					if(o.hasClass("jstree-closed")) { this.open_node(o); }
+					else { this.hover_node(this._get_next(o)); }
+				}
+				return false;
+			},
+			"shift+right" : function () { 
+				var o = this.data.ui.hovered || this.data.ui.last_selected;
+				if(o && o.length) {
+					if(o.hasClass("jstree-closed")) { this.open_node(o); }
+					else { this.hover_node(this._get_next(o)); }
+				}
+				return false;
+			},
+			"space" : function () { 
+				if(this.data.ui.hovered) { this.data.ui.hovered.children("a:eq(0)").click(); } 
+				return false; 
+			},
+			"ctrl+space" : function (event) { 
+				event.type = "click";
+				if(this.data.ui.hovered) { this.data.ui.hovered.children("a:eq(0)").trigger(event); } 
+				return false; 
+			},
+			"shift+space" : function (event) { 
+				event.type = "click";
+				if(this.data.ui.hovered) { this.data.ui.hovered.children("a:eq(0)").trigger(event); } 
+				return false; 
+			},
+			"f2" : function () { this.rename(this.data.ui.hovered || this.data.ui.last_selected); },
+			"del" : function () { this.remove(this.data.ui.hovered || this._get_node(null)); }
+		},
+		_fn : {
+			enable_hotkeys : function () {
+				this.data.hotkeys.enabled = true;
+			},
+			disable_hotkeys : function () {
+				this.data.hotkeys.enabled = false;
+			}
+		}
+	});
+})(jQuery);
+//*/
+
+/* 
+ * jsTree JSON plugin
+ * The JSON data store. Datastores are build by overriding the `load_node` and `_is_loaded` functions.
+ */
+(function ($) {
+	$.jstree.plugin("json_data", {
+		__init : function() {
+			var s = this._get_settings().json_data;
+			if(s.progressive_unload) {
+				this.get_container().bind("after_close.jstree", function (e, data) {
+					data.rslt.obj.children("ul").remove();
+				});
+			}
+		},
+		defaults : { 
+			// `data` can be a function:
+			//  * accepts two arguments - node being loaded and a callback to pass the result to
+			//  * will be executed in the current tree's scope & ajax won't be supported
+			data : false, 
+			ajax : false,
+			correct_state : true,
+			progressive_render : false,
+			progressive_unload : false
+		},
+		_fn : {
+			load_node : function (obj, s_call, e_call) { var _this = this; this.load_node_json(obj, function () { _this.__callback({ "obj" : _this._get_node(obj) }); s_call.call(this); }, e_call); },
+			_is_loaded : function (obj) { 
+				var s = this._get_settings().json_data;
+				obj = this._get_node(obj); 
+				return obj == -1 || !obj || (!s.ajax && !s.progressive_render && !$.isFunction(s.data)) || obj.is(".jstree-open, .jstree-leaf") || obj.children("ul").children("li").length > 0;
+			},
+			refresh : function (obj) {
+				obj = this._get_node(obj);
+				var s = this._get_settings().json_data;
+				if(obj && obj !== -1 && s.progressive_unload && ($.isFunction(s.data) || !!s.ajax)) {
+					obj.removeData("jstree_children");
+				}
+				return this.__call_old();
+			},
+			load_node_json : function (obj, s_call, e_call) {
+				var s = this.get_settings().json_data, d,
+					error_func = function () {},
+					success_func = function () {};
+				obj = this._get_node(obj);
+
+				if(obj && obj !== -1 && (s.progressive_render || s.progressive_unload) && !obj.is(".jstree-open, .jstree-leaf") && obj.children("ul").children("li").length === 0 && obj.data("jstree_children")) {
+					d = this._parse_json(obj.data("jstree_children"), obj);
+					if(d) {
+						obj.append(d);
+						if(!s.progressive_unload) { obj.removeData("jstree_children"); }
+					}
+					this.clean_node(obj);
+					if(s_call) { s_call.call(this); }
+					return;
+				}
+
+				if(obj && obj !== -1) {
+					if(obj.data("jstree_is_loading")) { return; }
+					else { obj.data("jstree_is_loading",true); }
+				}
+				switch(!0) {
+					case (!s.data && !s.ajax): throw "Neither data nor ajax settings supplied.";
+					// function option added here for easier model integration (also supporting async - see callback)
+					case ($.isFunction(s.data)):
+						s.data.call(this, obj, $.proxy(function (d) {
+							d = this._parse_json(d, obj);
+							if(!d) { 
+								if(obj === -1 || !obj) {
+									if(s.correct_state) { this.get_container().children("ul").empty(); }
+								}
+								else {
+									obj.children("a.jstree-loading").removeClass("jstree-loading");
+									obj.removeData("jstree_is_loading");
+									if(s.correct_state) { this.correct_state(obj); }
+								}
+								if(e_call) { e_call.call(this); }
+							}
+							else {
+								if(obj === -1 || !obj) { this.get_container().children("ul").empty().append(d.children()); }
+								else { obj.append(d).children("a.jstree-loading").removeClass("jstree-loading"); obj.removeData("jstree_is_loading"); }
+								this.clean_node(obj);
+								if(s_call) { s_call.call(this); }
+							}
+						}, this));
+						break;
+					case (!!s.data && !s.ajax) || (!!s.data && !!s.ajax && (!obj || obj === -1)):
+						if(!obj || obj == -1) {
+							d = this._parse_json(s.data, obj);
+							if(d) {
+								this.get_container().children("ul").empty().append(d.children());
+								this.clean_node();
+							}
+							else { 
+								if(s.correct_state) { this.get_container().children("ul").empty(); }
+							}
+						}
+						if(s_call) { s_call.call(this); }
+						break;
+					case (!s.data && !!s.ajax) || (!!s.data && !!s.ajax && obj && obj !== -1):
+						error_func = function (x, t, e) {
+							var ef = this.get_settings().json_data.ajax.error; 
+							if(ef) { ef.call(this, x, t, e); }
+							if(obj != -1 && obj.length) {
+								obj.children("a.jstree-loading").removeClass("jstree-loading");
+								obj.removeData("jstree_is_loading");
+								if(t === "success" && s.correct_state) { this.correct_state(obj); }
+							}
+							else {
+								if(t === "success" && s.correct_state) { this.get_container().children("ul").empty(); }
+							}
+							if(e_call) { e_call.call(this); }
+						};
+						success_func = function (d, t, x) {
+							var sf = this.get_settings().json_data.ajax.success; 
+							if(sf) { d = sf.call(this,d,t,x) || d; }
+							if(d === "" || (d && d.toString && d.toString().replace(/^[\s\n]+$/,"") === "") || (!$.isArray(d) && !$.isPlainObject(d))) {
+								return error_func.call(this, x, t, "");
+							}
+							d = this._parse_json(d, obj);
+							if(d) {
+								if(obj === -1 || !obj) { this.get_container().children("ul").empty().append(d.children()); }
+								else { obj.append(d).children("a.jstree-loading").removeClass("jstree-loading"); obj.removeData("jstree_is_loading"); }
+								this.clean_node(obj);
+								if(s_call) { s_call.call(this); }
+							}
+							else {
+								if(obj === -1 || !obj) {
+									if(s.correct_state) { 
+										this.get_container().children("ul").empty(); 
+										if(s_call) { s_call.call(this); }
+									}
+								}
+								else {
+									obj.children("a.jstree-loading").removeClass("jstree-loading");
+									obj.removeData("jstree_is_loading");
+									if(s.correct_state) { 
+										this.correct_state(obj);
+										if(s_call) { s_call.call(this); } 
+									}
+								}
+							}
+						};
+						s.ajax.context = this;
+						s.ajax.error = error_func;
+						s.ajax.success = success_func;
+						if(!s.ajax.dataType) { s.ajax.dataType = "json"; }
+						if($.isFunction(s.ajax.url)) { s.ajax.url = s.ajax.url.call(this, obj); }
+						if($.isFunction(s.ajax.data)) { s.ajax.data = s.ajax.data.call(this, obj); }
+						$.ajax(s.ajax);
+						break;
+				}
+			},
+			_parse_json : function (js, obj, is_callback) {
+				var d = false, 
+					p = this._get_settings(),
+					s = p.json_data,
+					t = p.core.html_titles,
+					tmp, i, j, ul1, ul2;
+
+				if(!js) { return d; }
+				if(s.progressive_unload && obj && obj !== -1) { 
+					obj.data("jstree_children", d);
+				}
+				if($.isArray(js)) {
+					d = $();
+					if(!js.length) { return false; }
+					for(i = 0, j = js.length; i < j; i++) {
+						tmp = this._parse_json(js[i], obj, true);
+						if(tmp.length) { d = d.add(tmp); }
+					}
+				}
+				else {
+					if(typeof js == "string") { js = { data : js }; }
+					if(!js.data && js.data !== "") { return d; }
+					d = $("<li />");
+					if(js.attr) { d.attr(js.attr); }
+					if(js.metadata) { d.data(js.metadata); }
+					if(js.state) { d.addClass("jstree-" + js.state); }
+					if(!$.isArray(js.data)) { tmp = js.data; js.data = []; js.data.push(tmp); }
+					$.each(js.data, function (i, m) {
+						tmp = $("<a />");
+						if($.isFunction(m)) { m = m.call(this, js); }
+						if(typeof m == "string") { tmp.attr('href','#')[ t ? "html" : "text" ](m); }
+						else {
+							if(!m.attr) { m.attr = {}; }
+							if(!m.attr.href) { m.attr.href = '#'; }
+							tmp.attr(m.attr)[ t ? "html" : "text" ](m.title);
+							if(m.language) { tmp.addClass(m.language); }
+						}
+						tmp.prepend("<ins class='jstree-icon'>&#160;</ins>");
+						if(!m.icon && js.icon) { m.icon = js.icon; }
+						if(m.icon) { 
+							if(m.icon.indexOf("/") === -1) { tmp.children("ins").addClass(m.icon); }
+							else { tmp.children("ins").css("background","url('" + m.icon + "') center center no-repeat"); }
+						}
+						d.append(tmp);
+					});
+					d.prepend("<ins class='jstree-icon'>&#160;</ins>");
+					if(js.children) { 
+						if(s.progressive_render && js.state !== "open") {
+							d.addClass("jstree-closed").data("jstree_children", js.children);
+						}
+						else {
+							if(s.progressive_unload) { d.data("jstree_children", js.children); }
+							if($.isArray(js.children) && js.children.length) {
+								tmp = this._parse_json(js.children, obj, true);
+								if(tmp.length) {
+									ul2 = $("<ul />");
+									ul2.append(tmp);
+									d.append(ul2);
+								}
+							}
+						}
+					}
+				}
+				if(!is_callback) {
+					ul1 = $("<ul />");
+					ul1.append(d);
+					d = ul1;
+				}
+				return d;
+			},
+			get_json : function (obj, li_attr, a_attr, is_callback) {
+				var result = [], 
+					s = this._get_settings(), 
+					_this = this,
+					tmp1, tmp2, li, a, t, lang;
+				obj = this._get_node(obj);
+				if(!obj || obj === -1) { obj = this.get_container().find("> ul > li"); }
+				li_attr = $.isArray(li_attr) ? li_attr : [ "id", "class" ];
+				if(!is_callback && this.data.types) { li_attr.push(s.types.type_attr); }
+				a_attr = $.isArray(a_attr) ? a_attr : [ ];
+
+				obj.each(function () {
+					li = $(this);
+					tmp1 = { data : [] };
+					if(li_attr.length) { tmp1.attr = { }; }
+					$.each(li_attr, function (i, v) { 
+						tmp2 = li.attr(v); 
+						if(tmp2 && tmp2.length && tmp2.replace(/jstree[^ ]*/ig,'').length) {
+							tmp1.attr[v] = (" " + tmp2).replace(/ jstree[^ ]*/ig,'').replace(/\s+$/ig," ").replace(/^ /,"").replace(/ $/,""); 
+						}
+					});
+					if(li.hasClass("jstree-open")) { tmp1.state = "open"; }
+					if(li.hasClass("jstree-closed")) { tmp1.state = "closed"; }
+					if(li.data()) { tmp1.metadata = li.data(); }
+					a = li.children("a");
+					a.each(function () {
+						t = $(this);
+						if(
+							a_attr.length || 
+							$.inArray("languages", s.plugins) !== -1 || 
+							t.children("ins").get(0).style.backgroundImage.length || 
+							(t.children("ins").get(0).className && t.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').length)
+						) { 
+							lang = false;
+							if($.inArray("languages", s.plugins) !== -1 && $.isArray(s.languages) && s.languages.length) {
+								$.each(s.languages, function (l, lv) {
+									if(t.hasClass(lv)) {
+										lang = lv;
+										return false;
+									}
+								});
+							}
+							tmp2 = { attr : { }, title : _this.get_text(t, lang) }; 
+							$.each(a_attr, function (k, z) {
+								tmp2.attr[z] = (" " + (t.attr(z) || "")).replace(/ jstree[^ ]*/ig,'').replace(/\s+$/ig," ").replace(/^ /,"").replace(/ $/,"");
+							});
+							if($.inArray("languages", s.plugins) !== -1 && $.isArray(s.languages) && s.languages.length) {
+								$.each(s.languages, function (k, z) {
+									if(t.hasClass(z)) { tmp2.language = z; return true; }
+								});
+							}
+							if(t.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').replace(/^\s+$/ig,"").length) {
+								tmp2.icon = t.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').replace(/\s+$/ig," ").replace(/^ /,"").replace(/ $/,"");
+							}
+							if(t.children("ins").get(0).style.backgroundImage.length) {
+								tmp2.icon = t.children("ins").get(0).style.backgroundImage.replace("url(","").replace(")","");
+							}
+						}
+						else {
+							tmp2 = _this.get_text(t);
+						}
+						if(a.length > 1) { tmp1.data.push(tmp2); }
+						else { tmp1.data = tmp2; }
+					});
+					li = li.find("> ul > li");
+					if(li.length) { tmp1.children = _this.get_json(li, li_attr, a_attr, true); }
+					result.push(tmp1);
+				});
+				return result;
+			}
+		}
+	});
+})(jQuery);
+//*/
+
+/* 
+ * jsTree languages plugin
+ * Adds support for multiple language versions in one tree
+ * This basically allows for many titles coexisting in one node, but only one of them being visible at any given time
+ * This is useful for maintaining the same structure in many languages (hence the name of the plugin)
+ */
+(function ($) {
+	$.jstree.plugin("languages", {
+		__init : function () { this._load_css();  },
+		defaults : [],
+		_fn : {
+			set_lang : function (i) { 
+				var langs = this._get_settings().languages,
+					st = false,
+					selector = ".jstree-" + this.get_index() + ' a';
+				if(!$.isArray(langs) || langs.length === 0) { return false; }
+				if($.inArray(i,langs) == -1) {
+					if(!!langs[i]) { i = langs[i]; }
+					else { return false; }
+				}
+				if(i == this.data.languages.current_language) { return true; }
+				st = $.vakata.css.get_css(selector + "." + this.data.languages.current_language, false, this.data.languages.language_css);
+				if(st !== false) { st.style.display = "none"; }
+				st = $.vakata.css.get_css(selector + "." + i, false, this.data.languages.language_css);
+				if(st !== false) { st.style.display = ""; }
+				this.data.languages.current_language = i;
+				this.__callback(i);
+				return true;
+			},
+			get_lang : function () {
+				return this.data.languages.current_language;
+			},
+			_get_string : function (key, lang) {
+				var langs = this._get_settings().languages,
+					s = this._get_settings().core.strings;
+				if($.isArray(langs) && langs.length) {
+					lang = (lang && $.inArray(lang,langs) != -1) ? lang : this.data.languages.current_language;
+				}
+				if(s[lang] && s[lang][key]) { return s[lang][key]; }
+				if(s[key]) { return s[key]; }
+				return key;
+			},
+			get_text : function (obj, lang) {
+				obj = this._get_node(obj) || this.data.ui.last_selected;
+				if(!obj.size()) { return false; }
+				var langs = this._get_settings().languages,
+					s = this._get_settings().core.html_titles;
+				if($.isArray(langs) && langs.length) {
+					lang = (lang && $.inArray(lang,langs) != -1) ? lang : this.data.languages.current_language;
+					obj = obj.children("a." + lang);
+				}
+				else { obj = obj.children("a:eq(0)"); }
+				if(s) {
+					obj = obj.clone();
+					obj.children("INS").remove();
+					return obj.html();
+				}
+				else {
+					obj = obj.contents().filter(function() { return this.nodeType == 3; })[0];
+					return obj.nodeValue;
+				}
+			},
+			set_text : function (obj, val, lang) {
+				obj = this._get_node(obj) || this.data.ui.last_selected;
+				if(!obj.size()) { return false; }
+				var langs = this._get_settings().languages,
+					s = this._get_settings().core.html_titles,
+					tmp;
+				if($.isArray(langs) && langs.length) {
+					lang = (lang && $.inArray(lang,langs) != -1) ? lang : this.data.languages.current_language;
+					obj = obj.children("a." + lang);
+				}
+				else { obj = obj.children("a:eq(0)"); }
+				if(s) {
+					tmp = obj.children("INS").clone();
+					obj.html(val).prepend(tmp);
+					this.__callback({ "obj" : obj, "name" : val, "lang" : lang });
+					return true;
+				}
+				else {
+					obj = obj.contents().filter(function() { return this.nodeType == 3; })[0];
+					this.__callback({ "obj" : obj, "name" : val, "lang" : lang });
+					return (obj.nodeValue = val);
+				}
+			},
+			_load_css : function () {
+				var langs = this._get_settings().languages,
+					str = "/* languages css */",
+					selector = ".jstree-" + this.get_index() + ' a',
+					ln;
+				if($.isArray(langs) && langs.length) {
+					this.data.languages.current_language = langs[0];
+					for(ln = 0; ln < langs.length; ln++) {
+						str += selector + "." + langs[ln] + " {";
+						if(langs[ln] != this.data.languages.current_language) { str += " display:none; "; }
+						str += " } ";
+					}
+					this.data.languages.language_css = $.vakata.css.add_sheet({ 'str' : str, 'title' : "jstree-languages" });
+				}
+			},
+			create_node : function (obj, position, js, callback) {
+				var t = this.__call_old(true, obj, position, js, function (t) {
+					var langs = this._get_settings().languages,
+						a = t.children("a"),
+						ln;
+					if($.isArray(langs) && langs.length) {
+						for(ln = 0; ln < langs.length; ln++) {
+							if(!a.is("." + langs[ln])) {
+								t.append(a.eq(0).clone().removeClass(langs.join(" ")).addClass(langs[ln]));
+							}
+						}
+						a.not("." + langs.join(", .")).remove();
+					}
+					if(callback) { callback.call(this, t); }
+				});
+				return t;
+			}
+		}
+	});
+})(jQuery);
+//*/
+
+/*
+ * jsTree cookies plugin
+ * Stores the currently opened/selected nodes in a cookie and then restores them
+ * Depends on the jquery.cookie plugin
+ */
+(function ($) {
+	$.jstree.plugin("cookies", {
+		__init : function () {
+			if(typeof $.cookie === "undefined") { throw "jsTree cookie: jQuery cookie plugin not included."; }
+
+			var s = this._get_settings().cookies,
+				tmp;
+			if(!!s.save_loaded) {
+				tmp = $.cookie(s.save_loaded);
+				if(tmp && tmp.length) { this.data.core.to_load = tmp.split(","); }
+			}
+			if(!!s.save_opened) {
+				tmp = $.cookie(s.save_opened);
+				if(tmp && tmp.length) { this.data.core.to_open = tmp.split(","); }
+			}
+			if(!!s.save_selected) {
+				tmp = $.cookie(s.save_selected);
+				if(tmp && tmp.length && this.data.ui) { this.data.ui.to_select = tmp.split(","); }
+			}
+			this.get_container()
+				.one( ( this.data.ui ? "reselect" : "reopen" ) + ".jstree", $.proxy(function () {
+					this.get_container()
+						.bind("open_node.jstree close_node.jstree select_node.jstree deselect_node.jstree", $.proxy(function (e) { 
+								if(this._get_settings().cookies.auto_save) { this.save_cookie((e.handleObj.namespace + e.handleObj.type).replace("jstree","")); }
+							}, this));
+				}, this));
+		},
+		defaults : {
+			save_loaded		: "jstree_load",
+			save_opened		: "jstree_open",
+			save_selected	: "jstree_select",
+			auto_save		: true,
+			cookie_options	: {}
+		},
+		_fn : {
+			save_cookie : function (c) {
+				if(this.data.core.refreshing) { return; }
+				var s = this._get_settings().cookies;
+				if(!c) { // if called manually and not by event
+					if(s.save_loaded) {
+						this.save_loaded();
+						$.cookie(s.save_loaded, this.data.core.to_load.join(","), s.cookie_options);
+					}
+					if(s.save_opened) {
+						this.save_opened();
+						$.cookie(s.save_opened, this.data.core.to_open.join(","), s.cookie_options);
+					}
+					if(s.save_selected && this.data.ui) {
+						this.save_selected();
+						$.cookie(s.save_selected, this.data.ui.to_select.join(","), s.cookie_options);
+					}
+					return;
+				}
+				switch(c) {
+					case "open_node":
+					case "close_node":
+						if(!!s.save_opened) { 
+							this.save_opened(); 
+							$.cookie(s.save_opened, this.data.core.to_open.join(","), s.cookie_options); 
+						}
+						if(!!s.save_loaded) { 
+							this.save_loaded(); 
+							$.cookie(s.save_loaded, this.data.core.to_load.join(","), s.cookie_options); 
+						}
+						break;
+					case "select_node":
+					case "deselect_node":
+						if(!!s.save_selected && this.data.ui) { 
+							this.save_selected(); 
+							$.cookie(s.save_selected, this.data.ui.to_select.join(","), s.cookie_options); 
+						}
+						break;
+				}
+			}
+		}
+	});
+	// include cookies by default
+	// $.jstree.defaults.plugins.push("cookies");
+})(jQuery);
+//*/
+
+/*
+ * jsTree sort plugin
+ * Sorts items alphabetically (or using any other function)
+ */
+(function ($) {
+	$.jstree.plugin("sort", {
+		__init : function () {
+			this.get_container()
+				.bind("load_node.jstree", $.proxy(function (e, data) {
+						var obj = this._get_node(data.rslt.obj);
+						obj = obj === -1 ? this.get_container().children("ul") : obj.children("ul");
+						this.sort(obj);
+					}, this))
+				.bind("rename_node.jstree create_node.jstree create.jstree", $.proxy(function (e, data) {
+						this.sort(data.rslt.obj.parent());
+					}, this))
+				.bind("move_node.jstree", $.proxy(function (e, data) {
+						var m = data.rslt.np == -1 ? this.get_container() : data.rslt.np;
+						this.sort(m.children("ul"));
+					}, this));
+		},
+		defaults : function (a, b) { return this.get_text(a) > this.get_text(b) ? 1 : -1; },
+		_fn : {
+			sort : function (obj) {
+				var s = this._get_settings().sort,
+					t = this;
+				obj.append($.makeArray(obj.children("li")).sort($.proxy(s, t)));
+				obj.find("> li > ul").each(function() { t.sort($(this)); });
+				this.clean_node(obj);
+			}
+		}
+	});
+})(jQuery);
+//*/
+
+/*
+ * jsTree DND plugin
+ * Drag and drop plugin for moving/copying nodes
+ */
+(function ($) {
+	var o = false,
+		r = false,
+		m = false,
+		ml = false,
+		sli = false,
+		sti = false,
+		dir1 = false,
+		dir2 = false,
+		last_pos = false;
+	$.vakata.dnd = {
+		is_down : false,
+		is_drag : false,
+		helper : false,
+		scroll_spd : 10,
+		init_x : 0,
+		init_y : 0,
+		threshold : 5,
+		helper_left : 5,
+		helper_top : 10,
+		user_data : {},
+
+		drag_start : function (e, data, html) { 
+			if($.vakata.dnd.is_drag) { $.vakata.drag_stop({}); }
+			try {
+				e.currentTarget.unselectable = "on";
+				e.currentTarget.onselectstart = function() { return false; };
+				if(e.currentTarget.style) { e.currentTarget.style.MozUserSelect = "none"; }
+			} catch(err) { }
+			$.vakata.dnd.init_x = e.pageX;
+			$.vakata.dnd.init_y = e.pageY;
+			$.vakata.dnd.user_data = data;
+			$.vakata.dnd.is_down = true;
+			$.vakata.dnd.helper = $("<div id='vakata-dragged' />").html(html); //.fadeTo(10,0.25);
+			$(document).bind("mousemove", $.vakata.dnd.drag);
+			$(document).bind("mouseup", $.vakata.dnd.drag_stop);
+			return false;
+		},
+		drag : function (e) { 
+			if(!$.vakata.dnd.is_down) { return; }
+			if(!$.vakata.dnd.is_drag) {
+				if(Math.abs(e.pageX - $.vakata.dnd.init_x) > 5 || Math.abs(e.pageY - $.vakata.dnd.init_y) > 5) { 
+					$.vakata.dnd.helper.appendTo("body");
+					$.vakata.dnd.is_drag = true;
+					$(document).triggerHandler("drag_start.vakata", { "event" : e, "data" : $.vakata.dnd.user_data });
+				}
+				else { return; }
+			}
+
+			// maybe use a scrolling parent element instead of document?
+			if(e.type === "mousemove") { // thought of adding scroll in order to move the helper, but mouse poisition is n/a
+				var d = $(document), t = d.scrollTop(), l = d.scrollLeft();
+				if(e.pageY - t < 20) { 
+					if(sti && dir1 === "down") { clearInterval(sti); sti = false; }
+					if(!sti) { dir1 = "up"; sti = setInterval(function () { $(document).scrollTop($(document).scrollTop() - $.vakata.dnd.scroll_spd); }, 150); }
+				}
+				else { 
+					if(sti && dir1 === "up") { clearInterval(sti); sti = false; }
+				}
+				if($(window).height() - (e.pageY - t) < 20) {
+					if(sti && dir1 === "up") { clearInterval(sti); sti = false; }
+					if(!sti) { dir1 = "down"; sti = setInterval(function () { $(document).scrollTop($(document).scrollTop() + $.vakata.dnd.scroll_spd); }, 150); }
+				}
+				else { 
+					if(sti && dir1 === "down") { clearInterval(sti); sti = false; }
+				}
+
+				if(e.pageX - l < 20) {
+					if(sli && dir2 === "right") { clearInterval(sli); sli = false; }
+					if(!sli) { dir2 = "left"; sli = setInterval(function () { $(document).scrollLeft($(document).scrollLeft() - $.vakata.dnd.scroll_spd); }, 150); }
+				}
+				else { 
+					if(sli && dir2 === "left") { clearInterval(sli); sli = false; }
+				}
+				if($(window).width() - (e.pageX - l) < 20) {
+					if(sli && dir2 === "left") { clearInterval(sli); sli = false; }
+					if(!sli) { dir2 = "right"; sli = setInterval(function () { $(document).scrollLeft($(document).scrollLeft() + $.vakata.dnd.scroll_spd); }, 150); }
+				}
+				else { 
+					if(sli && dir2 === "right") { clearInterval(sli); sli = false; }
+				}
+			}
+
+			$.vakata.dnd.helper.css({ left : (e.pageX + $.vakata.dnd.helper_left) + "px", top : (e.pageY + $.vakata.dnd.helper_top) + "px" });
+			$(document).triggerHandler("drag.vakata", { "event" : e, "data" : $.vakata.dnd.user_data });
+		},
+		drag_stop : function (e) {
+			if(sli) { clearInterval(sli); }
+			if(sti) { clearInterval(sti); }
+			$(document).unbind("mousemove", $.vakata.dnd.drag);
+			$(document).unbind("mouseup", $.vakata.dnd.drag_stop);
+			$(document).triggerHandler("drag_stop.vakata", { "event" : e, "data" : $.vakata.dnd.user_data });
+			$.vakata.dnd.helper.remove();
+			$.vakata.dnd.init_x = 0;
+			$.vakata.dnd.init_y = 0;
+			$.vakata.dnd.user_data = {};
+			$.vakata.dnd.is_down = false;
+			$.vakata.dnd.is_drag = false;
+		}
+	};
+	$(function() {
+		var css_string = '#vakata-dragged { display:block; margin:0 0 0 0; padding:4px 4px 4px 24px; position:absolute; top:-2000px; line-height:16px; z-index:10000; } ';
+		$.vakata.css.add_sheet({ str : css_string, title : "vakata" });
+	});
+
+	$.jstree.plugin("dnd", {
+		__init : function () {
+			this.data.dnd = {
+				active : false,
+				after : false,
+				inside : false,
+				before : false,
+				off : false,
+				prepared : false,
+				w : 0,
+				to1 : false,
+				to2 : false,
+				cof : false,
+				cw : false,
+				ch : false,
+				i1 : false,
+				i2 : false,
+				mto : false
+			};
+			this.get_container()
+				.bind("mouseenter.jstree", $.proxy(function (e) {
+						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
+							if(this.data.themes) {
+								m.attr("class", "jstree-" + this.data.themes.theme); 
+								if(ml) { ml.attr("class", "jstree-" + this.data.themes.theme); }
+								$.vakata.dnd.helper.attr("class", "jstree-dnd-helper jstree-" + this.data.themes.theme);
+							}
+							//if($(e.currentTarget).find("> ul > li").length === 0) {
+							if(e.currentTarget === e.target && $.vakata.dnd.user_data.obj && $($.vakata.dnd.user_data.obj).length && $($.vakata.dnd.user_data.obj).parents(".jstree:eq(0)")[0] !== e.target) { // node should not be from the same tree
+								var tr = $.jstree._reference(e.target), dc;
+								if(tr.data.dnd.foreign) {
+									dc = tr._get_settings().dnd.drag_check.call(this, { "o" : o, "r" : tr.get_container(), is_root : true });
+									if(dc === true || dc.inside === true || dc.before === true || dc.after === true) {
+										$.vakata.dnd.helper.children("ins").attr("class","jstree-ok");
+									}
+								}
+								else {
+									tr.prepare_move(o, tr.get_container(), "last");
+									if(tr.check_move()) {
+										$.vakata.dnd.helper.children("ins").attr("class","jstree-ok");
+									}
+								}
+							}
+						}
+					}, this))
+				.bind("mouseup.jstree", $.proxy(function (e) {
+						//if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree && $(e.currentTarget).find("> ul > li").length === 0) {
+						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree && e.currentTarget === e.target && $.vakata.dnd.user_data.obj && $($.vakata.dnd.user_data.obj).length && $($.vakata.dnd.user_data.obj).parents(".jstree:eq(0)")[0] !== e.target) { // node should not be from the same tree
+							var tr = $.jstree._reference(e.currentTarget), dc;
+							if(tr.data.dnd.foreign) {
+								dc = tr._get_settings().dnd.drag_check.call(this, { "o" : o, "r" : tr.get_container(), is_root : true });
+								if(dc === true || dc.inside === true || dc.before === true || dc.after === true) {
+									tr._get_settings().dnd.drag_finish.call(this, { "o" : o, "r" : tr.get_container(), is_root : true });
+								}
+							}
+							else {
+								tr.move_node(o, tr.get_container(), "last", e[tr._get_settings().dnd.copy_modifier + "Key"]);
+							}
+						}
+					}, this))
+				.bind("mouseleave.jstree", $.proxy(function (e) {
+						if(e.relatedTarget && e.relatedTarget.id && e.relatedTarget.id === "jstree-marker-line") {
+							return false; 
+						}
+						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
+							if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); }
+							if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); }
+							if(this.data.dnd.to1) { clearTimeout(this.data.dnd.to1); }
+							if(this.data.dnd.to2) { clearTimeout(this.data.dnd.to2); }
+							if($.vakata.dnd.helper.children("ins").hasClass("jstree-ok")) {
+								$.vakata.dnd.helper.children("ins").attr("class","jstree-invalid");
+							}
+						}
+					}, this))
+				.bind("mousemove.jstree", $.proxy(function (e) {
+						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
+							var cnt = this.get_container()[0];
+
+							// Horizontal scroll
+							if(e.pageX + 24 > this.data.dnd.cof.left + this.data.dnd.cw) {
+								if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); }
+								this.data.dnd.i1 = setInterval($.proxy(function () { this.scrollLeft += $.vakata.dnd.scroll_spd; }, cnt), 100);
+							}
+							else if(e.pageX - 24 < this.data.dnd.cof.left) {
+								if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); }
+								this.data.dnd.i1 = setInterval($.proxy(function () { this.scrollLeft -= $.vakata.dnd.scroll_spd; }, cnt), 100);
+							}
+							else {
+								if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); }
+							}
+
+							// Vertical scroll
+							if(e.pageY + 24 > this.data.dnd.cof.top + this.data.dnd.ch) {
+								if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); }
+								this.data.dnd.i2 = setInterval($.proxy(function () { this.scrollTop += $.vakata.dnd.scroll_spd; }, cnt), 100);
+							}
+							else if(e.pageY - 24 < this.data.dnd.cof.top) {
+								if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); }
+								this.data.dnd.i2 = setInterval($.proxy(function () { this.scrollTop -= $.vakata.dnd.scroll_spd; }, cnt), 100);
+							}
+							else {
+								if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); }
+							}
+
+						}
+					}, this))
+				.bind("scroll.jstree", $.proxy(function (e) { 
+						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree && m && ml) {
+							m.hide();
+							ml.hide();
+						}
+					}, this))
+				.delegate("a", "mousedown.jstree", $.proxy(function (e) { 
+						if(e.which === 1) {
+							this.start_drag(e.currentTarget, e);
+							return false;
+						}
+					}, this))
+				.delegate("a", "mouseenter.jstree", $.proxy(function (e) { 
+						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
+							this.dnd_enter(e.currentTarget);
+						}
+					}, this))
+				.delegate("a", "mousemove.jstree", $.proxy(function (e) { 
+						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
+							if(!r || !r.length || r.children("a")[0] !== e.currentTarget) {
+								this.dnd_enter(e.currentTarget);
+							}
+							if(typeof this.data.dnd.off.top === "undefined") { this.data.dnd.off = $(e.target).offset(); }
+							this.data.dnd.w = (e.pageY - (this.data.dnd.off.top || 0)) % this.data.core.li_height;
+							if(this.data.dnd.w < 0) { this.data.dnd.w += this.data.core.li_height; }
+							this.dnd_show();
+						}
+					}, this))
+				.delegate("a", "mouseleave.jstree", $.proxy(function (e) { 
+						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
+							if(e.relatedTarget && e.relatedTarget.id && e.relatedTarget.id === "jstree-marker-line") {
+								return false; 
+							}
+								if(m) { m.hide(); }
+								if(ml) { ml.hide(); }
+							/*
+							var ec = $(e.currentTarget).closest("li"), 
+								er = $(e.relatedTarget).closest("li");
+							if(er[0] !== ec.prev()[0] && er[0] !== ec.next()[0]) {
+								if(m) { m.hide(); }
+								if(ml) { ml.hide(); }
+							}
+							*/
+							this.data.dnd.mto = setTimeout( 
+								(function (t) { return function () { t.dnd_leave(e); }; })(this),
+							0);
+						}
+					}, this))
+				.delegate("a", "mouseup.jstree", $.proxy(function (e) { 
+						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree) {
+							this.dnd_finish(e);
+						}
+					}, this));
+
+			$(document)
+				.bind("drag_stop.vakata", $.proxy(function () {
+						if(this.data.dnd.to1) { clearTimeout(this.data.dnd.to1); }
+						if(this.data.dnd.to2) { clearTimeout(this.data.dnd.to2); }
+						if(this.data.dnd.i1) { clearInterval(this.data.dnd.i1); }
+						if(this.data.dnd.i2) { clearInterval(this.data.dnd.i2); }
+						this.data.dnd.after		= false;
+						this.data.dnd.before	= false;
+						this.data.dnd.inside	= false;
+						this.data.dnd.off		= false;
+						this.data.dnd.prepared	= false;
+						this.data.dnd.w			= false;
+						this.data.dnd.to1		= false;
+						this.data.dnd.to2		= false;
+						this.data.dnd.i1		= false;
+						this.data.dnd.i2		= false;
+						this.data.dnd.active	= false;
+						this.data.dnd.foreign	= false;
+						if(m) { m.css({ "top" : "-2000px" }); }
+						if(ml) { ml.css({ "top" : "-2000px" }); }
+					}, this))
+				.bind("drag_start.vakata", $.proxy(function (e, data) {
+						if(data.data.jstree) { 
+							var et = $(data.event.target);
+							if(et.closest(".jstree").hasClass("jstree-" + this.get_index())) {
+								this.dnd_enter(et);
+							}
+						}
+					}, this));
+				/*
+				.bind("keydown.jstree-" + this.get_index() + " keyup.jstree-" + this.get_index(), $.proxy(function(e) {
+						if($.vakata.dnd.is_drag && $.vakata.dnd.user_data.jstree && !this.data.dnd.foreign) {
+							var h = $.vakata.dnd.helper.children("ins");
+							if(e[this._get_settings().dnd.copy_modifier + "Key"] && h.hasClass("jstree-ok")) {
+								h.parent().html(h.parent().html().replace(/ \(Copy\)$/, "") + " (Copy)");
+							} 
+							else {
+								h.parent().html(h.parent().html().replace(/ \(Copy\)$/, ""));
+							}
+						}
+					}, this)); */
+
+
+
+			var s = this._get_settings().dnd;
+			if(s.drag_target) {
+				$(document)
+					.delegate(s.drag_target, "mousedown.jstree-" + this.get_index(), $.proxy(function (e) {
+						o = e.target;
+						$.vakata.dnd.drag_start(e, { jstree : true, obj : e.target }, "<ins class='jstree-icon'></ins>" + $(e.target).text() );
+						if(this.data.themes) { 
+							if(m) { m.attr("class", "jstree-" + this.data.themes.theme); }
+							if(ml) { ml.attr("class", "jstree-" + this.data.themes.theme); }
+							$.vakata.dnd.helper.attr("class", "jstree-dnd-helper jstree-" + this.data.themes.theme); 
+						}
+						$.vakata.dnd.helper.children("ins").attr("class","jstree-invalid");
+						var cnt = this.get_container();
+						this.data.dnd.cof = cnt.offset();
+						this.data.dnd.cw = parseInt(cnt.width(),10);
+						this.data.dnd.ch = parseInt(cnt.height(),10);
+						this.data.dnd.foreign = true;
+						e.preventDefault();
+					}, this));
+			}
+			if(s.drop_target) {
+				$(document)
+					.delegate(s.drop_target, "mouseenter.jstree-" + this.get_index(), $.proxy(function (e) {
+							if(this.data.dnd.active && this._get_settings().dnd.drop_check.call(this, { "o" : o, "r" : $(e.target), "e" : e })) {
+								$.vakata.dnd.helper.children("ins").attr("class","jstree-ok");
+							}
+						}, this))
+					.delegate(s.drop_target, "mouseleave.jstree-" + this.get_index(), $.proxy(function (e) {
+							if(this.data.dnd.active) {
+								$.vakata.dnd.helper.children("ins").attr("class","jstree-invalid");
+							}
+						}, this))
+					.delegate(s.drop_target, "mouseup.jstree-" + this.get_index(), $.proxy(function (e) {
+							if(this.data.dnd.active && $.vakata.dnd.helper.children("ins").hasClass("jstree-ok")) {
+								this._get_settings().dnd.drop_finish.call(this, { "o" : o, "r" : $(e.target), "e" : e });
+							}
+						}, this));
+			}
+		},
+		defaults : {
+			copy_modifier	: "ctrl",
+			check_timeout	: 100,
+			open_timeout	: 500,
+			drop_target		: ".jstree-drop",
+			drop_check		: function (data) { return true; },
+			drop_finish		: $.noop,
+			drag_target		: ".jstree-draggable",
+			drag_finish		: $.noop,
+			drag_check		: function (data) { return { after : false, before : false, inside : true }; }
+		},
+		_fn : {
+			dnd_prepare : function () {
+				if(!r || !r.length) { return; }
+				this.data.dnd.off = r.offset();
+				if(this._get_settings().core.rtl) {
+					this.data.dnd.off.right = this.data.dnd.off.left + r.width();
+				}
+				if(this.data.dnd.foreign) {
+					var a = this._get_settings().dnd.drag_check.call(this, { "o" : o, "r" : r });
+					this.data.dnd.after = a.after;
+					this.data.dnd.before = a.before;
+					this.data.dnd.inside = a.inside;
+					this.data.dnd.prepared = true;
+					return this.dnd_show();
+				}
+				this.prepare_move(o, r, "before");
+				this.data.dnd.before = this.check_move();
+				this.prepare_move(o, r, "after");
+				this.data.dnd.after = this.check_move();
+				if(this._is_loaded(r)) {
+					this.prepare_move(o, r, "inside");
+					this.data.dnd.inside = this.check_move();
+				}
+				else {
+					this.data.dnd.inside = false;
+				}
+				this.data.dnd.prepared = true;
+				return this.dnd_show();
+			},
+			dnd_show : function () {
+				if(!this.data.dnd.prepared) { return; }
+				var o = ["before","inside","after"],
+					r = false,
+					rtl = this._get_settings().core.rtl,
+					pos;
+				if(this.data.dnd.w < this.data.core.li_height/3) { o = ["before","inside","after"]; }
+				else if(this.data.dnd.w <= this.data.core.li_height*2/3) {
+					o = this.data.dnd.w < this.data.core.li_height/2 ? ["inside","before","after"] : ["inside","after","before"];
+				}
+				else { o = ["after","inside","before"]; }
+				$.each(o, $.proxy(function (i, val) { 
+					if(this.data.dnd[val]) {
+						$.vakata.dnd.helper.children("ins").attr("class","jstree-ok");
+						r = val;
+						return false;
+					}
+				}, this));
+				if(r === false) { $.vakata.dnd.helper.children("ins").attr("class","jstree-invalid"); }
+				
+				pos = rtl ? (this.data.dnd.off.right - 18) : (this.data.dnd.off.left + 10);
+				switch(r) {
+					case "before":
+						m.css({ "left" : pos + "px", "top" : (this.data.dnd.off.top - 6) + "px" }).show();
+						if(ml) { ml.css({ "left" : (pos + 8) + "px", "top" : (this.data.dnd.off.top - 1) + "px" }).show(); }
+						break;
+					case "after":
+						m.css({ "left" : pos + "px", "top" : (this.data.dnd.off.top + this.data.core.li_height - 6) + "px" }).show();
+						if(ml) { ml.css({ "left" : (pos + 8) + "px", "top" : (this.data.dnd.off.top + this.data.core.li_height - 1) + "px" }).show(); }
+						break;
+					case "inside":
+						m.css({ "left" : pos + ( rtl ? -4 : 4) + "px", "top" : (this.data.dnd.off.top + this.data.core.li_height/2 - 5) + "px" }).show();
+						if(ml) { ml.hide(); }
+						break;
+					default:
+						m.hide();
+						if(ml) { ml.hide(); }
+						break;
+				}
+				last_pos = r;
+				return r;
+			},
+			dnd_open : function () {
+				this.data.dnd.to2 = false;
+				this.open_node(r, $.proxy(this.dnd_prepare,this), true);
+			},
+			dnd_finish : function (e) {
+				if(this.data.dnd.foreign) {
+					if(this.data.dnd.after || this.data.dnd.before || this.data.dnd.inside) {
+						this._get_settings().dnd.drag_finish.call(this, { "o" : o, "r" : r, "p" : last_pos });
+					}
+				}
+				else {
+					this.dnd_prepare();
+					this.move_node(o, r, last_pos, e[this._get_settings().dnd.copy_modifier + "Key"]);
+				}
+				o = false;
+				r = false;
+				m.hide();
+				if(ml) { ml.hide(); }
+			},
+			dnd_enter : function (obj) {
+				if(this.data.dnd.mto) { 
+					clearTimeout(this.data.dnd.mto);
+					this.data.dnd.mto = false;
+				}
+				var s = this._get_settings().dnd;
+				this.data.dnd.prepared = false;
+				r = this._get_node(obj);
+				if(s.check_timeout) { 
+					// do the calculations after a minimal timeout (users tend to drag quickly to the desired location)
+					if(this.data.dnd.to1) { clearTimeout(this.data.dnd.to1); }
+					this.data.dnd.to1 = setTimeout($.proxy(this.dnd_prepare, this), s.check_timeout); 
+				}
+				else { 
+					this.dnd_prepare(); 
+				}
+				if(s.open_timeout) { 
+					if(this.data.dnd.to2) { clearTimeout(this.data.dnd.to2); }
+					if(r && r.length && r.hasClass("jstree-closed")) { 
+						// if the node is closed - open it, then recalculate
+						this.data.dnd.to2 = setTimeout($.proxy(this.dnd_open, this), s.open_timeout);
+					}
+				}
+				else {
+					if(r && r.length && r.hasClass("jstree-closed")) { 
+						this.dnd_open();
+					}
+				}
+			},
+			dnd_leave : function (e) {
+				this.data.dnd.after		= false;
+				this.data.dnd.before	= false;
+				this.data.dnd.inside	= false;
+				$.vakata.dnd.helper.children("ins").attr("class","jstree-invalid");
+				m.hide();
+				if(ml) { ml.hide(); }
+				if(r && r[0] === e.target.parentNode) {
+					if(this.data.dnd.to1) {
+						clearTimeout(this.data.dnd.to1);
+						this.data.dnd.to1 = false;
+					}
+					if(this.data.dnd.to2) {
+						clearTimeout(this.data.dnd.to2);
+						this.data.dnd.to2 = false;
+					}
+				}
+			},
+			start_drag : function (obj, e) {
+				o = this._get_node(obj);
+				if(this.data.ui && this.is_selected(o)) { o = this._get_node(null, true); }
+				var dt = o.length > 1 ? this._get_string("multiple_selection") : this.get_text(o),
+					cnt = this.get_container();
+				if(!this._get_settings().core.html_titles) { dt = dt.replace(/</ig,"&lt;").replace(/>/ig,"&gt;"); }
+				$.vakata.dnd.drag_start(e, { jstree : true, obj : o }, "<ins class='jstree-icon'></ins>" + dt );
+				if(this.data.themes) { 
+					if(m) { m.attr("class", "jstree-" + this.data.themes.theme); }
+					if(ml) { ml.attr("class", "jstree-" + this.data.themes.theme); }
+					$.vakata.dnd.helper.attr("class", "jstree-dnd-helper jstree-" + this.data.themes.theme); 
+				}
+				this.data.dnd.cof = cnt.offset();
+				this.data.dnd.cw = parseInt(cnt.width(),10);
+				this.data.dnd.ch = parseInt(cnt.height(),10);
+				this.data.dnd.active = true;
+			}
+		}
+	});
+	$(function() {
+		var css_string = '' + 
+			'#vakata-dragged ins { display:block; text-decoration:none; width:16px; height:16px; margin:0 0 0 0; padding:0; position:absolute; top:4px; left:4px; ' + 
+			' -moz-border-radius:4px; border-radius:4px; -webkit-border-radius:4px; ' +
+			'} ' + 
+			'#vakata-dragged .jstree-ok { background:green; } ' + 
+			'#vakata-dragged .jstree-invalid { background:red; } ' + 
+			'#jstree-marker { padding:0; margin:0; font-size:12px; overflow:hidden; height:12px; width:8px; position:absolute; top:-30px; z-index:10001; background-repeat:no-repeat; display:none; background-color:transparent; text-shadow:1px 1px 1px white; color:black; line-height:10px; } ' + 
+			'#jstree-marker-line { padding:0; margin:0; line-height:0%; font-size:1px; overflow:hidden; height:1px; width:100px; position:absolute; top:-30px; z-index:10000; background-repeat:no-repeat; display:none; background-color:#456c43; ' + 
+			' cursor:pointer; border:1px solid #eeeeee; border-left:0; -moz-box-shadow: 0px 0px 2px #666; -webkit-box-shadow: 0px 0px 2px #666; box-shadow: 0px 0px 2px #666; ' + 
+			' -moz-border-radius:1px; border-radius:1px; -webkit-border-radius:1px; ' +
+			'}' + 
+			'';
+		$.vakata.css.add_sheet({ str : css_string, title : "jstree" });
+		m = $("<div />").attr({ id : "jstree-marker" }).hide().html("&raquo;")
+			.bind("mouseleave mouseenter", function (e) { 
+				m.hide();
+				ml.hide();
+				e.preventDefault(); 
+				e.stopImmediatePropagation(); 
+				return false; 
+			})
+			.appendTo("body");
+		ml = $("<div />").attr({ id : "jstree-marker-line" }).hide()
+			.bind("mouseup", function (e) { 
+				if(r && r.length) { 
+					r.children("a").trigger(e); 
+					e.preventDefault(); 
+					e.stopImmediatePropagation(); 
+					return false; 
+				} 
+			})
+			.bind("mouseleave", function (e) { 
+				var rt = $(e.relatedTarget);
+				if(rt.is(".jstree") || rt.closest(".jstree").length === 0) {
+					if(r && r.length) { 
+						r.children("a").trigger(e); 
+						m.hide();
+						ml.hide();
+						e.preventDefault(); 
+						e.stopImmediatePropagation(); 
+						return false; 
+					}
+				}
+			})
+			.appendTo("body");
+		$(document).bind("drag_start.vakata", function (e, data) {
+			if(data.data.jstree) { m.show(); if(ml) { ml.show(); } }
+		});
+		$(document).bind("drag_stop.vakata", function (e, data) {
+			if(data.data.jstree) { m.hide(); if(ml) { ml.hide(); } }
+		});
+	});
+})(jQuery);
+//*/
+
+/*
+ * jsTree checkbox plugin
+ * Inserts checkboxes in front of every node
+ * Depends on the ui plugin
+ * DOES NOT WORK NICELY WITH MULTITREE DRAG'N'DROP
+ */
+(function ($) {
+	$.jstree.plugin("checkbox", {
+		__init : function () {
+			this.data.checkbox.noui = this._get_settings().checkbox.override_ui;
+			if(this.data.ui && this.data.checkbox.noui) {
+				this.select_node = this.deselect_node = this.deselect_all = $.noop;
+				this.get_selected = this.get_checked;
+			}
+
+			this.get_container()
+				.bind("open_node.jstree create_node.jstree clean_node.jstree refresh.jstree", $.proxy(function (e, data) { 
+						this._prepare_checkboxes(data.rslt.obj);
+					}, this))
+				.bind("loaded.jstree", $.proxy(function (e) {
+						this._prepare_checkboxes();
+					}, this))
+				.delegate( (this.data.ui && this.data.checkbox.noui ? "a" : "ins.jstree-checkbox") , "click.jstree", $.proxy(function (e) {
+						e.preventDefault();
+						if(this._get_node(e.target).hasClass("jstree-checked")) { this.uncheck_node(e.target); }
+						else { this.check_node(e.target); }
+						if(this.data.ui && this.data.checkbox.noui) {
+							this.save_selected();
+							if(this.data.cookies) { this.save_cookie("select_node"); }
+						}
+						else {
+							e.stopImmediatePropagation();
+							return false;
+						}
+					}, this));
+		},
+		defaults : {
+			override_ui : false,
+			two_state : false,
+			real_checkboxes : false,
+			checked_parent_open : true,
+			real_checkboxes_names : function (n) { return [ ("check_" + (n[0].id || Math.ceil(Math.random() * 10000))) , 1]; }
+		},
+		__destroy : function () {
+			this.get_container()
+				.find("input.jstree-real-checkbox").removeClass("jstree-real-checkbox").end()
+				.find("ins.jstree-checkbox").remove();
+		},
+		_fn : {
+			_checkbox_notify : function (n, data) {
+				if(data.checked) {
+					this.check_node(n, false);
+				}
+			},
+			_prepare_checkboxes : function (obj) {
+				obj = !obj || obj == -1 ? this.get_container().find("> ul > li") : this._get_node(obj);
+				if(obj === false) { return; } // added for removing root nodes
+				var c, _this = this, t, ts = this._get_settings().checkbox.two_state, rc = this._get_settings().checkbox.real_checkboxes, rcn = this._get_settings().checkbox.real_checkboxes_names;
+				obj.each(function () {
+					t = $(this);
+					c = t.is("li") && (t.hasClass("jstree-checked") || (rc && t.children(":checked").length)) ? "jstree-checked" : "jstree-unchecked";
+					t.find("li").andSelf().each(function () {
+						var $t = $(this), nm;
+						$t.children("a" + (_this.data.languages ? "" : ":eq(0)") ).not(":has(.jstree-checkbox)").prepend("<ins class='jstree-checkbox'>&#160;</ins>").parent().not(".jstree-checked, .jstree-unchecked").addClass( ts ? "jstree-unchecked" : c );
+						if(rc) {
+							if(!$t.children(":checkbox").length) {
+								nm = rcn.call(_this, $t);
+								$t.prepend("<input type='checkbox' class='jstree-real-checkbox' id='" + nm[0] + "' name='" + nm[0] + "' value='" + nm[1] + "' />");
+							}
+							else {
+								$t.children(":checkbox").addClass("jstree-real-checkbox");
+							}
+						}
+						if(!ts) {
+							if(c === "jstree-checked" || $t.hasClass("jstree-checked") || $t.children(':checked').length) {
+								$t.find("li").andSelf().addClass("jstree-checked").children(":checkbox").prop("checked", true);
+							}
+						}
+						else {
+							if($t.hasClass("jstree-checked") || $t.children(':checked').length) {
+								$t.addClass("jstree-checked").children(":checkbox").prop("checked", true);
+							}
+						}
+					});
+				});
+				if(!ts) {
+					obj.find(".jstree-checked").parent().parent().each(function () { _this._repair_state(this); }); 
+				}
+			},
+			change_state : function (obj, state) {
+				obj = this._get_node(obj);
+				var coll = false, rc = this._get_settings().checkbox.real_checkboxes;
+				if(!obj || obj === -1) { return false; }
+				state = (state === false || state === true) ? state : obj.hasClass("jstree-checked");
+				if(this._get_settings().checkbox.two_state) {
+					if(state) { 
+						obj.removeClass("jstree-checked").addClass("jstree-unchecked"); 
+						if(rc) { obj.children(":checkbox").prop("checked", false); }
+					}
+					else { 
+						obj.removeClass("jstree-unchecked").addClass("jstree-checked"); 
+						if(rc) { obj.children(":checkbox").prop("checked", true); }
+					}
+				}
+				else {
+					if(state) { 
+						coll = obj.find("li").andSelf();
+						if(!coll.filter(".jstree-checked, .jstree-undetermined").length) { return false; }
+						coll.removeClass("jstree-checked jstree-undetermined").addClass("jstree-unchecked"); 
+						if(rc) { coll.children(":checkbox").prop("checked", false); }
+					}
+					else { 
+						coll = obj.find("li").andSelf();
+						if(!coll.filter(".jstree-unchecked, .jstree-undetermined").length) { return false; }
+						coll.removeClass("jstree-unchecked jstree-undetermined").addClass("jstree-checked"); 
+						if(rc) { coll.children(":checkbox").prop("checked", true); }
+						if(this.data.ui) { this.data.ui.last_selected = obj; }
+						this.data.checkbox.last_selected = obj;
+					}
+					obj.parentsUntil(".jstree", "li").each(function () {
+						var $this = $(this);
+						if(state) {
+							if($this.children("ul").children("li.jstree-checked, li.jstree-undetermined").length) {
+								$this.parentsUntil(".jstree", "li").andSelf().removeClass("jstree-checked jstree-unchecked").addClass("jstree-undetermined");
+								if(rc) { $this.parentsUntil(".jstree", "li").andSelf().children(":checkbox").prop("checked", false); }
+								return false;
+							}
+							else {
+								$this.removeClass("jstree-checked jstree-undetermined").addClass("jstree-unchecked");
+								if(rc) { $this.children(":checkbox").prop("checked", false); }
+							}
+						}
+						else {
+							if($this.children("ul").children("li.jstree-unchecked, li.jstree-undetermined").length) {
+								$this.parentsUntil(".jstree", "li").andSelf().removeClass("jstree-checked jstree-unchecked").addClass("jstree-undetermined");
+								if(rc) { $this.parentsUntil(".jstree", "li").andSelf().children(":checkbox").prop("checked", false); }
+								return false;
+							}
+							else {
+								$this.removeClass("jstree-unchecked jstree-undetermined").addClass("jstree-checked");
+								if(rc) { $this.children(":checkbox").prop("checked", true); }
+							}
+						}
+					});
+				}
+				if(this.data.ui && this.data.checkbox.noui) { this.data.ui.selected = this.get_checked(); }
+				this.__callback(obj);
+				return true;
+			},
+			check_node : function (obj) {
+				if(this.change_state(obj, false)) { 
+					obj = this._get_node(obj);
+					if(this._get_settings().checkbox.checked_parent_open) {
+						var t = this;
+						obj.parents(".jstree-closed").each(function () { t.open_node(this, false, true); });
+					}
+					this.__callback({ "obj" : obj }); 
+				}
+			},
+			uncheck_node : function (obj) {
+				if(this.change_state(obj, true)) { this.__callback({ "obj" : this._get_node(obj) }); }
+			},
+			check_all : function () {
+				var _this = this, 
+					coll = this._get_settings().checkbox.two_state ? this.get_container_ul().find("li") : this.get_container_ul().children("li");
+				coll.each(function () {
+					_this.change_state(this, false);
+				});
+				this.__callback();
+			},
+			uncheck_all : function () {
+				var _this = this,
+					coll = this._get_settings().checkbox.two_state ? this.get_container_ul().find("li") : this.get_container_ul().children("li");
+				coll.each(function () {
+					_this.change_state(this, true);
+				});
+				this.__callback();
+			},
+
+			is_checked : function(obj) {
+				obj = this._get_node(obj);
+				return obj.length ? obj.is(".jstree-checked") : false;
+			},
+			get_checked : function (obj, get_all) {
+				obj = !obj || obj === -1 ? this.get_container() : this._get_node(obj);
+				return get_all || this._get_settings().checkbox.two_state ? obj.find(".jstree-checked") : obj.find("> ul > .jstree-checked, .jstree-undetermined > ul > .jstree-checked");
+			},
+			get_unchecked : function (obj, get_all) { 
+				obj = !obj || obj === -1 ? this.get_container() : this._get_node(obj);
+				return get_all || this._get_settings().checkbox.two_state ? obj.find(".jstree-unchecked") : obj.find("> ul > .jstree-unchecked, .jstree-undetermined > ul > .jstree-unchecked");
+			},
+
+			show_checkboxes : function () { this.get_container().children("ul").removeClass("jstree-no-checkboxes"); },
+			hide_checkboxes : function () { this.get_container().children("ul").addClass("jstree-no-checkboxes"); },
+
+			_repair_state : function (obj) {
+				obj = this._get_node(obj);
+				if(!obj.length) { return; }
+				if(this._get_settings().checkbox.two_state) {
+					obj.find('li').andSelf().not('.jstree-checked').removeClass('jstree-undetermined').addClass('jstree-unchecked').children(':checkbox').prop('checked', true);
+					return;
+				}
+				var rc = this._get_settings().checkbox.real_checkboxes,
+					a = obj.find("> ul > .jstree-checked").length,
+					b = obj.find("> ul > .jstree-undetermined").length,
+					c = obj.find("> ul > li").length;
+				if(c === 0) { if(obj.hasClass("jstree-undetermined")) { this.change_state(obj, false); } }
+				else if(a === 0 && b === 0) { this.change_state(obj, true); }
+				else if(a === c) { this.change_state(obj, false); }
+				else { 
+					obj.parentsUntil(".jstree","li").andSelf().removeClass("jstree-checked jstree-unchecked").addClass("jstree-undetermined");
+					if(rc) { obj.parentsUntil(".jstree", "li").andSelf().children(":checkbox").prop("checked", false); }
+				}
+			},
+			reselect : function () {
+				if(this.data.ui && this.data.checkbox.noui) { 
+					var _this = this,
+						s = this.data.ui.to_select;
+					s = $.map($.makeArray(s), function (n) { return "#" + n.toString().replace(/^#/,"").replace(/\\\//g,"/").replace(/\//g,"\\\/").replace(/\\\./g,".").replace(/\./g,"\\.").replace(/\:/g,"\\:"); });
+					this.deselect_all();
+					$.each(s, function (i, val) { _this.check_node(val); });
+					this.__callback();
+				}
+				else { 
+					this.__call_old(); 
+				}
+			},
+			save_loaded : function () {
+				var _this = this;
+				this.data.core.to_load = [];
+				this.get_container_ul().find("li.jstree-closed.jstree-undetermined").each(function () {
+					if(this.id) { _this.data.core.to_load.push("#" + this.id); }
+				});
+			}
+		}
+	});
+	$(function() {
+		var css_string = '.jstree .jstree-real-checkbox { display:none; } ';
+		$.vakata.css.add_sheet({ str : css_string, title : "jstree" });
+	});
+})(jQuery);
+//*/
+
+/* 
+ * jsTree XML plugin
+ * The XML data store. Datastores are build by overriding the `load_node` and `_is_loaded` functions.
+ */
+(function ($) {
+	$.vakata.xslt = function (xml, xsl, callback) {
+		var rs = "", xm, xs, processor, support;
+		// TODO: IE9 no XSLTProcessor, no document.recalc
+		if(document.recalc) {
+			xm = document.createElement('xml');
+			xs = document.createElement('xml');
+			xm.innerHTML = xml;
+			xs.innerHTML = xsl;
+			$("body").append(xm).append(xs);
+			setTimeout( (function (xm, xs, callback) {
+				return function () {
+					callback.call(null, xm.transformNode(xs.XMLDocument));
+					setTimeout( (function (xm, xs) { return function () { $(xm).remove(); $(xs).remove(); }; })(xm, xs), 200);
+				};
+			})(xm, xs, callback), 100);
+			return true;
+		}
+		if(typeof window.DOMParser !== "undefined" && typeof window.XMLHttpRequest !== "undefined" && typeof window.XSLTProcessor === "undefined") {
+			xml = new DOMParser().parseFromString(xml, "text/xml");
+			xsl = new DOMParser().parseFromString(xsl, "text/xml");
+			// alert(xml.transformNode());
+			// callback.call(null, new XMLSerializer().serializeToString(rs));
+			
+		}
+		if(typeof window.DOMParser !== "undefined" && typeof window.XMLHttpRequest !== "undefined" && typeof window.XSLTProcessor !== "undefined") {
+			processor = new XSLTProcessor();
+			support = $.isFunction(processor.transformDocument) ? (typeof window.XMLSerializer !== "undefined") : true;
+			if(!support) { return false; }
+			xml = new DOMParser().parseFromString(xml, "text/xml");
+			xsl = new DOMParser().parseFromString(xsl, "text/xml");
+			if($.isFunction(processor.transformDocument)) {
+				rs = document.implementation.createDocument("", "", null);
+				processor.transformDocument(xml, xsl, rs, null);
+				callback.call(null, new XMLSerializer().serializeToString(rs));
+				return true;
+			}
+			else {
+				processor.importStylesheet(xsl);
+				rs = processor.transformToFragment(xml, document);
+				callback.call(null, $("<div />").append(rs).html());
+				return true;
+			}
+		}
+		return false;
+	};
+	var xsl = {
+		'nest' : '<' + '?xml version="1.0" encoding="utf-8" ?>' + 
+			'<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >' + 
+			'<xsl:output method="html" encoding="utf-8" omit-xml-declaration="yes" standalone="no" indent="no" media-type="text/html" />' + 
+			'<xsl:template match="/">' + 
+			'	<xsl:call-template name="nodes">' + 
+			'		<xsl:with-param name="node" select="/root" />' + 
+			'	</xsl:call-template>' + 
+			'</xsl:template>' + 
+			'<xsl:template name="nodes">' + 
+			'	<xsl:param name="node" />' + 
+			'	<ul>' + 
+			'	<xsl:for-each select="$node/item">' + 
+			'		<xsl:variable name="children" select="count(./item) &gt; 0" />' + 
+			'		<li>' + 
+			'			<xsl:attribute name="class">' + 
+			'				<xsl:if test="position() = last()">jstree-last </xsl:if>' + 
+			'				<xsl:choose>' + 
+			'					<xsl:when test="@state = \'open\'">jstree-open </xsl:when>' + 
+			'					<xsl:when test="$children or @hasChildren or @state = \'closed\'">jstree-closed </xsl:when>' + 
+			'					<xsl:otherwise>jstree-leaf </xsl:otherwise>' + 
+			'				</xsl:choose>' + 
+			'				<xsl:value-of select="@class" />' + 
+			'			</xsl:attribute>' + 
+			'			<xsl:for-each select="@*">' + 
+			'				<xsl:if test="name() != \'class\' and name() != \'state\' and name() != \'hasChildren\'">' + 
+			'					<xsl:attribute name="{name()}"><xsl:value-of select="." /></xsl:attribute>' + 
+			'				</xsl:if>' + 
+			'			</xsl:for-each>' + 
+			'	<ins class="jstree-icon"><xsl:text>&#xa0;</xsl:text></ins>' + 
+			'			<xsl:for-each select="content/name">' + 
+			'				<a>' + 
+			'				<xsl:attribute name="href">' + 
+			'					<xsl:choose>' + 
+			'					<xsl:when test="@href"><xsl:value-of select="@href" /></xsl:when>' + 
+			'					<xsl:otherwise>#</xsl:otherwise>' + 
+			'					</xsl:choose>' + 
+			'				</xsl:attribute>' + 
+			'				<xsl:attribute name="class"><xsl:value-of select="@lang" /> <xsl:value-of select="@class" /></xsl:attribute>' + 
+			'				<xsl:attribute name="style"><xsl:value-of select="@style" /></xsl:attribute>' + 
+			'				<xsl:for-each select="@*">' + 
+			'					<xsl:if test="name() != \'style\' and name() != \'class\' and name() != \'href\'">' + 
+			'						<xsl:attribute name="{name()}"><xsl:value-of select="." /></xsl:attribute>' + 
+			'					</xsl:if>' + 
+			'				</xsl:for-each>' + 
+			'					<ins>' + 
+			'						<xsl:attribute name="class">jstree-icon ' + 
+			'							<xsl:if test="string-length(attribute::icon) > 0 and not(contains(@icon,\'/\'))"><xsl:value-of select="@icon" /></xsl:if>' + 
+			'						</xsl:attribute>' + 
+			'						<xsl:if test="string-length(attribute::icon) > 0 and contains(@icon,\'/\')"><xsl:attribute name="style">background:url(<xsl:value-of select="@icon" />) center center no-repeat;</xsl:attribute></xsl:if>' + 
+			'						<xsl:text>&#xa0;</xsl:text>' + 
+			'					</ins>' + 
+			'					<xsl:copy-of select="./child::node()" />' + 
+			'				</a>' + 
+			'			</xsl:for-each>' + 
+			'			<xsl:if test="$children or @hasChildren"><xsl:call-template name="nodes"><xsl:with-param name="node" select="current()" /></xsl:call-template></xsl:if>' + 
+			'		</li>' + 
+			'	</xsl:for-each>' + 
+			'	</ul>' + 
+			'</xsl:template>' + 
+			'</xsl:stylesheet>',
+
+		'flat' : '<' + '?xml version="1.0" encoding="utf-8" ?>' + 
+			'<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >' + 
+			'<xsl:output method="html" encoding="utf-8" omit-xml-declaration="yes" standalone="no" indent="no" media-type="text/xml" />' + 
+			'<xsl:template match="/">' + 
+			'	<ul>' + 
+			'	<xsl:for-each select="//item[not(@parent_id) or @parent_id=0 or not(@parent_id = //item/@id)]">' + /* the last `or` may be removed */
+			'		<xsl:call-template name="nodes">' + 
+			'			<xsl:with-param name="node" select="." />' + 
+			'			<xsl:with-param name="is_last" select="number(position() = last())" />' + 
+			'		</xsl:call-template>' + 
+			'	</xsl:for-each>' + 
+			'	</ul>' + 
+			'</xsl:template>' + 
+			'<xsl:template name="nodes">' + 
+			'	<xsl:param name="node" />' + 
+			'	<xsl:param name="is_last" />' + 
+			'	<xsl:variable name="children" select="count(//item[@parent_id=$node/attribute::id]) &gt; 0" />' + 
+			'	<li>' + 
+			'	<xsl:attribute name="class">' + 
+			'		<xsl:if test="$is_last = true()">jstree-last </xsl:if>' + 
+			'		<xsl:choose>' + 
+			'			<xsl:when test="@state = \'open\'">jstree-open </xsl:when>' + 
+			'			<xsl:when test="$children or @hasChildren or @state = \'closed\'">jstree-closed </xsl:when>' + 
+			'			<xsl:otherwise>jstree-leaf </xsl:otherwise>' + 
+			'		</xsl:choose>' + 
+			'		<xsl:value-of select="@class" />' + 
+			'	</xsl:attribute>' + 
+			'	<xsl:for-each select="@*">' + 
+			'		<xsl:if test="name() != \'parent_id\' and name() != \'hasChildren\' and name() != \'class\' and name() != \'state\'">' + 
+			'		<xsl:attribute name="{name()}"><xsl:value-of select="." /></xsl:attribute>' + 
+			'		</xsl:if>' + 
+			'	</xsl:for-each>' + 
+			'	<ins class="jstree-icon"><xsl:text>&#xa0;</xsl:text></ins>' + 
+			'	<xsl:for-each select="content/name">' + 
+			'		<a>' + 
+			'		<xsl:attribute name="href">' + 
+			'			<xsl:choose>' + 
+			'			<xsl:when test="@href"><xsl:value-of select="@href" /></xsl:when>' + 
+			'			<xsl:otherwise>#</xsl:otherwise>' + 
+			'			</xsl:choose>' + 
+			'		</xsl:attribute>' + 
+			'		<xsl:attribute name="class"><xsl:value-of select="@lang" /> <xsl:value-of select="@class" /></xsl:attribute>' + 
+			'		<xsl:attribute name="style"><xsl:value-of select="@style" /></xsl:attribute>' + 
+			'		<xsl:for-each select="@*">' + 
+			'			<xsl:if test="name() != \'style\' and name() != \'class\' and name() != \'href\'">' + 
+			'				<xsl:attribute name="{name()}"><xsl:value-of select="." /></xsl:attribute>' + 
+			'			</xsl:if>' + 
+			'		</xsl:for-each>' + 
+			'			<ins>' + 
+			'				<xsl:attribute name="class">jstree-icon ' + 
+			'					<xsl:if test="string-length(attribute::icon) > 0 and not(contains(@icon,\'/\'))"><xsl:value-of select="@icon" /></xsl:if>' + 
+			'				</xsl:attribute>' + 
+			'				<xsl:if test="string-length(attribute::icon) > 0 and contains(@icon,\'/\')"><xsl:attribute name="style">background:url(<xsl:value-of select="@icon" />) center center no-repeat;</xsl:attribute></xsl:if>' + 
+			'				<xsl:text>&#xa0;</xsl:text>' + 
+			'			</ins>' + 
+			'			<xsl:copy-of select="./child::node()" />' + 
+			'		</a>' + 
+			'	</xsl:for-each>' + 
+			'	<xsl:if test="$children">' + 
+			'		<ul>' + 
+			'		<xsl:for-each select="//item[@parent_id=$node/attribute::id]">' + 
+			'			<xsl:call-template name="nodes">' + 
+			'				<xsl:with-param name="node" select="." />' + 
+			'				<xsl:with-param name="is_last" select="number(position() = last())" />' + 
+			'			</xsl:call-template>' + 
+			'		</xsl:for-each>' + 
+			'		</ul>' + 
+			'	</xsl:if>' + 
+			'	</li>' + 
+			'</xsl:template>' + 
+			'</xsl:stylesheet>'
+	},
+	escape_xml = function(string) {
+		return string
+			.toString()
+			.replace(/&/g, '&amp;')
+			.replace(/</g, '&lt;')
+			.replace(/>/g, '&gt;')
+			.replace(/"/g, '&quot;')
+			.replace(/'/g, '&apos;');
+	};
+	$.jstree.plugin("xml_data", {
+		defaults : { 
+			data : false,
+			ajax : false,
+			xsl : "flat",
+			clean_node : false,
+			correct_state : true,
+			get_skip_empty : false,
+			get_include_preamble : true
+		},
+		_fn : {
+			load_node : function (obj, s_call, e_call) { var _this = this; this.load_node_xml(obj, function () { _this.__callback({ "obj" : _this._get_node(obj) }); s_call.call(this); }, e_call); },
+			_is_loaded : function (obj) { 
+				var s = this._get_settings().xml_data;
+				obj = this._get_node(obj);
+				return obj == -1 || !obj || (!s.ajax && !$.isFunction(s.data)) || obj.is(".jstree-open, .jstree-leaf") || obj.children("ul").children("li").size() > 0;
+			},
+			load_node_xml : function (obj, s_call, e_call) {
+				var s = this.get_settings().xml_data,
+					error_func = function () {},
+					success_func = function () {};
+
+				obj = this._get_node(obj);
+				if(obj && obj !== -1) {
+					if(obj.data("jstree_is_loading")) { return; }
+					else { obj.data("jstree_is_loading",true); }
+				}
+				switch(!0) {
+					case (!s.data && !s.ajax): throw "Neither data nor ajax settings supplied.";
+					case ($.isFunction(s.data)):
+						s.data.call(this, obj, $.proxy(function (d) {
+							this.parse_xml(d, $.proxy(function (d) {
+								if(d) {
+									d = d.replace(/ ?xmlns="[^"]*"/ig, "");
+									if(d.length > 10) {
+										d = $(d);
+										if(obj === -1 || !obj) { this.get_container().children("ul").empty().append(d.children()); }
+										else { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.append(d); obj.removeData("jstree_is_loading"); }
+										if(s.clean_node) { this.clean_node(obj); }
+										if(s_call) { s_call.call(this); }
+									}
+									else {
+										if(obj && obj !== -1) { 
+											obj.children("a.jstree-loading").removeClass("jstree-loading");
+											obj.removeData("jstree_is_loading");
+											if(s.correct_state) { 
+												this.correct_state(obj);
+												if(s_call) { s_call.call(this); } 
+											}
+										}
+										else {
+											if(s.correct_state) { 
+												this.get_container().children("ul").empty();
+												if(s_call) { s_call.call(this); } 
+											}
+										}
+									}
+								}
+							}, this));
+						}, this));
+						break;
+					case (!!s.data && !s.ajax) || (!!s.data && !!s.ajax && (!obj || obj === -1)):
+						if(!obj || obj == -1) {
+							this.parse_xml(s.data, $.proxy(function (d) {
+								if(d) {
+									d = d.replace(/ ?xmlns="[^"]*"/ig, "");
+									if(d.length > 10) {
+										d = $(d);
+										this.get_container().children("ul").empty().append(d.children());
+										if(s.clean_node) { this.clean_node(obj); }
+										if(s_call) { s_call.call(this); }
+									}
+								}
+								else { 
+									if(s.correct_state) { 
+										this.get_container().children("ul").empty(); 
+										if(s_call) { s_call.call(this); }
+									}
+								}
+							}, this));
+						}
+						break;
+					case (!s.data && !!s.ajax) || (!!s.data && !!s.ajax && obj && obj !== -1):
+						error_func = function (x, t, e) {
+							var ef = this.get_settings().xml_data.ajax.error; 
+							if(ef) { ef.call(this, x, t, e); }
+							if(obj !== -1 && obj.length) {
+								obj.children("a.jstree-loading").removeClass("jstree-loading");
+								obj.removeData("jstree_is_loading");
+								if(t === "success" && s.correct_state) { this.correct_state(obj); }
+							}
+							else {
+								if(t === "success" && s.correct_state) { this.get_container().children("ul").empty(); }
+							}
+							if(e_call) { e_call.call(this); }
+						};
+						success_func = function (d, t, x) {
+							d = x.responseText;
+							var sf = this.get_settings().xml_data.ajax.success; 
+							if(sf) { d = sf.call(this,d,t,x) || d; }
+							if(d === "" || (d && d.toString && d.toString().replace(/^[\s\n]+$/,"") === "")) {
+								return error_func.call(this, x, t, "");
+							}
+							this.parse_xml(d, $.proxy(function (d) {
+								if(d) {
+									d = d.replace(/ ?xmlns="[^"]*"/ig, "");
+									if(d.length > 10) {
+										d = $(d);
+										if(obj === -1 || !obj) { this.get_container().children("ul").empty().append(d.children()); }
+										else { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.append(d); obj.removeData("jstree_is_loading"); }
+										if(s.clean_node) { this.clean_node(obj); }
+										if(s_call) { s_call.call(this); }
+									}
+									else {
+										if(obj && obj !== -1) { 
+											obj.children("a.jstree-loading").removeClass("jstree-loading");
+											obj.removeData("jstree_is_loading");
+											if(s.correct_state) { 
+												this.correct_state(obj);
+												if(s_call) { s_call.call(this); } 
+											}
+										}
+										else {
+											if(s.correct_state) { 
+												this.get_container().children("ul").empty();
+												if(s_call) { s_call.call(this); } 
+											}
+										}
+									}
+								}
+							}, this));
+						};
+						s.ajax.context = this;
+						s.ajax.error = error_func;
+						s.ajax.success = success_func;
+						if(!s.ajax.dataType) { s.ajax.dataType = "xml"; }
+						if($.isFunction(s.ajax.url)) { s.ajax.url = s.ajax.url.call(this, obj); }
+						if($.isFunction(s.ajax.data)) { s.ajax.data = s.ajax.data.call(this, obj); }
+						$.ajax(s.ajax);
+						break;
+				}
+			},
+			parse_xml : function (xml, callback) {
+				var s = this._get_settings().xml_data;
+				$.vakata.xslt(xml, xsl[s.xsl], callback);
+			},
+			get_xml : function (tp, obj, li_attr, a_attr, is_callback) {
+				var result = "", 
+					s = this._get_settings(), 
+					_this = this,
+					tmp1, tmp2, li, a, lang;
+				if(!tp) { tp = "flat"; }
+				if(!is_callback) { is_callback = 0; }
+				obj = this._get_node(obj);
+				if(!obj || obj === -1) { obj = this.get_container().find("> ul > li"); }
+				li_attr = $.isArray(li_attr) ? li_attr : [ "id", "class" ];
+				if(!is_callback && this.data.types && $.inArray(s.types.type_attr, li_attr) === -1) { li_attr.push(s.types.type_attr); }
+
+				a_attr = $.isArray(a_attr) ? a_attr : [ ];
+
+				if(!is_callback) { 
+					if(s.xml_data.get_include_preamble) { 
+						result += '<' + '?xml version="1.0" encoding="UTF-8"?' + '>'; 
+					}
+					result += "<root>"; 
+				}
+				obj.each(function () {
+					result += "<item";
+					li = $(this);
+					$.each(li_attr, function (i, v) { 
+						var t = li.attr(v);
+						if(!s.xml_data.get_skip_empty || typeof t !== "undefined") {
+							result += " " + v + "=\"" + escape_xml((" " + (t || "")).replace(/ jstree[^ ]*/ig,'').replace(/\s+$/ig," ").replace(/^ /,"").replace(/ $/,"")) + "\""; 
+						}
+					});
+					if(li.hasClass("jstree-open")) { result += " state=\"open\""; }
+					if(li.hasClass("jstree-closed")) { result += " state=\"closed\""; }
+					if(tp === "flat") { result += " parent_id=\"" + escape_xml(is_callback) + "\""; }
+					result += ">";
+					result += "<content>";
+					a = li.children("a");
+					a.each(function () {
+						tmp1 = $(this);
+						lang = false;
+						result += "<name";
+						if($.inArray("languages", s.plugins) !== -1) {
+							$.each(s.languages, function (k, z) {
+								if(tmp1.hasClass(z)) { result += " lang=\"" + escape_xml(z) + "\""; lang = z; return false; }
+							});
+						}
+						if(a_attr.length) { 
+							$.each(a_attr, function (k, z) {
+								var t = tmp1.attr(z);
+								if(!s.xml_data.get_skip_empty || typeof t !== "undefined") {
+									result += " " + z + "=\"" + escape_xml((" " + t || "").replace(/ jstree[^ ]*/ig,'').replace(/\s+$/ig," ").replace(/^ /,"").replace(/ $/,"")) + "\"";
+								}
+							});
+						}
+						if(tmp1.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').replace(/^\s+$/ig,"").length) {
+							result += ' icon="' + escape_xml(tmp1.children("ins").get(0).className.replace(/jstree[^ ]*|$/ig,'').replace(/\s+$/ig," ").replace(/^ /,"").replace(/ $/,"")) + '"';
+						}
+						if(tmp1.children("ins").get(0).style.backgroundImage.length) {
+							result += ' icon="' + escape_xml(tmp1.children("ins").get(0).style.backgroundImage.replace("url(","").replace(")","").replace(/'/ig,"").replace(/"/ig,"")) + '"';
+						}
+						result += ">";
+						result += "<![CDATA[" + _this.get_text(tmp1, lang) + "]]>";
+						result += "</name>";
+					});
+					result += "</content>";
+					tmp2 = li[0].id || true;
+					li = li.find("> ul > li");
+					if(li.length) { tmp2 = _this.get_xml(tp, li, li_attr, a_attr, tmp2); }
+					else { tmp2 = ""; }
+					if(tp == "nest") { result += tmp2; }
+					result += "</item>";
+					if(tp == "flat") { result += tmp2; }
+				});
+				if(!is_callback) { result += "</root>"; }
+				return result;
+			}
+		}
+	});
+})(jQuery);
+//*/
+
+/*
+ * jsTree search plugin
+ * Enables both sync and async search on the tree
+ * DOES NOT WORK WITH JSON PROGRESSIVE RENDER
+ */
+(function ($) {
+	$.expr[':'].jstree_contains = function(a,i,m){
+		return (a.textContent || a.innerText || "").toLowerCase().indexOf(m[3].toLowerCase())>=0;
+	};
+	$.expr[':'].jstree_title_contains = function(a,i,m) {
+		return (a.getAttribute("title") || "").toLowerCase().indexOf(m[3].toLowerCase())>=0;
+	};
+	$.jstree.plugin("search", {
+		__init : function () {
+			this.data.search.str = "";
+			this.data.search.result = $();
+			if(this._get_settings().search.show_only_matches) {
+				this.get_container()
+					.bind("search.jstree", function (e, data) {
+						$(this).children("ul").find("li").hide().removeClass("jstree-last");
+						data.rslt.nodes.parentsUntil(".jstree").andSelf().show()
+							.filter("ul").each(function () { $(this).children("li:visible").eq(-1).addClass("jstree-last"); });
+					})
+					.bind("clear_search.jstree", function () {
+						$(this).children("ul").find("li").css("display","").end().end().jstree("clean_node", -1);
+					});
+			}
+		},
+		defaults : {
+			ajax : false,
+			search_method : "jstree_contains", // for case insensitive - jstree_contains
+			show_only_matches : false
+		},
+		_fn : {
+			search : function (str, skip_async) {
+				if($.trim(str) === "") { this.clear_search(); return; }
+				var s = this.get_settings().search, 
+					t = this,
+					error_func = function () { },
+					success_func = function () { };
+				this.data.search.str = str;
+
+				if(!skip_async && s.ajax !== false && this.get_container_ul().find("li.jstree-closed:not(:has(ul)):eq(0)").length > 0) {
+					this.search.supress_callback = true;
+					error_func = function () { };
+					success_func = function (d, t, x) {
+						var sf = this.get_settings().search.ajax.success; 
+						if(sf) { d = sf.call(this,d,t,x) || d; }
+						this.data.search.to_open = d;
+						this._search_open();
+					};
+					s.ajax.context = this;
+					s.ajax.error = error_func;
+					s.ajax.success = success_func;
+					if($.isFunction(s.ajax.url)) { s.ajax.url = s.ajax.url.call(this, str); }
+					if($.isFunction(s.ajax.data)) { s.ajax.data = s.ajax.data.call(this, str); }
+					if(!s.ajax.data) { s.ajax.data = { "search_string" : str }; }
+					if(!s.ajax.dataType || /^json/.exec(s.ajax.dataType)) { s.ajax.dataType = "json"; }
+					$.ajax(s.ajax);
+					return;
+				}
+				if(this.data.search.result.length) { this.clear_search(); }
+				this.data.search.result = this.get_container().find("a" + (this.data.languages ? "." + this.get_lang() : "" ) + ":" + (s.search_method) + "(" + this.data.search.str + ")");
+				this.data.search.result.addClass("jstree-search").parent().parents(".jstree-closed").each(function () {
+					t.open_node(this, false, true);
+				});
+				this.__callback({ nodes : this.data.search.result, str : str });
+			},
+			clear_search : function (str) {
+				this.data.search.result.removeClass("jstree-search");
+				this.__callback(this.data.search.result);
+				this.data.search.result = $();
+			},
+			_search_open : function (is_callback) {
+				var _this = this,
+					done = true,
+					current = [],
+					remaining = [];
+				if(this.data.search.to_open.length) {
+					$.each(this.data.search.to_open, function (i, val) {
+						if(val == "#") { return true; }
+						if($(val).length && $(val).is(".jstree-closed")) { current.push(val); }
+						else { remaining.push(val); }
+					});
+					if(current.length) {
+						this.data.search.to_open = remaining;
+						$.each(current, function (i, val) { 
+							_this.open_node(val, function () { _this._search_open(true); }); 
+						});
+						done = false;
+					}
+				}
+				if(done) { this.search(this.data.search.str, true); }
+			}
+		}
+	});
+})(jQuery);
+//*/
+
+/* 
+ * jsTree contextmenu plugin
+ */
+(function ($) {
+	$.vakata.context = {
+		hide_on_mouseleave : false,
+
+		cnt		: $("<div id='vakata-contextmenu' />"),
+		vis		: false,
+		tgt		: false,
+		par		: false,
+		func	: false,
+		data	: false,
+		rtl		: false,
+		show	: function (s, t, x, y, d, p, rtl) {
+			$.vakata.context.rtl = !!rtl;
+			var html = $.vakata.context.parse(s), h, w;
+			if(!html) { return; }
+			$.vakata.context.vis = true;
+			$.vakata.context.tgt = t;
+			$.vakata.context.par = p || t || null;
+			$.vakata.context.data = d || null;
+			$.vakata.context.cnt
+				.html(html)
+				.css({ "visibility" : "hidden", "display" : "block", "left" : 0, "top" : 0 });
+
+			if($.vakata.context.hide_on_mouseleave) {
+				$.vakata.context.cnt
+					.one("mouseleave", function(e) { $.vakata.context.hide(); });
+			}
+
+			h = $.vakata.context.cnt.height();
+			w = $.vakata.context.cnt.width();
+			if(x + w > $(document).width()) { 
+				x = $(document).width() - (w + 5); 
+				$.vakata.context.cnt.find("li > ul").addClass("right"); 
+			}
+			if(y + h > $(document).height()) { 
+				y = y - (h + t[0].offsetHeight); 
+				$.vakata.context.cnt.find("li > ul").addClass("bottom"); 
+			}
+
+			$.vakata.context.cnt
+				.css({ "left" : x, "top" : y })
+				.find("li:has(ul)")
+					.bind("mouseenter", function (e) { 
+						var w = $(document).width(),
+							h = $(document).height(),
+							ul = $(this).children("ul").show(); 
+						if(w !== $(document).width()) { ul.toggleClass("right"); }
+						if(h !== $(document).height()) { ul.toggleClass("bottom"); }
+					})
+					.bind("mouseleave", function (e) { 
+						$(this).children("ul").hide(); 
+					})
+					.end()
+				.css({ "visibility" : "visible" })
+				.show();
+			$(document).triggerHandler("context_show.vakata");
+		},
+		hide	: function () {
+			$.vakata.context.vis = false;
+			$.vakata.context.cnt.attr("class","").css({ "visibility" : "hidden" });
+			$(document).triggerHandler("context_hide.vakata");
+		},
+		parse	: function (s, is_callback) {
+			if(!s) { return false; }
+			var str = "",
+				tmp = false,
+				was_sep = true;
+			if(!is_callback) { $.vakata.context.func = {}; }
+			str += "<ul>";
+			$.each(s, function (i, val) {
+				if(!val) { return true; }
+				$.vakata.context.func[i] = val.action;
+				if(!was_sep && val.separator_before) {
+					str += "<li class='vakata-separator vakata-separator-before'></li>";
+				}
+				was_sep = false;
+				str += "<li class='" + (val._class || "") + (val._disabled ? " jstree-contextmenu-disabled " : "") + "'><ins ";
+				if(val.icon && val.icon.indexOf("/") === -1) { str += " class='" + val.icon + "' "; }
+				if(val.icon && val.icon.indexOf("/") !== -1) { str += " style='background:url(" + val.icon + ") center center no-repeat;' "; }
+				str += ">&#160;</ins><a href='#' rel='" + i + "'>";
+				if(val.submenu) {
+					str += "<span style='float:" + ($.vakata.context.rtl ? "left" : "right") + ";'>&raquo;</span>";
+				}
+				str += val.label + "</a>";
+				if(val.submenu) {
+					tmp = $.vakata.context.parse(val.submenu, true);
+					if(tmp) { str += tmp; }
+				}
+				str += "</li>";
+				if(val.separator_after) {
+					str += "<li class='vakata-separator vakata-separator-after'></li>";
+					was_sep = true;
+				}
+			});
+			str = str.replace(/<li class\='vakata-separator vakata-separator-after'\><\/li\>$/,"");
+			str += "</ul>";
+			$(document).triggerHandler("context_parse.vakata");
+			return str.length > 10 ? str : false;
+		},
+		exec	: function (i) {
+			if($.isFunction($.vakata.context.func[i])) {
+				// if is string - eval and call it!
+				$.vakata.context.func[i].call($.vakata.context.data, $.vakata.context.par);
+				return true;
+			}
+			else { return false; }
+		}
+	};
+	$(function () {
+		var css_string = '' + 
+			'#vakata-contextmenu { display:block; visibility:hidden; left:0; top:-200px; position:absolute; margin:0; padding:0; min-width:180px; background:#ebebeb; border:1px solid silver; z-index:10000; *width:180px; } ' + 
+			'#vakata-contextmenu ul { min-width:180px; *width:180px; } ' + 
+			'#vakata-contextmenu ul, #vakata-contextmenu li { margin:0; padding:0; list-style-type:none; display:block; } ' + 
+			'#vakata-contextmenu li { line-height:20px; min-height:20px; position:relative; padding:0px; } ' + 
+			'#vakata-contextmenu li a { padding:1px 6px; line-height:17px; display:block; text-decoration:none; margin:1px 1px 0 1px; } ' + 
+			'#vakata-contextmenu li ins { float:left; width:16px; height:16px; text-decoration:none; margin-right:2px; } ' + 
+			'#vakata-contextmenu li a:hover, #vakata-contextmenu li.vakata-hover > a { background:gray; color:white; } ' + 
+			'#vakata-contextmenu li ul { display:none; position:absolute; top:-2px; left:100%; background:#ebebeb; border:1px solid gray; } ' + 
+			'#vakata-contextmenu .right { right:100%; left:auto; } ' + 
+			'#vakata-contextmenu .bottom { bottom:-1px; top:auto; } ' + 
+			'#vakata-contextmenu li.vakata-separator { min-height:0; height:1px; line-height:1px; font-size:1px; overflow:hidden; margin:0 2px; background:silver; /* border-top:1px solid #fefefe; */ padding:0; } ';
+		$.vakata.css.add_sheet({ str : css_string, title : "vakata" });
+		$.vakata.context.cnt
+			.delegate("a","click", function (e) { e.preventDefault(); })
+			.delegate("a","mouseup", function (e) {
+				if(!$(this).parent().hasClass("jstree-contextmenu-disabled") && $.vakata.context.exec($(this).attr("rel"))) {
+					$.vakata.context.hide();
+				}
+				else { $(this).blur(); }
+			})
+			.delegate("a","mouseover", function () {
+				$.vakata.context.cnt.find(".vakata-hover").removeClass("vakata-hover");
+			})
+			.appendTo("body");
+		$(document).bind("mousedown", function (e) { if($.vakata.context.vis && !$.contains($.vakata.context.cnt[0], e.target)) { $.vakata.context.hide(); } });
+		if(typeof $.hotkeys !== "undefined") {
+			$(document)
+				.bind("keydown", "up", function (e) { 
+					if($.vakata.context.vis) { 
+						var o = $.vakata.context.cnt.find("ul:visible").last().children(".vakata-hover").removeClass("vakata-hover").prevAll("li:not(.vakata-separator)").first();
+						if(!o.length) { o = $.vakata.context.cnt.find("ul:visible").last().children("li:not(.vakata-separator)").last(); }
+						o.addClass("vakata-hover");
+						e.stopImmediatePropagation(); 
+						e.preventDefault();
+					} 
+				})
+				.bind("keydown", "down", function (e) { 
+					if($.vakata.context.vis) { 
+						var o = $.vakata.context.cnt.find("ul:visible").last().children(".vakata-hover").removeClass("vakata-hover").nextAll("li:not(.vakata-separator)").first();
+						if(!o.length) { o = $.vakata.context.cnt.find("ul:visible").last().children("li:not(.vakata-separator)").first(); }
+						o.addClass("vakata-hover");
+						e.stopImmediatePropagation(); 
+						e.preventDefault();
+					} 
+				})
+				.bind("keydown", "right", function (e) { 
+					if($.vakata.context.vis) { 
+						$.vakata.context.cnt.find(".vakata-hover").children("ul").show().children("li:not(.vakata-separator)").removeClass("vakata-hover").first().addClass("vakata-hover");
+						e.stopImmediatePropagation(); 
+						e.preventDefault();
+					} 
+				})
+				.bind("keydown", "left", function (e) { 
+					if($.vakata.context.vis) { 
+						$.vakata.context.cnt.find(".vakata-hover").children("ul").hide().children(".vakata-separator").removeClass("vakata-hover");
+						e.stopImmediatePropagation(); 
+						e.preventDefault();
+					} 
+				})
+				.bind("keydown", "esc", function (e) { 
+					$.vakata.context.hide(); 
+					e.preventDefault();
+				})
+				.bind("keydown", "space", function (e) { 
+					$.vakata.context.cnt.find(".vakata-hover").last().children("a").click();
+					e.preventDefault();
+				});
+		}
+	});
+
+	$.jstree.plugin("contextmenu", {
+		__init : function () {
+			this.get_container()
+				.delegate("a", "contextmenu.jstree", $.proxy(function (e) {
+						e.preventDefault();
+						if(!$(e.currentTarget).hasClass("jstree-loading")) {
+							this.show_contextmenu(e.currentTarget, e.pageX, e.pageY);
+						}
+					}, this))
+				.delegate("a", "click.jstree", $.proxy(function (e) {
+						if(this.data.contextmenu) {
+							$.vakata.context.hide();
+						}
+					}, this))
+				.bind("destroy.jstree", $.proxy(function () {
+						// TODO: move this to descruct method
+						if(this.data.contextmenu) {
+							$.vakata.context.hide();
+						}
+					}, this));
+			$(document).bind("context_hide.vakata", $.proxy(function () { this.data.contextmenu = false; }, this));
+		},
+		defaults : { 
+			select_node : false, // requires UI plugin
+			show_at_node : true,
+			items : { // Could be a function that should return an object like this one
+				"create" : {
+					"separator_before"	: false,
+					"separator_after"	: true,
+					"label"				: "Create",
+					"action"			: function (obj) { this.create(obj); }
+				},
+				"rename" : {
+					"separator_before"	: false,
+					"separator_after"	: false,
+					"label"				: "Rename",
+					"action"			: function (obj) { this.rename(obj); }
+				},
+				"remove" : {
+					"separator_before"	: false,
+					"icon"				: false,
+					"separator_after"	: false,
+					"label"				: "Delete",
+					"action"			: function (obj) { if(this.is_selected(obj)) { this.remove(); } else { this.remove(obj); } }
+				},
+				"ccp" : {
+					"separator_before"	: true,
+					"icon"				: false,
+					"separator_after"	: false,
+					"label"				: "Edit",
+					"action"			: false,
+					"submenu" : { 
+						"cut" : {
+							"separator_before"	: false,
+							"separator_after"	: false,
+							"label"				: "Cut",
+							"action"			: function (obj) { this.cut(obj); }
+						},
+						"copy" : {
+							"separator_before"	: false,
+							"icon"				: false,
+							"separator_after"	: false,
+							"label"				: "Copy",
+							"action"			: function (obj) { this.copy(obj); }
+						},
+						"paste" : {
+							"separator_before"	: false,
+							"icon"				: false,
+							"separator_after"	: false,
+							"label"				: "Paste",
+							"action"			: function (obj) { this.paste(obj); }
+						}
+					}
+				}
+			}
+		},
+		_fn : {
+			show_contextmenu : function (obj, x, y) {
+				obj = this._get_node(obj);
+				var s = this.get_settings().contextmenu,
+					a = obj.children("a:visible:eq(0)"),
+					o = false,
+					i = false;
+				if(s.select_node && this.data.ui && !this.is_selected(obj)) {
+					this.deselect_all();
+					this.select_node(obj, true);
+				}
+				if(s.show_at_node || typeof x === "undefined" || typeof y === "undefined") {
+					o = a.offset();
+					x = o.left;
+					y = o.top + this.data.core.li_height;
+				}
+				i = obj.data("jstree") && obj.data("jstree").contextmenu ? obj.data("jstree").contextmenu : s.items;
+				if($.isFunction(i)) { i = i.call(this, obj); }
+				this.data.contextmenu = true;
+				$.vakata.context.show(i, a, x, y, this, obj, this._get_settings().core.rtl);
+				if(this.data.themes) { $.vakata.context.cnt.attr("class", "jstree-" + this.data.themes.theme + "-context"); }
+			}
+		}
+	});
+})(jQuery);
+//*/
+
+/* 
+ * jsTree types plugin
+ * Adds support types of nodes
+ * You can set an attribute on each li node, that represents its type.
+ * According to the type setting the node may get custom icon/validation rules
+ */
+(function ($) {
+	$.jstree.plugin("types", {
+		__init : function () {
+			var s = this._get_settings().types;
+			this.data.types.attach_to = [];
+			this.get_container()
+				.bind("init.jstree", $.proxy(function () { 
+						var types = s.types, 
+							attr  = s.type_attr, 
+							icons_css = "", 
+							_this = this;
+
+						$.each(types, function (i, tp) {
+							$.each(tp, function (k, v) { 
+								if(!/^(max_depth|max_children|icon|valid_children)$/.test(k)) { _this.data.types.attach_to.push(k); }
+							});
+							if(!tp.icon) { return true; }
+							if( tp.icon.image || tp.icon.position) {
+								if(i == "default")	{ icons_css += '.jstree-' + _this.get_index() + ' a > .jstree-icon { '; }
+								else				{ icons_css += '.jstree-' + _this.get_index() + ' li[' + attr + '="' + i + '"] > a > .jstree-icon { '; }
+								if(tp.icon.image)	{ icons_css += ' background-image:url(' + tp.icon.image + '); '; }
+								if(tp.icon.position){ icons_css += ' background-position:' + tp.icon.position + '; '; }
+								else				{ icons_css += ' background-position:0 0; '; }
+								icons_css += '} ';
+							}
+						});
+						if(icons_css !== "") { $.vakata.css.add_sheet({ 'str' : icons_css, title : "jstree-types" }); }
+					}, this))
+				.bind("before.jstree", $.proxy(function (e, data) { 
+						var s, t, 
+							o = this._get_settings().types.use_data ? this._get_node(data.args[0]) : false, 
+							d = o && o !== -1 && o.length ? o.data("jstree") : false;
+						if(d && d.types && d.types[data.func] === false) { e.stopImmediatePropagation(); return false; }
+						if($.inArray(data.func, this.data.types.attach_to) !== -1) {
+							if(!data.args[0] || (!data.args[0].tagName && !data.args[0].jquery)) { return; }
+							s = this._get_settings().types.types;
+							t = this._get_type(data.args[0]);
+							if(
+								( 
+									(s[t] && typeof s[t][data.func] !== "undefined") || 
+									(s["default"] && typeof s["default"][data.func] !== "undefined") 
+								) && this._check(data.func, data.args[0]) === false
+							) {
+								e.stopImmediatePropagation();
+								return false;
+							}
+						}
+					}, this));
+			if(is_ie6) {
+				this.get_container()
+					.bind("load_node.jstree set_type.jstree", $.proxy(function (e, data) {
+							var r = data && data.rslt && data.rslt.obj && data.rslt.obj !== -1 ? this._get_node(data.rslt.obj).parent() : this.get_container_ul(),
+								c = false,
+								s = this._get_settings().types;
+							$.each(s.types, function (i, tp) {
+								if(tp.icon && (tp.icon.image || tp.icon.position)) {
+									c = i === "default" ? r.find("li > a > .jstree-icon") : r.find("li[" + s.type_attr + "='" + i + "'] > a > .jstree-icon");
+									if(tp.icon.image) { c.css("backgroundImage","url(" + tp.icon.image + ")"); }
+									c.css("backgroundPosition", tp.icon.position || "0 0");
+								}
+							});
+						}, this));
+			}
+		},
+		defaults : {
+			// defines maximum number of root nodes (-1 means unlimited, -2 means disable max_children checking)
+			max_children		: -1,
+			// defines the maximum depth of the tree (-1 means unlimited, -2 means disable max_depth checking)
+			max_depth			: -1,
+			// defines valid node types for the root nodes
+			valid_children		: "all",
+
+			// whether to use $.data
+			use_data : false, 
+			// where is the type stores (the rel attribute of the LI element)
+			type_attr : "rel",
+			// a list of types
+			types : {
+				// the default type
+				"default" : {
+					"max_children"	: -1,
+					"max_depth"		: -1,
+					"valid_children": "all"
+
+					// Bound functions - you can bind any other function here (using boolean or function)
+					//"select_node"	: true
+				}
+			}
+		},
+		_fn : {
+			_types_notify : function (n, data) {
+				if(data.type && this._get_settings().types.use_data) {
+					this.set_type(data.type, n);
+				}
+			},
+			_get_type : function (obj) {
+				obj = this._get_node(obj);
+				return (!obj || !obj.length) ? false : obj.attr(this._get_settings().types.type_attr) || "default";
+			},
+			set_type : function (str, obj) {
+				obj = this._get_node(obj);
+				var ret = (!obj.length || !str) ? false : obj.attr(this._get_settings().types.type_attr, str);
+				if(ret) { this.__callback({ obj : obj, type : str}); }
+				return ret;
+			},
+			_check : function (rule, obj, opts) {
+				obj = this._get_node(obj);
+				var v = false, t = this._get_type(obj), d = 0, _this = this, s = this._get_settings().types, data = false;
+				if(obj === -1) { 
+					if(!!s[rule]) { v = s[rule]; }
+					else { return; }
+				}
+				else {
+					if(t === false) { return; }
+					data = s.use_data ? obj.data("jstree") : false;
+					if(data && data.types && typeof data.types[rule] !== "undefined") { v = data.types[rule]; }
+					else if(!!s.types[t] && typeof s.types[t][rule] !== "undefined") { v = s.types[t][rule]; }
+					else if(!!s.types["default"] && typeof s.types["default"][rule] !== "undefined") { v = s.types["default"][rule]; }
+				}
+				if($.isFunction(v)) { v = v.call(this, obj); }
+				if(rule === "max_depth" && obj !== -1 && opts !== false && s.max_depth !== -2 && v !== 0) {
+					// also include the node itself - otherwise if root node it is not checked
+					obj.children("a:eq(0)").parentsUntil(".jstree","li").each(function (i) {
+						// check if current depth already exceeds global tree depth
+						if(s.max_depth !== -1 && s.max_depth - (i + 1) <= 0) { v = 0; return false; }
+						d = (i === 0) ? v : _this._check(rule, this, false);
+						// check if current node max depth is already matched or exceeded
+						if(d !== -1 && d - (i + 1) <= 0) { v = 0; return false; }
+						// otherwise - set the max depth to the current value minus current depth
+						if(d >= 0 && (d - (i + 1) < v || v < 0) ) { v = d - (i + 1); }
+						// if the global tree depth exists and it minus the nodes calculated so far is less than `v` or `v` is unlimited
+						if(s.max_depth >= 0 && (s.max_depth - (i + 1) < v || v < 0) ) { v = s.max_depth - (i + 1); }
+					});
+				}
+				return v;
+			},
+			check_move : function () {
+				if(!this.__call_old()) { return false; }
+				var m  = this._get_move(),
+					s  = m.rt._get_settings().types,
+					mc = m.rt._check("max_children", m.cr),
+					md = m.rt._check("max_depth", m.cr),
+					vc = m.rt._check("valid_children", m.cr),
+					ch = 0, d = 1, t;
+
+				if(vc === "none") { return false; } 
+				if($.isArray(vc) && m.ot && m.ot._get_type) {
+					m.o.each(function () {
+						if($.inArray(m.ot._get_type(this), vc) === -1) { d = false; return false; }
+					});
+					if(d === false) { return false; }
+				}
+				if(s.max_children !== -2 && mc !== -1) {
+					ch = m.cr === -1 ? this.get_container().find("> ul > li").not(m.o).length : m.cr.find("> ul > li").not(m.o).length;
+					if(ch + m.o.length > mc) { return false; }
+				}
+				if(s.max_depth !== -2 && md !== -1) {
+					d = 0;
+					if(md === 0) { return false; }
+					if(typeof m.o.d === "undefined") {
+						// TODO: deal with progressive rendering and async when checking max_depth (how to know the depth of the moved node)
+						t = m.o;
+						while(t.length > 0) {
+							t = t.find("> ul > li");
+							d ++;
+						}
+						m.o.d = d;
+					}
+					if(md - m.o.d < 0) { return false; }
+				}
+				return true;
+			},
+			create_node : function (obj, position, js, callback, is_loaded, skip_check) {
+				if(!skip_check && (is_loaded || this._is_loaded(obj))) {
+					var p  = (typeof position == "string" && position.match(/^before|after$/i) && obj !== -1) ? this._get_parent(obj) : this._get_node(obj),
+						s  = this._get_settings().types,
+						mc = this._check("max_children", p),
+						md = this._check("max_depth", p),
+						vc = this._check("valid_children", p),
+						ch;
+					if(typeof js === "string") { js = { data : js }; }
+					if(!js) { js = {}; }
+					if(vc === "none") { return false; } 
+					if($.isArray(vc)) {
+						if(!js.attr || !js.attr[s.type_attr]) { 
+							if(!js.attr) { js.attr = {}; }
+							js.attr[s.type_attr] = vc[0]; 
+						}
+						else {
+							if($.inArray(js.attr[s.type_attr], vc) === -1) { return false; }
+						}
+					}
+					if(s.max_children !== -2 && mc !== -1) {
+						ch = p === -1 ? this.get_container().find("> ul > li").length : p.find("> ul > li").length;
+						if(ch + 1 > mc) { return false; }
+					}
+					if(s.max_depth !== -2 && md !== -1 && (md - 1) < 0) { return false; }
+				}
+				return this.__call_old(true, obj, position, js, callback, is_loaded, skip_check);
+			}
+		}
+	});
+})(jQuery);
+//*/
+
+/* 
+ * jsTree HTML plugin
+ * The HTML data store. Datastores are build by replacing the `load_node` and `_is_loaded` functions.
+ */
+(function ($) {
+	$.jstree.plugin("html_data", {
+		__init : function () { 
+			// this used to use html() and clean the whitespace, but this way any attached data was lost
+			this.data.html_data.original_container_html = this.get_container().find(" > ul > li").clone(true);
+			// remove white space from LI node - otherwise nodes appear a bit to the right
+			this.data.html_data.original_container_html.find("li").andSelf().contents().filter(function() { return this.nodeType == 3; }).remove();
+		},
+		defaults : { 
+			data : false,
+			ajax : false,
+			correct_state : true
+		},
+		_fn : {
+			load_node : function (obj, s_call, e_call) { var _this = this; this.load_node_html(obj, function () { _this.__callback({ "obj" : _this._get_node(obj) }); s_call.call(this); }, e_call); },
+			_is_loaded : function (obj) { 
+				obj = this._get_node(obj); 
+				return obj == -1 || !obj || (!this._get_settings().html_data.ajax && !$.isFunction(this._get_settings().html_data.data)) || obj.is(".jstree-open, .jstree-leaf") || obj.children("ul").children("li").size() > 0;
+			},
+			load_node_html : function (obj, s_call, e_call) {
+				var d,
+					s = this.get_settings().html_data,
+					error_func = function () {},
+					success_func = function () {};
+				obj = this._get_node(obj);
+				if(obj && obj !== -1) {
+					if(obj.data("jstree_is_loading")) { return; }
+					else { obj.data("jstree_is_loading",true); }
+				}
+				switch(!0) {
+					case ($.isFunction(s.data)):
+						s.data.call(this, obj, $.proxy(function (d) {
+							if(d && d !== "" && d.toString && d.toString().replace(/^[\s\n]+$/,"") !== "") {
+								d = $(d);
+								if(!d.is("ul")) { d = $("<ul />").append(d); }
+								if(obj == -1 || !obj) { this.get_container().children("ul").empty().append(d.children()).find("li, a").filter(function () { return !this.firstChild || !this.firstChild.tagName || this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'>&#160;</ins>").end().filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon"); }
+								else { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.append(d).children("ul").find("li, a").filter(function () { return !this.firstChild || !this.firstChild.tagName || this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'>&#160;</ins>").end().filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon"); obj.removeData("jstree_is_loading"); }
+								this.clean_node(obj);
+								if(s_call) { s_call.call(this); }
+							}
+							else {
+								if(obj && obj !== -1) {
+									obj.children("a.jstree-loading").removeClass("jstree-loading");
+									obj.removeData("jstree_is_loading");
+									if(s.correct_state) { 
+										this.correct_state(obj);
+										if(s_call) { s_call.call(this); } 
+									}
+								}
+								else {
+									if(s.correct_state) { 
+										this.get_container().children("ul").empty();
+										if(s_call) { s_call.call(this); } 
+									}
+								}
+							}
+						}, this));
+						break;
+					case (!s.data && !s.ajax):
+						if(!obj || obj == -1) {
+							this.get_container()
+								.children("ul").empty()
+								.append(this.data.html_data.original_container_html)
+								.find("li, a").filter(function () { return !this.firstChild || !this.firstChild.tagName || this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'>&#160;</ins>").end()
+								.filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon");
+							this.clean_node();
+						}
+						if(s_call) { s_call.call(this); }
+						break;
+					case (!!s.data && !s.ajax) || (!!s.data && !!s.ajax && (!obj || obj === -1)):
+						if(!obj || obj == -1) {
+							d = $(s.data);
+							if(!d.is("ul")) { d = $("<ul />").append(d); }
+							this.get_container()
+								.children("ul").empty().append(d.children())
+								.find("li, a").filter(function () { return !this.firstChild || !this.firstChild.tagName || this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'>&#160;</ins>").end()
+								.filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon");
+							this.clean_node();
+						}
+						if(s_call) { s_call.call(this); }
+						break;
+					case (!s.data && !!s.ajax) || (!!s.data && !!s.ajax && obj && obj !== -1):
+						obj = this._get_node(obj);
+						error_func = function (x, t, e) {
+							var ef = this.get_settings().html_data.ajax.error; 
+							if(ef) { ef.call(this, x, t, e); }
+							if(obj != -1 && obj.length) {
+								obj.children("a.jstree-loading").removeClass("jstree-loading");
+								obj.removeData("jstree_is_loading");
+								if(t === "success" && s.correct_state) { this.correct_state(obj); }
+							}
+							else {
+								if(t === "success" && s.correct_state) { this.get_container().children("ul").empty(); }
+							}
+							if(e_call) { e_call.call(this); }
+						};
+						success_func = function (d, t, x) {
+							var sf = this.get_settings().html_data.ajax.success; 
+							if(sf) { d = sf.call(this,d,t,x) || d; }
+							if(d === "" || (d && d.toString && d.toString().replace(/^[\s\n]+$/,"") === "")) {
+								return error_func.call(this, x, t, "");
+							}
+							if(d) {
+								d = $(d);
+								if(!d.is("ul")) { d = $("<ul />").append(d); }
+								if(obj == -1 || !obj) { this.get_container().children("ul").empty().append(d.children()).find("li, a").filter(function () { return !this.firstChild || !this.firstChild.tagName || this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'>&#160;</ins>").end().filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon"); }
+								else { obj.children("a.jstree-loading").removeClass("jstree-loading"); obj.append(d).children("ul").find("li, a").filter(function () { return !this.firstChild || !this.firstChild.tagName || this.firstChild.tagName !== "INS"; }).prepend("<ins class='jstree-icon'>&#160;</ins>").end().filter("a").children("ins:first-child").not(".jstree-icon").addClass("jstree-icon"); obj.removeData("jstree_is_loading"); }
+								this.clean_node(obj);
+								if(s_call) { s_call.call(this); }
+							}
+							else {
+								if(obj && obj !== -1) {
+									obj.children("a.jstree-loading").removeClass("jstree-loading");
+									obj.removeData("jstree_is_loading");
+									if(s.correct_state) { 
+										this.correct_state(obj);
+										if(s_call) { s_call.call(this); } 
+									}
+								}
+								else {
+									if(s.correct_state) { 
+										this.get_container().children("ul").empty();
+										if(s_call) { s_call.call(this); } 
+									}
+								}
+							}
+						};
+						s.ajax.context = this;
+						s.ajax.error = error_func;
+						s.ajax.success = success_func;
+						if(!s.ajax.dataType) { s.ajax.dataType = "html"; }
+						if($.isFunction(s.ajax.url)) { s.ajax.url = s.ajax.url.call(this, obj); }
+						if($.isFunction(s.ajax.data)) { s.ajax.data = s.ajax.data.call(this, obj); }
+						$.ajax(s.ajax);
+						break;
+				}
+			}
+		}
+	});
+	// include the HTML data plugin by default
+	$.jstree.defaults.plugins.push("html_data");
+})(jQuery);
+//*/
+
+/* 
+ * jsTree themeroller plugin
+ * Adds support for jQuery UI themes. Include this at the end of your plugins list, also make sure "themes" is not included.
+ */
+(function ($) {
+	$.jstree.plugin("themeroller", {
+		__init : function () {
+			var s = this._get_settings().themeroller;
+			this.get_container()
+				.addClass("ui-widget-content")
+				.addClass("jstree-themeroller")
+				.delegate("a","mouseenter.jstree", function (e) {
+					if(!$(e.currentTarget).hasClass("jstree-loading")) {
+						$(this).addClass(s.item_h);
+					}
+				})
+				.delegate("a","mouseleave.jstree", function () {
+					$(this).removeClass(s.item_h);
+				})
+				.bind("init.jstree", $.proxy(function (e, data) { 
+						data.inst.get_container().find("> ul > li > .jstree-loading > ins").addClass("ui-icon-refresh");
+						this._themeroller(data.inst.get_container().find("> ul > li"));
+					}, this))
+				.bind("open_node.jstree create_node.jstree", $.proxy(function (e, data) { 
+						this._themeroller(data.rslt.obj);
+					}, this))
+				.bind("loaded.jstree refresh.jstree", $.proxy(function (e) {
+						this._themeroller();
+					}, this))
+				.bind("close_node.jstree", $.proxy(function (e, data) {
+						this._themeroller(data.rslt.obj);
+					}, this))
+				.bind("delete_node.jstree", $.proxy(function (e, data) {
+						this._themeroller(data.rslt.parent);
+					}, this))
+				.bind("correct_state.jstree", $.proxy(function (e, data) {
+						data.rslt.obj
+							.children("ins.jstree-icon").removeClass(s.opened + " " + s.closed + " ui-icon").end()
+							.find("> a > ins.ui-icon")
+								.filter(function() { 
+									return this.className.toString()
+										.replace(s.item_clsd,"").replace(s.item_open,"").replace(s.item_leaf,"")
+										.indexOf("ui-icon-") === -1; 
+								}).removeClass(s.item_open + " " + s.item_clsd).addClass(s.item_leaf || "jstree-no-icon");
+					}, this))
+				.bind("select_node.jstree", $.proxy(function (e, data) {
+						data.rslt.obj.children("a").addClass(s.item_a);
+					}, this))
+				.bind("deselect_node.jstree deselect_all.jstree", $.proxy(function (e, data) {
+						this.get_container()
+							.find("a." + s.item_a).removeClass(s.item_a).end()
+							.find("a.jstree-clicked").addClass(s.item_a);
+					}, this))
+				.bind("dehover_node.jstree", $.proxy(function (e, data) {
+						data.rslt.obj.children("a").removeClass(s.item_h);
+					}, this))
+				.bind("hover_node.jstree", $.proxy(function (e, data) {
+						this.get_container()
+							.find("a." + s.item_h).not(data.rslt.obj).removeClass(s.item_h);
+						data.rslt.obj.children("a").addClass(s.item_h);
+					}, this))
+				.bind("move_node.jstree", $.proxy(function (e, data) {
+						this._themeroller(data.rslt.o);
+						this._themeroller(data.rslt.op);
+					}, this));
+		},
+		__destroy : function () {
+			var s = this._get_settings().themeroller,
+				c = [ "ui-icon" ];
+			$.each(s, function (i, v) {
+				v = v.split(" ");
+				if(v.length) { c = c.concat(v); }
+			});
+			this.get_container()
+				.removeClass("ui-widget-content")
+				.find("." + c.join(", .")).removeClass(c.join(" "));
+		},
+		_fn : {
+			_themeroller : function (obj) {
+				var s = this._get_settings().themeroller;
+				obj = !obj || obj == -1 ? this.get_container_ul() : this._get_node(obj).parent();
+				obj
+					.find("li.jstree-closed")
+						.children("ins.jstree-icon").removeClass(s.opened).addClass("ui-icon " + s.closed).end()
+						.children("a").addClass(s.item)
+							.children("ins.jstree-icon").addClass("ui-icon")
+								.filter(function() { 
+									return this.className.toString()
+										.replace(s.item_clsd,"").replace(s.item_open,"").replace(s.item_leaf,"")
+										.indexOf("ui-icon-") === -1; 
+								}).removeClass(s.item_leaf + " " + s.item_open).addClass(s.item_clsd || "jstree-no-icon")
+								.end()
+							.end()
+						.end()
+					.end()
+					.find("li.jstree-open")
+						.children("ins.jstree-icon").removeClass(s.closed).addClass("ui-icon " + s.opened).end()
+						.children("a").addClass(s.item)
+							.children("ins.jstree-icon").addClass("ui-icon")
+								.filter(function() { 
+									return this.className.toString()
+										.replace(s.item_clsd,"").replace(s.item_open,"").replace(s.item_leaf,"")
+										.indexOf("ui-icon-") === -1; 
+								}).removeClass(s.item_leaf + " " + s.item_clsd).addClass(s.item_open || "jstree-no-icon")
+								.end()
+							.end()
+						.end()
+					.end()
+					.find("li.jstree-leaf")
+						.children("ins.jstree-icon").removeClass(s.closed + " ui-icon " + s.opened).end()
+						.children("a").addClass(s.item)
+							.children("ins.jstree-icon").addClass("ui-icon")
+								.filter(function() { 
+									return this.className.toString()
+										.replace(s.item_clsd,"").replace(s.item_open,"").replace(s.item_leaf,"")
+										.indexOf("ui-icon-") === -1; 
+								}).removeClass(s.item_clsd + " " + s.item_open).addClass(s.item_leaf || "jstree-no-icon");
+			}
+		},
+		defaults : {
+			"opened"	: "ui-icon-triangle-1-se",
+			"closed"	: "ui-icon-triangle-1-e",
+			"item"		: "ui-state-default",
+			"item_h"	: "ui-state-hover",
+			"item_a"	: "ui-state-active",
+			"item_open"	: "ui-icon-folder-open",
+			"item_clsd"	: "ui-icon-folder-collapsed",
+			"item_leaf"	: "ui-icon-document"
+		}
+	});
+	$(function() {
+		var css_string = '' + 
+			'.jstree-themeroller .ui-icon { overflow:visible; } ' + 
+			'.jstree-themeroller a { padding:0 2px; } ' + 
+			'.jstree-themeroller .jstree-no-icon { display:none; }';
+		$.vakata.css.add_sheet({ str : css_string, title : "jstree" });
+	});
+})(jQuery);
+//*/
+
+/* 
+ * jsTree unique plugin
+ * Forces different names amongst siblings (still a bit experimental)
+ * NOTE: does not check language versions (it will not be possible to have nodes with the same title, even in different languages)
+ */
+(function ($) {
+	$.jstree.plugin("unique", {
+		__init : function () {
+			this.get_container()
+				.bind("before.jstree", $.proxy(function (e, data) { 
+						var nms = [], res = true, p, t;
+						if(data.func == "move_node") {
+							// obj, ref, position, is_copy, is_prepared, skip_check
+							if(data.args[4] === true) {
+								if(data.args[0].o && data.args[0].o.length) {
+									data.args[0].o.children("a").each(function () { nms.push($(this).text().replace(/^\s+/g,"")); });
+									res = this._check_unique(nms, data.args[0].np.find("> ul > li").not(data.args[0].o), "move_node");
+								}
+							}
+						}
+						if(data.func == "create_node") {
+							// obj, position, js, callback, is_loaded
+							if(data.args[4] || this._is_loaded(data.args[0])) {
+								p = this._get_node(data.args[0]);
+								if(data.args[1] && (data.args[1] === "before" || data.args[1] === "after")) {
+									p = this._get_parent(data.args[0]);
+									if(!p || p === -1) { p = this.get_container(); }
+								}
+								if(typeof data.args[2] === "string") { nms.push(data.args[2]); }
+								else if(!data.args[2] || !data.args[2].data) { nms.push(this._get_string("new_node")); }
+								else { nms.push(data.args[2].data); }
+								res = this._check_unique(nms, p.find("> ul > li"), "create_node");
+							}
+						}
+						if(data.func == "rename_node") {
+							// obj, val
+							nms.push(data.args[1]);
+							t = this._get_node(data.args[0]);
+							p = this._get_parent(t);
+							if(!p || p === -1) { p = this.get_container(); }
+							res = this._check_unique(nms, p.find("> ul > li").not(t), "rename_node");
+						}
+						if(!res) {
+							e.stopPropagation();
+							return false;
+						}
+					}, this));
+		},
+		defaults : { 
+			error_callback : $.noop
+		},
+		_fn : { 
+			_check_unique : function (nms, p, func) {
+				var cnms = [];
+				p.children("a").each(function () { cnms.push($(this).text().replace(/^\s+/g,"")); });
+				if(!cnms.length || !nms.length) { return true; }
+				cnms = cnms.sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(",");
+				if((cnms.length + nms.length) != cnms.concat(nms).sort().join(",,").replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,"$1$2$4").replace(/,,+/g,",").replace(/,$/,"").split(",").length) {
+					this._get_settings().unique.error_callback.call(null, nms, p, func);
+					return false;
+				}
+				return true;
+			},
+			check_move : function () {
+				if(!this.__call_old()) { return false; }
+				var p = this._get_move(), nms = [];
+				if(p.o && p.o.length) {
+					p.o.children("a").each(function () { nms.push($(this).text().replace(/^\s+/g,"")); });
+					return this._check_unique(nms, p.np.find("> ul > li").not(p.o), "check_move");
+				}
+				return true;
+			}
+		}
+	});
+})(jQuery);
+//*/
+
+/*
+ * jsTree wholerow plugin
+ * Makes select and hover work on the entire width of the node
+ * MAY BE HEAVY IN LARGE DOM
+ */
+(function ($) {
+	$.jstree.plugin("wholerow", {
+		__init : function () {
+			if(!this.data.ui) { throw "jsTree wholerow: jsTree UI plugin not included."; }
+			this.data.wholerow.html = false;
+			this.data.wholerow.to = false;
+			this.get_container()
+				.bind("init.jstree", $.proxy(function (e, data) { 
+						this._get_settings().core.animation = 0;
+					}, this))
+				.bind("open_node.jstree create_node.jstree clean_node.jstree loaded.jstree", $.proxy(function (e, data) { 
+						this._prepare_wholerow_span( data && data.rslt && data.rslt.obj ? data.rslt.obj : -1 );
+					}, this))
+				.bind("search.jstree clear_search.jstree reopen.jstree after_open.jstree after_close.jstree create_node.jstree delete_node.jstree clean_node.jstree", $.proxy(function (e, data) { 
+						if(this.data.to) { clearTimeout(this.data.to); }
+						this.data.to = setTimeout( (function (t, o) { return function() { t._prepare_wholerow_ul(o); }; })(this,  data && data.rslt && data.rslt.obj ? data.rslt.obj : -1), 0);
+					}, this))
+				.bind("deselect_all.jstree", $.proxy(function (e, data) { 
+						this.get_container().find(" > .jstree-wholerow .jstree-clicked").removeClass("jstree-clicked " + (this.data.themeroller ? this._get_settings().themeroller.item_a : "" ));
+					}, this))
+				.bind("select_node.jstree deselect_node.jstree ", $.proxy(function (e, data) { 
+						data.rslt.obj.each(function () { 
+							var ref = data.inst.get_container().find(" > .jstree-wholerow li:visible:eq(" + ( parseInt((($(this).offset().top - data.inst.get_container().offset().top + data.inst.get_container()[0].scrollTop) / data.inst.data.core.li_height),10)) + ")");
+							// ref.children("a")[e.type === "select_node" ? "addClass" : "removeClass"]("jstree-clicked");
+							ref.children("a").attr("class",data.rslt.obj.children("a").attr("class"));
+						});
+					}, this))
+				.bind("hover_node.jstree dehover_node.jstree", $.proxy(function (e, data) { 
+						this.get_container().find(" > .jstree-wholerow .jstree-hovered").removeClass("jstree-hovered " + (this.data.themeroller ? this._get_settings().themeroller.item_h : "" ));
+						if(e.type === "hover_node") {
+							var ref = this.get_container().find(" > .jstree-wholerow li:visible:eq(" + ( parseInt(((data.rslt.obj.offset().top - this.get_container().offset().top + this.get_container()[0].scrollTop) / this.data.core.li_height),10)) + ")");
+							// ref.children("a").addClass("jstree-hovered");
+							ref.children("a").attr("class",data.rslt.obj.children(".jstree-hovered").attr("class"));
+						}
+					}, this))
+				.delegate(".jstree-wholerow-span, ins.jstree-icon, li", "click.jstree", function (e) {
+						var n = $(e.currentTarget);
+						if(e.target.tagName === "A" || (e.target.tagName === "INS" && n.closest("li").is(".jstree-open, .jstree-closed"))) { return; }
+						n.closest("li").children("a:visible:eq(0)").click();
+						e.stopImmediatePropagation();
+					})
+				.delegate("li", "mouseover.jstree", $.proxy(function (e) {
+						e.stopImmediatePropagation();
+						if($(e.currentTarget).children(".jstree-hovered, .jstree-clicked").length) { return false; }
+						this.hover_node(e.currentTarget);
+						return false;
+					}, this))
+				.delegate("li", "mouseleave.jstree", $.proxy(function (e) {
+						if($(e.currentTarget).children("a").hasClass("jstree-hovered").length) { return; }
+						this.dehover_node(e.currentTarget);
+					}, this));
+			if(is_ie7 || is_ie6) {
+				$.vakata.css.add_sheet({ str : ".jstree-" + this.get_index() + " { position:relative; } ", title : "jstree" });
+			}
+		},
+		defaults : {
+		},
+		__destroy : function () {
+			this.get_container().children(".jstree-wholerow").remove();
+			this.get_container().find(".jstree-wholerow-span").remove();
+		},
+		_fn : {
+			_prepare_wholerow_span : function (obj) {
+				obj = !obj || obj == -1 ? this.get_container().find("> ul > li") : this._get_node(obj);
+				if(obj === false) { return; } // added for removing root nodes
+				obj.each(function () {
+					$(this).find("li").andSelf().each(function () {
+						var $t = $(this);
+						if($t.children(".jstree-wholerow-span").length) { return true; }
+						$t.prepend("<span class='jstree-wholerow-span' style='width:" + ($t.parentsUntil(".jstree","li").length * 18) + "px;'>&#160;</span>");
+					});
+				});
+			},
+			_prepare_wholerow_ul : function () {
+				var o = this.get_container().children("ul").eq(0), h = o.html();
+				o.addClass("jstree-wholerow-real");
+				if(this.data.wholerow.last_html !== h) {
+					this.data.wholerow.last_html = h;
+					this.get_container().children(".jstree-wholerow").remove();
+					this.get_container().append(
+						o.clone().removeClass("jstree-wholerow-real")
+							.wrapAll("<div class='jstree-wholerow' />").parent()
+							.width(o.parent()[0].scrollWidth)
+							.css("top", (o.height() + ( is_ie7 ? 5 : 0)) * -1 )
+							.find("li[id]").each(function () { this.removeAttribute("id"); }).end()
+					);
+				}
+			}
+		}
+	});
+	$(function() {
+		var css_string = '' + 
+			'.jstree .jstree-wholerow-real { position:relative; z-index:1; } ' + 
+			'.jstree .jstree-wholerow-real li { cursor:pointer; } ' + 
+			'.jstree .jstree-wholerow-real a { border-left-color:transparent !important; border-right-color:transparent !important; } ' + 
+			'.jstree .jstree-wholerow { position:relative; z-index:0; height:0; } ' + 
+			'.jstree .jstree-wholerow ul, .jstree .jstree-wholerow li { width:100%; } ' + 
+			'.jstree .jstree-wholerow, .jstree .jstree-wholerow ul, .jstree .jstree-wholerow li, .jstree .jstree-wholerow a { margin:0 !important; padding:0 !important; } ' + 
+			'.jstree .jstree-wholerow, .jstree .jstree-wholerow ul, .jstree .jstree-wholerow li { background:transparent !important; }' + 
+			'.jstree .jstree-wholerow ins, .jstree .jstree-wholerow span, .jstree .jstree-wholerow input { display:none !important; }' + 
+			'.jstree .jstree-wholerow a, .jstree .jstree-wholerow a:hover { text-indent:-9999px; !important; width:100%; padding:0 !important; border-right-width:0px !important; border-left-width:0px !important; } ' + 
+			'.jstree .jstree-wholerow-span { position:absolute; left:0; margin:0px; padding:0; height:18px; border-width:0; padding:0; z-index:0; }';
+		if(is_ff2) {
+			css_string += '' + 
+				'.jstree .jstree-wholerow a { display:block; height:18px; margin:0; padding:0; border:0; } ' + 
+				'.jstree .jstree-wholerow-real a { border-color:transparent !important; } ';
+		}
+		if(is_ie7 || is_ie6) {
+			css_string += '' + 
+				'.jstree .jstree-wholerow, .jstree .jstree-wholerow li, .jstree .jstree-wholerow ul, .jstree .jstree-wholerow a { margin:0; padding:0; line-height:18px; } ' + 
+				'.jstree .jstree-wholerow a { display:block; height:18px; line-height:18px; overflow:hidden; } ';
+		}
+		$.vakata.css.add_sheet({ str : css_string, title : "jstree" });
+	});
+})(jQuery);
+//*/
+
+/*
+* jsTree model plugin
+* This plugin gets jstree to use a class model to retrieve data, creating great dynamism
+*/
+(function ($) {
+	var nodeInterface = ["getChildren","getChildrenCount","getAttr","getName","getProps"],
+		validateInterface = function(obj, inter) {
+			var valid = true;
+			obj = obj || {};
+			inter = [].concat(inter);
+			$.each(inter, function (i, v) {
+				if(!$.isFunction(obj[v])) { valid = false; return false; }
+			});
+			return valid;
+		};
+	$.jstree.plugin("model", {
+		__init : function () {
+			if(!this.data.json_data) { throw "jsTree model: jsTree json_data plugin not included."; }
+			this._get_settings().json_data.data = function (n, b) {
+				var obj = (n == -1) ? this._get_settings().model.object : n.data("jstree_model");
+				if(!validateInterface(obj, nodeInterface)) { return b.call(null, false); }
+				if(this._get_settings().model.async) {
+					obj.getChildren($.proxy(function (data) {
+						this.model_done(data, b);
+					}, this));
+				}
+				else {
+					this.model_done(obj.getChildren(), b);
+				}
+			};
+		},
+		defaults : {
+			object : false,
+			id_prefix : false,
+			async : false
+		},
+		_fn : {
+			model_done : function (data, callback) {
+				var ret = [], 
+					s = this._get_settings(),
+					_this = this;
+
+				if(!$.isArray(data)) { data = [data]; }
+				$.each(data, function (i, nd) {
+					var r = nd.getProps() || {};
+					r.attr = nd.getAttr() || {};
+					if(nd.getChildrenCount()) { r.state = "closed"; }
+					r.data = nd.getName();
+					if(!$.isArray(r.data)) { r.data = [r.data]; }
+					if(_this.data.types && $.isFunction(nd.getType)) {
+						r.attr[s.types.type_attr] = nd.getType();
+					}
+					if(r.attr.id && s.model.id_prefix) { r.attr.id = s.model.id_prefix + r.attr.id; }
+					if(!r.metadata) { r.metadata = { }; }
+					r.metadata.jstree_model = nd;
+					ret.push(r);
+				});
+				callback.call(null, ret);
+			}
+		}
+	});
+})(jQuery);
+//*/
+
+})();
\ No newline at end of file
diff --git a/pub/js/jquery/jstree/themes/apple/bg.jpg b/pub/js/jquery/jstree/themes/apple/bg.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..3aad05d8fadd75f8d9e02866f695b486f0b46343
Binary files /dev/null and b/pub/js/jquery/jstree/themes/apple/bg.jpg differ
diff --git a/pub/js/jquery/jstree/themes/apple/d.png b/pub/js/jquery/jstree/themes/apple/d.png
new file mode 100644
index 0000000000000000000000000000000000000000..2463ba6df91e1668434abdd623bbca914a4fcbe6
Binary files /dev/null and b/pub/js/jquery/jstree/themes/apple/d.png differ
diff --git a/pub/js/jquery/jstree/themes/apple/dot_for_ie.gif b/pub/js/jquery/jstree/themes/apple/dot_for_ie.gif
new file mode 100644
index 0000000000000000000000000000000000000000..c0cc5fda7cfb9539720de442a3caca9c9a3fc4cb
Binary files /dev/null and b/pub/js/jquery/jstree/themes/apple/dot_for_ie.gif differ
diff --git a/pub/js/jquery/jstree/themes/apple/style.css b/pub/js/jquery/jstree/themes/apple/style.css
new file mode 100644
index 0000000000000000000000000000000000000000..d0c4163cef03d32f83e09831203faa805ab23151
--- /dev/null
+++ b/pub/js/jquery/jstree/themes/apple/style.css
@@ -0,0 +1,61 @@
+/*
+ * jsTree apple theme 1.0
+ * Supported features: dots/no-dots, icons/no-icons, focused, loading
+ * Supported plugins: ui (hovered, clicked), checkbox, contextmenu, search
+ */
+
+.jstree-apple > ul { background:url("bg.jpg") left top repeat; }
+.jstree-apple li, 
+.jstree-apple ins { background-image:url("d.png"); background-repeat:no-repeat; background-color:transparent; }
+.jstree-apple li { background-position:-90px 0; background-repeat:repeat-y;  }
+.jstree-apple li.jstree-last { background:transparent; }
+.jstree-apple .jstree-open > ins { background-position:-72px 0; }
+.jstree-apple .jstree-closed > ins { background-position:-54px 0; }
+.jstree-apple .jstree-leaf > ins { background-position:-36px 0; }
+
+.jstree-apple a { border-radius:4px; -moz-border-radius:4px; -webkit-border-radius:4px; text-shadow:1px 1px 1px white; }
+.jstree-apple .jstree-hovered { background:#e7f4f9; border:1px solid #d8f0fa; padding:0 3px 0 1px; text-shadow:1px 1px 1px silver; }
+.jstree-apple .jstree-clicked { background:#beebff; border:1px solid #99defd; padding:0 3px 0 1px; }
+.jstree-apple a .jstree-icon { background-position:-56px -20px; }
+.jstree-apple a.jstree-loading .jstree-icon { background:url("throbber.gif") center center no-repeat !important; }
+
+.jstree-apple.jstree-focused { background:white; }
+
+.jstree-apple .jstree-no-dots li, 
+.jstree-apple .jstree-no-dots .jstree-leaf > ins { background:transparent; }
+.jstree-apple .jstree-no-dots .jstree-open > ins { background-position:-18px 0; }
+.jstree-apple .jstree-no-dots .jstree-closed > ins { background-position:0 0; }
+
+.jstree-apple .jstree-no-icons a .jstree-icon { display:none; }
+
+.jstree-apple .jstree-search { font-style:italic; }
+
+.jstree-apple .jstree-no-icons .jstree-checkbox { display:inline-block; }
+.jstree-apple .jstree-no-checkboxes .jstree-checkbox { display:none !important; }
+.jstree-apple .jstree-checked > a > .jstree-checkbox { background-position:-38px -19px; }
+.jstree-apple .jstree-unchecked > a > .jstree-checkbox { background-position:-2px -19px; }
+.jstree-apple .jstree-undetermined > a > .jstree-checkbox { background-position:-20px -19px; }
+.jstree-apple .jstree-checked > a > .checkbox:hover { background-position:-38px -37px; }
+.jstree-apple .jstree-unchecked > a > .jstree-checkbox:hover { background-position:-2px -37px; }
+.jstree-apple .jstree-undetermined > a > .jstree-checkbox:hover { background-position:-20px -37px; }
+
+#vakata-dragged.jstree-apple ins { background:transparent !important; }
+#vakata-dragged.jstree-apple .jstree-ok { background:url("d.png") -2px -53px no-repeat !important; }
+#vakata-dragged.jstree-apple .jstree-invalid { background:url("d.png") -18px -53px no-repeat !important; }
+#jstree-marker.jstree-apple { background:url("d.png") -41px -57px no-repeat !important; text-indent:-100px; }
+
+.jstree-apple a.jstree-search { color:aqua; }
+.jstree-apple .jstree-locked a { color:silver; cursor:default; }
+
+#vakata-contextmenu.jstree-apple-context, 
+#vakata-contextmenu.jstree-apple-context li ul { background:#f0f0f0; border:1px solid #979797; -moz-box-shadow: 1px 1px 2px #999; -webkit-box-shadow: 1px 1px 2px #999; box-shadow: 1px 1px 2px #999; }
+#vakata-contextmenu.jstree-apple-context li { }
+#vakata-contextmenu.jstree-apple-context a { color:black; }
+#vakata-contextmenu.jstree-apple-context a:hover, 
+#vakata-contextmenu.jstree-apple-context .vakata-hover > a { padding:0 5px; background:#e8eff7; border:1px solid #aecff7; color:black; -moz-border-radius:2px; -webkit-border-radius:2px; border-radius:2px; }
+#vakata-contextmenu.jstree-apple-context li.jstree-contextmenu-disabled a, 
+#vakata-contextmenu.jstree-apple-context li.jstree-contextmenu-disabled a:hover { color:silver; background:transparent; border:0; padding:1px 4px; }
+#vakata-contextmenu.jstree-apple-context li.vakata-separator { background:white; border-top:1px solid #e0e0e0; margin:0; }
+#vakata-contextmenu.jstree-apple-context li ul { margin-left:-4px; }
+
+/* TODO: IE6 support - the `>` selectors */
\ No newline at end of file
diff --git a/pub/js/jquery/jstree/themes/apple/throbber.gif b/pub/js/jquery/jstree/themes/apple/throbber.gif
new file mode 100644
index 0000000000000000000000000000000000000000..5b33f7e54f4e55b6b8774d86d96895db9af044b4
Binary files /dev/null and b/pub/js/jquery/jstree/themes/apple/throbber.gif differ
diff --git a/pub/js/jquery/jstree/themes/classic/d.gif b/pub/js/jquery/jstree/themes/classic/d.gif
new file mode 100644
index 0000000000000000000000000000000000000000..6eb0004ce3544f9973ddbd5a2c450fc0e1a354b1
Binary files /dev/null and b/pub/js/jquery/jstree/themes/classic/d.gif differ
diff --git a/pub/js/jquery/jstree/themes/classic/d.png b/pub/js/jquery/jstree/themes/classic/d.png
new file mode 100644
index 0000000000000000000000000000000000000000..275daeca2d6ae2ba9cf59bd23a194d13a35a825d
Binary files /dev/null and b/pub/js/jquery/jstree/themes/classic/d.png differ
diff --git a/pub/js/jquery/jstree/themes/classic/dot_for_ie.gif b/pub/js/jquery/jstree/themes/classic/dot_for_ie.gif
new file mode 100644
index 0000000000000000000000000000000000000000..c0cc5fda7cfb9539720de442a3caca9c9a3fc4cb
Binary files /dev/null and b/pub/js/jquery/jstree/themes/classic/dot_for_ie.gif differ
diff --git a/pub/js/jquery/jstree/themes/classic/style.css b/pub/js/jquery/jstree/themes/classic/style.css
new file mode 100644
index 0000000000000000000000000000000000000000..0351b4cef5df2714a30a28cc7c101771e1819826
--- /dev/null
+++ b/pub/js/jquery/jstree/themes/classic/style.css
@@ -0,0 +1,77 @@
+/*
+ * jsTree classic theme 1.0
+ * Supported features: dots/no-dots, icons/no-icons, focused, loading
+ * Supported plugins: ui (hovered, clicked), checkbox, contextmenu, search
+ */
+
+.jstree-classic li, 
+.jstree-classic ins { background-image:url("d.png"); background-repeat:no-repeat; background-color:transparent; }
+.jstree-classic li { background-position:-90px 0; background-repeat:repeat-y;  }
+.jstree-classic li.jstree-last { background:transparent; }
+.jstree-classic .jstree-open > ins { background-position:-72px 0; }
+.jstree-classic .jstree-closed > ins { background-position:-54px 0; }
+.jstree-classic .jstree-leaf > ins { background-position:-36px 0; }
+
+.jstree-classic .jstree-hovered { background:#e7f4f9; border:1px solid #e7f4f9; padding:0 2px 0 1px; }
+.jstree-classic .jstree-clicked { background:navy; border:1px solid navy; padding:0 2px 0 1px; color:white; }
+.jstree-classic a .jstree-icon { background-position:-56px -19px; }
+.jstree-classic .jstree-open > a .jstree-icon { background-position:-56px -36px; }
+.jstree-classic a.jstree-loading .jstree-icon { background:url("throbber.gif") center center no-repeat !important; }
+
+.jstree-classic.jstree-focused { background:white; }
+
+.jstree-classic .jstree-no-dots li, 
+.jstree-classic .jstree-no-dots .jstree-leaf > ins { background:transparent; }
+.jstree-classic .jstree-no-dots .jstree-open > ins { background-position:-18px 0; }
+.jstree-classic .jstree-no-dots .jstree-closed > ins { background-position:0 0; }
+
+.jstree-classic .jstree-no-icons a .jstree-icon { display:none; }
+
+.jstree-classic .jstree-search { font-style:italic; }
+
+.jstree-classic .jstree-no-icons .jstree-checkbox { display:inline-block; }
+.jstree-classic .jstree-no-checkboxes .jstree-checkbox { display:none !important; }
+.jstree-classic .jstree-checked > a > .jstree-checkbox { background-position:-38px -19px; }
+.jstree-classic .jstree-unchecked > a > .jstree-checkbox { background-position:-2px -19px; }
+.jstree-classic .jstree-undetermined > a > .jstree-checkbox { background-position:-20px -19px; }
+.jstree-classic .jstree-checked > a > .jstree-checkbox:hover { background-position:-38px -37px; }
+.jstree-classic .jstree-unchecked > a > .jstree-checkbox:hover { background-position:-2px -37px; }
+.jstree-classic .jstree-undetermined > a > .jstree-checkbox:hover { background-position:-20px -37px; }
+
+#vakata-dragged.jstree-classic ins { background:transparent !important; }
+#vakata-dragged.jstree-classic .jstree-ok { background:url("d.png") -2px -53px no-repeat !important; }
+#vakata-dragged.jstree-classic .jstree-invalid { background:url("d.png") -18px -53px no-repeat !important; }
+#jstree-marker.jstree-classic { background:url("d.png") -41px -57px no-repeat !important; text-indent:-100px; }
+
+.jstree-classic a.jstree-search { color:aqua; }
+.jstree-classic .jstree-locked a { color:silver; cursor:default; }
+
+#vakata-contextmenu.jstree-classic-context, 
+#vakata-contextmenu.jstree-classic-context li ul { background:#f0f0f0; border:1px solid #979797; -moz-box-shadow: 1px 1px 2px #999; -webkit-box-shadow: 1px 1px 2px #999; box-shadow: 1px 1px 2px #999; }
+#vakata-contextmenu.jstree-classic-context li { }
+#vakata-contextmenu.jstree-classic-context a { color:black; }
+#vakata-contextmenu.jstree-classic-context a:hover, 
+#vakata-contextmenu.jstree-classic-context .vakata-hover > a { padding:0 5px; background:#e8eff7; border:1px solid #aecff7; color:black; -moz-border-radius:2px; -webkit-border-radius:2px; border-radius:2px; }
+#vakata-contextmenu.jstree-classic-context li.jstree-contextmenu-disabled a, 
+#vakata-contextmenu.jstree-classic-context li.jstree-contextmenu-disabled a:hover { color:silver; background:transparent; border:0; padding:1px 4px; }
+#vakata-contextmenu.jstree-classic-context li.vakata-separator { background:white; border-top:1px solid #e0e0e0; margin:0; }
+#vakata-contextmenu.jstree-classic-context li ul { margin-left:-4px; }
+
+/* IE6 BEGIN */
+.jstree-classic li, 
+.jstree-classic ins,
+#vakata-dragged.jstree-classic .jstree-invalid, 
+#vakata-dragged.jstree-classic .jstree-ok, 
+#jstree-marker.jstree-classic { _background-image:url("d.gif"); }
+.jstree-classic .jstree-open ins { _background-position:-72px 0; }
+.jstree-classic .jstree-closed ins { _background-position:-54px 0; }
+.jstree-classic .jstree-leaf ins { _background-position:-36px 0; }
+.jstree-classic .jstree-open a ins.jstree-icon { _background-position:-56px -36px; }
+.jstree-classic .jstree-closed a ins.jstree-icon { _background-position:-56px -19px; }
+.jstree-classic .jstree-leaf a ins.jstree-icon { _background-position:-56px -19px; }
+#vakata-contextmenu.jstree-classic-context ins { _display:none; }
+#vakata-contextmenu.jstree-classic-context li { _zoom:1; }
+.jstree-classic .jstree-undetermined a .jstree-checkbox { _background-position:-20px -19px; }
+.jstree-classic .jstree-checked a .jstree-checkbox { _background-position:-38px -19px; }
+.jstree-classic .jstree-unchecked a .jstree-checkbox { _background-position:-2px -19px; }
+/* IE6 END */
\ No newline at end of file
diff --git a/pub/js/jquery/jstree/themes/classic/throbber.gif b/pub/js/jquery/jstree/themes/classic/throbber.gif
new file mode 100644
index 0000000000000000000000000000000000000000..5b33f7e54f4e55b6b8774d86d96895db9af044b4
Binary files /dev/null and b/pub/js/jquery/jstree/themes/classic/throbber.gif differ
diff --git a/pub/js/jquery/jstree/themes/default-rtl/d.gif b/pub/js/jquery/jstree/themes/default-rtl/d.gif
new file mode 100644
index 0000000000000000000000000000000000000000..d85aba049b5c45649fcbb889a3765c39f3a3678a
Binary files /dev/null and b/pub/js/jquery/jstree/themes/default-rtl/d.gif differ
diff --git a/pub/js/jquery/jstree/themes/default-rtl/d.png b/pub/js/jquery/jstree/themes/default-rtl/d.png
new file mode 100644
index 0000000000000000000000000000000000000000..5179cf64e4adc0a09bf0d0e321cf5665d722f5a3
Binary files /dev/null and b/pub/js/jquery/jstree/themes/default-rtl/d.png differ
diff --git a/pub/js/jquery/jstree/themes/default-rtl/dots.gif b/pub/js/jquery/jstree/themes/default-rtl/dots.gif
new file mode 100644
index 0000000000000000000000000000000000000000..00433648c0769d3b473e6c972e6314f16e5a29f6
Binary files /dev/null and b/pub/js/jquery/jstree/themes/default-rtl/dots.gif differ
diff --git a/pub/js/jquery/jstree/themes/default-rtl/style.css b/pub/js/jquery/jstree/themes/default-rtl/style.css
new file mode 100644
index 0000000000000000000000000000000000000000..1343cf343e06db0c9f89e2ece0f986b0a0698843
--- /dev/null
+++ b/pub/js/jquery/jstree/themes/default-rtl/style.css
@@ -0,0 +1,84 @@
+/*
+ * jsTree default-rtl theme 1.0
+ * Supported features: dots/no-dots, icons/no-icons, focused, loading
+ * Supported plugins: ui (hovered, clicked), checkbox, contextmenu, search
+ */
+
+.jstree-default-rtl li, 
+.jstree-default-rtl ins { background-image:url("d.png"); background-repeat:no-repeat; background-color:transparent; }
+.jstree-default-rtl li { background-position:-90px 0; background-repeat:repeat-y; }
+.jstree-default-rtl li.jstree-last { background:transparent; }
+.jstree-default-rtl .jstree-open > ins { background-position:-72px 0; }
+.jstree-default-rtl .jstree-closed > ins { background-position:-54px 0; }
+.jstree-default-rtl .jstree-leaf > ins { background-position:-36px 0; }
+
+.jstree-default-rtl .jstree-hovered { background:#e7f4f9; border:1px solid #d8f0fa; padding:0 2px 0 1px; }
+.jstree-default-rtl .jstree-clicked { background:#beebff; border:1px solid #99defd; padding:0 2px 0 1px; }
+.jstree-default-rtl a .jstree-icon { background-position:-56px -19px; }
+.jstree-default-rtl a.jstree-loading .jstree-icon { background:url("throbber.gif") center center no-repeat !important; }
+
+.jstree-default-rtl.jstree-focused { background:#ffffee; }
+
+.jstree-default-rtl .jstree-no-dots li, 
+.jstree-default-rtl .jstree-no-dots .jstree-leaf > ins { background:transparent; }
+.jstree-default-rtl .jstree-no-dots .jstree-open > ins { background-position:-18px 0; }
+.jstree-default-rtl .jstree-no-dots .jstree-closed > ins { background-position:0 0; }
+
+.jstree-default-rtl .jstree-no-icons a .jstree-icon { display:none; }
+
+.jstree-default-rtl .jstree-search { font-style:italic; }
+
+.jstree-default-rtl .jstree-no-icons .jstree-checkbox { display:inline-block; }
+.jstree-default-rtl .jstree-no-checkboxes .jstree-checkbox { display:none !important; }
+.jstree-default-rtl .jstree-checked > a > .jstree-checkbox { background-position:-38px -19px; }
+.jstree-default-rtl .jstree-unchecked > a > .jstree-checkbox { background-position:-2px -19px; }
+.jstree-default-rtl .jstree-undetermined > a > .jstree-checkbox { background-position:-20px -19px; }
+.jstree-default-rtl .jstree-checked > a > .jstree-checkbox:hover { background-position:-38px -37px; }
+.jstree-default-rtl .jstree-unchecked > a > .jstree-checkbox:hover { background-position:-2px -37px; }
+.jstree-default-rtl .jstree-undetermined > a > .jstree-checkbox:hover { background-position:-20px -37px; }
+
+#vakata-dragged.jstree-default-rtl ins { background:transparent !important; }
+#vakata-dragged.jstree-default-rtl .jstree-ok { background:url("d.png") -2px -53px no-repeat !important; }
+#vakata-dragged.jstree-default-rtl .jstree-invalid { background:url("d.png") -18px -53px no-repeat !important; }
+#jstree-marker.jstree-default-rtl { background:url("d.png") -41px -57px no-repeat !important; text-indent:-100px; }
+
+.jstree-default-rtl a.jstree-search { color:aqua; }
+.jstree-default-rtl .jstree-locked a { color:silver; cursor:default; }
+
+#vakata-contextmenu.jstree-default-rtl-context, 
+#vakata-contextmenu.jstree-default-rtl-context li ul { background:#f0f0f0; border:1px solid #979797; -moz-box-shadow: 1px 1px 2px #999; -webkit-box-shadow: 1px 1px 2px #999; box-shadow: 1px 1px 2px #999; }
+#vakata-contextmenu.jstree-default-rtl-context li { }
+#vakata-contextmenu.jstree-default-rtl-context a { color:black; }
+#vakata-contextmenu.jstree-default-rtl-context a:hover, 
+#vakata-contextmenu.jstree-default-rtl-context .vakata-hover > a { padding:0 5px; background:#e8eff7; border:1px solid #aecff7; color:black; -moz-border-radius:2px; -webkit-border-radius:2px; border-radius:2px; }
+#vakata-contextmenu.jstree-default-rtl-context li.jstree-contextmenu-disabled a, 
+#vakata-contextmenu.jstree-default-rtl-context li.jstree-contextmenu-disabled a:hover { color:silver; background:transparent; border:0; padding:1px 4px; }
+#vakata-contextmenu.jstree-default-rtl-context li.vakata-separator { background:white; border-top:1px solid #e0e0e0; margin:0; }
+#vakata-contextmenu.jstree-default-rtl-context li ul { margin-left:-4px; }
+
+/* IE6 BEGIN */
+.jstree-default-rtl li, 
+.jstree-default-rtl ins,
+#vakata-dragged.jstree-default-rtl .jstree-invalid, 
+#vakata-dragged.jstree-default-rtl .jstree-ok, 
+#jstree-marker.jstree-default-rtl { _background-image:url("d.gif"); }
+.jstree-default-rtl .jstree-open ins { _background-position:-72px 0; }
+.jstree-default-rtl .jstree-closed ins { _background-position:-54px 0; }
+.jstree-default-rtl .jstree-leaf ins { _background-position:-36px 0; }
+.jstree-default-rtl a ins.jstree-icon { _background-position:-56px -19px; }
+#vakata-contextmenu.jstree-default-rtl-context ins { _display:none; }
+#vakata-contextmenu.jstree-default-rtl-context li { _zoom:1; }
+.jstree-default-rtl .jstree-undetermined a .jstree-checkbox { _background-position:-18px -19px; }
+.jstree-default-rtl .jstree-checked a .jstree-checkbox { _background-position:-36px -19px; }
+.jstree-default-rtl .jstree-unchecked a .jstree-checkbox { _background-position:0px -19px; }
+/* IE6 END */
+
+/* RTL part */
+.jstree-default-rtl .jstree-hovered, .jstree-default-rtl .jstree-clicked { padding:0 1px 0 2px; }
+.jstree-default-rtl li { background-image:url("dots.gif"); background-position: 100% 0px; }
+.jstree-default-rtl .jstree-checked > a > .jstree-checkbox { background-position:-36px -19px; margin-left:2px; }
+.jstree-default-rtl .jstree-unchecked > a > .jstree-checkbox { background-position:0px -19px; margin-left:2px; }
+.jstree-default-rtl .jstree-undetermined > a > .jstree-checkbox { background-position:-18px -19px; margin-left:2px; }
+.jstree-default-rtl .jstree-checked > a > .jstree-checkbox:hover { background-position:-36px -37px; }
+.jstree-default-rtl .jstree-unchecked > a > .jstree-checkbox:hover { background-position:0px -37px; }
+.jstree-default-rtl .jstree-undetermined > a > .jstree-checkbox:hover { background-position:-18px -37px; }
\ No newline at end of file
diff --git a/pub/js/jquery/jstree/themes/default-rtl/throbber.gif b/pub/js/jquery/jstree/themes/default-rtl/throbber.gif
new file mode 100644
index 0000000000000000000000000000000000000000..5b33f7e54f4e55b6b8774d86d96895db9af044b4
Binary files /dev/null and b/pub/js/jquery/jstree/themes/default-rtl/throbber.gif differ
diff --git a/pub/js/jquery/jstree/themes/default/d.gif b/pub/js/jquery/jstree/themes/default/d.gif
new file mode 100644
index 0000000000000000000000000000000000000000..0e958d38716d93d4050a993398dec77490f836c7
Binary files /dev/null and b/pub/js/jquery/jstree/themes/default/d.gif differ
diff --git a/pub/js/jquery/jstree/themes/default/d.png b/pub/js/jquery/jstree/themes/default/d.png
new file mode 100644
index 0000000000000000000000000000000000000000..8540175a04b0cd303e3966d1727f30ee9b8a7254
Binary files /dev/null and b/pub/js/jquery/jstree/themes/default/d.png differ
diff --git a/pub/js/jquery/jstree/themes/default/style.css b/pub/js/jquery/jstree/themes/default/style.css
new file mode 100644
index 0000000000000000000000000000000000000000..7ef6a04308050b5ed3fc10b3c102a71f716f1084
--- /dev/null
+++ b/pub/js/jquery/jstree/themes/default/style.css
@@ -0,0 +1,74 @@
+/*
+ * jsTree default theme 1.0
+ * Supported features: dots/no-dots, icons/no-icons, focused, loading
+ * Supported plugins: ui (hovered, clicked), checkbox, contextmenu, search
+ */
+
+.jstree-default li, 
+.jstree-default ins { background-image:url("d.png"); background-repeat:no-repeat; background-color:transparent; }
+.jstree-default li { background-position:-90px 0; background-repeat:repeat-y; }
+.jstree-default li.jstree-last { background:transparent; }
+.jstree-default .jstree-open > ins { background-position:-72px 0; }
+.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 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-no-dots li, 
+.jstree-default .jstree-no-dots .jstree-leaf > ins { background:transparent; }
+.jstree-default .jstree-no-dots .jstree-open > ins { background-position:-18px 0; }
+.jstree-default .jstree-no-dots .jstree-closed > ins { background-position:0 0; }
+
+.jstree-default .jstree-no-icons a .jstree-icon { display:none; }
+
+.jstree-default .jstree-search { font-style:italic; }
+
+.jstree-default .jstree-no-icons .jstree-checkbox { display:inline-block; }
+.jstree-default .jstree-no-checkboxes .jstree-checkbox { display:none !important; }
+.jstree-default .jstree-checked > a > .jstree-checkbox { background-position:-38px -19px; }
+.jstree-default .jstree-unchecked > a > .jstree-checkbox { background-position:-2px -19px; }
+.jstree-default .jstree-undetermined > a > .jstree-checkbox { background-position:-20px -19px; }
+.jstree-default .jstree-checked > a > .jstree-checkbox:hover { background-position:-38px -37px; }
+.jstree-default .jstree-unchecked > a > .jstree-checkbox:hover { background-position:-2px -37px; }
+.jstree-default .jstree-undetermined > a > .jstree-checkbox:hover { background-position:-20px -37px; }
+
+#vakata-dragged.jstree-default ins { background:transparent !important; }
+#vakata-dragged.jstree-default .jstree-ok { background:url("d.png") -2px -53px no-repeat !important; }
+#vakata-dragged.jstree-default .jstree-invalid { background:url("d.png") -18px -53px no-repeat !important; }
+#jstree-marker.jstree-default { background:url("d.png") -41px -57px no-repeat !important; text-indent:-100px; }
+
+.jstree-default a.jstree-search { color:aqua; }
+.jstree-default .jstree-locked a { color:silver; cursor:default; }
+
+#vakata-contextmenu.jstree-default-context, 
+#vakata-contextmenu.jstree-default-context li ul { background:#f0f0f0; border:1px solid #979797; -moz-box-shadow: 1px 1px 2px #999; -webkit-box-shadow: 1px 1px 2px #999; box-shadow: 1px 1px 2px #999; }
+#vakata-contextmenu.jstree-default-context li { }
+#vakata-contextmenu.jstree-default-context a { color:black; }
+#vakata-contextmenu.jstree-default-context a:hover, 
+#vakata-contextmenu.jstree-default-context .vakata-hover > a { padding:0 5px; background:#e8eff7; border:1px solid #aecff7; color:black; -moz-border-radius:2px; -webkit-border-radius:2px; border-radius:2px; }
+#vakata-contextmenu.jstree-default-context li.jstree-contextmenu-disabled a, 
+#vakata-contextmenu.jstree-default-context li.jstree-contextmenu-disabled a:hover { color:silver; background:transparent; border:0; padding:1px 4px; }
+#vakata-contextmenu.jstree-default-context li.vakata-separator { background:white; border-top:1px solid #e0e0e0; margin:0; }
+#vakata-contextmenu.jstree-default-context li ul { margin-left:-4px; }
+
+/* IE6 BEGIN */
+.jstree-default li, 
+.jstree-default ins,
+#vakata-dragged.jstree-default .jstree-invalid, 
+#vakata-dragged.jstree-default .jstree-ok, 
+#jstree-marker.jstree-default { _background-image:url("d.gif"); }
+.jstree-default .jstree-open ins { _background-position:-72px 0; }
+.jstree-default .jstree-closed ins { _background-position:-54px 0; }
+.jstree-default .jstree-leaf ins { _background-position:-36px 0; }
+.jstree-default a ins.jstree-icon { _background-position:-56px -19px; }
+#vakata-contextmenu.jstree-default-context ins { _display:none; }
+#vakata-contextmenu.jstree-default-context li { _zoom:1; }
+.jstree-default .jstree-undetermined a .jstree-checkbox { _background-position:-20px -19px; }
+.jstree-default .jstree-checked a .jstree-checkbox { _background-position:-38px -19px; }
+.jstree-default .jstree-unchecked a .jstree-checkbox { _background-position:-2px -19px; }
+/* IE6 END */
\ No newline at end of file
diff --git a/pub/js/jquery/jstree/themes/default/throbber.gif b/pub/js/jquery/jstree/themes/default/throbber.gif
new file mode 100644
index 0000000000000000000000000000000000000000..5b33f7e54f4e55b6b8774d86d96895db9af044b4
Binary files /dev/null and b/pub/js/jquery/jstree/themes/default/throbber.gif differ
diff --git a/pub/js/mage/adminhtml/backup.js b/pub/js/mage/adminhtml/backup.js
index 0b28a2ab0bab4518ddf213dc11b4990c8349bf55..cd49b35aa19bfeb2870d7180c2982608ca82df38 100644
--- a/pub/js/mage/adminhtml/backup.js
+++ b/pub/js/mage/adminhtml/backup.js
@@ -37,6 +37,9 @@ AdminBackup.prototype = {
         $('use-ftp-checkbox-row').hide();
         $('use_ftp').checked = false;
         $('ftp-credentials-container').hide();
+        $$('#ftp-credentials-container input').each(function(item) {
+            item.removeClassName('required-entry');
+        });
         $('backup_maintenance_mode').checked = false;
         $('rollback_maintenance_mode').checked = false;
         $('exclude_media').checked = false;
diff --git a/pub/js/mage/adminhtml/fix-extjs-defer-before.js b/pub/js/mage/adminhtml/fix-extjs-defer-before.js
index 50aa3d0ebaaa0130d7fdcc1e78459d8c1bb58f99..6c11c9c48f0212d948c75f0a21dec97ab475e2e7 100644
--- a/pub/js/mage/adminhtml/fix-extjs-defer-before.js
+++ b/pub/js/mage/adminhtml/fix-extjs-defer-before.js
@@ -27,6 +27,8 @@
 (function(){
     var last = null;
     var ie7 = @if(@_jscript_version==5.7) 1 @end + 0;
+    var ie8 = @if(@_jscript_version==5.8) 1 @end + 0;
+    if (ie7 || ie8) {
     if (ie7) {
         var eDefer = Function.prototype.defer;
         Function.prototype.defer = function() {
diff --git a/pub/js/mage/adminhtml/form.js b/pub/js/mage/adminhtml/form.js
index 4b5a657ad09ebd81df355ed76b337d3fabf3dbe0..e88b2dc5edae8bc6168fc33f97b7006de05a6bae 100644
--- a/pub/js/mage/adminhtml/form.js
+++ b/pub/js/mage/adminhtml/form.js
@@ -101,10 +101,11 @@ varienForm.prototype = {
     },
 
     _submit : function(){
+        var $form = $(this.formId);
         if(this.submitUrl){
-            $(this.formId).action = this.submitUrl;
+            $form.action = this.submitUrl;
         }
-        $(this.formId).submit();
+        $form.submit();
     }
 }
 
@@ -191,6 +192,8 @@ RegionUpdater.prototype = {
 //        // clone for select element (#6924)
 //        this._regionSelectEl = {};
 //        this.tpl = new Template('<select class="#{className}" name="#{name}" id="#{id}">#{innerHTML}</select>');
+        this.config = regions['config'];
+        delete regions.config;
         this.regions = regions;
         this.disableAction = (typeof disableAction=='undefined') ? 'hide' : disableAction;
         this.clearRegionValueOnDisable = (typeof clearRegionValueOnDisable == 'undefined') ? false : clearRegionValueOnDisable;
@@ -207,6 +210,64 @@ RegionUpdater.prototype = {
         Event.observe(this.countryEl, 'change', this.update.bind(this));
     },
 
+    _checkRegionRequired: function()
+    {
+        var label, wildCard;
+        var elements = [this.regionTextEl, this.regionSelectEl];
+        var that = this;
+        if (typeof this.config == 'undefined') {
+            return;
+        }
+        var regionRequired = this.config.regions_required.indexOf(this.countryEl.value) >= 0;
+
+        elements.each(function(currentElement) {
+            if(!currentElement) {
+                return;
+            }
+            Validation.reset(currentElement);
+            label = $$('label[for="' + currentElement.id + '"]')[0];
+            if (label) {
+                wildCard = label.down('em') || label.down('span.required');
+                var topElement = label.up('tr') || label.up('li');
+                if (!that.config.show_all_regions && topElement) {
+                    if (regionRequired) {
+                        topElement.show();
+                    } else {
+                        topElement.hide();
+                    }
+                }
+            }
+
+            if (label && wildCard) {
+                if (!regionRequired) {
+                    wildCard.hide();
+                } else {
+                    wildCard.show();
+                }
+            }
+
+            if (!regionRequired || !currentElement.visible()) {
+                if (currentElement.hasClassName('required-entry')) {
+                    currentElement.removeClassName('required-entry');
+                }
+                if ('select' == currentElement.tagName.toLowerCase() &&
+                    currentElement.hasClassName('validate-select')
+                ) {
+                    currentElement.removeClassName('validate-select');
+                }
+            } else {
+                if (!currentElement.hasClassName('required-entry')) {
+                    currentElement.addClassName('required-entry');
+                }
+                if ('select' == currentElement.tagName.toLowerCase() &&
+                    !currentElement.hasClassName('validate-select')
+                ) {
+                    currentElement.addClassName('validate-select');
+                }
+            }
+        });
+    },
+
     update: function()
     {
         if (this.regions[this.countryEl.value]) {
@@ -217,13 +278,13 @@ RegionUpdater.prototype = {
             if (this.lastCountryId!=this.countryEl.value) {
                 var i, option, region, def;
 
+                def = this.regionSelectEl.getAttribute('defaultValue');
                 if (this.regionTextEl) {
-                    def = this.regionTextEl.value.toLowerCase();
+                    if (!def) {
+                        def = this.regionTextEl.value.toLowerCase();
+                    }
                     this.regionTextEl.value = '';
                 }
-                if (!def) {
-                    def = this.regionSelectEl.getAttribute('defaultValue');
-                }
 
                 this.regionSelectEl.options.length = 1;
                 for (regionId in this.regions[this.countryEl.value]) {
@@ -295,6 +356,7 @@ RegionUpdater.prototype = {
 //            this.regionSelectEl = null;
         }
         varienGlobalEvents.fireEvent("address_country_changed", this.countryEl);
+        this._checkRegionRequired();
     },
 
     setMarkDisplay: function(elem, display){
diff --git a/pub/js/jquery/jquery-no-conflict.js b/pub/js/mage/jquery-no-conflict.js
similarity index 100%
rename from pub/js/jquery/jquery-no-conflict.js
rename to pub/js/mage/jquery-no-conflict.js
diff --git a/pub/js/mage/translate_inline.css b/pub/js/mage/translate_inline.css
index dbd742b2d480cb5ea2df94dd140889b86b276494..62510a84c33310b4cd95e522ab713e40294bc20a 100644
--- a/pub/js/mage/translate_inline.css
+++ b/pub/js/mage/translate_inline.css
@@ -23,11 +23,11 @@
  * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
  */
 
-.translate-inline { /* background:black; font-weight:bold; color:red; */ outline: dotted 1px red!important;}
+[translate], .translate-inline { /* background:black; font-weight:bold; color:red; */ outline: dotted 1px red!important;}
 * html .translate-inline,
 *+html .translate-inline{ border: dotted 1px red !important;}
 .translate-inline-script, .translate-inline-title { background:yellow; color:black; font-weight:bold; }
-#translate-inline-trig { position:absolute;left:-1000px; opacity:.8; filter:alpha(opacity=80); cursor:pointer; margin-top:10px; z-index:1000;}
+#translate-inline-trig { position:absolute;left:-1000px; opacity:.8; filter:alpha(opacity=80); cursor:pointer; margin-top:10px; z-index:2000;}
 
 .magento_table_container { background:#e7efef; margin:10px; padding:10px; }
 .magento_table_container table { width:100%; }
diff --git a/pub/js/mage/translate_inline.js b/pub/js/mage/translate_inline.js
index c78c6255731e105bdaf1450b1344f26979fde095..8d68c86a980037daf9c86096729bd132de30555f 100644
--- a/pub/js/mage/translate_inline.js
+++ b/pub/js/mage/translate_inline.js
@@ -25,50 +25,70 @@
 
 var TranslateInline = Class.create();
 TranslateInline.prototype = {
-    initialize: function(trigEl, ajaxUrl, area){
+    initialize: function(trigEl, ajaxUrl, area) {
         this.ajaxUrl = ajaxUrl;
         this.area = area;
 
         this.trigTimer = null;
         this.trigContentEl = null;
-
-        $$('*[translate]').each(this.initializeElement.bind(this));
-        var scope = this;
-        Ajax.Responders.register({onComplete: function() {setTimeout(scope.reinitElements.bind(scope), 50)}});
+        if (Prototype.Browser.IE) {
+            $$('*[translate]').each(this.initializeElement.bind(this));
+            var scope = this;
+            Ajax.Responders.register({ onComplete: function() {
+                window.setTimeout(scope.reinitElements.bind(scope), 50)
+            }
+            });
+            var ElementNode = (typeof HTMLElement != 'undefined' ? HTMLElement : Element)
+            var ElementUpdate = ElementNode.prototype.update;
+            ElementNode.prototype.update = function() {
+                ElementUpdate.apply(this, arguments);
+                $(this).select('*[translate]').each(scope.initializeElement.bind(scope));
+            }
+        }
         this.trigEl = $(trigEl);
-        this.trigEl.observe('mouseover', this.trigHideClear.bind(this));
-        this.trigEl.observe('mouseout', this.trigHideDelayed.bind(this));
         this.trigEl.observe('click', this.formShow.bind(this));
 
+        Event.observe(document.body, 'mousemove', function(e) {
+            var target = Event.element(e);
+            if (!$(target).match('*[translate]')) {
+                target = target.up('*[translate]');
+            }
+
+            if (target && $(target).match('*[translate]')) {
+                this.trigShow(target, e);
+            } else {
+                if (Event.element(e).match('#' + trigEl)) {
+                    this.trigHideClear();
+                } else {
+                    this.trigHideDelayed();
+                }
+            }
+        }.bind(this));
+
         this.helperDiv = document.createElement('div');
     },
 
     initializeElement: function(el) {
-        if(!el.initializedTranslate) {
+        if (!el.initializedTranslate) {
             el.addClassName('translate-inline');
             el.initializedTranslate = true;
-            // mouseover is not suitable here because for some reason this handler is executed before the handler
-            // specified in menu element description. This causes 'book' to be shown out of the screen because
-            // 'over' CSS class has not been added yet.
-            Event.observe(el, 'mousemove', this.trigShow.bind(this, el));
-            Event.observe(el, 'mouseout', this.trigHideDelayed.bind(this));
         }
     },
 
-    reinitElements: function (el) {
+    reinitElements: function(el) {
         $$('*[translate]').each(this.initializeElement.bind(this));
     },
 
-    trigShow: function (el, event) {
+    trigShow: function(el, event) {
         if (this.trigContentEl != el) {
             this.trigHideClear();
             this.trigContentEl = el;
-
             var p = Element.cumulativeOffset(el);
 
-            this.trigEl.style.left = p[0]+'px';
-            this.trigEl.style.top = p[1]+'px';
+            this.trigEl.style.left = p[0] + 'px';
+            this.trigEl.style.top = p[1] + 'px';
             this.trigEl.style.display = 'block';
+
             Event.stop(event);
         };
     },
@@ -78,15 +98,18 @@ TranslateInline.prototype = {
         this.trigContentEl = null;
     },
 
-    trigHideDelayed: function () {
-        this.trigTimer = window.setTimeout(this.trigHide.bind(this), 500);
+    trigHideDelayed: function() {
+        if (this.trigTimer === null) {
+            this.trigTimer = window.setTimeout(this.trigHide.bind(this), 2000);
+        }
     },
 
     trigHideClear: function() {
         clearInterval(this.trigTimer);
+        this.trigTimer = null;
     },
 
-    formShow: function () {
+    formShow: function() {
         if (this.formIsShown) {
             return;
         }
@@ -96,27 +119,27 @@ TranslateInline.prototype = {
         if (!el) {
             return;
         }
-
-        eval('var data = '+el.getAttribute('translate'));
+        this.trigHideClear();
+        eval('var data = ' + el.getAttribute('translate'));
 
         var content = '<form id="translate-inline-form">';
         var t = new Template(
-            '<div class="magento_table_container"><table cellspacing="0">'+
-            '<tr><th class="label">Location:</th><td class="value">#{location}</td></tr>'+
-            '<tr><th class="label">Scope:</th><td class="value">#{scope}</td></tr>'+
-            '<tr><th class="label">Shown:</th><td class="value">#{shown_escape}</td></tr>'+
-            '<tr><th class="label">Original:</th><td class="value">#{original_escape}</td></tr>'+
-            '<tr><th class="label">Translated:</th><td class="value">#{translated_escape}</td></tr>'+
-            '<tr><th class="label"><label for="perstore_#{i}">Store View Specific:</label></th><td class="value">'+
-                '<input id="perstore_#{i}" name="translate[#{i}][perstore]" type="checkbox" value="1"/>'+
-            '</td></tr>'+
-            '<tr><th class="label"><label for="custom_#{i}">Custom:</label></th><td class="value">'+
-                '<input name="translate[#{i}][original]" type="hidden" value="#{scope}::#{original_escape}"/>'+
-                '<input id="custom_#{i}" name="translate[#{i}][custom]" class="input-text" value="#{translated_escape}" />'+
-            '</td></tr>'+
+            '<div class="magento_table_container"><table cellspacing="0">' +
+                '<tr><th class="label">Location:</th><td class="value">#{location}</td></tr>' +
+                '<tr><th class="label">Scope:</th><td class="value">#{scope}</td></tr>' +
+                '<tr><th class="label">Shown:</th><td class="value">#{shown_escape}</td></tr>' +
+                '<tr><th class="label">Original:</th><td class="value">#{original_escape}</td></tr>' +
+                '<tr><th class="label">Translated:</th><td class="value">#{translated_escape}</td></tr>' +
+                '<tr><th class="label"><label for="perstore_#{i}">Store View Specific:</label></th><td class="value">' +
+                    '<input id="perstore_#{i}" name="translate[#{i}][perstore]" type="checkbox" value="1"/>' +
+                '</td></tr>' +
+                '<tr><th class="label"><label for="custom_#{i}">Custom:</label></th><td class="value">' +
+                    '<input name="translate[#{i}][original]" type="hidden" value="#{scope}::#{original_escape}"/>' +
+                    '<input id="custom_#{i}" name="translate[#{i}][custom]" class="input-text" value="#{translated_escape}" />' +
+                '</td></tr>' +
             '</table></div>'
         );
-        for (i=0; i<data.length; i++) {
+        for (i = 0; i < data.length; i++) {
             data[i]['i'] = i;
             data[i]['shown_escape'] = this.escapeHTML(data[i]['shown']);
             data[i]['translated_escape'] = this.escapeHTML(data[i]['translated']);
@@ -127,28 +150,29 @@ TranslateInline.prototype = {
 
         this.overlayShowEffectOptions = Windows.overlayShowEffectOptions;
         this.overlayHideEffectOptions = Windows.overlayHideEffectOptions;
-        Windows.overlayShowEffectOptions = {duration:0};
-        Windows.overlayHideEffectOptions = {duration:0};
+        Windows.overlayShowEffectOptions = {duration: 0};
+        Windows.overlayHideEffectOptions = {duration: 0};
 
         Dialog.confirm(content, {
-            draggable:true,
-            resizable:true,
-            closable:true,
-            className:"magento",
-            title:"Translation",
-            width:650,
-            height:470,
-            zIndex:1000,
-            recenterAuto:false,
-            hideEffect:Element.hide,
-            showEffect:Element.show,
-            id:"translate-inline",
-            buttonClass:"form-button button",
-            okLabel:"Submit",
+            draggable: true,
+            resizable: true,
+            closable: true,
+            className: "magento",
+            title: "Translation",
+            width: 650,
+            height: 470,
+            zIndex: 2100,
+            recenterAuto: false,
+            hideEffect: Element.hide,
+            showEffect: Element.show,
+            id: "translate-inline",
+            buttonClass: "form-button button",
+            okLabel: "Submit",
             ok: this.formOk.bind(this),
             cancel: this.formClose.bind(this),
             onClose: this.formClose.bind(this)
         });
+        this.trigHide();
     },
 
     formOk: function(win) {
@@ -158,7 +182,7 @@ TranslateInline.prototype = {
         this.formIsSubmitted = true;
 
         var inputs = $('translate-inline-form').getInputs(), parameters = {};
-        for (var i=0; i<inputs.length; i++) {
+        for (var i = 0; i < inputs.length; i++) {
             if (inputs[i].type == 'checkbox') {
                 if (inputs[i].checked) {
                     parameters[inputs[i].name] = inputs[i].value;
@@ -171,9 +195,9 @@ TranslateInline.prototype = {
         parameters['area'] = this.area;
 
         new Ajax.Request(this.ajaxUrl, {
-            method:'post',
-            parameters:parameters,
-            onComplete:this.ajaxComplete.bind(this, win)
+            method: 'post',
+            parameters: parameters,
+            onComplete: this.ajaxComplete.bind(this, win)
         });
 
         this.formIsSubmitted = false;
@@ -190,12 +214,12 @@ TranslateInline.prototype = {
         this.formIsShown = false;
     },
 
-    escapeHTML: function (str) {
-       this.helperDiv.innerHTML = '';
-       var text = document.createTextNode(str);
-       this.helperDiv.appendChild(text);
-       var escaped = this.helperDiv.innerHTML;
-       escaped = escaped.replace(/"/g, '&quot;');
-       return escaped;
+    escapeHTML: function(str) {
+        this.helperDiv.innerHTML = '';
+        var text = document.createTextNode(str);
+        this.helperDiv.appendChild(text);
+        var escaped = this.helperDiv.innerHTML;
+        escaped = escaped.replace(/"/g, '&quot;');
+        return escaped;
     }
 }
diff --git a/pub/js/prototype/validation.js b/pub/js/prototype/validation.js
index 92dd31ff0543c8336819b4b8dc5d0d46086f1234..fe52526127be17e696db5f335c8325834a6bb0a7 100644
--- a/pub/js/prototype/validation.js
+++ b/pub/js/prototype/validation.js
@@ -421,29 +421,29 @@ Validation.addAllThese([
     ['required-entry', 'This is a required field.', function(v) {
                 return !Validation.get('IsEmpty').test(v);
             }],
-    ['validate-number', 'Please enter a valid number in this field.', function(v, elm) {
-                if (elm.hasClassName('required-entry') && !Validation.get('required-entry').test(v)) {
-                    return true; // hardcode, should be achieved by CSS classes ordering
-                }
-
-                return !Validation.get('IsEmpty').test(v)
-                    && !isNaN(parseNumber(v)) && /^\s*-?\d*([.,]\d*)?\s*$/.test(v);
+    ['validate-number', 'Please enter a valid number in this field.', function(v) {
+                return Validation.get('IsEmpty').test(v)
+                    || (!isNaN(parseNumber(v)) && /^\s*-?\d*(\.\d*)?\s*$/.test(v));
             }],
     ['validate-number-range', 'The value is not within the specified range.', function(v, elm) {
+                if (Validation.get('IsEmpty').test(v)) {
+                    return true;
+                }
+
                 var numValue = parseNumber(v);
-                if (Validation.get('IsEmpty').test(v) || isNaN(numValue)) {
+                if (isNaN(numValue)) {
                     return false;
                 }
 
-                var reRange = /^number-range-([-\d.,]+)-([-\d.,]+)$/,
+                var reRange = /^number-range-(-?[\d.,]+)?-(-?[\d.,]+)?$/,
                     result = true;
 
                 $w(elm.className).each(function(name) {
-                    var m = reRange.exec(name), min, max;
+                    var m = reRange.exec(name);
                     if (m) {
-                        min = parseNumber(m[1]);
-                        max = parseNumber(m[2]);
-                        result = result && numValue >= min && numValue <= max;
+                        result = result
+                            && (m[1] == null || m[1] == '' || numValue >= parseNumber(m[1]))
+                            && (m[2] == null || m[2] == '' || numValue <= parseNumber(m[2]));
                     }
                 });
 
@@ -453,16 +453,27 @@ Validation.addAllThese([
                 return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
             }],
     ['validate-digits-range', 'The value is not within the specified range.', function(v, elm) {
-                var result = Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
-                var reRange = new RegExp(/^digits-range-[0-9]+-[0-9]+$/);
-                $w(elm.className).each(function(name, index) {
-                    if (name.match(reRange) && result) {
-                        var min = parseInt(name.split('-')[2], 10);
-                        var max = parseInt(name.split('-')[3], 10);
-                        var val = parseInt(v, 10);
-                        result = (v >= min) && (v <= max);
+                if (Validation.get('IsEmpty').test(v)) {
+                    return true;
+                }
+
+                var numValue = parseNumber(v);
+                if (isNaN(numValue)) {
+                    return false;
+                }
+
+                var reRange = /^digits-range-(-?\d+)?-(-?\d+)?$/,
+                    result = true;
+
+                $w(elm.className).each(function(name) {
+                    var m = reRange.exec(name);
+                    if (m) {
+                        result = result
+                            && (m[1] == null || m[1] == '' || numValue >= parseNumber(m[1]))
+                            && (m[2] == null || m[2] == '' || numValue <= parseNumber(m[2]));
                     }
                 });
+
                 return result;
             }],
     ['validate-alpha', 'Please use letters only (a-z or A-Z) in this field.', function (v) {
@@ -472,10 +483,10 @@ Validation.addAllThese([
                 return Validation.get('IsEmpty').test(v) ||  /^[a-z]+[a-z0-9_]+$/.test(v)
             }],
     ['validate-alphanum', 'Please use only letters (a-z or A-Z) or numbers (0-9) only in this field. No spaces or other characters are allowed.', function(v) {
-                return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z0-9]+$/.test(v) /*!/\W/.test(v)*/
+                return Validation.get('IsEmpty').test(v) || /^[a-zA-Z0-9]+$/.test(v)
             }],
     ['validate-alphanum-with-spaces', 'Please use only letters (a-z or A-Z), numbers (0-9) or spaces only in this field.', function(v) {
-                    return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z0-9 ]+$/.test(v) /*!/\W/.test(v)*/
+                    return Validation.get('IsEmpty').test(v) || /^[a-zA-Z0-9 ]+$/.test(v)
             }],
     ['validate-street', 'Please use only letters (a-z or A-Z) or numbers (0-9) or spaces and # only in this field.', function(v) {
                 return Validation.get('IsEmpty').test(v) ||  /^[ \w]{3,}([A-Za-z]\.)?([ \w]*\#\d+)?(\r\n| )[ \w]{3,}/.test(v)
@@ -599,14 +610,23 @@ Validation.addAllThese([
                     return false;
                 }
             }],
-    ['validate-not-negative-number', 'Please enter a valid number in this field.', function(v, elm) {
-                if (elm.hasClassName('required-entry') && !Validation.get('required-entry').test(v)) {
-                    return true; // hardcode, should be achieved by CSS classes ordering
+    ['validate-not-negative-number', 'Please enter a number 0 or greater in this field.', function(v) {
+                if (Validation.get('IsEmpty').test(v)) {
+                    return true;
                 }
-
                 v = parseNumber(v);
-                return !isNaN(v) && v>=0;
+                return !isNaN(v) && v >= 0;
             }],
+    ['validate-zero-or-greater', 'Please enter a number 0 or greater in this field.', function(v) {
+            return Validation.get('validate-not-negative-number').test(v);
+        }],
+    ['validate-greater-than-zero', 'Please enter a number greater than 0 in this field.', function(v) {
+            if (Validation.get('IsEmpty').test(v)) {
+                return true;
+            }
+            v = parseNumber(v);
+            return !isNaN(v) && v > 0;
+        }],
     ['validate-state', 'Please select State/Province.', function(v) {
                 return (v!=0 || v == '');
             }],
@@ -615,18 +635,6 @@ Validation.addAllThese([
                 if (Validation.get('IsEmpty').test(v) && v != '') return false;
                 return true;
             }],
-    ['validate-greater-than-zero', 'Please enter a number greater than 0 in this field.', function(v) {
-                if(v.length)
-                    return parseNumber(v) > 0;
-                else
-                    return true;
-            }],
-    ['validate-zero-or-greater', 'Please enter a number 0 or greater in this field.', function(v) {
-                if(v.length)
-                    return parseNumber(v) >= 0;
-                else
-                    return true;
-            }],
     ['validate-cc-number', 'Please enter a valid credit card number.', function(v, elm) {
                 // remove non-numerics
                 var ccTypeContainer = $(elm.id.substr(0,elm.id.indexOf('_cc_number')) + '_cc_type');
diff --git a/pub/js/prototype/window.js b/pub/js/prototype/window.js
index 7eb203c626c846b457118fb8c44b9cca3699e7ee..f7ae25d3a9b9ebd7bc2781f8c03bcd3e0d959627 100644
--- a/pub/js/prototype/window.js
+++ b/pub/js/prototype/window.js
@@ -1435,12 +1435,19 @@ var Dialog = {
 
     var okButtonClass = "class ='" + (parameters.buttonClass ? parameters.buttonClass + " " : "") + " ok_button'" 
     var cancelButtonClass = "class ='" + (parameters.buttonClass ? parameters.buttonClass + " " : "") + " cancel_button'" 
-    var content = "\
+/*     var content = "\
       <div class='" + parameters.className + "_message'>" + content  + "</div>\
         <div class='" + parameters.className + "_buttons'>\
           <input type='button' value='" + okLabel + "' onclick='Dialog.okCallback()' " + okButtonClass + "/>\
           <input type='button' value='" + cancelLabel + "' onclick='Dialog.cancelCallback()' " + cancelButtonClass + "/>\
         </div>\
+    "; */
+    var content = "\
+      <div class='" + parameters.className + "_message'>" + content  + "</div>\
+        <div class='" + parameters.className + "_buttons'>\
+          <button type='button' title='" + okLabel + "' onclick='Dialog.okCallback()' " + okButtonClass + "><span><span><span>" + okLabel + "</span></span></span></button>\
+          <button type='button' title='" + cancelLabel + "' onclick='Dialog.cancelCallback()' " + cancelButtonClass + "><span><span><span>" + cancelLabel + "</span></span></span></button>\
+        </div>\
     ";
     return this._openDialog(content, parameters)
   },
@@ -1463,10 +1470,15 @@ var Dialog = {
     parameters.className = parameters.className || "alert";
     
     var okButtonClass = "class ='" + (parameters.buttonClass ? parameters.buttonClass + " " : "") + " ok_button'" 
-    var content = "\
+/*     var content = "\
       <div class='" + parameters.className + "_message'>" + content  + "</div>\
         <div class='" + parameters.className + "_buttons'>\
           <input type='button' value='" + okLabel + "' onclick='Dialog.okCallback()' " + okButtonClass + "/>\
+        </div>";   */
+    var content = "\
+      <div class='" + parameters.className + "_message'>" + content  + "</div>\
+        <div class='" + parameters.className + "_buttons'>\
+          <button type='button' title='" + okLabel + "' onclick='Dialog.okCallback()' " + okButtonClass + "><span><span><span>" + okLabel + "</span></span></span></button>\
         </div>";                  
     return this._openDialog(content, parameters)
   },
diff --git a/pub/js/scriptaculous/dragdrop.js b/pub/js/scriptaculous/dragdrop.js
index 24e8908d45714a1637537a235ee08eb196ff277d..9ebfe24d3c03ca874c1877af842d80ce2ede87c9 100644
--- a/pub/js/scriptaculous/dragdrop.js
+++ b/pub/js/scriptaculous/dragdrop.js
@@ -1,7 +1,6 @@
-// script.aculo.us dragdrop.js v1.8.2, Tue Nov 18 18:30:58 +0100 2008
+// script.aculo.us dragdrop.js v1.9.0, Thu Dec 23 16:54:48 -0500 2010
 
-// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
-//           (c) 2005-2008 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
+// Copyright (c) 2005-2010 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
 //
 // script.aculo.us is freely distributable under the terms of an MIT-style license.
 // For details, see the script.aculo.us web site: http://script.aculo.us/
@@ -136,7 +135,7 @@ var Draggables = {
       this.eventKeypress  = this.keyPress.bindAsEventListener(this);
 
       Event.observe(document, "mouseup", this.eventMouseUp);
-      Event.observe(draggable.element, "mousemove", this.eventMouseMove);
+      Event.observe(document, "mousemove", this.eventMouseMove);
       Event.observe(document, "keypress", this.eventKeypress);
     }
     this.drags.push(draggable);
@@ -146,7 +145,7 @@ var Draggables = {
     this.drags = this.drags.reject(function(d) { return d==draggable });
     if(this.drags.length == 0) {
       Event.stopObserving(document, "mouseup", this.eventMouseUp);
-      Event.stopObserving(draggable.element, "mousemove", this.eventMouseMove);
+      Event.stopObserving(document, "mousemove", this.eventMouseMove);
       Event.stopObserving(document, "keypress", this.eventKeypress);
     }
   },
@@ -313,7 +312,7 @@ var Draggable = Class.create({
         tag_name=='TEXTAREA')) return;
 
       var pointer = [Event.pointerX(event), Event.pointerY(event)];
-      var pos     = Position.cumulativeOffset(this.element);
+      var pos     = this.element.cumulativeOffset();
       this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
 
       Draggables.activate(this);
@@ -375,7 +374,7 @@ var Draggable = Class.create({
       if (this.options.scroll == window) {
         with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
       } else {
-        p = Position.page(this.options.scroll);
+        p = Position.page(this.options.scroll).toArray();
         p[0] += this.options.scroll.scrollLeft + Position.deltaX;
         p[1] += this.options.scroll.scrollTop + Position.deltaY;
         p.push(p[0]+this.options.scroll.offsetWidth);
@@ -456,7 +455,7 @@ var Draggable = Class.create({
   },
 
   draw: function(point) {
-    var pos = Position.cumulativeOffset(this.element);
+    var pos = this.element.cumulativeOffset();
     if(this.options.ghosting) {
       var r   = Position.realOffset(this.element);
       pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
@@ -732,7 +731,7 @@ var Sortable = {
     }
 
     // keep reference
-    this.sortables[element.id] = options;
+    this.sortables[element.identify()] = options;
 
     // for onupdate
     Draggables.addObserver(new SortableObserver(element, options.onUpdate));
@@ -827,7 +826,7 @@ var Sortable = {
           hide().addClassName('dropmarker').setStyle({position:'absolute'});
       document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
     }
-    var offsets = Position.cumulativeOffset(dropon);
+    var offsets = dropon.cumulativeOffset();
     Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
 
     if(position=='after')
diff --git a/pub/js/varien/form.js b/pub/js/varien/form.js
index be90e86bf88639519a46be072ea70908d1348e96..ba13c4b8278829eefde16aadda3cfa448f6d8198 100644
--- a/pub/js/varien/form.js
+++ b/pub/js/varien/form.js
@@ -168,6 +168,8 @@ RegionUpdater.prototype = {
         this.regionTextEl = $(regionTextEl);
         this.regionSelectEl = $(regionSelectEl);
         this.zipEl = $(zipEl);
+        this.config = regions['config'];
+        delete regions.config;
         this.regions = regions;
 
         this.disableAction = (typeof disableAction=='undefined') ? 'hide' : disableAction;
@@ -180,18 +182,76 @@ RegionUpdater.prototype = {
         Event.observe(this.countryEl, 'change', this.update.bind(this));
     },
 
+    _checkRegionRequired: function()
+    {
+        var label, wildCard;
+        var elements = [this.regionTextEl, this.regionSelectEl];
+        var that = this;
+        if (typeof this.config == 'undefined') {
+            return;
+        }
+        var regionRequired = this.config.regions_required.indexOf(this.countryEl.value) >= 0;
+
+        elements.each(function(currentElement) {
+            Validation.reset(currentElement);
+            label = $$('label[for="' + currentElement.id + '"]')[0];
+            if (label) {
+                wildCard = label.down('em') || label.down('span.required');
+                if (!that.config.show_all_regions) {
+                    if (regionRequired) {
+                        label.up().show();
+                    } else {
+                        label.up().hide();
+                    }
+                }
+            }
+
+            if (label && wildCard) {
+                if (!regionRequired) {
+                    wildCard.hide();
+                    if (label.hasClassName('required')) {
+                        label.removeClassName('required');
+                    }
+                } else if (regionRequired) {
+                    wildCard.show();
+                    if (!label.hasClassName('required')) {
+                        label.addClassName('required')
+                    }
+                }
+            }
+
+            if (!regionRequired) {
+                if (currentElement.hasClassName('required-entry')) {
+                    currentElement.removeClassName('required-entry');
+                }
+                if ('select' == currentElement.tagName.toLowerCase() &&
+                    currentElement.hasClassName('validate-select')) {
+                    currentElement.removeClassName('validate-select');
+                }
+            } else {
+                if (!currentElement.hasClassName('required-entry')) {
+                    currentElement.addClassName('required-entry');
+                }
+                if ('select' == currentElement.tagName.toLowerCase() &&
+                    !currentElement.hasClassName('validate-select')) {
+                    currentElement.addClassName('validate-select');
+                }
+            }
+        });
+    },
+
     update: function()
     {
         if (this.regions[this.countryEl.value]) {
             var i, option, region, def;
 
+            def = this.regionSelectEl.getAttribute('defaultValue');
             if (this.regionTextEl) {
-                def = this.regionTextEl.value.toLowerCase();
+                if (!def) {
+                    def = this.regionTextEl.value.toLowerCase();
+                }
                 this.regionTextEl.value = '';
             }
-            if (!def) {
-                def = this.regionSelectEl.getAttribute('defaultValue');
-            }
 
             this.regionSelectEl.options.length = 1;
             for (regionId in this.regions[this.countryEl.value]) {
@@ -208,7 +268,9 @@ RegionUpdater.prototype = {
                     this.regionSelectEl.appendChild(option);
                 }
 
-                if (regionId==def || region.name.toLowerCase()==def || region.code.toLowerCase()==def) {
+                if (regionId==def || (region.name && region.name.toLowerCase()==def) ||
+                    (region.name && region.code.toLowerCase()==def)
+                ) {
                     this.regionSelectEl.value = regionId;
                 }
             }
@@ -247,6 +309,7 @@ RegionUpdater.prototype = {
             this.setMarkDisplay(this.regionSelectEl, false);
         }
 
+        this._checkRegionRequired();
         // Make Zip and its label required/optional
         var zipUpdater = new ZipUpdater(this.countryEl.value, this.zipEl);
         zipUpdater.update();
diff --git a/pub/js/varien/js.js b/pub/js/varien/js.js
index a6b67f6c5eecaf680c900bffb1ed602d6a2282ae..3f335bf9738966ba25f2c725d12691ac26e48584 100644
--- a/pub/js/varien/js.js
+++ b/pub/js/varien/js.js
@@ -667,6 +667,27 @@ function fireEvent(element, event) {
     }
 }
 
+/**
+ * Returns more accurate results of floating-point modulo division
+ * E.g.:
+ * 0.6 % 0.2 = 0.19999999999999996
+ * modulo(0.6, 0.2) = 0
+ *
+ * @param dividend
+ * @param divisor
+ */
+function modulo(dividend, divisor)
+{
+    var epsilon = divisor / 10000;
+    var remainder = dividend % divisor;
+
+    if (Math.abs(remainder - divisor) < epsilon || Math.abs(remainder) < epsilon) {
+        remainder = 0;
+    }
+
+    return remainder;
+}
+
 /**
  * createContextualFragment is not supported in IE9. Adding its support.
  */
diff --git a/pub/js/varien/product.js b/pub/js/varien/product.js
index dd1c43fa0e62f1146f60cd681d8d51ac2a1598e1..b02104adefb9d60fb460ed594892c7e700ff681f 100644
--- a/pub/js/varien/product.js
+++ b/pub/js/varien/product.js
@@ -664,20 +664,6 @@ Product.OptionsPrice.prototype = {
                     _priceInclTax += parseFloat(_productPrice) * (100 + this.currentTax) / 100;
                 }
 
-                var subPrice = 0;
-                var subPriceincludeTax = 0;
-                Object.values(this.customPrices).each(function(el){
-                    if (el.excludeTax && el.includeTax) {
-                        subPrice += el.excludeTax;
-                        subPriceincludeTax += el.includeTax;
-                    } else {
-                        subPrice += el.price;
-                        subPriceincludeTax += el.price;
-                    }
-                });
-                price += subPrice;
-                _priceInclTax += subPriceincludeTax;
-
                 if (this.specialTaxPrice == 'true') {
                     var excl = price;
                     var incl = _priceInclTax;
@@ -692,6 +678,20 @@ Product.OptionsPrice.prototype = {
                     var incl = excl + tax;
                 }
 
+                var subPrice = 0;
+                var subPriceincludeTax = 0;
+                Object.values(this.customPrices).each(function(el){
+                    if (el.excludeTax && el.includeTax) {
+                        subPrice += parseFloat(el.excludeTax);
+                        subPriceincludeTax += parseFloat(el.includeTax);
+                    } else {
+                        subPrice += parseFloat(el.price);
+                        subPriceincludeTax += parseFloat(el.price);
+                    }
+                });
+                excl += subPrice;
+                incl += subPriceincludeTax;
+
                 if (typeof this.exclDisposition == 'undefined') {
                     excl += parseFloat(_plusDisposition);
                 }