From 10efb0f7b426426057fed757fe3c851a249358dd Mon Sep 17 00:00:00 2001 From: Rene Ae Date: Fri, 4 Dec 2015 20:32:44 -0600 Subject: android build --- .../cordova-js-src/android/nativeapiprovider.js | 36 + .../cordova-js-src/android/promptbasednativeapi.js | 35 + .../android/assets/www/cordova-js-src/exec.js | 283 ++ .../android/assets/www/cordova-js-src/platform.js | 91 + .../www/cordova-js-src/plugin/android/app.js | 108 + .../platforms/android/assets/www/cordova.js | 1979 ++++++++ .../android/assets/www/cordova_plugins.js | 133 + .../platforms/android/assets/www/css/account.css | 489 ++ .../platforms/android/assets/www/css/blogs.css | 340 ++ .../platforms/android/assets/www/css/cart.css | 358 ++ .../android/assets/www/css/fonts/andale_mono.ttf | Bin 0 -> 109700 bytes .../android/assets/www/css/fonts/andale_mono.woff | Bin 0 -> 53751 bytes .../android/assets/www/css/fonts/fonts.css | 37 + .../android/assets/www/css/fonts/ionicons.css | 1480 ++++++ .../android/assets/www/css/fonts/ionicons.eot | Bin 0 -> 120724 bytes .../android/assets/www/css/fonts/ionicons.svg | 2230 +++++++++ .../android/assets/www/css/fonts/ionicons.ttf | Bin 0 -> 188508 bytes .../android/assets/www/css/fonts/ionicons.woff | Bin 0 -> 67904 bytes .../www/css/fonts/pfdintextpro-bold-webfont.woff | Bin 0 -> 25068 bytes .../www/css/fonts/pfdintextpro-italic-webfont.woff | Bin 0 -> 30160 bytes .../www/css/fonts/pfdintextpro-light-webfont.woff | Bin 0 -> 28824 bytes .../www/css/fonts/pfdintextpro-medium-webfont.woff | Bin 0 -> 26668 bytes .../css/fonts/pfdintextpro-regular-webfont.woff | Bin 0 -> 25352 bytes .../platforms/android/assets/www/css/index.css | 61 + .../platforms/android/assets/www/css/nav.css | 341 ++ .../platforms/android/assets/www/css/products.css | 200 + .../android/assets/www/css/vendor/flickity.css | 141 + StoneIsland/platforms/android/assets/www/db.json | 485 ++ .../assets/www/icons/android-icon-144x144.png | Bin 0 -> 4091 bytes .../assets/www/icons/android-icon-192x192.png | Bin 0 -> 4431 bytes .../assets/www/icons/android-icon-36x36.png | Bin 0 -> 1578 bytes .../assets/www/icons/android-icon-48x48.png | Bin 0 -> 1879 bytes .../assets/www/icons/android-icon-72x72.png | Bin 0 -> 2334 bytes .../assets/www/icons/android-icon-96x96.png | Bin 0 -> 2817 bytes .../assets/www/icons/apple-icon-114x114.png | Bin 0 -> 3155 bytes .../assets/www/icons/apple-icon-120x120.png | Bin 0 -> 3326 bytes .../assets/www/icons/apple-icon-144x144.png | Bin 0 -> 4091 bytes .../assets/www/icons/apple-icon-152x152.png | Bin 0 -> 4383 bytes .../assets/www/icons/apple-icon-180x180.png | Bin 0 -> 5212 bytes .../android/assets/www/icons/apple-icon-57x57.png | Bin 0 -> 2069 bytes .../android/assets/www/icons/apple-icon-60x60.png | Bin 0 -> 2133 bytes .../android/assets/www/icons/apple-icon-72x72.png | Bin 0 -> 2334 bytes .../android/assets/www/icons/apple-icon-76x76.png | Bin 0 -> 2432 bytes .../assets/www/icons/apple-icon-precomposed.png | Bin 0 -> 5000 bytes .../android/assets/www/icons/apple-icon.png | Bin 0 -> 5000 bytes .../android/assets/www/icons/browserconfig.xml | 2 + .../android/assets/www/icons/favicon-16x16.png | Bin 0 -> 1062 bytes .../android/assets/www/icons/favicon-32x32.png | Bin 0 -> 1499 bytes .../android/assets/www/icons/favicon-96x96.png | Bin 0 -> 2817 bytes .../platforms/android/assets/www/icons/favicon.ico | Bin 0 -> 1150 bytes .../android/assets/www/icons/manifest.json | 41 + .../android/assets/www/icons/ms-icon-144x144.png | Bin 0 -> 4091 bytes .../android/assets/www/icons/ms-icon-150x150.png | Bin 0 -> 4310 bytes .../android/assets/www/icons/ms-icon-310x310.png | Bin 0 -> 11333 bytes .../android/assets/www/icons/ms-icon-70x70.png | Bin 0 -> 2291 bytes .../img/Resources/CDVNotification.bundle/beep.wav | Bin 0 -> 8114 bytes .../Resources/splash/Default-568h@2x~iphone.png | Bin 0 -> 34225 bytes .../www/img/Resources/splash/Default-667h.png | Bin 0 -> 57532 bytes .../www/img/Resources/splash/Default-736h.png | Bin 0 -> 80929 bytes .../Resources/splash/Default-Landscape-736h.png | Bin 0 -> 79491 bytes .../Resources/splash/Default-Landscape@2x~ipad.png | Bin 0 -> 212234 bytes .../Resources/splash/Default-Landscape~ipad.png | Bin 0 -> 91810 bytes .../Resources/splash/Default-Portrait@2x~ipad.png | Bin 0 -> 212860 bytes .../img/Resources/splash/Default-Portrait~ipad.png | Bin 0 -> 91713 bytes .../www/img/Resources/splash/Default@2x~iphone.png | Bin 0 -> 29475 bytes .../www/img/Resources/splash/Default~iphone.png | Bin 0 -> 10394 bytes .../android/assets/www/img/compass-logo.png | Bin 0 -> 75721 bytes .../android/assets/www/img/compass-logo.png.old | Bin 0 -> 137677 bytes .../android/assets/www/img/left-arrow.png | Bin 0 -> 5147 bytes .../android/assets/www/img/right-arrow.png | Bin 0 -> 5264 bytes .../platforms/android/assets/www/img/spinner.gif | Bin 0 -> 5694 bytes .../platforms/android/assets/www/img/wide-logo.png | Bin 0 -> 18354 bytes .../platforms/android/assets/www/index.html | 1153 +++++ .../platforms/android/assets/www/js/index.js | 86 + .../platforms/android/assets/www/js/lib/_router.js | 105 + .../assets/www/js/lib/account/AccountView.js | 129 + .../assets/www/js/lib/account/OrdersView.js | 189 + .../assets/www/js/lib/account/PaymentView.js | 115 + .../assets/www/js/lib/account/ProfileView.js | 82 + .../assets/www/js/lib/account/SettingsView.js | 24 + .../assets/www/js/lib/account/ShippingView.js | 77 + .../android/assets/www/js/lib/auth/LoginView.js | 53 + .../android/assets/www/js/lib/auth/LogoutView.js | 16 + .../android/assets/www/js/lib/auth/SignupView.js | 117 + .../android/assets/www/js/lib/blogs/ArchiveView.js | 228 + .../android/assets/www/js/lib/blogs/BlogView.js | 70 + .../android/assets/www/js/lib/blogs/HubView.js | 113 + .../android/assets/www/js/lib/blogs/PageView.js | 24 + .../android/assets/www/js/lib/blogs/StoryView.js | 65 + .../android/assets/www/js/lib/cart/CartConfirm.js | 174 + .../android/assets/www/js/lib/cart/CartError.js | 28 + .../android/assets/www/js/lib/cart/CartPayment.js | 185 + .../android/assets/www/js/lib/cart/CartShipping.js | 136 + .../android/assets/www/js/lib/cart/CartSummary.js | 202 + .../android/assets/www/js/lib/cart/CartThanks.js | 25 + .../android/assets/www/js/lib/cart/CartView.js | 66 + .../android/assets/www/js/lib/etc/deeplink.js | 3 + .../platforms/android/assets/www/js/lib/etc/geo.js | 39 + .../android/assets/www/js/lib/etc/push.js | 1 + .../android/assets/www/js/lib/nav/AddressView.js | 267 + .../assets/www/js/lib/nav/CreditCardView.js | 61 + .../android/assets/www/js/lib/nav/CurtainView.js | 39 + .../android/assets/www/js/lib/nav/FooterView.js | 40 + .../android/assets/www/js/lib/nav/HeaderView.js | 57 + .../android/assets/www/js/lib/nav/IntroView.js | 46 + .../android/assets/www/js/lib/nav/NavView.js | 157 + .../android/assets/www/js/lib/nav/SearchView.js | 16 + .../assets/www/js/lib/products/ClosedStoreView.js | 56 + .../assets/www/js/lib/products/CollectionView.js | 114 + .../assets/www/js/lib/products/GalleryView.js | 65 + .../assets/www/js/lib/products/ProductView.js | 397 ++ .../android/assets/www/js/lib/products/Selector.js | 48 + .../www/js/lib/products/filters/CategoryFilter.js | 40 + .../android/assets/www/js/lib/view/Router.js | 75 + .../android/assets/www/js/lib/view/Scrollable.js | 27 + .../android/assets/www/js/lib/view/Serializable.js | 164 + .../android/assets/www/js/lib/view/View.js | 147 + .../platforms/android/assets/www/js/sdk/_sdk.js | 38 + .../platforms/android/assets/www/js/sdk/account.js | 133 + .../platforms/android/assets/www/js/sdk/address.js | 74 + .../platforms/android/assets/www/js/sdk/auth.js | 129 + .../platforms/android/assets/www/js/sdk/cart.js | 248 + .../platforms/android/assets/www/js/sdk/payment.js | 72 + .../platforms/android/assets/www/js/sdk/product.js | 37 + .../android/assets/www/js/sdk/shipping.js | 85 + .../android/assets/www/js/vendor/fastclick.js | 790 +++ .../android/assets/www/js/vendor/flickity.pkgd.js | 5090 ++++++++++++++++++++ .../android/assets/www/js/vendor/iscroll.js | 2011 ++++++++ .../assets/www/js/vendor/jquery-2.1.4.min.js | 4 + .../www/js/vendor/jquery.creditCardValidator.js | 208 + .../android/assets/www/js/vendor/loader.js | 97 + .../android/assets/www/js/vendor/lodash.min.js | 98 + .../android/assets/www/js/vendor/moment.js | 3195 ++++++++++++ .../android/assets/www/js/vendor/oktween.js | 125 + .../android/assets/www/js/vendor/prefixfree.js | 497 ++ .../android/assets/www/js/vendor/promise.js | 34 + .../platforms/android/assets/www/js/vendor/util.js | 199 + .../www/plugins/com.ionic.keyboard/www/keyboard.js | 39 + .../www/console-via-logger.js | 189 + .../plugins/cordova-plugin-console/www/logger.js | 357 ++ .../www/android/LaunchMyApp.js | 26 + .../plugins/cordova-plugin-device/www/device.js | 81 + .../www/android/notification.js | 76 + .../cordova-plugin-dialogs/www/notification.js | 114 + .../www/inappbrowser.js | 112 + .../www/Connection.js | 36 + .../www/network.js | 93 + .../www/splashscreen.js | 35 + .../plugins/cordova-plugin-whitelist/whitelist.js | 29 + .../www/SocialSharing.js | 117 + .../www/plugins/phonegap-plugin-push/www/push.js | 231 + 151 files changed, 28890 insertions(+) create mode 100755 StoneIsland/platforms/android/assets/www/cordova-js-src/android/nativeapiprovider.js create mode 100755 StoneIsland/platforms/android/assets/www/cordova-js-src/android/promptbasednativeapi.js create mode 100755 StoneIsland/platforms/android/assets/www/cordova-js-src/exec.js create mode 100755 StoneIsland/platforms/android/assets/www/cordova-js-src/platform.js create mode 100755 StoneIsland/platforms/android/assets/www/cordova-js-src/plugin/android/app.js create mode 100755 StoneIsland/platforms/android/assets/www/cordova.js create mode 100755 StoneIsland/platforms/android/assets/www/cordova_plugins.js create mode 100755 StoneIsland/platforms/android/assets/www/css/account.css create mode 100755 StoneIsland/platforms/android/assets/www/css/blogs.css create mode 100755 StoneIsland/platforms/android/assets/www/css/cart.css create mode 100755 StoneIsland/platforms/android/assets/www/css/fonts/andale_mono.ttf create mode 100755 StoneIsland/platforms/android/assets/www/css/fonts/andale_mono.woff create mode 100755 StoneIsland/platforms/android/assets/www/css/fonts/fonts.css create mode 100755 StoneIsland/platforms/android/assets/www/css/fonts/ionicons.css create mode 100755 StoneIsland/platforms/android/assets/www/css/fonts/ionicons.eot create mode 100755 StoneIsland/platforms/android/assets/www/css/fonts/ionicons.svg create mode 100755 StoneIsland/platforms/android/assets/www/css/fonts/ionicons.ttf create mode 100755 StoneIsland/platforms/android/assets/www/css/fonts/ionicons.woff create mode 100755 StoneIsland/platforms/android/assets/www/css/fonts/pfdintextpro-bold-webfont.woff create mode 100755 StoneIsland/platforms/android/assets/www/css/fonts/pfdintextpro-italic-webfont.woff create mode 100755 StoneIsland/platforms/android/assets/www/css/fonts/pfdintextpro-light-webfont.woff create mode 100755 StoneIsland/platforms/android/assets/www/css/fonts/pfdintextpro-medium-webfont.woff create mode 100755 StoneIsland/platforms/android/assets/www/css/fonts/pfdintextpro-regular-webfont.woff create mode 100755 StoneIsland/platforms/android/assets/www/css/index.css create mode 100755 StoneIsland/platforms/android/assets/www/css/nav.css create mode 100755 StoneIsland/platforms/android/assets/www/css/products.css create mode 100755 StoneIsland/platforms/android/assets/www/css/vendor/flickity.css create mode 100755 StoneIsland/platforms/android/assets/www/db.json create mode 100755 StoneIsland/platforms/android/assets/www/icons/android-icon-144x144.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/android-icon-192x192.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/android-icon-36x36.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/android-icon-48x48.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/android-icon-72x72.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/android-icon-96x96.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/apple-icon-114x114.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/apple-icon-120x120.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/apple-icon-144x144.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/apple-icon-152x152.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/apple-icon-180x180.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/apple-icon-57x57.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/apple-icon-60x60.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/apple-icon-72x72.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/apple-icon-76x76.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/apple-icon-precomposed.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/apple-icon.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/browserconfig.xml create mode 100755 StoneIsland/platforms/android/assets/www/icons/favicon-16x16.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/favicon-32x32.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/favicon-96x96.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/favicon.ico create mode 100755 StoneIsland/platforms/android/assets/www/icons/manifest.json create mode 100755 StoneIsland/platforms/android/assets/www/icons/ms-icon-144x144.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/ms-icon-150x150.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/ms-icon-310x310.png create mode 100755 StoneIsland/platforms/android/assets/www/icons/ms-icon-70x70.png create mode 100755 StoneIsland/platforms/android/assets/www/img/Resources/CDVNotification.bundle/beep.wav create mode 100755 StoneIsland/platforms/android/assets/www/img/Resources/splash/Default-568h@2x~iphone.png create mode 100755 StoneIsland/platforms/android/assets/www/img/Resources/splash/Default-667h.png create mode 100755 StoneIsland/platforms/android/assets/www/img/Resources/splash/Default-736h.png create mode 100755 StoneIsland/platforms/android/assets/www/img/Resources/splash/Default-Landscape-736h.png create mode 100755 StoneIsland/platforms/android/assets/www/img/Resources/splash/Default-Landscape@2x~ipad.png create mode 100755 StoneIsland/platforms/android/assets/www/img/Resources/splash/Default-Landscape~ipad.png create mode 100755 StoneIsland/platforms/android/assets/www/img/Resources/splash/Default-Portrait@2x~ipad.png create mode 100755 StoneIsland/platforms/android/assets/www/img/Resources/splash/Default-Portrait~ipad.png create mode 100755 StoneIsland/platforms/android/assets/www/img/Resources/splash/Default@2x~iphone.png create mode 100755 StoneIsland/platforms/android/assets/www/img/Resources/splash/Default~iphone.png create mode 100755 StoneIsland/platforms/android/assets/www/img/compass-logo.png create mode 100755 StoneIsland/platforms/android/assets/www/img/compass-logo.png.old create mode 100755 StoneIsland/platforms/android/assets/www/img/left-arrow.png create mode 100755 StoneIsland/platforms/android/assets/www/img/right-arrow.png create mode 100755 StoneIsland/platforms/android/assets/www/img/spinner.gif create mode 100755 StoneIsland/platforms/android/assets/www/img/wide-logo.png create mode 100755 StoneIsland/platforms/android/assets/www/index.html create mode 100755 StoneIsland/platforms/android/assets/www/js/index.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/_router.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/account/AccountView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/account/OrdersView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/account/PaymentView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/account/ProfileView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/account/SettingsView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/account/ShippingView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/auth/LoginView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/auth/LogoutView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/auth/SignupView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/blogs/ArchiveView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/blogs/BlogView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/blogs/HubView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/blogs/PageView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/blogs/StoryView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/cart/CartConfirm.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/cart/CartError.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/cart/CartPayment.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/cart/CartShipping.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/cart/CartSummary.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/cart/CartThanks.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/cart/CartView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/etc/deeplink.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/etc/geo.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/etc/push.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/nav/AddressView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/nav/CreditCardView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/nav/CurtainView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/nav/FooterView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/nav/HeaderView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/nav/IntroView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/nav/NavView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/nav/SearchView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/products/ClosedStoreView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/products/CollectionView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/products/GalleryView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/products/ProductView.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/products/Selector.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/products/filters/CategoryFilter.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/view/Router.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/view/Scrollable.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/view/Serializable.js create mode 100755 StoneIsland/platforms/android/assets/www/js/lib/view/View.js create mode 100755 StoneIsland/platforms/android/assets/www/js/sdk/_sdk.js create mode 100755 StoneIsland/platforms/android/assets/www/js/sdk/account.js create mode 100755 StoneIsland/platforms/android/assets/www/js/sdk/address.js create mode 100755 StoneIsland/platforms/android/assets/www/js/sdk/auth.js create mode 100755 StoneIsland/platforms/android/assets/www/js/sdk/cart.js create mode 100755 StoneIsland/platforms/android/assets/www/js/sdk/payment.js create mode 100755 StoneIsland/platforms/android/assets/www/js/sdk/product.js create mode 100755 StoneIsland/platforms/android/assets/www/js/sdk/shipping.js create mode 100755 StoneIsland/platforms/android/assets/www/js/vendor/fastclick.js create mode 100755 StoneIsland/platforms/android/assets/www/js/vendor/flickity.pkgd.js create mode 100755 StoneIsland/platforms/android/assets/www/js/vendor/iscroll.js create mode 100755 StoneIsland/platforms/android/assets/www/js/vendor/jquery-2.1.4.min.js create mode 100755 StoneIsland/platforms/android/assets/www/js/vendor/jquery.creditCardValidator.js create mode 100755 StoneIsland/platforms/android/assets/www/js/vendor/loader.js create mode 100755 StoneIsland/platforms/android/assets/www/js/vendor/lodash.min.js create mode 100755 StoneIsland/platforms/android/assets/www/js/vendor/moment.js create mode 100755 StoneIsland/platforms/android/assets/www/js/vendor/oktween.js create mode 100755 StoneIsland/platforms/android/assets/www/js/vendor/prefixfree.js create mode 100755 StoneIsland/platforms/android/assets/www/js/vendor/promise.js create mode 100755 StoneIsland/platforms/android/assets/www/js/vendor/util.js create mode 100755 StoneIsland/platforms/android/assets/www/plugins/com.ionic.keyboard/www/keyboard.js create mode 100755 StoneIsland/platforms/android/assets/www/plugins/cordova-plugin-console/www/console-via-logger.js create mode 100755 StoneIsland/platforms/android/assets/www/plugins/cordova-plugin-console/www/logger.js create mode 100755 StoneIsland/platforms/android/assets/www/plugins/cordova-plugin-customurlscheme/www/android/LaunchMyApp.js create mode 100755 StoneIsland/platforms/android/assets/www/plugins/cordova-plugin-device/www/device.js create mode 100755 StoneIsland/platforms/android/assets/www/plugins/cordova-plugin-dialogs/www/android/notification.js create mode 100755 StoneIsland/platforms/android/assets/www/plugins/cordova-plugin-dialogs/www/notification.js create mode 100755 StoneIsland/platforms/android/assets/www/plugins/cordova-plugin-inappbrowser/www/inappbrowser.js create mode 100755 StoneIsland/platforms/android/assets/www/plugins/cordova-plugin-network-information/www/Connection.js create mode 100755 StoneIsland/platforms/android/assets/www/plugins/cordova-plugin-network-information/www/network.js create mode 100755 StoneIsland/platforms/android/assets/www/plugins/cordova-plugin-splashscreen/www/splashscreen.js create mode 100755 StoneIsland/platforms/android/assets/www/plugins/cordova-plugin-whitelist/whitelist.js create mode 100755 StoneIsland/platforms/android/assets/www/plugins/cordova-plugin-x-socialsharing/www/SocialSharing.js create mode 100755 StoneIsland/platforms/android/assets/www/plugins/phonegap-plugin-push/www/push.js (limited to 'StoneIsland/platforms/android/assets') diff --git a/StoneIsland/platforms/android/assets/www/cordova-js-src/android/nativeapiprovider.js b/StoneIsland/platforms/android/assets/www/cordova-js-src/android/nativeapiprovider.js new file mode 100755 index 00000000..2e9aa67b --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/cordova-js-src/android/nativeapiprovider.js @@ -0,0 +1,36 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +*/ + +/** + * Exports the ExposedJsApi.java object if available, otherwise exports the PromptBasedNativeApi. + */ + +var nativeApi = this._cordovaNative || require('cordova/android/promptbasednativeapi'); +var currentApi = nativeApi; + +module.exports = { + get: function() { return currentApi; }, + setPreferPrompt: function(value) { + currentApi = value ? require('cordova/android/promptbasednativeapi') : nativeApi; + }, + // Used only by tests. + set: function(value) { + currentApi = value; + } +}; diff --git a/StoneIsland/platforms/android/assets/www/cordova-js-src/android/promptbasednativeapi.js b/StoneIsland/platforms/android/assets/www/cordova-js-src/android/promptbasednativeapi.js new file mode 100755 index 00000000..f7fb6bc7 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/cordova-js-src/android/promptbasednativeapi.js @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +*/ + +/** + * Implements the API of ExposedJsApi.java, but uses prompt() to communicate. + * This is used pre-JellyBean, where addJavascriptInterface() is disabled. + */ + +module.exports = { + exec: function(bridgeSecret, service, action, callbackId, argsJson) { + return prompt(argsJson, 'gap:'+JSON.stringify([bridgeSecret, service, action, callbackId])); + }, + setNativeToJsBridgeMode: function(bridgeSecret, value) { + prompt(value, 'gap_bridge_mode:' + bridgeSecret); + }, + retrieveJsMessages: function(bridgeSecret, fromOnlineEvent) { + return prompt(+fromOnlineEvent, 'gap_poll:' + bridgeSecret); + } +}; diff --git a/StoneIsland/platforms/android/assets/www/cordova-js-src/exec.js b/StoneIsland/platforms/android/assets/www/cordova-js-src/exec.js new file mode 100755 index 00000000..fa8b41be --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/cordova-js-src/exec.js @@ -0,0 +1,283 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +/** + * Execute a cordova command. It is up to the native side whether this action + * is synchronous or asynchronous. The native side can return: + * Synchronous: PluginResult object as a JSON string + * Asynchronous: Empty string "" + * If async, the native side will cordova.callbackSuccess or cordova.callbackError, + * depending upon the result of the action. + * + * @param {Function} success The success callback + * @param {Function} fail The fail callback + * @param {String} service The name of the service to use + * @param {String} action Action to be run in cordova + * @param {String[]} [args] Zero or more arguments to pass to the method + */ +var cordova = require('cordova'), + nativeApiProvider = require('cordova/android/nativeapiprovider'), + utils = require('cordova/utils'), + base64 = require('cordova/base64'), + channel = require('cordova/channel'), + jsToNativeModes = { + PROMPT: 0, + JS_OBJECT: 1 + }, + nativeToJsModes = { + // Polls for messages using the JS->Native bridge. + POLLING: 0, + // For LOAD_URL to be viable, it would need to have a work-around for + // the bug where the soft-keyboard gets dismissed when a message is sent. + LOAD_URL: 1, + // For the ONLINE_EVENT to be viable, it would need to intercept all event + // listeners (both through addEventListener and window.ononline) as well + // as set the navigator property itself. + ONLINE_EVENT: 2 + }, + jsToNativeBridgeMode, // Set lazily. + nativeToJsBridgeMode = nativeToJsModes.ONLINE_EVENT, + pollEnabled = false, + bridgeSecret = -1; + +var messagesFromNative = []; +var isProcessing = false; +var resolvedPromise = typeof Promise == 'undefined' ? null : Promise.resolve(); +var nextTick = resolvedPromise ? function(fn) { resolvedPromise.then(fn); } : function(fn) { setTimeout(fn); }; + +function androidExec(success, fail, service, action, args) { + if (bridgeSecret < 0) { + // If we ever catch this firing, we'll need to queue up exec()s + // and fire them once we get a secret. For now, I don't think + // it's possible for exec() to be called since plugins are parsed but + // not run until until after onNativeReady. + throw new Error('exec() called without bridgeSecret'); + } + // Set default bridge modes if they have not already been set. + // By default, we use the failsafe, since addJavascriptInterface breaks too often + if (jsToNativeBridgeMode === undefined) { + androidExec.setJsToNativeBridgeMode(jsToNativeModes.JS_OBJECT); + } + + // Process any ArrayBuffers in the args into a string. + for (var i = 0; i < args.length; i++) { + if (utils.typeName(args[i]) == 'ArrayBuffer') { + args[i] = base64.fromArrayBuffer(args[i]); + } + } + + var callbackId = service + cordova.callbackId++, + argsJson = JSON.stringify(args); + + if (success || fail) { + cordova.callbacks[callbackId] = {success:success, fail:fail}; + } + + var msgs = nativeApiProvider.get().exec(bridgeSecret, service, action, callbackId, argsJson); + // If argsJson was received by Java as null, try again with the PROMPT bridge mode. + // This happens in rare circumstances, such as when certain Unicode characters are passed over the bridge on a Galaxy S2. See CB-2666. + if (jsToNativeBridgeMode == jsToNativeModes.JS_OBJECT && msgs === "@Null arguments.") { + androidExec.setJsToNativeBridgeMode(jsToNativeModes.PROMPT); + androidExec(success, fail, service, action, args); + androidExec.setJsToNativeBridgeMode(jsToNativeModes.JS_OBJECT); + } else if (msgs) { + messagesFromNative.push(msgs); + // Always process async to avoid exceptions messing up stack. + nextTick(processMessages); + } +} + +androidExec.init = function() { + bridgeSecret = +prompt('', 'gap_init:' + nativeToJsBridgeMode); + channel.onNativeReady.fire(); +}; + +function pollOnceFromOnlineEvent() { + pollOnce(true); +} + +function pollOnce(opt_fromOnlineEvent) { + if (bridgeSecret < 0) { + // This can happen when the NativeToJsMessageQueue resets the online state on page transitions. + // We know there's nothing to retrieve, so no need to poll. + return; + } + var msgs = nativeApiProvider.get().retrieveJsMessages(bridgeSecret, !!opt_fromOnlineEvent); + if (msgs) { + messagesFromNative.push(msgs); + // Process sync since we know we're already top-of-stack. + processMessages(); + } +} + +function pollingTimerFunc() { + if (pollEnabled) { + pollOnce(); + setTimeout(pollingTimerFunc, 50); + } +} + +function hookOnlineApis() { + function proxyEvent(e) { + cordova.fireWindowEvent(e.type); + } + // The network module takes care of firing online and offline events. + // It currently fires them only on document though, so we bridge them + // to window here (while first listening for exec()-releated online/offline + // events). + window.addEventListener('online', pollOnceFromOnlineEvent, false); + window.addEventListener('offline', pollOnceFromOnlineEvent, false); + cordova.addWindowEventHandler('online'); + cordova.addWindowEventHandler('offline'); + document.addEventListener('online', proxyEvent, false); + document.addEventListener('offline', proxyEvent, false); +} + +hookOnlineApis(); + +androidExec.jsToNativeModes = jsToNativeModes; +androidExec.nativeToJsModes = nativeToJsModes; + +androidExec.setJsToNativeBridgeMode = function(mode) { + if (mode == jsToNativeModes.JS_OBJECT && !window._cordovaNative) { + mode = jsToNativeModes.PROMPT; + } + nativeApiProvider.setPreferPrompt(mode == jsToNativeModes.PROMPT); + jsToNativeBridgeMode = mode; +}; + +androidExec.setNativeToJsBridgeMode = function(mode) { + if (mode == nativeToJsBridgeMode) { + return; + } + if (nativeToJsBridgeMode == nativeToJsModes.POLLING) { + pollEnabled = false; + } + + nativeToJsBridgeMode = mode; + // Tell the native side to switch modes. + // Otherwise, it will be set by androidExec.init() + if (bridgeSecret >= 0) { + nativeApiProvider.get().setNativeToJsBridgeMode(bridgeSecret, mode); + } + + if (mode == nativeToJsModes.POLLING) { + pollEnabled = true; + setTimeout(pollingTimerFunc, 1); + } +}; + +function buildPayload(payload, message) { + var payloadKind = message.charAt(0); + if (payloadKind == 's') { + payload.push(message.slice(1)); + } else if (payloadKind == 't') { + payload.push(true); + } else if (payloadKind == 'f') { + payload.push(false); + } else if (payloadKind == 'N') { + payload.push(null); + } else if (payloadKind == 'n') { + payload.push(+message.slice(1)); + } else if (payloadKind == 'A') { + var data = message.slice(1); + payload.push(base64.toArrayBuffer(data)); + } else if (payloadKind == 'S') { + payload.push(window.atob(message.slice(1))); + } else if (payloadKind == 'M') { + var multipartMessages = message.slice(1); + while (multipartMessages !== "") { + var spaceIdx = multipartMessages.indexOf(' '); + var msgLen = +multipartMessages.slice(0, spaceIdx); + var multipartMessage = multipartMessages.substr(spaceIdx + 1, msgLen); + multipartMessages = multipartMessages.slice(spaceIdx + msgLen + 1); + buildPayload(payload, multipartMessage); + } + } else { + payload.push(JSON.parse(message)); + } +} + +// Processes a single message, as encoded by NativeToJsMessageQueue.java. +function processMessage(message) { + var firstChar = message.charAt(0); + if (firstChar == 'J') { + // This is deprecated on the .java side. It doesn't work with CSP enabled. + eval(message.slice(1)); + } else if (firstChar == 'S' || firstChar == 'F') { + var success = firstChar == 'S'; + var keepCallback = message.charAt(1) == '1'; + var spaceIdx = message.indexOf(' ', 2); + var status = +message.slice(2, spaceIdx); + var nextSpaceIdx = message.indexOf(' ', spaceIdx + 1); + var callbackId = message.slice(spaceIdx + 1, nextSpaceIdx); + var payloadMessage = message.slice(nextSpaceIdx + 1); + var payload = []; + buildPayload(payload, payloadMessage); + cordova.callbackFromNative(callbackId, success, status, payload, keepCallback); + } else { + console.log("processMessage failed: invalid message: " + JSON.stringify(message)); + } +} + +function processMessages() { + // Check for the reentrant case. + if (isProcessing) { + return; + } + if (messagesFromNative.length === 0) { + return; + } + isProcessing = true; + try { + var msg = popMessageFromQueue(); + // The Java side can send a * message to indicate that it + // still has messages waiting to be retrieved. + if (msg == '*' && messagesFromNative.length === 0) { + nextTick(pollOnce); + return; + } + processMessage(msg); + } finally { + isProcessing = false; + if (messagesFromNative.length > 0) { + nextTick(processMessages); + } + } +} + +function popMessageFromQueue() { + var messageBatch = messagesFromNative.shift(); + if (messageBatch == '*') { + return '*'; + } + + var spaceIdx = messageBatch.indexOf(' '); + var msgLen = +messageBatch.slice(0, spaceIdx); + var message = messageBatch.substr(spaceIdx + 1, msgLen); + messageBatch = messageBatch.slice(spaceIdx + msgLen + 1); + if (messageBatch) { + messagesFromNative.unshift(messageBatch); + } + return message; +} + +module.exports = androidExec; diff --git a/StoneIsland/platforms/android/assets/www/cordova-js-src/platform.js b/StoneIsland/platforms/android/assets/www/cordova-js-src/platform.js new file mode 100755 index 00000000..bffc6751 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/cordova-js-src/platform.js @@ -0,0 +1,91 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +module.exports = { + id: 'android', + bootstrap: function() { + var channel = require('cordova/channel'), + cordova = require('cordova'), + exec = require('cordova/exec'), + modulemapper = require('cordova/modulemapper'); + + // Get the shared secret needed to use the bridge. + exec.init(); + + // TODO: Extract this as a proper plugin. + modulemapper.clobbers('cordova/plugin/android/app', 'navigator.app'); + + var APP_PLUGIN_NAME = Number(cordova.platformVersion.split('.')[0]) >= 4 ? 'CoreAndroid' : 'App'; + + // Inject a listener for the backbutton on the document. + var backButtonChannel = cordova.addDocumentEventHandler('backbutton'); + backButtonChannel.onHasSubscribersChange = function() { + // If we just attached the first handler or detached the last handler, + // let native know we need to override the back button. + exec(null, null, APP_PLUGIN_NAME, "overrideBackbutton", [this.numHandlers == 1]); + }; + + // Add hardware MENU and SEARCH button handlers + cordova.addDocumentEventHandler('menubutton'); + cordova.addDocumentEventHandler('searchbutton'); + + function bindButtonChannel(buttonName) { + // generic button bind used for volumeup/volumedown buttons + var volumeButtonChannel = cordova.addDocumentEventHandler(buttonName + 'button'); + volumeButtonChannel.onHasSubscribersChange = function() { + exec(null, null, APP_PLUGIN_NAME, "overrideButton", [buttonName, this.numHandlers == 1]); + }; + } + // Inject a listener for the volume buttons on the document. + bindButtonChannel('volumeup'); + bindButtonChannel('volumedown'); + + // Let native code know we are all done on the JS side. + // Native code will then un-hide the WebView. + channel.onCordovaReady.subscribe(function() { + exec(onMessageFromNative, null, APP_PLUGIN_NAME, 'messageChannel', []); + exec(null, null, APP_PLUGIN_NAME, "show", []); + }); + } +}; + +function onMessageFromNative(msg) { + var cordova = require('cordova'); + var action = msg.action; + + switch (action) + { + // Button events + case 'backbutton': + case 'menubutton': + case 'searchbutton': + // App life cycle events + case 'pause': + case 'resume': + // Volume events + case 'volumedownbutton': + case 'volumeupbutton': + cordova.fireDocumentEvent(action); + break; + default: + throw new Error('Unknown event action ' + action); + } +} diff --git a/StoneIsland/platforms/android/assets/www/cordova-js-src/plugin/android/app.js b/StoneIsland/platforms/android/assets/www/cordova-js-src/plugin/android/app.js new file mode 100755 index 00000000..22cf96e8 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/cordova-js-src/plugin/android/app.js @@ -0,0 +1,108 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * +*/ + +var exec = require('cordova/exec'); +var APP_PLUGIN_NAME = Number(require('cordova').platformVersion.split('.')[0]) >= 4 ? 'CoreAndroid' : 'App'; + +module.exports = { + /** + * Clear the resource cache. + */ + clearCache:function() { + exec(null, null, APP_PLUGIN_NAME, "clearCache", []); + }, + + /** + * Load the url into the webview or into new browser instance. + * + * @param url The URL to load + * @param props Properties that can be passed in to the activity: + * wait: int => wait msec before loading URL + * loadingDialog: "Title,Message" => display a native loading dialog + * loadUrlTimeoutValue: int => time in msec to wait before triggering a timeout error + * clearHistory: boolean => clear webview history (default=false) + * openExternal: boolean => open in a new browser (default=false) + * + * Example: + * navigator.app.loadUrl("http://server/myapp/index.html", {wait:2000, loadingDialog:"Wait,Loading App", loadUrlTimeoutValue: 60000}); + */ + loadUrl:function(url, props) { + exec(null, null, APP_PLUGIN_NAME, "loadUrl", [url, props]); + }, + + /** + * Cancel loadUrl that is waiting to be loaded. + */ + cancelLoadUrl:function() { + exec(null, null, APP_PLUGIN_NAME, "cancelLoadUrl", []); + }, + + /** + * Clear web history in this web view. + * Instead of BACK button loading the previous web page, it will exit the app. + */ + clearHistory:function() { + exec(null, null, APP_PLUGIN_NAME, "clearHistory", []); + }, + + /** + * Go to previous page displayed. + * This is the same as pressing the backbutton on Android device. + */ + backHistory:function() { + exec(null, null, APP_PLUGIN_NAME, "backHistory", []); + }, + + /** + * Override the default behavior of the Android back button. + * If overridden, when the back button is pressed, the "backKeyDown" JavaScript event will be fired. + * + * Note: The user should not have to call this method. Instead, when the user + * registers for the "backbutton" event, this is automatically done. + * + * @param override T=override, F=cancel override + */ + overrideBackbutton:function(override) { + exec(null, null, APP_PLUGIN_NAME, "overrideBackbutton", [override]); + }, + + /** + * Override the default behavior of the Android volume button. + * If overridden, when the volume button is pressed, the "volume[up|down]button" + * JavaScript event will be fired. + * + * Note: The user should not have to call this method. Instead, when the user + * registers for the "volume[up|down]button" event, this is automatically done. + * + * @param button volumeup, volumedown + * @param override T=override, F=cancel override + */ + overrideButton:function(button, override) { + exec(null, null, APP_PLUGIN_NAME, "overrideButton", [button, override]); + }, + + /** + * Exit and terminate the application. + */ + exitApp:function() { + return exec(null, null, APP_PLUGIN_NAME, "exitApp", []); + } +}; diff --git a/StoneIsland/platforms/android/assets/www/cordova.js b/StoneIsland/platforms/android/assets/www/cordova.js new file mode 100755 index 00000000..23f6e475 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/cordova.js @@ -0,0 +1,1979 @@ +// Platform: android +// 2c29e187e4206a6a77fba940ef6f77aef5c7eb8c +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, + software distributed under the License is distributed on an + "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, either express or implied. See the License for the + specific language governing permissions and limitations + under the License. +*/ +;(function() { +var PLATFORM_VERSION_BUILD_LABEL = '4.1.1'; +// file: src/scripts/require.js + +/*jshint -W079 */ +/*jshint -W020 */ + +var require, + define; + +(function () { + var modules = {}, + // Stack of moduleIds currently being built. + requireStack = [], + // Map of module ID -> index into requireStack of modules currently being built. + inProgressModules = {}, + SEPARATOR = "."; + + + + function build(module) { + var factory = module.factory, + localRequire = function (id) { + var resultantId = id; + //Its a relative path, so lop off the last portion and add the id (minus "./") + if (id.charAt(0) === ".") { + resultantId = module.id.slice(0, module.id.lastIndexOf(SEPARATOR)) + SEPARATOR + id.slice(2); + } + return require(resultantId); + }; + module.exports = {}; + delete module.factory; + factory(localRequire, module.exports, module); + return module.exports; + } + + require = function (id) { + if (!modules[id]) { + throw "module " + id + " not found"; + } else if (id in inProgressModules) { + var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id; + throw "Cycle in require graph: " + cycle; + } + if (modules[id].factory) { + try { + inProgressModules[id] = requireStack.length; + requireStack.push(id); + return build(modules[id]); + } finally { + delete inProgressModules[id]; + requireStack.pop(); + } + } + return modules[id].exports; + }; + + define = function (id, factory) { + if (modules[id]) { + throw "module " + id + " already defined"; + } + + modules[id] = { + id: id, + factory: factory + }; + }; + + define.remove = function (id) { + delete modules[id]; + }; + + define.moduleMap = modules; +})(); + +//Export for use in node +if (typeof module === "object" && typeof require === "function") { + module.exports.require = require; + module.exports.define = define; +} + +// file: src/cordova.js +define("cordova", function(require, exports, module) { + +if(window.cordova){ + throw new Error("cordova already defined"); +} + + +var channel = require('cordova/channel'); +var platform = require('cordova/platform'); + + +/** + * Intercept calls to addEventListener + removeEventListener and handle deviceready, + * resume, and pause events. + */ +var m_document_addEventListener = document.addEventListener; +var m_document_removeEventListener = document.removeEventListener; +var m_window_addEventListener = window.addEventListener; +var m_window_removeEventListener = window.removeEventListener; + +/** + * Houses custom event handlers to intercept on document + window event listeners. + */ +var documentEventHandlers = {}, + windowEventHandlers = {}; + +document.addEventListener = function(evt, handler, capture) { + var e = evt.toLowerCase(); + if (typeof documentEventHandlers[e] != 'undefined') { + documentEventHandlers[e].subscribe(handler); + } else { + m_document_addEventListener.call(document, evt, handler, capture); + } +}; + +window.addEventListener = function(evt, handler, capture) { + var e = evt.toLowerCase(); + if (typeof windowEventHandlers[e] != 'undefined') { + windowEventHandlers[e].subscribe(handler); + } else { + m_window_addEventListener.call(window, evt, handler, capture); + } +}; + +document.removeEventListener = function(evt, handler, capture) { + var e = evt.toLowerCase(); + // If unsubscribing from an event that is handled by a plugin + if (typeof documentEventHandlers[e] != "undefined") { + documentEventHandlers[e].unsubscribe(handler); + } else { + m_document_removeEventListener.call(document, evt, handler, capture); + } +}; + +window.removeEventListener = function(evt, handler, capture) { + var e = evt.toLowerCase(); + // If unsubscribing from an event that is handled by a plugin + if (typeof windowEventHandlers[e] != "undefined") { + windowEventHandlers[e].unsubscribe(handler); + } else { + m_window_removeEventListener.call(window, evt, handler, capture); + } +}; + +function createEvent(type, data) { + var event = document.createEvent('Events'); + event.initEvent(type, false, false); + if (data) { + for (var i in data) { + if (data.hasOwnProperty(i)) { + event[i] = data[i]; + } + } + } + return event; +} + + +var cordova = { + define:define, + require:require, + version:PLATFORM_VERSION_BUILD_LABEL, + platformVersion:PLATFORM_VERSION_BUILD_LABEL, + platformId:platform.id, + /** + * Methods to add/remove your own addEventListener hijacking on document + window. + */ + addWindowEventHandler:function(event) { + return (windowEventHandlers[event] = channel.create(event)); + }, + addStickyDocumentEventHandler:function(event) { + return (documentEventHandlers[event] = channel.createSticky(event)); + }, + addDocumentEventHandler:function(event) { + return (documentEventHandlers[event] = channel.create(event)); + }, + removeWindowEventHandler:function(event) { + delete windowEventHandlers[event]; + }, + removeDocumentEventHandler:function(event) { + delete documentEventHandlers[event]; + }, + /** + * Retrieve original event handlers that were replaced by Cordova + * + * @return object + */ + getOriginalHandlers: function() { + return {'document': {'addEventListener': m_document_addEventListener, 'removeEventListener': m_document_removeEventListener}, + 'window': {'addEventListener': m_window_addEventListener, 'removeEventListener': m_window_removeEventListener}}; + }, + /** + * Method to fire event from native code + * bNoDetach is required for events which cause an exception which needs to be caught in native code + */ + fireDocumentEvent: function(type, data, bNoDetach) { + var evt = createEvent(type, data); + if (typeof documentEventHandlers[type] != 'undefined') { + if( bNoDetach ) { + documentEventHandlers[type].fire(evt); + } + else { + setTimeout(function() { + // Fire deviceready on listeners that were registered before cordova.js was loaded. + if (type == 'deviceready') { + document.dispatchEvent(evt); + } + documentEventHandlers[type].fire(evt); + }, 0); + } + } else { + document.dispatchEvent(evt); + } + }, + fireWindowEvent: function(type, data) { + var evt = createEvent(type,data); + if (typeof windowEventHandlers[type] != 'undefined') { + setTimeout(function() { + windowEventHandlers[type].fire(evt); + }, 0); + } else { + window.dispatchEvent(evt); + } + }, + + /** + * Plugin callback mechanism. + */ + // Randomize the starting callbackId to avoid collisions after refreshing or navigating. + // This way, it's very unlikely that any new callback would get the same callbackId as an old callback. + callbackId: Math.floor(Math.random() * 2000000000), + callbacks: {}, + callbackStatus: { + NO_RESULT: 0, + OK: 1, + CLASS_NOT_FOUND_EXCEPTION: 2, + ILLEGAL_ACCESS_EXCEPTION: 3, + INSTANTIATION_EXCEPTION: 4, + MALFORMED_URL_EXCEPTION: 5, + IO_EXCEPTION: 6, + INVALID_ACTION: 7, + JSON_EXCEPTION: 8, + ERROR: 9 + }, + + /** + * Called by native code when returning successful result from an action. + */ + callbackSuccess: function(callbackId, args) { + cordova.callbackFromNative(callbackId, true, args.status, [args.message], args.keepCallback); + }, + + /** + * Called by native code when returning error result from an action. + */ + callbackError: function(callbackId, args) { + // TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative. + // Derive success from status. + cordova.callbackFromNative(callbackId, false, args.status, [args.message], args.keepCallback); + }, + + /** + * Called by native code when returning the result from an action. + */ + callbackFromNative: function(callbackId, isSuccess, status, args, keepCallback) { + try { + var callback = cordova.callbacks[callbackId]; + if (callback) { + if (isSuccess && status == cordova.callbackStatus.OK) { + callback.success && callback.success.apply(null, args); + } else if (!isSuccess) { + callback.fail && callback.fail.apply(null, args); + } + /* + else + Note, this case is intentionally not caught. + this can happen if isSuccess is true, but callbackStatus is NO_RESULT + which is used to remove a callback from the list without calling the callbacks + typically keepCallback is false in this case + */ + // Clear callback if not expecting any more results + if (!keepCallback) { + delete cordova.callbacks[callbackId]; + } + } + } + catch (err) { + var msg = "Error in " + (isSuccess ? "Success" : "Error") + " callbackId: " + callbackId + " : " + err; + console && console.log && console.log(msg); + cordova.fireWindowEvent("cordovacallbackerror", { 'message': msg }); + throw err; + } + }, + addConstructor: function(func) { + channel.onCordovaReady.subscribe(function() { + try { + func(); + } catch(e) { + console.log("Failed to run constructor: " + e); + } + }); + } +}; + + +module.exports = cordova; + +}); + +// file: /Users/steveng/repo/cordova/cordova-android/cordova-js-src/android/nativeapiprovider.js +define("cordova/android/nativeapiprovider", function(require, exports, module) { + +/** + * Exports the ExposedJsApi.java object if available, otherwise exports the PromptBasedNativeApi. + */ + +var nativeApi = this._cordovaNative || require('cordova/android/promptbasednativeapi'); +var currentApi = nativeApi; + +module.exports = { + get: function() { return currentApi; }, + setPreferPrompt: function(value) { + currentApi = value ? require('cordova/android/promptbasednativeapi') : nativeApi; + }, + // Used only by tests. + set: function(value) { + currentApi = value; + } +}; + +}); + +// file: /Users/steveng/repo/cordova/cordova-android/cordova-js-src/android/promptbasednativeapi.js +define("cordova/android/promptbasednativeapi", function(require, exports, module) { + +/** + * Implements the API of ExposedJsApi.java, but uses prompt() to communicate. + * This is used pre-JellyBean, where addJavascriptInterface() is disabled. + */ + +module.exports = { + exec: function(bridgeSecret, service, action, callbackId, argsJson) { + return prompt(argsJson, 'gap:'+JSON.stringify([bridgeSecret, service, action, callbackId])); + }, + setNativeToJsBridgeMode: function(bridgeSecret, value) { + prompt(value, 'gap_bridge_mode:' + bridgeSecret); + }, + retrieveJsMessages: function(bridgeSecret, fromOnlineEvent) { + return prompt(+fromOnlineEvent, 'gap_poll:' + bridgeSecret); + } +}; + +}); + +// file: src/common/argscheck.js +define("cordova/argscheck", function(require, exports, module) { + +var utils = require('cordova/utils'); + +var moduleExports = module.exports; + +var typeMap = { + 'A': 'Array', + 'D': 'Date', + 'N': 'Number', + 'S': 'String', + 'F': 'Function', + 'O': 'Object' +}; + +function extractParamName(callee, argIndex) { + return (/.*?\((.*?)\)/).exec(callee)[1].split(', ')[argIndex]; +} + +function checkArgs(spec, functionName, args, opt_callee) { + if (!moduleExports.enableChecks) { + return; + } + var errMsg = null; + var typeName; + for (var i = 0; i < spec.length; ++i) { + var c = spec.charAt(i), + cUpper = c.toUpperCase(), + arg = args[i]; + // Asterix means allow anything. + if (c == '*') { + continue; + } + typeName = utils.typeName(arg); + if ((arg === null || arg === undefined) && c == cUpper) { + continue; + } + if (typeName != typeMap[cUpper]) { + errMsg = 'Expected ' + typeMap[cUpper]; + break; + } + } + if (errMsg) { + errMsg += ', but got ' + typeName + '.'; + errMsg = 'Wrong type for parameter "' + extractParamName(opt_callee || args.callee, i) + '" of ' + functionName + ': ' + errMsg; + // Don't log when running unit tests. + if (typeof jasmine == 'undefined') { + console.error(errMsg); + } + throw TypeError(errMsg); + } +} + +function getValue(value, defaultValue) { + return value === undefined ? defaultValue : value; +} + +moduleExports.checkArgs = checkArgs; +moduleExports.getValue = getValue; +moduleExports.enableChecks = true; + + +}); + +// file: src/common/base64.js +define("cordova/base64", function(require, exports, module) { + +var base64 = exports; + +base64.fromArrayBuffer = function(arrayBuffer) { + var array = new Uint8Array(arrayBuffer); + return uint8ToBase64(array); +}; + +base64.toArrayBuffer = function(str) { + var decodedStr = typeof atob != 'undefined' ? atob(str) : new Buffer(str,'base64').toString('binary'); + var arrayBuffer = new ArrayBuffer(decodedStr.length); + var array = new Uint8Array(arrayBuffer); + for (var i=0, len=decodedStr.length; i < len; i++) { + array[i] = decodedStr.charCodeAt(i); + } + return arrayBuffer; +}; + +//------------------------------------------------------------------------------ + +/* This code is based on the performance tests at http://jsperf.com/b64tests + * This 12-bit-at-a-time algorithm was the best performing version on all + * platforms tested. + */ + +var b64_6bit = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var b64_12bit; + +var b64_12bitTable = function() { + b64_12bit = []; + for (var i=0; i<64; i++) { + for (var j=0; j<64; j++) { + b64_12bit[i*64+j] = b64_6bit[i] + b64_6bit[j]; + } + } + b64_12bitTable = function() { return b64_12bit; }; + return b64_12bit; +}; + +function uint8ToBase64(rawData) { + var numBytes = rawData.byteLength; + var output=""; + var segment; + var table = b64_12bitTable(); + for (var i=0;i> 12]; + output += table[segment & 0xfff]; + } + if (numBytes - i == 2) { + segment = (rawData[i] << 16) + (rawData[i+1] << 8); + output += table[segment >> 12]; + output += b64_6bit[(segment & 0xfff) >> 6]; + output += '='; + } else if (numBytes - i == 1) { + segment = (rawData[i] << 16); + output += table[segment >> 12]; + output += '=='; + } + return output; +} + +}); + +// file: src/common/builder.js +define("cordova/builder", function(require, exports, module) { + +var utils = require('cordova/utils'); + +function each(objects, func, context) { + for (var prop in objects) { + if (objects.hasOwnProperty(prop)) { + func.apply(context, [objects[prop], prop]); + } + } +} + +function clobber(obj, key, value) { + exports.replaceHookForTesting(obj, key); + var needsProperty = false; + try { + obj[key] = value; + } catch (e) { + needsProperty = true; + } + // Getters can only be overridden by getters. + if (needsProperty || obj[key] !== value) { + utils.defineGetter(obj, key, function() { + return value; + }); + } +} + +function assignOrWrapInDeprecateGetter(obj, key, value, message) { + if (message) { + utils.defineGetter(obj, key, function() { + console.log(message); + delete obj[key]; + clobber(obj, key, value); + return value; + }); + } else { + clobber(obj, key, value); + } +} + +function include(parent, objects, clobber, merge) { + each(objects, function (obj, key) { + try { + var result = obj.path ? require(obj.path) : {}; + + if (clobber) { + // Clobber if it doesn't exist. + if (typeof parent[key] === 'undefined') { + assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated); + } else if (typeof obj.path !== 'undefined') { + // If merging, merge properties onto parent, otherwise, clobber. + if (merge) { + recursiveMerge(parent[key], result); + } else { + assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated); + } + } + result = parent[key]; + } else { + // Overwrite if not currently defined. + if (typeof parent[key] == 'undefined') { + assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated); + } else { + // Set result to what already exists, so we can build children into it if they exist. + result = parent[key]; + } + } + + if (obj.children) { + include(result, obj.children, clobber, merge); + } + } catch(e) { + utils.alert('Exception building Cordova JS globals: ' + e + ' for key "' + key + '"'); + } + }); +} + +/** + * Merge properties from one object onto another recursively. Properties from + * the src object will overwrite existing target property. + * + * @param target Object to merge properties into. + * @param src Object to merge properties from. + */ +function recursiveMerge(target, src) { + for (var prop in src) { + if (src.hasOwnProperty(prop)) { + if (target.prototype && target.prototype.constructor === target) { + // If the target object is a constructor override off prototype. + clobber(target.prototype, prop, src[prop]); + } else { + if (typeof src[prop] === 'object' && typeof target[prop] === 'object') { + recursiveMerge(target[prop], src[prop]); + } else { + clobber(target, prop, src[prop]); + } + } + } + } +} + +exports.buildIntoButDoNotClobber = function(objects, target) { + include(target, objects, false, false); +}; +exports.buildIntoAndClobber = function(objects, target) { + include(target, objects, true, false); +}; +exports.buildIntoAndMerge = function(objects, target) { + include(target, objects, true, true); +}; +exports.recursiveMerge = recursiveMerge; +exports.assignOrWrapInDeprecateGetter = assignOrWrapInDeprecateGetter; +exports.replaceHookForTesting = function() {}; + +}); + +// file: src/common/channel.js +define("cordova/channel", function(require, exports, module) { + +var utils = require('cordova/utils'), + nextGuid = 1; + +/** + * Custom pub-sub "channel" that can have functions subscribed to it + * This object is used to define and control firing of events for + * cordova initialization, as well as for custom events thereafter. + * + * The order of events during page load and Cordova startup is as follows: + * + * onDOMContentLoaded* Internal event that is received when the web page is loaded and parsed. + * onNativeReady* Internal event that indicates the Cordova native side is ready. + * onCordovaReady* Internal event fired when all Cordova JavaScript objects have been created. + * onDeviceReady* User event fired to indicate that Cordova is ready + * onResume User event fired to indicate a start/resume lifecycle event + * onPause User event fired to indicate a pause lifecycle event + * + * The events marked with an * are sticky. Once they have fired, they will stay in the fired state. + * All listeners that subscribe after the event is fired will be executed right away. + * + * The only Cordova events that user code should register for are: + * deviceready Cordova native code is initialized and Cordova APIs can be called from JavaScript + * pause App has moved to background + * resume App has returned to foreground + * + * Listeners can be registered as: + * document.addEventListener("deviceready", myDeviceReadyListener, false); + * document.addEventListener("resume", myResumeListener, false); + * document.addEventListener("pause", myPauseListener, false); + * + * The DOM lifecycle events should be used for saving and restoring state + * window.onload + * window.onunload + * + */ + +/** + * Channel + * @constructor + * @param type String the channel name + */ +var Channel = function(type, sticky) { + this.type = type; + // Map of guid -> function. + this.handlers = {}; + // 0 = Non-sticky, 1 = Sticky non-fired, 2 = Sticky fired. + this.state = sticky ? 1 : 0; + // Used in sticky mode to remember args passed to fire(). + this.fireArgs = null; + // Used by onHasSubscribersChange to know if there are any listeners. + this.numHandlers = 0; + // Function that is called when the first listener is subscribed, or when + // the last listener is unsubscribed. + this.onHasSubscribersChange = null; +}, + channel = { + /** + * Calls the provided function only after all of the channels specified + * have been fired. All channels must be sticky channels. + */ + join: function(h, c) { + var len = c.length, + i = len, + f = function() { + if (!(--i)) h(); + }; + for (var j=0; jNative bridge. + POLLING: 0, + // For LOAD_URL to be viable, it would need to have a work-around for + // the bug where the soft-keyboard gets dismissed when a message is sent. + LOAD_URL: 1, + // For the ONLINE_EVENT to be viable, it would need to intercept all event + // listeners (both through addEventListener and window.ononline) as well + // as set the navigator property itself. + ONLINE_EVENT: 2 + }, + jsToNativeBridgeMode, // Set lazily. + nativeToJsBridgeMode = nativeToJsModes.ONLINE_EVENT, + pollEnabled = false, + bridgeSecret = -1; + +var messagesFromNative = []; +var isProcessing = false; +var resolvedPromise = typeof Promise == 'undefined' ? null : Promise.resolve(); +var nextTick = resolvedPromise ? function(fn) { resolvedPromise.then(fn); } : function(fn) { setTimeout(fn); }; + +function androidExec(success, fail, service, action, args) { + if (bridgeSecret < 0) { + // If we ever catch this firing, we'll need to queue up exec()s + // and fire them once we get a secret. For now, I don't think + // it's possible for exec() to be called since plugins are parsed but + // not run until until after onNativeReady. + throw new Error('exec() called without bridgeSecret'); + } + // Set default bridge modes if they have not already been set. + // By default, we use the failsafe, since addJavascriptInterface breaks too often + if (jsToNativeBridgeMode === undefined) { + androidExec.setJsToNativeBridgeMode(jsToNativeModes.JS_OBJECT); + } + + // Process any ArrayBuffers in the args into a string. + for (var i = 0; i < args.length; i++) { + if (utils.typeName(args[i]) == 'ArrayBuffer') { + args[i] = base64.fromArrayBuffer(args[i]); + } + } + + var callbackId = service + cordova.callbackId++, + argsJson = JSON.stringify(args); + + if (success || fail) { + cordova.callbacks[callbackId] = {success:success, fail:fail}; + } + + var msgs = nativeApiProvider.get().exec(bridgeSecret, service, action, callbackId, argsJson); + // If argsJson was received by Java as null, try again with the PROMPT bridge mode. + // This happens in rare circumstances, such as when certain Unicode characters are passed over the bridge on a Galaxy S2. See CB-2666. + if (jsToNativeBridgeMode == jsToNativeModes.JS_OBJECT && msgs === "@Null arguments.") { + androidExec.setJsToNativeBridgeMode(jsToNativeModes.PROMPT); + androidExec(success, fail, service, action, args); + androidExec.setJsToNativeBridgeMode(jsToNativeModes.JS_OBJECT); + } else if (msgs) { + messagesFromNative.push(msgs); + // Always process async to avoid exceptions messing up stack. + nextTick(processMessages); + } +} + +androidExec.init = function() { + bridgeSecret = +prompt('', 'gap_init:' + nativeToJsBridgeMode); + channel.onNativeReady.fire(); +}; + +function pollOnceFromOnlineEvent() { + pollOnce(true); +} + +function pollOnce(opt_fromOnlineEvent) { + if (bridgeSecret < 0) { + // This can happen when the NativeToJsMessageQueue resets the online state on page transitions. + // We know there's nothing to retrieve, so no need to poll. + return; + } + var msgs = nativeApiProvider.get().retrieveJsMessages(bridgeSecret, !!opt_fromOnlineEvent); + if (msgs) { + messagesFromNative.push(msgs); + // Process sync since we know we're already top-of-stack. + processMessages(); + } +} + +function pollingTimerFunc() { + if (pollEnabled) { + pollOnce(); + setTimeout(pollingTimerFunc, 50); + } +} + +function hookOnlineApis() { + function proxyEvent(e) { + cordova.fireWindowEvent(e.type); + } + // The network module takes care of firing online and offline events. + // It currently fires them only on document though, so we bridge them + // to window here (while first listening for exec()-releated online/offline + // events). + window.addEventListener('online', pollOnceFromOnlineEvent, false); + window.addEventListener('offline', pollOnceFromOnlineEvent, false); + cordova.addWindowEventHandler('online'); + cordova.addWindowEventHandler('offline'); + document.addEventListener('online', proxyEvent, false); + document.addEventListener('offline', proxyEvent, false); +} + +hookOnlineApis(); + +androidExec.jsToNativeModes = jsToNativeModes; +androidExec.nativeToJsModes = nativeToJsModes; + +androidExec.setJsToNativeBridgeMode = function(mode) { + if (mode == jsToNativeModes.JS_OBJECT && !window._cordovaNative) { + mode = jsToNativeModes.PROMPT; + } + nativeApiProvider.setPreferPrompt(mode == jsToNativeModes.PROMPT); + jsToNativeBridgeMode = mode; +}; + +androidExec.setNativeToJsBridgeMode = function(mode) { + if (mode == nativeToJsBridgeMode) { + return; + } + if (nativeToJsBridgeMode == nativeToJsModes.POLLING) { + pollEnabled = false; + } + + nativeToJsBridgeMode = mode; + // Tell the native side to switch modes. + // Otherwise, it will be set by androidExec.init() + if (bridgeSecret >= 0) { + nativeApiProvider.get().setNativeToJsBridgeMode(bridgeSecret, mode); + } + + if (mode == nativeToJsModes.POLLING) { + pollEnabled = true; + setTimeout(pollingTimerFunc, 1); + } +}; + +function buildPayload(payload, message) { + var payloadKind = message.charAt(0); + if (payloadKind == 's') { + payload.push(message.slice(1)); + } else if (payloadKind == 't') { + payload.push(true); + } else if (payloadKind == 'f') { + payload.push(false); + } else if (payloadKind == 'N') { + payload.push(null); + } else if (payloadKind == 'n') { + payload.push(+message.slice(1)); + } else if (payloadKind == 'A') { + var data = message.slice(1); + payload.push(base64.toArrayBuffer(data)); + } else if (payloadKind == 'S') { + payload.push(window.atob(message.slice(1))); + } else if (payloadKind == 'M') { + var multipartMessages = message.slice(1); + while (multipartMessages !== "") { + var spaceIdx = multipartMessages.indexOf(' '); + var msgLen = +multipartMessages.slice(0, spaceIdx); + var multipartMessage = multipartMessages.substr(spaceIdx + 1, msgLen); + multipartMessages = multipartMessages.slice(spaceIdx + msgLen + 1); + buildPayload(payload, multipartMessage); + } + } else { + payload.push(JSON.parse(message)); + } +} + +// Processes a single message, as encoded by NativeToJsMessageQueue.java. +function processMessage(message) { + var firstChar = message.charAt(0); + if (firstChar == 'J') { + // This is deprecated on the .java side. It doesn't work with CSP enabled. + eval(message.slice(1)); + } else if (firstChar == 'S' || firstChar == 'F') { + var success = firstChar == 'S'; + var keepCallback = message.charAt(1) == '1'; + var spaceIdx = message.indexOf(' ', 2); + var status = +message.slice(2, spaceIdx); + var nextSpaceIdx = message.indexOf(' ', spaceIdx + 1); + var callbackId = message.slice(spaceIdx + 1, nextSpaceIdx); + var payloadMessage = message.slice(nextSpaceIdx + 1); + var payload = []; + buildPayload(payload, payloadMessage); + cordova.callbackFromNative(callbackId, success, status, payload, keepCallback); + } else { + console.log("processMessage failed: invalid message: " + JSON.stringify(message)); + } +} + +function processMessages() { + // Check for the reentrant case. + if (isProcessing) { + return; + } + if (messagesFromNative.length === 0) { + return; + } + isProcessing = true; + try { + var msg = popMessageFromQueue(); + // The Java side can send a * message to indicate that it + // still has messages waiting to be retrieved. + if (msg == '*' && messagesFromNative.length === 0) { + nextTick(pollOnce); + return; + } + processMessage(msg); + } finally { + isProcessing = false; + if (messagesFromNative.length > 0) { + nextTick(processMessages); + } + } +} + +function popMessageFromQueue() { + var messageBatch = messagesFromNative.shift(); + if (messageBatch == '*') { + return '*'; + } + + var spaceIdx = messageBatch.indexOf(' '); + var msgLen = +messageBatch.slice(0, spaceIdx); + var message = messageBatch.substr(spaceIdx + 1, msgLen); + messageBatch = messageBatch.slice(spaceIdx + msgLen + 1); + if (messageBatch) { + messagesFromNative.unshift(messageBatch); + } + return message; +} + +module.exports = androidExec; + +}); + +// file: src/common/exec/proxy.js +define("cordova/exec/proxy", function(require, exports, module) { + + +// internal map of proxy function +var CommandProxyMap = {}; + +module.exports = { + + // example: cordova.commandProxy.add("Accelerometer",{getCurrentAcceleration: function(successCallback, errorCallback, options) {...},...); + add:function(id,proxyObj) { + console.log("adding proxy for " + id); + CommandProxyMap[id] = proxyObj; + return proxyObj; + }, + + // cordova.commandProxy.remove("Accelerometer"); + remove:function(id) { + var proxy = CommandProxyMap[id]; + delete CommandProxyMap[id]; + CommandProxyMap[id] = null; + return proxy; + }, + + get:function(service,action) { + return ( CommandProxyMap[service] ? CommandProxyMap[service][action] : null ); + } +}; +}); + +// file: src/common/init.js +define("cordova/init", function(require, exports, module) { + +var channel = require('cordova/channel'); +var cordova = require('cordova'); +var modulemapper = require('cordova/modulemapper'); +var platform = require('cordova/platform'); +var pluginloader = require('cordova/pluginloader'); +var utils = require('cordova/utils'); + +var platformInitChannelsArray = [channel.onNativeReady, channel.onPluginsReady]; + +function logUnfiredChannels(arr) { + for (var i = 0; i < arr.length; ++i) { + if (arr[i].state != 2) { + console.log('Channel not fired: ' + arr[i].type); + } + } +} + +window.setTimeout(function() { + if (channel.onDeviceReady.state != 2) { + console.log('deviceready has not fired after 5 seconds.'); + logUnfiredChannels(platformInitChannelsArray); + logUnfiredChannels(channel.deviceReadyChannelsArray); + } +}, 5000); + +// Replace navigator before any modules are required(), to ensure it happens as soon as possible. +// We replace it so that properties that can't be clobbered can instead be overridden. +function replaceNavigator(origNavigator) { + var CordovaNavigator = function() {}; + CordovaNavigator.prototype = origNavigator; + var newNavigator = new CordovaNavigator(); + // This work-around really only applies to new APIs that are newer than Function.bind. + // Without it, APIs such as getGamepads() break. + if (CordovaNavigator.bind) { + for (var key in origNavigator) { + if (typeof origNavigator[key] == 'function') { + newNavigator[key] = origNavigator[key].bind(origNavigator); + } + else { + (function(k) { + utils.defineGetterSetter(newNavigator,key,function() { + return origNavigator[k]; + }); + })(key); + } + } + } + return newNavigator; +} + +if (window.navigator) { + window.navigator = replaceNavigator(window.navigator); +} + +if (!window.console) { + window.console = { + log: function(){} + }; +} +if (!window.console.warn) { + window.console.warn = function(msg) { + this.log("warn: " + msg); + }; +} + +// Register pause, resume and deviceready channels as events on document. +channel.onPause = cordova.addDocumentEventHandler('pause'); +channel.onResume = cordova.addDocumentEventHandler('resume'); +channel.onActivated = cordova.addDocumentEventHandler('activated'); +channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready'); + +// Listen for DOMContentLoaded and notify our channel subscribers. +if (document.readyState == 'complete' || document.readyState == 'interactive') { + channel.onDOMContentLoaded.fire(); +} else { + document.addEventListener('DOMContentLoaded', function() { + channel.onDOMContentLoaded.fire(); + }, false); +} + +// _nativeReady is global variable that the native side can set +// to signify that the native code is ready. It is a global since +// it may be called before any cordova JS is ready. +if (window._nativeReady) { + channel.onNativeReady.fire(); +} + +modulemapper.clobbers('cordova', 'cordova'); +modulemapper.clobbers('cordova/exec', 'cordova.exec'); +modulemapper.clobbers('cordova/exec', 'Cordova.exec'); + +// Call the platform-specific initialization. +platform.bootstrap && platform.bootstrap(); + +// Wrap in a setTimeout to support the use-case of having plugin JS appended to cordova.js. +// The delay allows the attached modules to be defined before the plugin loader looks for them. +setTimeout(function() { + pluginloader.load(function() { + channel.onPluginsReady.fire(); + }); +}, 0); + +/** + * Create all cordova objects once native side is ready. + */ +channel.join(function() { + modulemapper.mapModules(window); + + platform.initialize && platform.initialize(); + + // Fire event to notify that all objects are created + channel.onCordovaReady.fire(); + + // Fire onDeviceReady event once page has fully loaded, all + // constructors have run and cordova info has been received from native + // side. + channel.join(function() { + require('cordova').fireDocumentEvent('deviceready'); + }, channel.deviceReadyChannelsArray); + +}, platformInitChannelsArray); + + +}); + +// file: src/common/init_b.js +define("cordova/init_b", function(require, exports, module) { + +var channel = require('cordova/channel'); +var cordova = require('cordova'); +var platform = require('cordova/platform'); +var utils = require('cordova/utils'); + +var platformInitChannelsArray = [channel.onDOMContentLoaded, channel.onNativeReady]; + +// setting exec +cordova.exec = require('cordova/exec'); + +function logUnfiredChannels(arr) { + for (var i = 0; i < arr.length; ++i) { + if (arr[i].state != 2) { + console.log('Channel not fired: ' + arr[i].type); + } + } +} + +window.setTimeout(function() { + if (channel.onDeviceReady.state != 2) { + console.log('deviceready has not fired after 5 seconds.'); + logUnfiredChannels(platformInitChannelsArray); + logUnfiredChannels(channel.deviceReadyChannelsArray); + } +}, 5000); + +// Replace navigator before any modules are required(), to ensure it happens as soon as possible. +// We replace it so that properties that can't be clobbered can instead be overridden. +function replaceNavigator(origNavigator) { + var CordovaNavigator = function() {}; + CordovaNavigator.prototype = origNavigator; + var newNavigator = new CordovaNavigator(); + // This work-around really only applies to new APIs that are newer than Function.bind. + // Without it, APIs such as getGamepads() break. + if (CordovaNavigator.bind) { + for (var key in origNavigator) { + if (typeof origNavigator[key] == 'function') { + newNavigator[key] = origNavigator[key].bind(origNavigator); + } + else { + (function(k) { + utils.defineGetterSetter(newNavigator,key,function() { + return origNavigator[k]; + }); + })(key); + } + } + } + return newNavigator; +} +if (window.navigator) { + window.navigator = replaceNavigator(window.navigator); +} + +if (!window.console) { + window.console = { + log: function(){} + }; +} +if (!window.console.warn) { + window.console.warn = function(msg) { + this.log("warn: " + msg); + }; +} + +// Register pause, resume and deviceready channels as events on document. +channel.onPause = cordova.addDocumentEventHandler('pause'); +channel.onResume = cordova.addDocumentEventHandler('resume'); +channel.onActivated = cordova.addDocumentEventHandler('activated'); +channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready'); + +// Listen for DOMContentLoaded and notify our channel subscribers. +if (document.readyState == 'complete' || document.readyState == 'interactive') { + channel.onDOMContentLoaded.fire(); +} else { + document.addEventListener('DOMContentLoaded', function() { + channel.onDOMContentLoaded.fire(); + }, false); +} + +// _nativeReady is global variable that the native side can set +// to signify that the native code is ready. It is a global since +// it may be called before any cordova JS is ready. +if (window._nativeReady) { + channel.onNativeReady.fire(); +} + +// Call the platform-specific initialization. +platform.bootstrap && platform.bootstrap(); + +/** + * Create all cordova objects once native side is ready. + */ +channel.join(function() { + + platform.initialize && platform.initialize(); + + // Fire event to notify that all objects are created + channel.onCordovaReady.fire(); + + // Fire onDeviceReady event once page has fully loaded, all + // constructors have run and cordova info has been received from native + // side. + channel.join(function() { + require('cordova').fireDocumentEvent('deviceready'); + }, channel.deviceReadyChannelsArray); + +}, platformInitChannelsArray); + +}); + +// file: src/common/modulemapper.js +define("cordova/modulemapper", function(require, exports, module) { + +var builder = require('cordova/builder'), + moduleMap = define.moduleMap, + symbolList, + deprecationMap; + +exports.reset = function() { + symbolList = []; + deprecationMap = {}; +}; + +function addEntry(strategy, moduleName, symbolPath, opt_deprecationMessage) { + if (!(moduleName in moduleMap)) { + throw new Error('Module ' + moduleName + ' does not exist.'); + } + symbolList.push(strategy, moduleName, symbolPath); + if (opt_deprecationMessage) { + deprecationMap[symbolPath] = opt_deprecationMessage; + } +} + +// Note: Android 2.3 does have Function.bind(). +exports.clobbers = function(moduleName, symbolPath, opt_deprecationMessage) { + addEntry('c', moduleName, symbolPath, opt_deprecationMessage); +}; + +exports.merges = function(moduleName, symbolPath, opt_deprecationMessage) { + addEntry('m', moduleName, symbolPath, opt_deprecationMessage); +}; + +exports.defaults = function(moduleName, symbolPath, opt_deprecationMessage) { + addEntry('d', moduleName, symbolPath, opt_deprecationMessage); +}; + +exports.runs = function(moduleName) { + addEntry('r', moduleName, null); +}; + +function prepareNamespace(symbolPath, context) { + if (!symbolPath) { + return context; + } + var parts = symbolPath.split('.'); + var cur = context; + for (var i = 0, part; part = parts[i]; ++i) { + cur = cur[part] = cur[part] || {}; + } + return cur; +} + +exports.mapModules = function(context) { + var origSymbols = {}; + context.CDV_origSymbols = origSymbols; + for (var i = 0, len = symbolList.length; i < len; i += 3) { + var strategy = symbolList[i]; + var moduleName = symbolList[i + 1]; + var module = require(moduleName); + // + if (strategy == 'r') { + continue; + } + var symbolPath = symbolList[i + 2]; + var lastDot = symbolPath.lastIndexOf('.'); + var namespace = symbolPath.substr(0, lastDot); + var lastName = symbolPath.substr(lastDot + 1); + + var deprecationMsg = symbolPath in deprecationMap ? 'Access made to deprecated symbol: ' + symbolPath + '. ' + deprecationMsg : null; + var parentObj = prepareNamespace(namespace, context); + var target = parentObj[lastName]; + + if (strategy == 'm' && target) { + builder.recursiveMerge(target, module); + } else if ((strategy == 'd' && !target) || (strategy != 'd')) { + if (!(symbolPath in origSymbols)) { + origSymbols[symbolPath] = target; + } + builder.assignOrWrapInDeprecateGetter(parentObj, lastName, module, deprecationMsg); + } + } +}; + +exports.getOriginalSymbol = function(context, symbolPath) { + var origSymbols = context.CDV_origSymbols; + if (origSymbols && (symbolPath in origSymbols)) { + return origSymbols[symbolPath]; + } + var parts = symbolPath.split('.'); + var obj = context; + for (var i = 0; i < parts.length; ++i) { + obj = obj && obj[parts[i]]; + } + return obj; +}; + +exports.reset(); + + +}); + +// file: /Users/steveng/repo/cordova/cordova-android/cordova-js-src/platform.js +define("cordova/platform", function(require, exports, module) { + +module.exports = { + id: 'android', + bootstrap: function() { + var channel = require('cordova/channel'), + cordova = require('cordova'), + exec = require('cordova/exec'), + modulemapper = require('cordova/modulemapper'); + + // Get the shared secret needed to use the bridge. + exec.init(); + + // TODO: Extract this as a proper plugin. + modulemapper.clobbers('cordova/plugin/android/app', 'navigator.app'); + + var APP_PLUGIN_NAME = Number(cordova.platformVersion.split('.')[0]) >= 4 ? 'CoreAndroid' : 'App'; + + // Inject a listener for the backbutton on the document. + var backButtonChannel = cordova.addDocumentEventHandler('backbutton'); + backButtonChannel.onHasSubscribersChange = function() { + // If we just attached the first handler or detached the last handler, + // let native know we need to override the back button. + exec(null, null, APP_PLUGIN_NAME, "overrideBackbutton", [this.numHandlers == 1]); + }; + + // Add hardware MENU and SEARCH button handlers + cordova.addDocumentEventHandler('menubutton'); + cordova.addDocumentEventHandler('searchbutton'); + + function bindButtonChannel(buttonName) { + // generic button bind used for volumeup/volumedown buttons + var volumeButtonChannel = cordova.addDocumentEventHandler(buttonName + 'button'); + volumeButtonChannel.onHasSubscribersChange = function() { + exec(null, null, APP_PLUGIN_NAME, "overrideButton", [buttonName, this.numHandlers == 1]); + }; + } + // Inject a listener for the volume buttons on the document. + bindButtonChannel('volumeup'); + bindButtonChannel('volumedown'); + + // Let native code know we are all done on the JS side. + // Native code will then un-hide the WebView. + channel.onCordovaReady.subscribe(function() { + exec(onMessageFromNative, null, APP_PLUGIN_NAME, 'messageChannel', []); + exec(null, null, APP_PLUGIN_NAME, "show", []); + }); + } +}; + +function onMessageFromNative(msg) { + var cordova = require('cordova'); + var action = msg.action; + + switch (action) + { + // Button events + case 'backbutton': + case 'menubutton': + case 'searchbutton': + // App life cycle events + case 'pause': + case 'resume': + // Volume events + case 'volumedownbutton': + case 'volumeupbutton': + cordova.fireDocumentEvent(action); + break; + default: + throw new Error('Unknown event action ' + action); + } +} + +}); + +// file: /Users/steveng/repo/cordova/cordova-android/cordova-js-src/plugin/android/app.js +define("cordova/plugin/android/app", function(require, exports, module) { + +var exec = require('cordova/exec'); +var APP_PLUGIN_NAME = Number(require('cordova').platformVersion.split('.')[0]) >= 4 ? 'CoreAndroid' : 'App'; + +module.exports = { + /** + * Clear the resource cache. + */ + clearCache:function() { + exec(null, null, APP_PLUGIN_NAME, "clearCache", []); + }, + + /** + * Load the url into the webview or into new browser instance. + * + * @param url The URL to load + * @param props Properties that can be passed in to the activity: + * wait: int => wait msec before loading URL + * loadingDialog: "Title,Message" => display a native loading dialog + * loadUrlTimeoutValue: int => time in msec to wait before triggering a timeout error + * clearHistory: boolean => clear webview history (default=false) + * openExternal: boolean => open in a new browser (default=false) + * + * Example: + * navigator.app.loadUrl("http://server/myapp/index.html", {wait:2000, loadingDialog:"Wait,Loading App", loadUrlTimeoutValue: 60000}); + */ + loadUrl:function(url, props) { + exec(null, null, APP_PLUGIN_NAME, "loadUrl", [url, props]); + }, + + /** + * Cancel loadUrl that is waiting to be loaded. + */ + cancelLoadUrl:function() { + exec(null, null, APP_PLUGIN_NAME, "cancelLoadUrl", []); + }, + + /** + * Clear web history in this web view. + * Instead of BACK button loading the previous web page, it will exit the app. + */ + clearHistory:function() { + exec(null, null, APP_PLUGIN_NAME, "clearHistory", []); + }, + + /** + * Go to previous page displayed. + * This is the same as pressing the backbutton on Android device. + */ + backHistory:function() { + exec(null, null, APP_PLUGIN_NAME, "backHistory", []); + }, + + /** + * Override the default behavior of the Android back button. + * If overridden, when the back button is pressed, the "backKeyDown" JavaScript event will be fired. + * + * Note: The user should not have to call this method. Instead, when the user + * registers for the "backbutton" event, this is automatically done. + * + * @param override T=override, F=cancel override + */ + overrideBackbutton:function(override) { + exec(null, null, APP_PLUGIN_NAME, "overrideBackbutton", [override]); + }, + + /** + * Override the default behavior of the Android volume button. + * If overridden, when the volume button is pressed, the "volume[up|down]button" + * JavaScript event will be fired. + * + * Note: The user should not have to call this method. Instead, when the user + * registers for the "volume[up|down]button" event, this is automatically done. + * + * @param button volumeup, volumedown + * @param override T=override, F=cancel override + */ + overrideButton:function(button, override) { + exec(null, null, APP_PLUGIN_NAME, "overrideButton", [button, override]); + }, + + /** + * Exit and terminate the application. + */ + exitApp:function() { + return exec(null, null, APP_PLUGIN_NAME, "exitApp", []); + } +}; + +}); + +// file: src/common/pluginloader.js +define("cordova/pluginloader", function(require, exports, module) { + +/* + NOTE: this file is NOT used when we use the browserify workflow +*/ + +var modulemapper = require('cordova/modulemapper'); +var urlutil = require('cordova/urlutil'); + +// Helper function to inject a + + + + +
+
+

HUB

+
+ +
+
+
+
+ +
+
+
+ +
+
+ +
+

ARCHIVE

+
'982-'015
+
+
+ +
+
+

PRIVACY POLICY

+
+
+
+
+
+

TERMS AND CONDITIONS

+
+
+
+
+
+

RETURN POLICY

+
+
+
+
+
+

CUSTOMER CARE

+
+
+
+ + + + +
+
+

COLLECTION NAME

+
+
+ +
+
+
+ + + +
+
+
+ + + +
+
+ + +
+
+ + +
+
+ +
+ + +
+
+ +
+
Fits Large
+
+
+
+ Sizing: The products of this collaboration fit slightly larger than the classic Stone Island garments. +

+ We suggest you choose a smaller size than yours. +
+
+
+
+ +
+
+

+ THIS STORE IS CURRENTLY CLOSED +

+ +
+
+ + + + +
+
+

LOGIN

+
+
+
+ + +
+
+
+ New User? +
+
+ +
+
+
+
+
+
+ +
+
+

LOGOUT

+
+
+ + You are now logged out. + +
+
+
+
+ +
+
+

NEW USER

+
+
+
+ + + + +
+ BIRTHDAY (MM/DD/YYYY) + +
+ +

PASSWORD

+ + +
+
+
+ + * Your personal and payment
+ information will always remain private +
+
+
+
+
+
+
+ + +
+ +
+
+
+ + +
+ +
+
+ Consult our PRIVACY POLICY for further information. +
+
+
+
+
+
+
+ +
+
+

PROFILE

+
+
+
+ + + +
+ BIRTHDAY (MM/DD/YYYY) + +
+ +

CHANGE PASSWORD

+ + +
+
+

Newsletter

+ Receive Stone Island Newsletter +
+
+ + +
+
+
+
+
+ + * Your personal and payment
+ information will always remain private +
+
+
+
+
+
+
+ + +
+
+

SHIPPING

+
+
+
+
+
+
+
+ + * Your personal and payment
+ information will always remain private +
+
+
+
+
+
+
+ +
+
+

PAYMENT

+
+
+
+
+
+
+
+
+ + * Your personal and payment
+ information will always remain private +
+
+
+
+
+
+
+ +
+
+

NOTIFICATIONS

+
+
+
+
+

Store

+ Receive notifications for Store +
+
+ + +
+
+
+
+

Hub

+ Receive notifications for Hub +
+
+ + +
+
+
+
+
+
+ +
+
+

ORDERS

+
+
+
You have no orders.
+ +
+ +
+
+

ORDER SUMMARY

+ +
+ +
+
+
+ SUB TOTAL + +
+
+ ESTIMATED SHIPPING & HANDLING + +
+
+ TAX + +
+
+ TOTAL + +
+
+
+ +
+

SHIP TO

+
+
+
+
+
+ +
+
+
+ + + +
+

+ + YOUR CART / + + + YOUR CART IS EMPTY + +

+ +
+ SUMMARY + SHIPPING + BILLING +
+ +
+
+
+
+
+
+ +
+
+
+ SUB TOTAL + +
+
+ ESTIMATED SHIPPING
& HANDLING
+ +
+
+ TAX + +
+
+ TOTAL + +
+
+
+
+
+
+ You have nothing in your cart. +
+
+
+
+
+ +
+
+
+ +
+ +
+
+ +

SHIPPING METHOD

+ +
+
+
+ + +
+ +
+
+
+ + +
+ +
+
+ +
+
+
+ + * Your personal and payment
+ information will always remain private +
+
+
+
+ +
+
+
+ +
+
+
+ +
+
+ +
+
+
+ + +
+ +
+
+ +
+ + +
+ +
+ +
+ +
+ + + +
+ +
+ +
+ +
+

PLEASE ENTER YOUR SECURITY CODE TO CONFIRM

+ +
+
+ +
+
+ + * Your personal and payment
+ information will always remain private +
+
+
+
+



+ +
+
+
+ +
+
+

CONFIRM

+ +
+

ORDER SUMMARY

+ +
+ +
+
+
+ SUB TOTAL + +
+
+ ESTIMATED SHIPPING
& HANDLING
+ +
+
+ TAX + +
+
+ TOTAL + +
+
+
+ +
+

SHIP TO

+ +
+
+
+ +
+

BILL TO

+ +
+
+
+ +
+
+ +
+
+ THANK YOU +

+ Please check your inbox for your confirmation email. +

+
+
+ +
+
+ WE'RE SORRY +

+
+
+ +
+ +
+
+
+ +
+
+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/StoneIsland/platforms/android/assets/www/js/index.js b/StoneIsland/platforms/android/assets/www/js/index.js new file mode 100755 index 00000000..0b3531dd --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/index.js @@ -0,0 +1,86 @@ +var app = (function(){ + var app = {} + + app.init = function(){ + + sdk.init({ env: "production" }) + + app.bind() + app.build() + + app.iscroll_options = { + mouseWheel: true, + scrollbars: true, + } + + if (window.cordova) { + document.addEventListener('deviceready', app.ready, false) + } + else { + app.ready() + } + } + + app.bind = function(){ + document.addEventListener('touchmove', function(e){ e.preventDefault() }) + FastClick.attach(document.body) + } + + app.build = function(){ + app.blog = new BlogView () + app.archive = new ArchiveView () + app.hub = new HubView () + app.story = new StoryView () + app.cart = new CartView () + + app.intro = new IntroView () + app.header = new HeaderView () + app.footer = new FooterView () + app.curtain = new CurtainView () + app.nav = new NavView () + + app.account = new AccountView () + app.login = new LoginView () + app.logout = new LogoutView () + app.signup = new SignupView () + app.profile = new ProfileView () + app.payment = new PaymentView () + app.shipping = new ShippingView () + app.settings = new SettingsView () + app.orders = new OrdersView () + + app.terms = new PageView ({ page: "terms" }) + app.privacy = new PageView ({ page: "privacy" }) + app.returns = new PageView ({ page: "returns" }) + app.care = new PageView ({ page: "care" }) + + app.collection = new CollectionView () + app.product = new ProductView () + app.closed = new ClosedStoreView () + app.search = new SearchView () + + app.selector = new Selector () + } + + app.ready = function(){ + if (window.cordova) { + cordova.plugins.Keyboard.disableScroll(true) + geo.fetch() + } + + app.view = null + app.router = new SiteRouter () +// if (sdk.env == "test") { +// app.router.launch() +// } +// else { + app.account.connect( app.router.launch.bind(app.router) ) +// } + + $("body").removeClass("loading") + } + + return app +})() + +app.init() diff --git a/StoneIsland/platforms/android/assets/www/js/lib/_router.js b/StoneIsland/platforms/android/assets/www/js/lib/_router.js new file mode 100755 index 00000000..b1fa1c97 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/_router.js @@ -0,0 +1,105 @@ +var SiteRouter = Router.extend({ + + el: 'body', + routeByHash: true, + + routes: { + '/': 'intro', + '/intro': 'intro', + '/hub': 'hub', + '/story': 'story', + '/archive': 'archive', + + '/store': 'collection', + '/store/closed': 'closed', + '/store/:code': 'product', + + '/account/login': 'login', + '/account/logout': 'logout', + '/account/signup': 'signup', + '/account/profile': 'profile', + '/account/payment': 'payment', + '/account/shipping': 'shipping', + '/account/orders': 'orders', + '/account/settings': 'settings', + + '/page/terms': 'terms', + '/page/privacy': 'privacy', + '/page/returns': 'returns', + '/page/care': 'care', + + '/search': 'search', + + '/cart': 'cart.summary', + '/cart/summary': 'cart.summary', + '/cart/payment': 'cart.payment', + '/cart/shipping': 'cart.shipping', + '/cart/confirm': 'cart.confirm', + '/cart/thanks': 'cart.thanks', + '/cart/error': 'cart.error', + }, + + initialize: function(){ + var fn + for (var route in this.routes) { + fn = this.routes[route] + if (! this[fn]) { + this[fn] = this.default_view(fn) + } + } + }, + + initial_route: null, + launch: function(){ + if (this.initial_route) { + this.parseRoute( this.initial_route ) + } + else { + this.route() + } + this.initial_route = null + }, + + go: function(url){ + if (app.view && app.view.hide) { + app.view.hide() + } + window.location.href = "#/" + url + this.parseRoute(url) + }, + + default_view: function(name){ + var fn = function(){ + console.log(name) + if (app.view != app.login && app.view != app.signin) { + app.last_view = app.view + } + if (app.view && app.view.hide) { + app.view.hide() + } + if (name.match(/\./)) { + var n = name.split(".") + console.log(name, n) + app.view = app[n[0]][n[1]] + } + else { + app.view = app[name] + } + app.header.set_back( !! app.view.back ) + app.view.show() + }.bind(this) + return fn + }, + + product: function(code){ + if (app.view && app.view.hide) { + app.view.hide() + } + app.view = app.product + app.header.set_back( true ) + app.product.load(code) + app.product.show() + }, + +}) + diff --git a/StoneIsland/platforms/android/assets/www/js/lib/account/AccountView.js b/StoneIsland/platforms/android/assets/www/js/lib/account/AccountView.js new file mode 100755 index 00000000..1c5c9f16 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/account/AccountView.js @@ -0,0 +1,129 @@ +var AccountView = View.extend({ + + initialize: function(){ + }, + + connect: function(cb){ + auth.init(this.ready.bind(this, cb)) + }, + + ready: function(cb){ + if (auth.logged_in()) { + this.logged_in(cb) + } + else { + this.logged_out(cb) + } + }, + + addresses: [], + addressLookup: {}, + ccs: [], + ccLookup: {}, + + listAddresses: function(cb){ + sdk.address.list({ + success: function(data){ + this.populateAddresses(data, cb) + }.bind(this) + }) + }, + + populateAddresses: function(data, cb){ + console.log("populate addresses:", data.AddressBook.addressBookItem) + + if (! data.AddressBook) { + console.log("no addresses") + cb && cb() + return + } + + this.addresses = data.AddressBook.addressBookItem + this.addressLookup = {} + data.AddressBook.addressBookItem.forEach(function(item){ + this.addressLookup[ item.Id ] = item + if (item.IsDefault) { + console.log("SHIPPING ADDRESS", item) + app.shipping.populate(item) + } + if (item.IsBillingDefault) { + console.log("BILLING ADDRESS") + app.payment.populate(item) + } + }.bind(this)) + + app.cart.shipping.populate() + + cb && cb() + }, + + listCreditCards: function(cb){ + sdk.payment.list_credit_cards({ + success: function(data){ + this.populateCreditCards(data, cb) + }.bind(this) + }) + }, + + populateCreditCards: function(data, cb){ + console.log("populate ccs:", data.CreditCards) + this.ccs = data.CreditCards + this.ccLookup = {} + if (! data.CreditCards || ! data.CreditCards.length) { + } + else { + data.CreditCards.forEach(function(cc){ + this.ccLookup[cc.Id] = cc + }.bind(this)) + app.payment.populate( data.CreditCards[0] ) + app.cart.payment.populate() + } + cb && cb() + }, + + logged_in: function(cb){ + this.listAddresses() + this.listCreditCards() + $("#nav .login").hide() + $("#nav .account, #nav .logout").show() + if (! auth.deferred_product && app.last_view) { + if (app.last_view != app.login && app.last_view != app.signin && app.last_view != app.logout) { + app.view && app.view.hide && app.view.hide() + app.view = app.last_view + app.view.show() + } + } + else { + cb && cb() + } + if ( ! auth.has_cart() ) { + app.curtain.show("loading") + auth.create_cart(function(){ + auth.add_deferred_product_to_cart(function(){ + app.router.go("cart") + setTimeout(function(){ + app.curtain.hide("loading") + }, 500) + }) + }) + } + else { + if (auth.deferred_product) { + auth.add_deferred_product_to_cart(function(){ + app.router.go("cart") + }) + } + else { + app.cart.load() + } + } + }, + + logged_out: function(cb){ + $("#nav .login").show() + $("#nav .account, #nav .logout").hide() + $("#nav").removeClass("account") + cb && cb() + }, + +}) diff --git a/StoneIsland/platforms/android/assets/www/js/lib/account/OrdersView.js b/StoneIsland/platforms/android/assets/www/js/lib/account/OrdersView.js new file mode 100755 index 00000000..a1b83767 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/account/OrdersView.js @@ -0,0 +1,189 @@ +var OrdersView = ScrollableView.extend({ + + el: "#orders", + + loaded: false, + + list_template: $("#orders .list_template").html(), + item_template: $("#orders .item_template").html(), + + events: { + "click .back": "back", + "click .item": "load_single", + }, + + initialize: function(){ + this.$list = this.$(".list") + this.$empty = this.$(".empty") + this.$single_order = this.$("#single_order") + + this.$rows = this.$(".rows") + this.$subtotal = this.$(".subtotal") + this.$shipping = this.$(".shipping") + this.$tax = this.$(".tax") + this.$total = this.$(".total") + + this.$shipping_address = this.$(".shipping_address") + this.$shipping_method = this.$(".shipping_method") + + this.scroller = new IScroll('#orders', app.iscroll_options) + }, + + show: function(){ + if (! auth.logged_in()) { return app.router.go("intro") } + app.header.set_back(false) + app.footer.hide() + document.body.className = "orders" + this.deferScrollToTop() + this.el.className = "" + + if (this.loaded) { + this.populate() + } + else { + this.fetch() + } + }, + + orders: null, + orderLookup: {}, + + fetch: function(){ + this.$list.empty() + this.$empty.hide() + this.loader = new Loader(this.ready.bind(this)) + app.curtain.show("loading") + sdk.account.fetch_orders({ + success: function(data){ + this.loader.register("orders") + this.orders = data.OrderDetails + data.OrderDetails.forEach(function(row){ + this.loader.register(row.OrderNumber) + sdk.account.fetch_single_order({ + id: row.OrderNumber, + success: function(row_data){ + this.orderLookup[ row.OrderNumber ] = row_data.OrderFullDetails + this.loader.ready(row.OrderNumber) + }.bind(this), + error: function(){ + this.orderLookup[ row.OrderNumber ] = null + this.loader.ready(row.OrderNumber) + }.bind(this), + }) + }.bind(this)) + this.loader.ready("orders") + }.bind(this), + error: function(){ + console.log("error fetching orders") + }.bind(this), + }) + }, + + ready: function(){ + this.populate() + app.curtain.hide("loading") + }, + + populate: function(){ + this.$list.empty() + + if (! this.orders.length) { + this.$empty.show() + return + } + else { + this.$empty.hide() + } + this.orders.forEach(function(row){ + var order = this.orderLookup[ row.OrderNumber ] + if (! order) { return } + var t = this.list_template.replace(/{{date}}/g, moment(order['Date']).format("ddd MM/DD/YYYY").toUpperCase()) + .replace(/{{id}}/g, row.OrderNumber) + .replace(/{{total}}/g, as_cash( order.TotalAmount )) + var $t = $(t), $images = $t.find(".images") + order.Items.forEach(function(item){ + var img = new Image () + img.src = sdk.image(item['Code10'], "11_f") + $images.append(img) + }.bind(this)) + this.$list.append($t) + }.bind(this)) + + this.refreshScroller() + }, + + load_single: function(e){ + var id = $(e.currentTarget).data("id") + var order = this.orderLookup[ id ] + if (! order) { return } + + console.log(order) + + this.$rows.empty() + + order.Items.forEach(function(item){ + var $el = $("
") + this.$rows.append($el) + var code_ten = item.Code10 + + var code = code_ten.substr(0, 8) + app.product.find(code, function(data, details){ + var descriptions = app.product.get_descriptions( details ) + + var name_partz = descriptions['ModelNames'].split(' ') + var num = name_partz.shift() + var title = name_partz.join(' ') + var type = title_case( descriptions['MicroCategory'] ) + + var color_name, size_name + + details.Item.ModelColors.some(function(color){ + if (color['Code10'] == code_ten) { + color_name = color['ColorDescription'] + return true + } + return false + }) + size_name = item.DefaultSize + " " + item.DefaultSizeClassFamily + + var t = this.item_template + .replace(/{{image}}/, sdk.image(item['Code10'], '11_f')) + .replace(/{{sku}}/, num) + .replace(/{{title}}/, title) + .replace(/{{type}}/, type) + .replace(/{{size}}/, size_name || "DEFAULT") + .replace(/{{color}}/, color_name || "DEFAULT") + .replace(/{{quantity}}/, 1) + .replace(/{{price}}/, as_cash(details.Item.Price.DiscountedPrice)) + $el.data("price", details.Item.Price.DiscountedPrice) + $el.html(t) + this.refreshScroller() + }.bind(this)) + }.bind(this)) + + var subtotal = order.ItemsTotalAmount + var shipping_cost = order.Delivery.Amount + var tax = order.SalesTaxAmount + var total = order.TotalToPay + + this.$subtotal.html( as_cash(subtotal) ) + this.$shipping.html( as_cash(shipping_cost) ) + this.$tax.html( as_cash(tax) ) + this.$total.html( as_cash(total) ) + + var street = order.Delivery.Address.replace(/\n$/,"").replace("\n","
") + var address = order.Delivery.Name + "
" + street + "
" + order.Delivery.City + " " + order.Delivery.ZipCode + this.$shipping_address.html(address) + this.$shipping_method.html(order.Delivery.Type + " - " + order.Delivery.Time) + + app.header.set_back(true) + this.$el.addClass("single") + }, + + back: function(){ + app.header.set_back(false) + this.el.className = "" + }, + +}) + diff --git a/StoneIsland/platforms/android/assets/www/js/lib/account/PaymentView.js b/StoneIsland/platforms/android/assets/www/js/lib/account/PaymentView.js new file mode 100755 index 00000000..03dc8cbf --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/account/PaymentView.js @@ -0,0 +1,115 @@ +var PaymentView = FormView.extend({ + + el: "#payment", + + action: sdk.payment.add_credit_card, + + events: { + }, + + test_data: { + "Name":"Name", + "Surname":"Surname", + "Address1":"address", + "Address2":"address2", + "City":"Ferrara", + "Province":"NY", + "HolderIsoCountry":"IT", + "CreditCardCountry": "US", + "ZipCode":"40200", + "Type":"Visa", + "Number":"4111111111111111", + "ExpirationMonth":"09", + "ExpirationYear":"2017", + "Cvv":"1233", + }, + + initialize: function(){ + this.$form = this.$("form") + this.$msg = this.$(".msg") + this.address = new AddressView ({ parent: this, checkPhone: false }) + this.cc = new CreditCardView ({ parent: this }) + this.scroller = new IScroll('#payment', app.iscroll_options) + }, + + show: function(){ + if (! auth.logged_in()) { return app.router.go("intro") } + app.footer.show("SAVE", "CANCEL") + document.body.className = "payment" + this.deferScrollToTop() + // this.preload() + }, + + populate: function(data){ + this.data = data || this.data + this.address.populate(data) + this.cc.populate(data) + }, + + finalize: function(data){ + if (this.cc.data && this.cc.data.Guid) { + sdk.payment.delete_credit_card({ + guid: this.cc.data.Guid, + success: function(){}, + error: function(){}, + }) + } + + data.IsDefault = "true" // this.$isDefault.prop("checked") ? "true" : "false" + data.UserId = sdk.auth.user_id + data.HolderIsoCountry = "US" + data.CreditCardNumber = data.Number + data.IsPreferred = "true" + + console.log(data) + return data + }, + + success: function(data){ + app.curtain.show("loading") + app.account.listAddresses(function(){ + app.curtain.hide("loading") + }) + }, + + error: function(data){ + console.log(data) + }, + + cancel: function(){ + app.router.go("intro") + }, + +}) + +/* + var new_card = { + "Name":"Name", + "Surname":"Surname", + "Address":"address", + "City":"Ferrara", + "Province":"FE", + "HolderIsoCountry":"IT", + "ZipCode":"40200", + "Type":"Visa", + "Number":"0000567890124285", + "ExpirationMonth":"02", + "ExpirationYear":"2017", + } + promise(sdk.payment.add_credit_card, { data: new_card }).then(function(data){ + last_guid = data['CreditCard']['Guid'] + assert(data.Header.StatusCode == 201) + assert(!! last_guid) + done() + }) + + promise(sdk.payment.list_credit_cards, { data: {} }).then(function(data){ + assert(data.Header.StatusCode == 201) + console.log(data) + done() + }) + + promise(sdk.payment.delete_credit_card, { guid: last_guid }).then(function(data){ + assert(data.Header.StatusCode == 200) + done() +*/ \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/account/ProfileView.js b/StoneIsland/platforms/android/assets/www/js/lib/account/ProfileView.js new file mode 100755 index 00000000..ed2f3536 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/account/ProfileView.js @@ -0,0 +1,82 @@ +var ProfileView = FormView.extend({ + + el: "#profile", + + events: { + }, + + action: sdk.account.update, + + initialize: function(){ + this.$form = this.$("form") + this.$msg = this.$(".msg") + this.scroller = new IScroll('#profile', app.iscroll_options) + }, + + show: function(){ + if (! auth.logged_in()) { return app.router.go("intro") } + app.footer.show("SAVE", "CANCEL") + document.body.className = "profile" + this.preload(auth.user) + this.deferScrollToTop() + }, + + validate_presence: { + "Name": "Please enter your first name.", + "Surname": "Please enter your last name.", + "Email": "Please enter a valid email address.", + }, + + validate_fields: function(data, errors){ + if (! data.Email.match("@")) { errors.push([ "Email", "Email address is not valid." ]) } + if (! data.CurrentPassword && (data.NewPassword || data.Email !== auth.user.Email)) { errors.push([ "CurrentPassword", "Please enter your current password." ]) } + if (data.CurrentPassword && ! data.NewPassword) { errors.push([ "NewPassword", "Please enter your new password." ]) } + if (data.NewPassword && data.NewPassword.length < 7) { errors.push([ "CurrentPassword", "New password must be 7 characters or more." ]) } + // if (data.Gender === "NONE") { errors.push([ "Gender", "Please supply your gender." ]) } + }, + + finalize: function(data){ + if (data.CurrentPassword && (data.NewPassword || data.Email !== auth.user.Email)) { + data.NewPassword = data.NewPassword || data.CurrentPassword + data.NewEmail = data.NewEmail || auth.user.Email + + sdk.account.update_mail_and_password({ + data: { + Password: data.CurrentPassword, + NewPassword: data.NewPassword || data.CurrentPassword, + Email: auth.user, + NewEmail: data.NewEmail || auth.user.Email, + }, + success: function(){ console.log("updated password") }, + error: function(){ console.log("error updating password") }, + }) + } + + var submissible_data = _.pick(data, "Name Surname BirthDay YooxLetter".split(" ")) + submissible_data.Gender = "U" +// submissible_data.idUser = auth.user_id +// submissible_data.AccessToken = auth.access_token +// submissible_data.Premium = "false" +// submissible_data.LanguageId = "" +// submissible_data.SiteCode = "STONEISLAND_US" +// submissible_data.FuriganaName = "" +// submissible_data.FuriganaSurname = "" +// submissible_data.UserPromocode = "" + submissible_data.BirthDay += "T00:00:00Z" + submissible_data.YooxLetter = data.YooxLetter || "false" + submissible_data.DataProfiling = "true" + + return submissible_data + }, + + success: function(data){ + }, + + error: function(data){ + }, + + cancel: function(){ + app.router.go("intro") + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/account/SettingsView.js b/StoneIsland/platforms/android/assets/www/js/lib/account/SettingsView.js new file mode 100755 index 00000000..7f96bb88 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/account/SettingsView.js @@ -0,0 +1,24 @@ +var SettingsView = FormView.extend({ + + el: "#settings", + + events: { + }, + + initialize: function(){ + this.$form = this.$("form") + this.$msg = this.$(".msg") + this.scroller = new IScroll('#settings', app.iscroll_options) + }, + + show: function(){ + if (! auth.logged_in()) { return app.router.go("intro") } + app.footer.show("SAVE", "CANCEL") + document.body.className = "settings" + this.deferScrollToTop() + }, + + save: function(){ + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/account/ShippingView.js b/StoneIsland/platforms/android/assets/www/js/lib/account/ShippingView.js new file mode 100755 index 00000000..39baf2aa --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/account/ShippingView.js @@ -0,0 +1,77 @@ +var ShippingView = FormView.extend({ + + el: "#shipping", + + action: sdk.address.add, + + events: { + }, + + test_data: { + "Name":"name", + "Surname":"surname", + "Address":"address1\naddress2", + "IsDefault":false, + "IsBillingDefault":false, + "IsOwner":false, + "ZipCode":"88040", + "City":"City", + "Province":"NY", + "Phone":"1234567890", + "Mobile":"Mobile", + "Mail":"Mail", + "UserId": sdk.auth.user_id, + }, + + initialize: function(){ + this.$form = this.$("form") + this.$msg = this.$(".msg") + this.address = new AddressView ({ parent: this }) + this.scroller = new IScroll('#shipping', app.iscroll_options) + }, + + show: function(){ + if (! auth.logged_in()) { return app.router.go("intro") } +// this.preload( this.data || this.test_data ) + app.footer.show("SAVE", "CANCEL") + document.body.className = "shipping" + this.deferScrollToTop() + }, + + populate: function(data){ + this.data = data || this.data + this.address.populate(data) + }, + + finalize: function(data){ + if (this.address.data && this.address.data.Id) { + sdk.address.destroy({ + id: this.address.data.Id, + success: function(){}, + error: function(){}, + }) + } + + data.IsDefault = "true" // this.$isDefault.prop("checked") ? "true" : "false" + data.UserId = sdk.auth.user_id + + console.log(data) + return data + }, + + success: function(data){ + app.curtain.show("loading") + app.account.listAddresses(function(){ + app.curtain.hide("loading") + }) + }, + + error: function(data){ + console.log(data) + }, + + cancel: function(){ + app.router.go("intro") + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/auth/LoginView.js b/StoneIsland/platforms/android/assets/www/js/lib/auth/LoginView.js new file mode 100755 index 00000000..1f7438cc --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/auth/LoginView.js @@ -0,0 +1,53 @@ +var LoginView = FormView.extend({ + + el: "#login", + + action: sdk.account.login, + + events: { + "click .newuser": "new_user", + "submit form": "save", + }, + + initialize: function(){ + this.$form = this.$("form") + this.$msg = this.$(".msg") + this.scroller = new IScroll('#login', app.iscroll_options) + }, + + show: function(){ + if (auth.logged_in()) { + app.router.go("intro") + return + } + var msg = "* Your personal and payment
information will always remain private" + app.footer.show("SUBMIT", "CANCEL") + this.$form.get(0).reset() + this.$msg.html(msg) + document.body.className = "login" + }, + + new_user: function(){ + app.router.go("account/signup") + }, + + validate_presence: { + "Email": "Please enter a valid email address.", + "Password": "Please enter your password.", + }, + + success: function(data){ + // console.log(data) + app.account.logged_in(function(){ app.router.go("store") }) + }, + + error: function(data){ + this.$msg.html("There was an error logging you in. Bad password?") + this.$msg.addClass('alert-notice') + }, + + cancel: function(){ + auth.deferred_product = null + }, + +}) diff --git a/StoneIsland/platforms/android/assets/www/js/lib/auth/LogoutView.js b/StoneIsland/platforms/android/assets/www/js/lib/auth/LogoutView.js new file mode 100755 index 00000000..481dcb8d --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/auth/LogoutView.js @@ -0,0 +1,16 @@ +var LogoutView = View.extend({ + + el: "#logout", + + events: { + }, + + show: function(){ + document.body.className = "logout" + app.header.set_cart_count(0) + app.footer.hide() + auth.log_out() + app.account.logged_out() + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/auth/SignupView.js b/StoneIsland/platforms/android/assets/www/js/lib/auth/SignupView.js new file mode 100755 index 00000000..afbb8877 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/auth/SignupView.js @@ -0,0 +1,117 @@ +var SignupView = FormView.extend({ + + el: "#signup", + + action: sdk.account.signup, + last_data: null, + +/* + test_data: { + "Email": "testit.account" + Math.floor(Math.random() * 10000000) + "@yoox.com", + "Password": "TestPassword", + "Password2": "TestPassword", + "Gender": "U", + "Name": "TestName", + "Surname": "TestSurname", + "BirthDay": "1978-11-12", + "DataProfiling": true, + "DataProfiling2": true, + }, +*/ + + events: { + "click .privacy-msg": "privacy_link", + "submit form": "save", + }, + + initialize: function(){ + this.$form = this.$("form") + this.$msg = this.$(".msg") + this.scroller = new IScroll('#signup', app.iscroll_options) + }, + + show: function(){ + if (auth.logged_in()) { + app.router.go("intro") + return + } + var msg = "* Your personal and payment
information will always remain private" + app.footer.show("SUBMIT", "CANCEL") + this.$form.get(0).reset() + this.$msg.html(msg) + document.body.className = "signup" + + this.preload() + this.deferScrollToTop() + }, + + validate_presence: { + "Name": "Please enter your first name.", + "Surname": "Please enter your last name.", + "Email": "Please enter a valid email address.", + "ConfirmEmail": "Please enter a valid email address.", + "BirthDay": "Please enter your birthday.", + "Password": "Please enter your password.", + "Password2": "Please enter your password again.", + "DataProfiling": "You must agree to data profiling.", + }, + + validate_fields: function(data, errors){ + if (data.Password.length < 7) { errors.push([ "Password", "Password must be 7 characters or more." ]) } + if (data.Password !== data.Password2) { errors.push([ "Password2", "Passwords don't match." ]) } + if (! data.Email.match("@")) { errors.push([ "Email", "Email address is not valid." ]) } + if (data.Email.toLowerCase() !== data.ConfirmEmail.toLowerCase()) { errors.push([ "ConfirmEmail", "Email addresses don't match." ]) } + // if (data.Gender === "NONE") { errors.push([ "Gender", "Please supply your gender." ]) } + if (data.DataProfiling !== "true") { errors.push([ "DataProfiling", "You must consent to use this service." ]) } + if (data.DataProfiling2 !== "true") { errors.push([ "DataProfiling2", "You must consent to use this service." ]) } + if (! data.YooxLetter) { data.YooxLetter = false } + }, + + finalize: function(data){ + delete data.DataProfiling2 + delete data.ConfirmEmail + + data.Gender = "U" + data.BirthDay += "T00:00:00Z" + + this.last_data = data + console.log(data) + return data + }, + + privacy_link: function(){ + // rewrite app.privacy instance temporarily + app.privacy.back = function(){ + app.router.go("account/signup") + } + app.privacy.hide = function(){ + app.privacy.back = app.privacy.hide = null + } + app.router.go("page/privacy") + }, + + success: function(data){ + console.log('success', data) + auth.user = auth.user || {} + auth.user.Name = this.last_data.Name + auth.user.Surname = this.last_data.Surname + auth.user.Email = this.last_data.Email + auth.user.BirthDay = this.last_data.BirthDay + app.account.logged_in(function(){ app.router.go("store") }) + }, + + error: function(data){ + try { + data = JSON.parse(data.responseText) + app.signup.show_errors([[ 'Name', data['Error']['Description'] ]]) + } + catch (e) { + app.signup.show_errors([[ 'Name', "There was an unknown error." ]]) + } + }, + + cancel: function(){ + auth.deferred_product = null + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/blogs/ArchiveView.js b/StoneIsland/platforms/android/assets/www/js/lib/blogs/ArchiveView.js new file mode 100755 index 00000000..254df6d1 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/blogs/ArchiveView.js @@ -0,0 +1,228 @@ +var ArchiveView = ScrollableView.extend({ + + el: "#archive", + menu_template: $("#archive .menu .template").html(), + row_template: $("#archive .scroll .template").html(), + + events: { + "click .item": "pick", + "mousedown .row": "mousedown", + "touchstart .row": "touchstart", + "mousemove .row": "mousemove", + "touchmove .row": "touchmove", + "mouseup .row": "mouseup", + "touchend .row": "touchend", + }, + + initialize: function(){ + this.$menu_items = this.$(".menu .items") + this.$content = this.$(".content") + this.$loader = this.$(".loader") + this.scroller = new IScroll('#archive .scroll', app.iscroll_options) + this.$subtitle = this.$('.subtitle') + this.subtitle_html = this.$subtitle.html() + + }, + + back: function(){ + this.$el.addClass("menu") + app.header.set_back(false) + this.$subtitle.html( this.subtitle_html ) + }, + + pick: function(e){ + this.$el.removeClass("menu") + app.header.set_back(true) + var index = $(e.currentTarget).data("index") + this.$subtitle.html( $(e.currentTarget).text() ) + this.populateDecade(index) + }, + + show: function(){ + this.deferScrollToTop() + app.footer.hide() + this.back() + document.body.className = "archive" + }, + + populate: function(data){ + if (this.loaded) { return } + this.loaded = true + this.data = data + this.$loader.hide() + this.$content.empty() + + // id title images[ uri label code caption ] + this.data.forEach(function(row, index){ + + var t = this.menu_template.replace(/{{title}}/, row.title) + var $t = $(t) + $t.data("title", row.title) + $t.data("index", index) + this.$menu_items.append($t) + }.bind(this)) + + this.back() + this.deferScrollToTop() + + this.populateDecade(0, 3) + }, + + populateDecade: function(index, count){ + this.$content.empty() + + var loader = new Loader() + + var row = this.data[index] + + count = count || row.images.length + + row.images.forEach(function(cell, i){ + var $t = $("
") + $t.addClass("row").addClass("loading") + var t = this.row_template.replace(/{{image}}/, cell.uri) + .replace(/{{label}}/, cell.label) + .replace(/{{code}}/, cell.code) + .replace(/{{caption}}/, cell.caption) + $t.html(t) + $t.data("flipped", false) + this.$content.append($t) + + var item = $t[0] + var aa = this.build_aa_item( item ) + aa.q = 0 + this.render( aa, 0 ) + aa.flipped = true + this.fix_z_index( aa ) + + var $text = $t.find(".text") + if ( ($text.height() % 2) == 1) { + $text.css("margin-bottom", "1px") + } + + loader.preloadImage(cell.uri, function(){ + aa.flipped = false + this.fix_z_index( aa ) + $t.removeClass('loading') + }.bind(this)) + }.bind(this)) + }, + +// ['transformProp'] = "translateZ(0) translateX(-50%) translateY(-50%) "; +// .image, .text + + touchstart: function(e){ + app.archive.row = e.currentTarget + app.archive.mousedown(e.originalEvent.touches[0]) + }, + touchmove: function(e){ + app.archive.mousemove(e.originalEvent.touches[0]) + }, + touchend: function(e){ + app.archive.mouseup() + }, + + row: null, + image: null, + text: null, + flipped: false, + q: 0, + + mousedown: function(e){ + var aa = app.archive.item = app.archive.build_aa_item( app.archive.row || e.currentTarget ) + aa.mouse_x = e.pageX + aa.mouse_y = e.pageY + }, + + build_aa_item: function(el){ + var aa = {} + aa.row = el + aa.flipped = $(aa.row).data('flipped') + aa.image = $(aa.row).find(".image")[0] + aa.text = $(aa.row).find(".text")[0] + aa.q = 0 + return aa + }, + + mousemove: function(e){ + if (! app.archive.item) return + aa = app.archive.item + var dx = ( aa.mouse_x - e.pageX ) / window.innerWidth + var dy = ( aa.mouse_y - e.pageY ) / window.innerWidth + + var gray, opacity, q + + dx = Math.abs(dx) + dx *= 2 + q = clamp( dx, 0, 1 ) + + this.render(aa, q) + + aa.q = q +/* + aa.row.style['transformProp'] = [ + "translateZ(0)", + "translateX(-50%)", + "translateY(-50%)", + "rotateY(" + dx + "deg)", + ].join(" ") +*/ + }, + + render: function(aa, q){ + if ( aa.flipped ) { + gray = Math.round( (1-q) * 100 ) + opacity = lerp(q, 0.2, 1) + text_opacity = lerp(q, 1, 0.3) +// console.log("<", gray, opacity) + } + else { + gray = Math.round( q * 100 ) + opacity = lerp(q, 1, 0.2) + text_opacity = lerp(q, 0.3, 1) +// console.log(">", gray, opacity) + } + aa.image.style.WebkitFilter = "grayscale(" + gray + "%)" + aa.image.style.opacity = opacity + aa.text.style.opacity = text_opacity + }, + + margin: 0.3, + + mouseup: function(e){ + aa = app.archive.item + app.archive.row = null + app.archive.item = null + var was_flipped = aa.flipped + var flipped = aa.flipped ? (aa.q < app.archive.margin) : (aa.q > app.archive.margin) + var dest = was_flipped == flipped ? 0 : 1 + $(aa.row).data('flipped', flipped) + + oktween.add({ + obj: {q: aa.q}, + to: {q: dest}, + duration: 200 * Math.abs(aa.q-dest), + update: function(o, dt){ + app.archive.render(aa, o.q) + }, + }) + + this.fix_z_index(aa) + }, + + fix_z_index: function (aa) { + if ( aa.flipped ) { + console.log(aa.q) + z = aa.q > app.archive.margin ? 2 : 1 + zz = aa.q > app.archive.margin ? 1 : 2 + } + else { + z = aa.q < app.archive.margin ? 2 : 1 + zz = aa.q < app.archive.margin ? 1 : 2 + } + aa.image.style.zIndex = z + aa.text.style.zIndex = zz + + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/blogs/BlogView.js b/StoneIsland/platforms/android/assets/www/js/lib/blogs/BlogView.js new file mode 100755 index 00000000..9b49abbd --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/blogs/BlogView.js @@ -0,0 +1,70 @@ +var BlogView = View.extend({ + + data: null, + loaded: false, + initialize: function(){ + this.loader = new Loader () + this.fetch() + }, + + fetch: function(){ + $.ajax({ + method: "GET", +// url: sdk.env == 'test' ? '/db.json' : "http://stone.sup.land/db.json", + url: "http://stone.sup.land/db.json", + success: this.success.bind(this), + cache: true, + }) + }, + + success: function(data){ + + if (this.loaded) return + + this.loaded = true + this.data = data = typeof data == "string" ? JSON.parse(data) : data + + app.archive.populate(data.archive) + this.loader.preloadImage(data.hub[0].image[0].uri, function(img){ + app.hub.populate(data.hub) + }) + this.loader.preloadImage(data.story[0].image.uri, function(img){ + app.story.populate(data.story) + }) + data.page.forEach(function(page){ + app[page.tag].populate(page) + + }) + app.collection.setCollectionName( data.store[0].collection ) + + app.closed.populate(data.store[0].ClosedStoreImages) + switch (data.store[0].StoreStatus) { + case "open": + app.closed.storeIsClosed = false + break + case "closed": + app.closed.storeIsClosed = true + app.closed.storeOpenDate = null + break + case "openson": + app.closed.storeIsClosed = true + app.closed.storeOpenDate = moment(data.store[0].OpensOn) + break + } + console.log(data.store[0].StoreStatus) + + var fits_large = (data.store[0].FitsLarge === "true") + app.product.$fit.toggle( fits_large ) + app.product.$sizing.toggle( fits_large ) + + if (data.store[0].BackgroundIsGray === "true") { + app.collection.$el.addClass("gray") + app.product.gallery.$el.addClass("gray") + } + + app.gallery_id = data.store[0].CollectionId + + app.collection.fetch() + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/blogs/HubView.js b/StoneIsland/platforms/android/assets/www/js/lib/blogs/HubView.js new file mode 100755 index 00000000..49c05ff6 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/blogs/HubView.js @@ -0,0 +1,113 @@ +var HubView = ScrollableView.extend({ + + el: "#hub", + template: $("#hub .template").html(), + + events: { + "click .share": "content-share", + "click .store": "store_link", + "click .gallery-left": "gallery_left", + "click .gallery-right": "gallery_right", + "click .play": "play_video", + }, + + initialize: function(){ + this.$content = this.$(".content") + this.$loader = this.$(".loader") + this.scroller = new IScroll('#hub', app.iscroll_options) + }, + + show: function(){ + this.deferScrollToTop() + app.footer.hide() + document.body.className = "hub" + }, + + galleries: {}, + populate: function(data){ + this.data = data + this.$loader.hide() + this.$content.empty() + this.galleries = {} + // id date subtitle body link store image[uri caption] + this.data.forEach(function(row){ + // console.log(row) + var t = this.template.replace(/{{id}}/g, row.id) + .replace(/{{date}}/, moment(row.date).format("MM.DD.YYYY")) + .replace(/{{title}}/, row.title) + .replace(/{{subtitle}}/, row.subtitle) + .replace(/{{link}}/, row.link) + .replace(/{{body}}/, row.body.replace(/\n/g, "
")) + var $t = $(t) + if (row.store != "true") { + $t.find(".store").remove() + } + this.$content.append($t) + + if (row.image.length > 1) { + // image gallery + var $gallery = $(".gallery-" + row.id) + row.image.forEach(function(img){ + var el = document.createElement("div") + el.style.backgroundImage = "url(" + img.uri + ")" + el.className = "item" + $gallery.append(el) + }) + this.galleries[row.id] = new Flickity( ".gallery-" + row.id, { + selector: '.item', + cellAlign: 'center', + autoPlay: false, + freeScroll: false, + wrapAround: true, + imagesLoaded: true, + prevNextButtons: false, + pageDots: false, + contain: true, + draggable: true, + }) + } + else { + // single image + var el = document.createElement("div") + el.style.backgroundImage = "url(" + row.image[0].uri + ")" + el.className = "item" + $(".gallery-" + row.id).append(el) + $(".gallery-" + row.id).data("row", row) + + // video, append play button + if (row.link.match(/youtube|youtu.be|vimeo/)) { + var play = document.createElement("div") + play.className = "play" + $(".gallery-" + row.id).append(play) + } + $t.find(".gallery-left").remove() + $t.find(".gallery-right").remove() + } + + }.bind(this)) + + this.deferScrollToTop() + }, + + store_link: function(){ + app.router.go("store") + }, + play_video: function(e){ + var row = $(e.currentTarget).closest('.gallery-video-post').data("row") + window.open(row.link, '_system') + }, + + gallery_left: function(e){ + var id = $(e.currentTarget).closest(".hub_item").data('id') + this.galleries[id].previous() + }, + gallery_right: function(e){ + var id = $(e.currentTarget).closest(".hub_item").data('id') + this.galleries[id].next() + }, + + share: function(){ + window.plugins.socialsharing.share( this.item['ModelNames'], null, null, "http://stoneisland.com/") + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/blogs/PageView.js b/StoneIsland/platforms/android/assets/www/js/lib/blogs/PageView.js new file mode 100755 index 00000000..4bf05430 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/blogs/PageView.js @@ -0,0 +1,24 @@ +var PageView = ScrollableView.extend({ + + events: { + }, + + initialize: function(opt){ + this.page = opt.page + this.setElement("#" + opt.page) + this.$content = this.$(".content") + this.$loader = this.$(".loader") + this.scroller = new IScroll('#' + this.page, app.iscroll_options) + }, + + show: function(){ + this.deferScrollToTop() + app.footer.hide() + document.body.className = this.page + }, + + populate: function(data){ + this.$content.html(data.body.replace(/\n/g, "
")) + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/blogs/StoryView.js b/StoneIsland/platforms/android/assets/www/js/lib/blogs/StoryView.js new file mode 100755 index 00000000..84684ff7 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/blogs/StoryView.js @@ -0,0 +1,65 @@ +var StoryView = ScrollableView.extend({ + + loaded: false, + + el: "#story", + template: $("#story .template").html(), + + events: { + "click .links li": "pick", + }, + + initialize: function(){ + this.sections = {} + this.$img = this.$("img") + this.$content = this.$(".content") + this.$links = this.$(".links") + this.$loader = this.$(".loader") + this.scroller = new IScroll('#story', app.iscroll_options) + }, + + show: function(){ + this.deferScrollToTop() + app.footer.hide() + document.body.className = "story" + }, + + populate: function(data){ + if (this.loaded) { console.warn("populate called twice"); return } + this.loaded = true + this.data = data + this.$loader.hide() + this.$content.empty() + // id title image[uri caption] body + this.data.forEach(function(row){ + var t = this.template.replace(/{{id}}/, row.id) + .replace(/{{body}}/, row.body.replace(/\n/g, "
")) + var li = document.createElement("li") + li.dataset.id = row.id + li.innerHTML = row.title + this.sections[row.id] = row + this.$links.append(li) + this.$content.append(t) + }.bind(this)) + + this.set_active( this.data[0].id ) + }, + + pick: function(e){ + var id = e.currentTarget.dataset.id + this.set_active(id) + }, + + set_active: function(id){ + this.$links.find(".active").removeClass("active") + this.$links.find("[data-id=" + id + "]").addClass("active") + + this.$content.find(".active").removeClass("active") + this.$content.find("[data-id=" + id + "]").addClass("active") + + var section = this.sections[id] + this.$img.attr("src", section.image.uri) + this.deferScrollToTop() + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/cart/CartConfirm.js b/StoneIsland/platforms/android/assets/www/js/lib/cart/CartConfirm.js new file mode 100755 index 00000000..f6c7f1f5 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/cart/CartConfirm.js @@ -0,0 +1,174 @@ +var CartConfirm = FormView.extend({ + + el: "#cart_confirm", + + template: $("#cart_confirm .template").html(), + + events: { + }, + + initialize: function(opt){ + this.parent = opt.parent + this.$rows = this.$(".rows") + this.$subtotal = this.$(".subtotal") + this.$shipping = this.$(".shipping") + this.$tax = this.$(".tax") + this.$total = this.$(".total") + + this.$shipping_address = this.$(".shipping_address") + this.$shipping_method = this.$(".shipping_method") + + this.$payment_name = this.$(".payment_name") + this.$payment_method = this.$(".payment_method") + this.$payment_address = this.$(".payment_address") + + this.scroller = new IScroll('#cart_confirm', app.iscroll_options) + }, + + show: function(){ + document.body.className = "cart" + app.cart.el.className = "confirm" + app.footer.show("PLACE ORDER", "CANCEL") + window.location.hash = "#/cart/confirm" + this.deferScrollToTop() + + app.curtain.show("loading") + promise(sdk.cart.get_status).then( this.populate.bind(this) ) + }, + + populate: function(data){ + console.log(data) + + data = data.Cart + + this.$rows.empty() + + data.Items.forEach(function(item){ + var $el = $("
") + this.$rows.append($el) + var code_ten = item.Code10 + var size_id = item.Size + + var code = code_ten.substr(0, 8) + app.product.find(code, function(data, details){ + var descriptions = app.product.get_descriptions( details ) + + var name_partz = descriptions['ModelNames'].split(' ') + var num = name_partz.shift() + var title = name_partz.join(' ') + var type = title_case( descriptions['MicroCategory'] ) + + var color_name, size_name + + details.Item.ModelColors.some(function(color){ + if (color['Code10'] == code_ten) { + color_name = color['ColorDescription'] + return true + } + return false + }) + + details.Item.ModelSizes.some(function(size){ + if (size['SizeId'] == size_id) { + // console.log(size) + size_name = size['Default']['Text'] + size_name = SIZE_LOOKUP[ size_name ] || size_name + if (! size_name && ! size['Default']['Labeled']) { + size_name = size['Default']['Text'] + " " + size['Default']['ClassFamily'] + } + + return true + } + return false + }) + +// size_name = item.DefaultSize + " " + item.DefaultSizeClassFamily + + var t = this.template + .replace(/{{image}}/, sdk.image(item['Code10'], '11_f')) + .replace(/{{sku}}/, num) + .replace(/{{title}}/, title) + .replace(/{{type}}/, type) + .replace(/{{size}}/, size_name || "DEFAULT") + .replace(/{{color}}/, color_name || "DEFAULT") + .replace(/{{quantity}}/, 1) + .replace(/{{price}}/, as_cash(details.Item.Price.DiscountedPrice)) + $el.data("price", details.Item.Price.DiscountedPrice) + $el.html(t) + this.refreshScroller() + }.bind(this)) + }.bind(this)) + + var subtotal = data.Totals.TotalWithoutPromotions + var shipping_cost = data.DeliveryMethod.Selected.Amount.Total + var tax = data.Totals.TotalSalesTax + var total = data.Totals.TotalToPay + + this.$subtotal.html( as_cash(subtotal) ) + this.$shipping.html( as_cash(shipping_cost) ) + this.$tax.html( as_cash(tax) ) + this.$total.html( as_cash(total) ) + + var street = data.Receiver.StreetWithNumber.replace(/\n$/,"").replace("\n", ", ") + var address = data.Receiver.Name.toUpperCase() + " " + data.Receiver.Surname.toUpperCase() + "
" + street + ", " + address += data.Receiver.City + ", " + data.Receiver.Region + " " + data.Receiver.PostalCode + + this.$shipping_address.html(address) + this.$shipping_method.html(data.DeliveryMethod.Selected.Type == 1 ? "* STANDARD SHIPPING" : "* EXPRESS SHIPPING") + + var cc = data.Payment.CreditCard + var cc_street = cc.HolderAddress.replace(/\n$/,"").replace("\n", ", ") + var cc_type = cc.Type == "AmericanExpress" ? "American Express" : cc.Type + + this.$payment_name.html( cc.HolderName.toUpperCase() + " " + cc.HolderSurname.toUpperCase() ) + this.$payment_method.html( cc_type.toUpperCase() + " XXXX-XXXX-XXXX-" + cc.Last4 ) + + app.curtain.hide("loading") + }, + + save: function(){ + promise(sdk.cart.finalize, {}).then(function(){ + app.router.go('cart/thanks') + }.bind(this)).error(function(data){ + // {"Header":{"StatusCode":403,"Description":"403 Forbidden"},"Error":{"Description":"GenericApiError:CartAlreadyClosed"}} + // {"Header":{"StatusCode":409,"Description":"304 NotModified"},"Error":{"Description":"FinalizationError:\\"Item has been removed from cart because it is no longer available.\\"\\n235"}}' + // {"Header":{"StatusCode":409,"Description":"304 NotModified"},"Error":{"Description":"FinalizationError:\"The cart cannot be empty.\"\n233"}} + // {"Header":{"StatusCode":409,"Description":"304 NotModified"},"Error":{"Description":"FinalizationError:\"The reciever validation fails."}} + // {"Header":{"StatusCode":440,"Description":"304 NotModified"},"Error":{"Description":"GenericApiError:CartFinalizationNotYetCompleted"}} + // {"Header":{"StatusCode":441,"Description":"304 NotModified"},"Error":{"Description":"GenericApiError:EmptyCreditCard"}} + switch (data.StatusCode) { + case 403: // cart already closed + auth.clear_cart(auth.create_cart) + app.router.go('thanks') + break + case 409: // finalization error + this.finalization_error(data) + break + case 440: // genericapierror (credit card error!) + case 441: // genericapierror (credit card empty) + app.router.go('cart/payment') + app.cart.payment.show_errors([["Number","There was a problem with your credit card."]]) + break + } + }.bind(this)) + }, + + finalization_error: function(data){ + if (data['Error']['Description'].match(/receiver validation fails/)) { + app.router.go('cart/shipping') + app.cart.payment.show_errors([["Number","There was a problem with your credit card."]]) + } + else if (data['Error']['Description'].match(/cart cannot be empty/)) { + app.router.go('cart/summary') + } + else if (data['Error']['Description'].match(/Item has been removed/)) { + app.router.go('cart/error') + app.cart.error.show_error("We're sorry, but one or more items was out of stock. Please check your cart and try again.") + } + }, + + cancel: function(){ + app.router.go('cart/payment') + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/cart/CartError.js b/StoneIsland/platforms/android/assets/www/js/lib/cart/CartError.js new file mode 100755 index 00000000..f9a1963e --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/cart/CartError.js @@ -0,0 +1,28 @@ +var CartError = View.extend({ + + el: "#cart_error", + + events: { + }, + + initialize: function(opt){ + this.parent = opt.parent + this.$error = this.$(".errrrrrrrrrrrrrrr") + }, + + show: function(){ + document.body.className = "cart" + app.cart.el.className = "error" + app.footer.show("< BACK TO CART") + app.footer.hide() + }, + + show_error: function(msg){ + this.$error.html(msg) + }, + + ok: function(){ + app.router.go("cart/summary") + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/cart/CartPayment.js b/StoneIsland/platforms/android/assets/www/js/lib/cart/CartPayment.js new file mode 100755 index 00000000..f3c54d55 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/cart/CartPayment.js @@ -0,0 +1,185 @@ +var CartPayment = FormView.extend({ + + el: "#cart_payment", + + address_template: $("#cart_payment .address_row_template").html(), + cc_template: $("#cart_payment .cc_template").html(), + + action: sdk.cart.set_credit_card, + + address_list_mode: false, + cc_list_mode: false, + data: {}, + + events: { + "change [name=SameAsShipping]": "toggle_shipping", + "click .address_dropdown": "toggle_address", + "click .cc_dropdown": "toggle_cc", + }, + + initialize: function(opt){ + this.parent = opt.parent + this.$form = this.$("form") + this.$msg = this.$(".msg") + this.$same_as_shipping = this.$("[name=SameAsShipping]") + this.$billing_address_rapper = this.$(".billing_address_rapper") + this.$address_list = this.$(".address_list") + this.$address_form = this.$(".address") + this.$address_dropdown = this.$(".address_dropdown") + this.$cc_list = this.$(".cc_list") + this.$cc_form = this.$(".cc") + this.$cc_dropdown = this.$(".cc_dropdown") + this.$cc_confirm = this.$(".cc_confirm") + + this.address = new AddressView ({ parent: this, checkPhone: false }) + this.cc = new CreditCardView ({ parent: this }) + this.scroller = new IScroll('#cart_payment', app.iscroll_options) + this.address.disabled = true + this.cc.disabled = true + }, + + show: function(){ + document.body.className = "cart" + app.cart.el.className = "payment" + app.footer.show("CONFIRM >", "CANCEL") + window.location.hash = "#/cart/payment" + + this.populate() + this.deferScrollToTop() + }, + + toggle_shipping: function(){ + setTimeout(function(){ + var state = this.$same_as_shipping.prop("checked") + this.$billing_address_rapper.toggle( ! state ) + this.address.disabled = state + }.bind(this)) + }, + + toggle_address: function(state){ + if (! app.account.ccs.length) { + state = false + } + // this.$address_dropdown.toggle( !! app.account.ccs.length ) + + this.address_list_mode = typeof state == "boolean" ? state : ! this.list_mode + this.address.disabled = this.address_list_mode + this.$address_form.toggle(! this.address_list_mode) + this.$address_list.toggle(this.address_list_mode) + }, + + toggle_cc: function(state){ + if (! app.account.ccs.length) { + state = false + } + // this.$cc_dropdown.toggle( !! app.account.ccs.length ) + + this.cc_list_mode = typeof state == "boolean" ? state : ! this.cc_list_mode + this.cc.disabled = this.cc_list_mode + this.$cc_form.toggle(! this.cc_list_mode) + this.$cc_list.toggle(this.cc_list_mode) + this.$cc_confirm.toggle(this.cc_list_mode) + }, + + populate: function(){ + this.$(".save_as_default").show() + this.$address_list.empty() + this.$cc_list.empty() + this.toggle_address( !! app.account.ccs.length ) + this.toggle_cc( !! app.account.ccs.length ) + + app.account.ccs.forEach(function(cc){ + var address_t = this.address_template.replace(/{{id}}/g, cc.Id) + .replace(/{{checked}}/g, cc.IsDefault ? "checked" : "") + .replace(/{{name}}/g, (cc.Name + " " + cc.Surname).toUpperCase()) + .replace(/{{address}}/g, cc.Address.replace(/\n$/,"").replace("\n", ", ")) + .replace(/{{city}}/g, cc.City) + .replace(/{{state}}/g, cc.Province) + .replace(/{{zip}}/g, cc.ZipCode) + + var cc_t = this.cc_template.replace(/{{id}}/g, cc.Id) + .replace(/{{checked}}/g, cc.IsDefault ? "checked" : "") + .replace(/{{number}}/g, cc['Number']) + .replace(/{{type}}/g, cc.Type.toUpperCase()) + .replace(/{{exp}}/g, cc.ExpirationMonth + "/" + cc.ExpirationYear) + + this.$address_list.append(address_t) + this.$cc_list.append(cc_t) + }.bind(this)) + }, + + finalize: function(data){ + var shipping_info = {}, address_data, address_id, cc_info = {}, cc_data, cc_id + var shipping_type = $("[name=ShippingType]").filter(function(){ return $(this).prop("checked") }).val() + + if (this.$same_as_shipping.prop("checked")) { + address_data = app.cart.shipping.data + } + else if (this.address_list_mode) { + address_id = this.$("[name=AddressId]").filter(function(){ return $(this).prop("checked") }).val() + address_data = app.account.addressLookup[ address_id ] + } + else { + address_data = data + } + + if (this.cc_list_mode) { + cc_id = this.$("[name=CCId]").filter(function(){ return $(this).prop("checked") }).val() + cc_data = app.account.ccLookup[ cc_id ] + + var card_on_file = { + "guid": cc_data.Guid, + "cvv": this.$("[name=CvvConfirm]"), + } + + app.curtain.show("loading") + promise(sdk.cart.use_stored_credit_card, { data: card_on_file }).then(function(data){ + app.curtain.hide("loading") + this.success() + }.bind(this)).error(function(data){ + app.curtain.hide("loading") + console.log(data) + }.bind(this)) + + return + } + else { + cc_data = data + } + + var credit_info = { + "HolderName": address_data.Name, + "HolderSurname": address_data.Surname, + "HolderAddress": address_data.Address || address_data.StreetWithNumber, + "HolderCity": address_data.City, + "HolderProvince": address_data.Province, + "HolderZip": address_data.PostalCode || address_data.ZipCode, + "HolderISOCountry": CANADIAN_LOOKUP[ address_data.Province ] ? "CA" : "US", + "HolderEmail": auth.user.Email, + "CardNumber": cc_data['Number'], + "Type": cc_data.Type, + "ExpirationMonth": cc_data.ExpirationMonth, + "ExpirationYear": cc_data.ExpirationYear.substr(2,3), + "Cvv": cc_data.Cvv, + } + + console.log( credit_info ) + + return credit_info + }, + + success: function(){ + app.router.go('cart/confirm') + }, + + error: function(data){ + console.log(data) + app.cart.payment.show_errors([["Number","There was a problem with your credit card."]]) + }, + + cancel: function(){ + app.router.go('cart/shipping') + }, + + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/cart/CartShipping.js b/StoneIsland/platforms/android/assets/www/js/lib/cart/CartShipping.js new file mode 100755 index 00000000..f17d42d2 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/cart/CartShipping.js @@ -0,0 +1,136 @@ +var CartShipping = FormView.extend({ + + el: "#cart_shipping", + + action: sdk.cart.set_shipping_address, + + list_mode: true, + data: {}, + + template: $("#cart_shipping .template").html(), + + events: { + "click .dropdown-wrapper": "toggle_dropdown", + }, + + initialize: function(opt){ + this.parent = opt.parent + this.$form = this.$("form") + this.$dropdown_wrapper = this.$(".dropdown-wrapper") + this.$address_list = this.$(".address_list") + this.$address_form = this.$(".address") + this.$msg = this.$(".msg") + this.address = new AddressView ({ parent: this }) + this.scroller = new IScroll('#cart_shipping', app.iscroll_options) + this.address.disabled = true + }, + + show: function(){ + document.body.className = "cart" + app.cart.el.className = "shipping" + app.footer.show("PAYMENT >", "CANCEL") + window.location.hash = "#/cart/shipping" + this.populate() + this.deferScrollToTop() + }, + + populate: function(){ + // id checked name address city state zip + this.$(".save_as_default").show() + this.$address_list.empty() + if (! app.account.addresses.length) { + this.toggle_dropdown(false) + return + } + app.account.addresses.forEach(function(address){ + var t = this.template.replace(/{{id}}/g, address.Id) + .replace(/{{checked}}/g, address.IsDefault ? "checked" : "") + .replace(/{{name}}/g, (address.Name + " " + address.Surname).toUpperCase()) + .replace(/{{address}}/g, address.Address.replace(/\n$/,"").replace("\n", ", ")) + .replace(/{{city}}/g, address.City) + .replace(/{{state}}/g, address.Province) + .replace(/{{zip}}/g, address.ZipCode) + this.$address_list.append(t) + }.bind(this)) + }, + + load_form: function(cart_data){ + var data = cart_data.Cart.Receiver + var addy = data.StreetWithNumber.split("\n") + data.Address1 = addy[0] || "" + data.Address2 = addy[1] || "" + data.ZipCode = data.PostalCode + data.Province = data.Region + this.load_data(data) + + this.data = data + if (cart_data.Cart.DeliveryMethod && cart_data.Cart.DeliveryMethod.Selected && cart_data.Cart.DeliveryMethod.Type) { + $("#standard-shipping").prop("checked", cart_data.Cart.DeliveryMethod.Type == 1) + $("#express-shipping").prop("checked", cart_data.Cart.DeliveryMethod.Type == 2) + } + }, + + toggle_dropdown: function(state){ + if (! app.account.addresses.length) { + state = false + } + this.list_mode = typeof state == "boolean" ? state : ! this.list_mode + this.$dropdown_wrapper.toggle( !! app.account.addresses.length ) + this.address.disabled = this.list_mode + this.$address_form.toggle(! this.list_mode) + this.$address_list.toggle(this.list_mode) + }, + + // sdk.cart.set_shipping_address + // sdk.shipping.get_delivery_types + // sdk.shipping.set_delivery_type + + shipping_types: { + Standard: 1, + Express: 2, + }, + + finalize: function(data){ + var shipping_info = {}, address_data, address_id + var shipping_type = $("[name=ShippingType]").filter(function(){ return $(this).prop("checked") }).val() + + sdk.shipping.set_delivery_type({ + id: this.shipping_types[shipping_type], + success: function(data){ console.log("set shipping type", data) }, + error: function(data){ console.log("didnt set shipping type", data) }, + }) + + if (this.list_mode) { + address_id = this.$("[name=AddressId]").filter(function(){ return $(this).prop("checked") }).val() + address_data = app.account.addressLookup[ address_id ] + } + else { + address_data = data + } + + shipping_info.Name = address_data.Name + shipping_info.Surname = address_data.Surname + shipping_info.Email = auth.user.Email + shipping_info.Phone = address_data.Phone + shipping_info.Mobile = address_data.Phone + shipping_info.StreetWithNumber = address_data.Address + shipping_info.PostalCode = address_data.ZipCode + shipping_info.City = address_data.City + shipping_info.Province = address_data.Province + shipping_info.Region = address_data.Province + shipping_info.CountryCode = CANADIAN_LOOKUP[ address_data.Province ] ? "CA" : "US" + + this.data = shipping_info + + return shipping_info + }, + + success: function(){ + app.router.go('cart/payment') + }, + + cancel: function(){ + app.router.go('cart/summary') + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/cart/CartSummary.js b/StoneIsland/platforms/android/assets/www/js/lib/cart/CartSummary.js new file mode 100755 index 00000000..ff1e001f --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/cart/CartSummary.js @@ -0,0 +1,202 @@ +var CartSummary = ScrollableView.extend({ + + el: "#cart_summary", + + template: $("#cart_summary .template").html(), + + events: { + "click .remove": "remove_item", + }, + + data: null, + + initialize: function(opt){ + this.parent = opt.parent + this.$loader = this.$(".loader") + this.$cart_body = this.$(".cart_body") + this.$cart_empty = this.$(".cart_empty") + this.scroller = new IScroll('#cart_summary', app.iscroll_options) + + this.$rows = this.$(".rows") + this.$subtotal = this.$(".subtotal") + this.$shipping = this.$(".shipping") + this.$tax = this.$(".tax") + this.$total = this.$(".total") + }, + + show: function(){ + document.body.className = "cart" + app.cart.el.className = "summary" + window.location.hash = "#/cart/summary" + if (auth.has_cart()) { + this.load() + } + else { + this.empty() + } + }, + + load: function(){ + this.el.className = "loading" + app.footer.show("SHIPPING >", "CANCEL") + app.curtain.show("loading") + sdk.cart.get_status({ + success: this.populate.bind(this), + error: this.empty.bind(this), + }) + }, + + populate: function(data){ + this.data = data + + console.log("CART", data) + + if (! data.Cart.Items || data.Cart.Items.length == 0) { + return this.empty() + } + + this.parent.$steps.show() + this.updateCounts() + + this.$rows.empty() + + data.Cart.Items.forEach(function(item){ + var code_ten = item['Code10'] + var code = code_ten.substr(0, 8) + var size_id = item['Size'] + + var $el = $("
").addClass("cart_item_row") + $el.html("") + $el.data({ + code: code_ten, + size: size_id, + }) + this.$rows.append($el) + app.product.find(code, function(data, details){ + // console.log(data, details) + + var descriptions = app.product.get_descriptions( details ) + // console.log(descriptions) + + var name_partz = descriptions['ModelNames'].split(' ') + var num = name_partz.shift() + var title = name_partz.join(' ') + var type = title_case( descriptions['MicroCategory'] ) + + var color_name, size_name + // console.log(code) + details.Item.ModelColors.some(function(color){ + if (color['Code10'] == code_ten) { + color_name = color['ColorDescription'] + // console.log(color) + return true + } + return false + }) + details.Item.ModelSizes.some(function(size){ + if (size['SizeId'] == size_id) { + // console.log(size) + size_name = size['Default']['Text'] + size_name = SIZE_LOOKUP[ size_name ] || size_name + if (! size_name && ! size['Default']['Labeled']) { + size_name = size['Default']['Text'] + " " + size['Default']['ClassFamily'] + } + + return true + } + return false + }) + + var t = this.template + .replace(/{{image}}/, sdk.image(item['Code10'], '11_f')) + .replace(/{{sku}}/, num) + .replace(/{{title}}/, title) + .replace(/{{type}}/, type) + .replace(/{{size}}/, size_name) + .replace(/{{color}}/, color_name) + .replace(/{{quantity}}/, 1) + .replace(/{{price}}/, as_cash(details.Item.Price.DiscountedPrice)) + $el.html(t) + this.refreshScroller() + }.bind(this)) + }.bind(this)) + + if (data.Cart.Receiver && data.Cart.Receiver.City) { + app.cart.shipping.load_form( data ) + } + + this.updateTotals() + + this.el.className = "full" + this.refreshScroller() + app.curtain.hide("loading") + }, + + updateCounts: function(){ + app.header.set_cart_count( this.data.Cart.Items.length ) + this.parent.setHeaderCount( this.data.Cart.Items.length ) + }, + + updateTotals: function(){ + var subtotal = this.data.Cart.Totals.TotalWithoutPromotions + var shipping_cost = this.data.Cart.DeliveryMethod.Selected.Amount.Total + var tax = this.data.Cart.Totals.TotalSalesTax + var total = this.data.Cart.Totals.TotalToPay + + this.$subtotal.html( as_cash(subtotal) ) + this.$shipping.html( as_cash(shipping_cost) ) + this.$tax.html( as_cash(tax) ) + this.$total.html( as_cash(total) ) + }, + + empty: function(){ + app.footer.hide() + app.header.set_cart_count(0) + this.parent.setHeaderCount( 0 ) + this.parent.$itemcount.html("0 ITEMS") + this.el.className = "empty" + this.parent.$steps.hide() + }, + + save: function(){ + app.router.go('cart/shipping') + }, + + cancel: function(){ + app.router.go('intro') + }, + + remove_item: function(e){ + var $el = $( e.currentTarget ).closest(".cart_item_row") + var data = $el.data() + + console.log(this.data.Cart) + + this.data.Cart.Totals.TotalWithoutPromotions -= data.price + this.data.Cart.Totals.TotalToPay -= data.price + this.data.Cart.Items = this.data.Cart.Items.filter(function(item){ + return ( item['Code10'] !== data.code || item['Size'] !== data.size) + }) + + this.updateTotals() + this.updateCounts() + $el.remove() + this.refreshScroller() + + if (this.data.Cart.Items.length == 0) { + this.empty() + } + + app.curtain.show("loading") + sdk.cart.delete_item({ + data: { + Code10: data.code, + Size: data.size, + }, + success: function(){ + app.curtain.hide("loading") + }, + }) + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/cart/CartThanks.js b/StoneIsland/platforms/android/assets/www/js/lib/cart/CartThanks.js new file mode 100755 index 00000000..eb95197b --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/cart/CartThanks.js @@ -0,0 +1,25 @@ +var CartThanks = View.extend({ + + el: "#cart_thanks", + + events: { + }, + + initialize: function(opt){ + this.parent = opt.parent + }, + + show: function(){ + document.body.className = "cart" + app.cart.el.className = "thanks" + app.footer.show("< BACK TO COLLECTION") + app.footer.hide() + + app.orders.loaded = false + }, + + ok: function(){ + app.router.go("store") + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/cart/CartView.js b/StoneIsland/platforms/android/assets/www/js/lib/cart/CartView.js new file mode 100755 index 00000000..1b08e418 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/cart/CartView.js @@ -0,0 +1,66 @@ +var CartView = View.extend({ + + el: "#cart", + + events: { + "click .summary_step": "show_summary", + "click .shipping_step": "show_shipping", + "click .payment_step": "show_payment", + }, + + initialize: function(){ + this.summary = new CartSummary ({ parent: this }) + this.payment = new CartPayment ({ parent: this }) + this.shipping = new CartShipping ({ parent: this }) + this.confirm = new CartConfirm ({ parent: this }) + this.thanks = new CartThanks ({ parent: this }) + this.error = new CartError ({ parent: this }) + + this.$steps = this.$(".steps") + this.$full_msg = this.$(".full_msg") + this.$empty_msg = this.$(".empty_msg") + this.$itemcount = this.$(".itemcount") + }, + + load: function(){ + sdk.cart.get_status({ + success: function(data){ + this.summary.data = data + this.summary.updateCounts() + }.bind(this), + error: function(data){ + console.log(data) + }, + }) + }, + + show: function(){ + document.body.className = "cart" + this.show_summary() + }, + + show_summary: function(){ + this.summary.show() + }, + + show_shipping: function(){ + this.shipping.show() + }, + + show_payment: function(){ + this.payment.show() + }, + + setHeaderCount: function(n){ + if (n) { + this.$itemcount.html(pluralize(n, "ITEM", "S")) + this.$full_msg.show() + this.$empty_msg.hide() + } + else { + this.$full_msg.hide() + this.$empty_msg.show() + } + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/etc/deeplink.js b/StoneIsland/platforms/android/assets/www/js/lib/etc/deeplink.js new file mode 100755 index 00000000..648dd167 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/etc/deeplink.js @@ -0,0 +1,3 @@ +function handleOpenURL (url) { + app.router.initial_route = url +} \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/etc/geo.js b/StoneIsland/platforms/android/assets/www/js/lib/etc/geo.js new file mode 100755 index 00000000..fac34c1e --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/etc/geo.js @@ -0,0 +1,39 @@ +var geo = (function(){ + var geo = {} + + geo.fetch = function(){ + navigator.geolocation.getCurrentPosition(geo.success, geo.error, {timeout: 15000}) + } + + geo.success = function(position){ + var lat_str = as_degrees( position.coords.latitude || 40.99167 ) + var lng_str = as_degrees( position.coords.longitude || -74.07944 ) + $(".latlng").html( lat_str + " " + lng_str ) + } + + geo.error = function(error){ + $(".latlng").html( "+40° 58' 90\" -74° 04' 46\"" ) + } + + function as_degrees (n) { + var s = "" + if (n >= 0) s += "+" + s += Math.floor(n) + "° " + + n = Math.abs(n) + n %= 1 + n *= 60 + nn = Math.floor(n) + if (nn < 10) nn = "0" + nn + s += nn + "' " + + n %= 1 + n *= 60 + nn = Math.floor(n) + if (nn < 10) nn = "0" + nn + s += nn + '"' + return s + } + + return geo +})() \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/etc/push.js b/StoneIsland/platforms/android/assets/www/js/lib/etc/push.js new file mode 100755 index 00000000..ab0c0141 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/etc/push.js @@ -0,0 +1 @@ +// \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/nav/AddressView.js b/StoneIsland/platforms/android/assets/www/js/lib/nav/AddressView.js new file mode 100755 index 00000000..ad5745fb --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/nav/AddressView.js @@ -0,0 +1,267 @@ + +var AddressView = SerializableView.extend({ + + template: $("#address_template").html(), + + disabled: false, + + events: { + "change [name=Province]": 'update_country', + }, + + initialize: function(opt){ + this.parent = opt.parent + this.checkPhone = 'checkPhone' in opt ? opt.checkPhone : true + this.setElement( this.parent.$(".address") ) + this.$el.html(this.template) + }, + + populate: function(data){ + this.data = data + var address = data.Address.split("\n") + data.Address1 = address[0] + data.Address2 = address[1] + this.$(".address input").val("") + this.load_data(data) + this.update_country() + }, + + validate_presence: { + "Name": "Please enter your first name.", + "Surname": "Please enter your last name.", + "Address1": "Please enter your street address.", + "City": "Please enter your city.", + "ZipCode": "Please enter your zip code.", + }, + + validate_fields: function(data, errors){ + if (this.disabled) { return } + if (this.checkPhone && ! data.Phone) { errors.push([ "Phone", "Please enter your phone number." ]) } + if (this.checkPhone && data.Phone && data.Phone.replace(/[^0-9]/g, "").length < 10) { errors.push([ "Phone", "Phone numbers must be at least 10 digits." ]) } + if (! data.Province || data.Province == "NONE") { errors.push([ "Province", "Please choose your state." ]) } + data.Address = data.Address1 + "\n" + data.Address2 + data.UserId = auth.user_id + delete data.Address1 + delete data.Address2 + }, + + update_country: function(){ + var state = this.$("[name=Province]").val() + console.log(state) + if (CANADIAN_LOOKUP[state]) { + this.$(".country-label").html("CANADA") + } + else { + this.$(".country-label").html("UNITED STATES") + } + }, + +}) + +var CANADIAN_PROVINCES = "AB BC MB NB NL NS NT NU ON PE SK QC YT".split(" ") +var CANADIAN_LOOKUP = {} +CANADIAN_PROVINCES.forEach(function(k){ CANADIAN_LOOKUP[k] = true }) + +var COUNTRIES = [ + ['Country Name', 'NONE'], + ['United States', 'US'], + ['Abkhazia', 'GE'], + ['Afghanistan', 'AF'], + ['Albania', 'AL'], + ['Algeria', 'DZ'], + ['Andorra', 'AD'], + ['Angola', 'AO'], + ['Antigua and Barbuda', 'AG'], + ['Argentina', 'AR'], + ['Armenia', 'AM'], + ['Australia', 'AU'], + ['Austria', 'AT'], + ['Azerbaijan', 'AZ'], + ['Bahamas', 'BS'], + ['Bahrain', 'BH'], + ['Bangladesh', 'BD'], + ['Barbados', 'BB'], + ['Belarus', 'BY'], + ['Belgium', 'BE'], + ['Belize', 'BZ'], + ['Benin', 'BJ'], + ['Bhutan', 'BT'], + ['Bolivia', 'BO'], + ['Bosnia and Herzegovina', 'BA'], + ['Botswana', 'BW'], + ['Brazil', 'BR'], + ['Brunei', 'BN'], + ['Bulgaria', 'BG'], + ['Burkina Faso', 'BF'], + ['Burundi', 'BI'], + ['Cambodia', 'KH'], + ['Cameroon', 'CM'], + ['Canada', 'CA'], + ['Cape Verde', 'CV'], + ['Central African Republic', 'CF'], + ['Chad', 'TD'], + ['Chile', 'CL'], + ['China', 'CN'], + ['Colombia', 'CO'], + ['Comoros', 'KM'], + ['Congo', 'CD'], + ['Congo-Brazzaville', 'CG'], + ['Costa Rica', 'CR'], + ['Cote d\'Ivoire (Ivory Coast)', 'CI'], + ['Croatia', 'HR'], + ['Cuba', 'CU'], + ['Cyprus', 'CY'], + ['Czech Republic', 'CZ'], + ['Denmark', 'DK'], + ['Djibouti', 'DJ'], + ['Dominica', 'DM'], + ['Dominican Republic', 'DO'], + ['Ecuador', 'EC'], + ['Egypt', 'EG'], + ['El Salvador', 'SV'], + ['Equatorial Guinea', 'GQ'], + ['Eritrea', 'ER'], + ['Estonia', 'EE'], + ['Ethiopia', 'ET'], + ['Fiji', 'FJ'], + ['Finland', 'FI'], + ['France', 'FR'], + ['Gabon', 'GA'], + ['Gambia', '220'], + ['Georgia', 'GE'], + ['Germany', 'DE'], + ['Ghana', 'GH'], + ['Greece', 'GR'], + ['Grenada', 'GD'], + ['Guatemala', 'GT'], + ['Guinea', 'GN'], + ['Guinea-Bissau', 'GW'], + ['Guyana', 'GY'], + ['Haiti', 'HT'], + ['Honduras', 'HN'], + ['Hungary', 'HU'], + ['Iceland', 'IS'], + ['India', 'IN'], + ['Indonesia', 'ID'], + ['Iran', 'IR'], + ['Iraq', 'IQ'], + ['Ireland', 'IE'], + ['Israel', 'IL'], + ['Italy', 'IT'], + ['Jamaica', 'JM'], + ['Japan', 'JP'], + ['Jordan', 'JO'], + ['Kazakhstan', 'KZ'], + ['Kenya', 'KE'], + ['Kiribati', 'KI'], + ['Kuwait', 'KW'], + ['Kyrgyzstan', 'KG'], + ['Laos', 'LA'], + ['Latvia', 'LV'], + ['Lebanon', 'LB'], + ['Lesotho', 'LS'], + ['Liberia', 'LR'], + ['Libya', 'LY'], + ['Liechtenstein', 'LI'], + ['Lithuania', 'LT'], + ['Luxembourg', 'LU'], + ['Macedonia', 'MK'], + ['Madagascar', 'MG'], + ['Malawi', 'MW'], + ['Malaysia', 'MY'], + ['Maldives', 'MV'], + ['Mali', 'ML'], + ['Malta', 'MT'], + ['Marshall Islands', 'MH'], + ['Mauritania', 'MR'], + ['Mauritius', 'MU'], + ['Mexico', 'MX'], + ['Micronesia', 'FM'], + ['Moldova', 'MD'], + ['Monaco', 'MC'], + ['Mongolia', 'MN'], + ['Montenegro', 'ME'], + ['Morocco', 'MA'], + ['Mozambique', 'MZ'], + ['Myanmar', 'MM'], + ['Nagorno-Karabakh', 'AZ'], + ['Namibia', 'NA'], + ['Nauru', 'NR'], + ['Nepal', 'NP'], + ['Netherlands', 'NL'], + ['New Zealand', 'NZ'], + ['Nicaragua', 'NI'], + ['Niger', 'NE'], + ['Nigeria', 'NG'], + ['North Korea', 'KP'], + ['Northern Cyprus', 'CY'], + ['Norway', 'NO'], + ['Oman', 'OM'], + ['Pakistan', 'PK'], + ['Palau', 'PW'], + ['Panama', 'PA'], + ['Papua New Guinea', 'PG'], + ['Paraguay', 'PY'], + ['Peru', 'PE'], + ['Philippines', 'PH'], + ['Poland', 'PL'], + ['Portugal', 'PT'], + ['Qatar', 'QA'], + ['Romania', 'RO'], + ['Russia', 'RU'], + ['Rwanda', 'RW'], + ['Saint Kitts and Nevis', 'KN'], + ['Saint Lucia', 'LC'], + ['Saint Vincent and the Grenadines', 'VC'], + ['Samoa', 'WS'], + ['San Marino', 'SM'], + ['Sao Tome and Principe', 'ST'], + ['Saudi Arabia', 'SA'], + ['Senegal', 'SN'], + ['Serbia', 'RS'], + ['Seychelles', 'SC'], + ['Sierra Leone', 'SL'], + ['Singapore', 'SG'], + ['Slovakia', 'SK'], + ['Slovenia', 'SI'], + ['Solomon Islands', 'SB'], + ['Somalia', 'SO'], + ['Somaliland', 'SO'], + ['South Africa', 'Rand'], + ['South Korea', 'KR'], + ['South Ossetia', 'GE'], + ['Spain', 'ES'], + ['Sri Lanka', 'LK'], + ['Sudan', 'SD'], + ['Suriname', 'SR'], + ['Swaziland', 'SZ'], + ['Sweden', 'SE'], + ['Switzerland', 'CH'], + ['Syria', 'SY'], + ['Taiwan', 'TW'], + ['Tajikistan', 'TJ'], + ['Tanzania', 'TZ'], + ['Thailand', 'TH'], + ['Timor-Leste', 'TL'], + ['Togo', 'TG'], + ['Tonga', 'TO'], + ['Transnistria', 'MD'], + ['Trinidad and Tobago', 'TT'], + ['Tunisia', 'TN'], + ['Turkey', 'TR'], + ['Turkmenistan', 'TM'], + ['Tuvalu', 'TV'], + ['Uganda', 'UG'], + ['Ukraine', 'UA'], + ['United Arab Emirates', 'AE'], + ['United Kingdom', 'GB'], + ['Uruguay', 'UY'], + ['Uzbekistan', 'UZ'], + ['Vanuatu', 'VU'], + ['Vatican City', 'VA'], + ['Venezuela', 'VE'], + ['Vietnam', 'VN'], + ['Yemen', 'YE'], + ['Zambia', 'ZM'], + ['Zimbabwe', 'ZW'], +] diff --git a/StoneIsland/platforms/android/assets/www/js/lib/nav/CreditCardView.js b/StoneIsland/platforms/android/assets/www/js/lib/nav/CreditCardView.js new file mode 100755 index 00000000..63784618 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/nav/CreditCardView.js @@ -0,0 +1,61 @@ + +var CreditCardView = SerializableView.extend({ + + template: $("#creditcard_template").html(), + + cardOptions: { + accept: ['visa', 'mastercard', 'amex', 'jcb'], + }, + + events: { + }, + + initialize: function(opt){ + this.parent = opt.parent + this.setElement( this.parent.$(".cc") ) + this.$el.html(this.template) + + this.$number = this.$("[name=Number]") + this.$number.validateCreditCard(this.updateCard.bind(this), this.cardOptions) + }, + + populate: function(data){ + this.data = data + data.Number = "XXXX XXXX XXXX " + data.Number + this.$number.attr("type", "text") + this.parent.$(".cc input").val("") + this.$(".cc input").val("") + this.load_data(data) + }, + + updateCard: function(card){ + // console.log(card) + // card.card_type.name + // card.card_type.valid + }, + + validate_presence: { + 'Number': 'Please enter your credit card number.', + 'Cvv': 'Please enter your security code.', + }, + + validate_fields: function(data, errors){ + if (this.disabled) { return } + var card = this.$number.validateCreditCard(this.cardOptions) + if (! card.valid) { errors.push([ "Number", "Your card number is invalid." ]) } + if (! data.ExpirationMonth || data.ExpirationMonth == "NONE") { errors.push([ "ExpirationMonth", "Please enter the expiration month." ]) } + if (! data.ExpirationYear || data.ExpirationYear == "NONE") { errors.push([ "ExpirationYear", "Please select the expiration month." ]) } + data.UserId = auth.user_id + if (card.valid) { + data.Type = YOOX_CREDIT_CARD_NAME_LOOKUP[ card.card_type.name ] + } + }, + +}) + +var YOOX_CREDIT_CARD_NAME_LOOKUP = { + "visa": "Visa", + "mastercard": "Mastercard", + "amex": "AmericanExpress", + "jcb": "JCB", +} diff --git a/StoneIsland/platforms/android/assets/www/js/lib/nav/CurtainView.js b/StoneIsland/platforms/android/assets/www/js/lib/nav/CurtainView.js new file mode 100755 index 00000000..d444fd60 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/nav/CurtainView.js @@ -0,0 +1,39 @@ +var CurtainView = View.extend({ + + el: "#curtain", + + events: { + "click": "click", + }, + + initialize: function(){ + }, + + klass: null, + show: function(klass){ + this.$el.addClass("visible") + if (klass) { + this.klass = klass + this.$el.addClass(klass) + } + }, + + hide: function(k){ + this.$el.removeClass("visible") + if (this.klass) { + setTimeout( function(){ + this.$el.removeClass(this.klass) + }.bind(this), 200 ) + } + }, + + click: function(){ + if (document.body.classList.contains("nav")) { + app.nav.hide() + } + if (app.selector.visible) { + app.selector.hide() + } + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/nav/FooterView.js b/StoneIsland/platforms/android/assets/www/js/lib/nav/FooterView.js new file mode 100755 index 00000000..74b249e6 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/nav/FooterView.js @@ -0,0 +1,40 @@ +var FooterView = View.extend({ + + el: "#footer", + + events: { + "click .ok": "ok", + "click .cancel": "cancel", + }, + + initialize: function(){ + this.$ok = this.$(".ok") + this.$cancel = this.$(".cancel") + }, + + show: function(ok, cancel){ + if (cancel) { + this.$ok.removeClass("wide") + this.$cancel.show().html(cancel) + } + else { + this.$ok.addClass("wide") + this.$cancel.hide() + } + this.$ok.html(ok) + this.$el.show() + }, + + hide: function(){ + this.$el.hide() + }, + + ok: function(){ + (app.view.save || app.view.ok).bind(app.view)() + }, + + cancel: function(){ + app.view.cancel ? app.view.cancel() : app.intro.show() + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/nav/HeaderView.js b/StoneIsland/platforms/android/assets/www/js/lib/nav/HeaderView.js new file mode 100755 index 00000000..b2f01208 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/nav/HeaderView.js @@ -0,0 +1,57 @@ +var HeaderView = View.extend({ + + el: "#header", + + events: { + "click .burger": "nav", + "click .logo": "logo", + "click .cart": "cart", + }, + + initialize: function(){ + this.$burger = this.$(".burger") + this.$cart = this.$(".cart") + this.$cart_count = this.$(".cart_count") + }, + + back_state: false, + set_back: function(state){ + this.back_state = state + if (state) { + this.$burger[0].className = "burger ion-ios-arrow-left" + } + else { + this.$burger[0].className = "burger ion-android-menu" + } + }, + + nav: function(){ + if (this.back_state) { + app.view.back() + } + else { + app.nav.show() + } + }, + + logo: function(){ + app.router.go("intro") + }, + + cart: function(){ + app.router.go("cart") + }, + + count: 0, + set_cart_count: function(n){ + this.count = n + this.$cart_count.html(n || " ") + }, + increment_cart_count: function(){ + this.$cart_count.html( ++this.count ) + }, + decrement_cart_count: function(){ + this.$cart_count.html( --this.count ) + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/nav/IntroView.js b/StoneIsland/platforms/android/assets/www/js/lib/nav/IntroView.js new file mode 100755 index 00000000..2d8dca43 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/nav/IntroView.js @@ -0,0 +1,46 @@ +var IntroView = View.extend({ + + el: "#intro", + + events: { + "click .store": "store", + "click .hub": "hub", + "click .story": "story", + "click .archive": "archive", + }, + + initialize: function(){ + this.compass = this.$("#compass").get(0) + this.orient = this.deviceorientation.bind(this) + }, + + show: function(){ + document.body.className = "intro" + window.addEventListener("deviceorientation", this.orient) + app.footer.hide() + this.orient({ alpha: 0 }) + // get location.. + }, + + hide: function(){ + window.removeEventListener("deviceorientation", this.orient) + }, + + deviceorientation: function(e){ + var heading + if ('webkitCompassHeading' in e) { + heading = e.webkitCompassHeading || 0 + } + else { + heading = e.alpha || 0 + } + heading = - heading + this.compass.style[transformProp] = "translateZ(0) translateX(-50%) translateY(-50%) rotate(" + heading + "deg)" + }, + + store: function(){ app.router.go("store") }, + hub: function(){ app.router.go("hub") }, + story: function(){ app.router.go("story") }, + archive: function(){ app.router.go("archive") }, + +}) diff --git a/StoneIsland/platforms/android/assets/www/js/lib/nav/NavView.js b/StoneIsland/platforms/android/assets/www/js/lib/nav/NavView.js new file mode 100755 index 00000000..704aaa34 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/nav/NavView.js @@ -0,0 +1,157 @@ +var NavView = View.extend({ + + el: "#nav", + + events: { + "click .logo": "intro", + + "click .store": "store", + "click .hub": "hub", + "click .story": "story", + "click .archive": "archive", + + "click .login": "login", + "click .logout": "logout", + "click .account": "account", + "click .faq": "faq", + "click .search": "search", + + "click .main": "back", + "click .account_back": "back", + "click .profile": "profile", + "click .payment": "payment", + "click .shipping": "shipping", + "click .settings": "settings", + "click .orders": "orders", + "click .return_link": "return_link", + + "click .faq_back": "back", + "click .privacy": "privacy", + "click .returns": "returns", + "click .terms": "terms", + "click .care": "care", + + "click .fb": "fb", + "click .insta": "insta", + "click .tw": "tw", + }, + + initialize: function(){ + }, + + show: function(klass){ + $("body").addClass("nav") + app.curtain.show("dark") + if (klass) { + setTimeout(function(){ + this.addClass(klass) + }.bind(this), 500) + } + }, + + hide: function(){ + $("body").removeClass("nav") + app.curtain.hide("dark") + }, + + intro: function(){ + this.hide() + app.router.go("intro") + }, + store: function(){ + this.hide() + app.router.go("store") + }, + hub: function(){ + this.hide() + app.router.go("hub") + }, + story: function(){ + this.hide() + app.router.go("story") + }, + archive: function(){ + this.hide() + app.router.go("archive") + }, + + login: function(){ + this.hide() + auth.last_view = app.view + app.router.go("account/login") + }, + logout: function(){ + this.hide() + auth.last_view = app.view + app.router.go("account/logout") + }, + account: function(){ + this.el.className = "account" + }, + + back: function(){ + this.el.className = "" + }, + + profile: function(){ + this.hide() + app.router.go("account/profile") + }, + payment: function(){ + this.hide() + app.router.go("account/payment") + }, + shipping: function(){ + this.hide() + app.router.go("account/shipping") + }, + orders: function(){ + this.hide() + app.router.go("account/orders") + }, + settings: function(){ + this.hide() + app.router.go("account/settings") + }, + return_link: function(){ + window.open("http://www.stoneisland.com/", '_system') + }, + + + faq: function(){ + this.el.className = "faq" + }, + privacy: function(){ + this.hide() + app.router.go("page/privacy") + }, + returns: function(){ + this.hide() + app.router.go("page/returns") + }, + terms: function(){ + this.hide() + app.router.go("page/terms") + }, + care: function(){ + window.open("http://www.stoneisland.com/localize.asp?tskay=4036416C&page=help/return&deviceYeti=smartphone", '_system') + }, + + + search: function(){ + this.hide() + app.router.go("search") + }, + + + fb: function(){ + window.open("https://www.facebook.com/StoneIsland", '_system') + }, + insta: function(){ + window.open("https://instagram.com/stoneisland_official", '_system') + }, + tw: function(){ + window.open("https://twitter.com/stoneisland", '_system') + }, + +}) diff --git a/StoneIsland/platforms/android/assets/www/js/lib/nav/SearchView.js b/StoneIsland/platforms/android/assets/www/js/lib/nav/SearchView.js new file mode 100755 index 00000000..f21634a5 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/nav/SearchView.js @@ -0,0 +1,16 @@ +var SearchView = View.extend({ + + el: "#search", + + events: { + }, + + show: function(){ + app.footer.show("SEARCH", "CANCEL") + document.body.className = "search" + }, + + save: function(){ + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/products/ClosedStoreView.js b/StoneIsland/platforms/android/assets/www/js/lib/products/ClosedStoreView.js new file mode 100755 index 00000000..5f8c1e84 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/products/ClosedStoreView.js @@ -0,0 +1,56 @@ +var ClosedStoreView = View.extend({ + + el: "#closed", + + storeIsClosed: false, + + events: { + "click .website_link": "website_link", + }, + + delay: 8000, + + timeout: -1, + images: null, + + initialize: function(){ + this.loader = new Loader () + }, + + show: function(){ + document.body.className = "closed" + this.animate() + app.footer.hide() + console.log(this) + if (this.storeOpenDate) { + var date = moment(this.storeOpenDate).format("MM/DD") + console.log(date) + $(".closed_store_msg h3").html("THIS STORE WILL OPEN ON " + date) + } + else { + $(".closed_store_msg h3").html("THIS STORE IS CURRENTLY CLOSED") + } + }, + + hide: function(){ + clearTimeout(this.timeout) + }, + + animate: function(){ + this.timeout = setTimeout(this.animate.bind(this), this.delay) + if (! this.images) return + var url = choice(this.images) + this.loader.preloadImage(url, function(img){ + this.el.style.backgroundImage = 'url(' + img.src + ')' + }.bind(this)) + }, + + populate: function(data){ + this.images = data.map(function(img){ return img.uri }) + }, + + website_link: function(){ + window.open("http://www.stoneisland.com/", '_system') + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/products/CollectionView.js b/StoneIsland/platforms/android/assets/www/js/lib/products/CollectionView.js new file mode 100755 index 00000000..d4315514 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/products/CollectionView.js @@ -0,0 +1,114 @@ + +var CollectionView = ScrollableView.extend({ + + el: "#collection", + template: $("#collection .template").html(), + loaded: false, + data: null, + items: {}, + + events: { + "touchstart .item": "touchstart", + "touchmove .item": "touchmove", + "touchend .item": "touchend", + "mousedown .item": "touchstart", + "mousemove .item": "touchmove", + "mouseup .item": "touchend", + }, + + initialize: function(){ + this.$title = this.$("h1") + this.$content = this.$(".content") + this.$loader = this.$(".loader") + this.scroller = new IScroll('#collection', app.iscroll_options) + this.filterView = new CategoryFilter ({ parent: this }) + }, + + show: function(){ + if (app.closed.storeIsClosed) { + // (! this.storeOpenDate || moment().diff(this.storeOpenDate) > 0 ) ) { + return app.closed.show() + } + app.footer.show("FILTER") + document.body.className = "collection" + if (this.loaded) { + return this.populate(this.data) + } + // this.fetch() + }, + + save: function(){ + this.filterView.filter() + }, + + fetch: function(){ + if (this.loaded) return + this.$loader.show() + sdk.product.collection({ + gallery_id: app.gallery_id, + success: this.populate.bind(this) + }) + }, + + populate: function(data){ + if (this.loaded && ! data) { + data = this.data + } + else { + this.data = data + } + if (! this.loaded) { + this.loaded = true + this.$loader.hide() + this.$content.empty() + // DefaultCode10 + data.SearchResponseFull.Results.Items.forEach(this.append.bind(this)) + this.deferScrollToTop() + } + this.afterFetchCallback && this.afterFetchCallback() + app.collection.deferRefresh() + }, + + append: function(item){ + this.items[ item['Code8'] ] = item + var t = this.template.replace(/{{image}}/, sdk.image(item['DefaultCode10'], '11_f')) + .replace(/{{code8}}/, item['Code8']) + this.$content.append(t) + }, + + pick: function(e){ + var code = $(e.currentTarget).data("code") + var data = this.items[code] + app.product.load(code, data) + }, + + collectionName: "STONE ISLAND", + setCollectionName: function(name){ + this.collectionName = name + this.$title.html(this.collectionName) + }, + + firstTouch: { x: 0, y: 0, id: "" }, + lastTouch: { x: 0, y: 0, id: "" }, + touchstart: function(e){ + var p = e.originalEvent.touches ? e.originalEvent.touches[0] : e.originalEvent + this.firstTouch.x = this.lastTouch.x = p.pageX + this.firstTouch.y = this.lastTouch.y = p.pageY + this.firstTouch.id = e.currentTarget.dataset.id + }, + touchmove: function(e){ + var p = e.originalEvent.touches ? e.originalEvent.touches[0] : e.originalEvent + this.lastTouch.x = p.pageX + this.lastTouch.y = p.pageY + this.lastTouch.id = e.currentTarget.dataset.id + }, + touchend: function(e){ + var first = app.collection.firstTouch + var last = app.collection.lastTouch + var distance = Math.sqrt( Math.pow(first.x - last.x, 2) + Math.pow(first.y - last.y, 2) ) + if (distance < 20) { + this.pick(e) + } + }, + +}) diff --git a/StoneIsland/platforms/android/assets/www/js/lib/products/GalleryView.js b/StoneIsland/platforms/android/assets/www/js/lib/products/GalleryView.js new file mode 100755 index 00000000..02193f14 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/products/GalleryView.js @@ -0,0 +1,65 @@ +var GalleryView = View.extend({ + + el: "#gallery", + template: $("#gallery .template").html(), + + events: { +// "click .left": "prev", +// "click .right": "next", +// "touchstart .gallery": "touchstart", +// "touchmove .gallery": "touchmove", +// "touchend .gallery": "touchend", + }, + + initialize: function(){ + this.$(".template").remove() + }, + + reset: function(){ + this.gallery && this.gallery.destroy() + this.$el.empty() + }, + + populate: function(code, image_ids){ + var valid_styles = {} + image_ids.forEach(function(id){ + if (id.indexOf("_") == -1) return + var partz = id.split("_") + var size = parseInt(partz[0]), style = partz[1] + if (size > 13) return; + if (! valid_styles[style] || valid_styles[style] < size) { + valid_styles[style] = size + } + }) + Object.keys(valid_styles).sort(sort_image_styles).forEach(function(style){ + var id = valid_styles[style] + "_" + style + var t = this.template.replace(/{{image}}/, sdk.image(code, id)) + this.$el.append(t) + }.bind(this)) + + this.gallery = new Flickity( "#gallery", { + selector: '.item', + cellAlign: 'center', + autoPlay: false, + freeScroll: false, + wrapAround: true, + imagesLoaded: true, + prevNextButtons: false, + pageDots: false, + contain: true, + draggable: true, + }) + }, + + touchstart: function(e){ + }, + touchmove: function(e){ + }, + touchend: function(e){ + }, + +}) + +var YOOX_IMAGE_STYLE_ORDER = "ZZZ d f".split(" ") + +function sort_image_styles (b,a){ return (YOOX_IMAGE_STYLE_ORDER.indexOf(a)) - (YOOX_IMAGE_STYLE_ORDER.indexOf(b)) } \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/products/ProductView.js b/StoneIsland/platforms/android/assets/www/js/lib/products/ProductView.js new file mode 100755 index 00000000..4789850a --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/products/ProductView.js @@ -0,0 +1,397 @@ + +var ProductView = ScrollableView.extend({ + + el: "#product", + + events: { + "click .fit": "scroll_to_bottom", + "click .size": "select_size", + "click .color": "select_color", + "click .share": "share", + "click .gallery-left": "gallery_left", + "click .gallery-right": "gallery_right", + }, + + initialize: function(){ + this.gallery = new GalleryView () + this.scroller = new IScroll('#product', app.iscroll_options) + + this.$num = this.$(".num") + this.$title = this.$(".title") + this.$type = this.$(".type") + this.$price = this.$(".price") + this.$size = this.$(".size") + this.$color = this.$(".color") + this.$body = this.$(".body") + this.$fit = this.$(".fit") + this.$sizing = this.$(".sizing") + }, + + show: function(){ + app.footer.show("ADD TO CART", "BUY NOW") + document.body.className = "product" + }, + hide: function(){ + }, + + item: null, + details: null, + size: null, + color: null, + code: null, + is_onesize: false, + + sizes: null, + colors: null, + + cache: {}, + + gallery_prev: function(){ + app.product.gallery.gallery.previous() + }, + gallery_right: function(){ + app.product.gallery.gallery.next() + }, + + find: function(code, cb){ + data = app.collection.items[code] || {} + if (code in this.cache) { + return cb(data, this.cache[code]) + } + sdk.product.item({ + code: code + }).done(function(details){ + this.cache[code] = details + cb(data, details) + }.bind(this)) + }, + + load: function(code, data){ + this.gallery.reset() + this.show() + if (app.view && app.view.hide) { + app.view.hide() + } + app.view = this + app.header.set_back(true) + + if (! app.collection.loaded) { + this.el.className = "loading" + app.collection.afterFetchCallback = this.load.bind(this, code, data) + app.collection.fetch() + return + } + else { + app.collection.afterFetchCallback = null + } + window.location.href = "#/store/" + code + + console.log(data) + if (data) { + app.collection.items[code] = data + } + + this.el.className = "loading" + this.find(code, this.populate.bind(this)) + }, + + populate: function(data, details){ + this.el.className = "" + + console.log(data, details) + + var descriptions = this.get_descriptions(details) + + this.gallery.populate( data['Code8'], details['Item']['ImageTypes'] ) + + var name_partz = data['ModelNames'].split(' ') + var num = name_partz.shift() + var title = name_partz.join(' ') + var type = title_case( data['MicroCategory'] ) + var price = "$" + data['DiscountedPrice'] + ".00" + var body = descriptions['EditorialDescription'].replace(/
/g, "

") + + var default_color_id = this.populate_selectors(data, details) + + var color = this.colors[default_color_id] + var color_label = color.label + var sizes = this.find_sizes_for_color(default_color_id) + var size = sizes[0] + var size_label = this.sizes[size].label + + this.is_onesize = !! this.sizes[1] + + // console.log(color, color_label, size, size_label) + + this.item = data + this.details = details['Item'] + this.code = data['DefaultCode10'] + + this.color = color + this.size = size + + this.$num.html(num) + this.$title.html(title) + this.$type.html(type) + this.$price.html(price) + this.$body.html(body) + + this.$size.html(size_label) + if (color_label) { + this.$color.show().html(color_label) + } + else { + this.$color.hide() + } + + this.deferScrollToTop() + }, + + get_descriptions: function (details){ + var descriptions = {} + details['Item']['Descriptions'].forEach(function(pair){ + descriptions[pair.Key] = pair.Value + }) + return descriptions + }, + find_sizes_for_color: function(color_id){ + return Object.keys( this.colors[color_id].sizes ).sort(function(a,b){ + var ao = SIZE_ORDER[ a.label ], bo = SIZE_ORDER[ b.label ] + return aoShort sleeve T-Shirt in cotton jersey. Garment dyed.
Stone Island Compass logo print on the front, made up of a series of numbers." +ItemDescription: "Logo detail
Jersey
Round collar
Solid color
" +KeywordDescription: "Logo detail Jersey Round collar Solid color Jersey Woven not made of fur " +Kind of fabric: "Woven" +MFC: "631520081CC-6315-81V0060" +MacroCategory: "POLO SHIRTS & T-SHIRTS" +MadeIn: "Made In Turkmenistan" +MadeInIsoCode: "TN" +MainMaterial: "Cotton" +Material Description: "Jersey" +MicroCategory: "Short sleeve t-shirt" +MicroCategoryPlural: "Short sleeve t-shirts" +ModelFabric: "631520081CC-6315-81" +ModelNames: "20081 DATA DRIP PIN" +Neckline: "Claudine or round collar" + +*/ \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/products/Selector.js b/StoneIsland/platforms/android/assets/www/js/lib/products/Selector.js new file mode 100755 index 00000000..76c498ec --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/products/Selector.js @@ -0,0 +1,48 @@ +var Selector = View.extend({ + + el: "#selector", + template: $("#selector .template").html(), + + events: { + "click .close": "hide", + "click .options div": "pick", + }, + + initialize: function(){ + this.$options = this.$(".options") + }, + + lookup: null, + callback: null, + select: function(options, callback){ + this.lookup = {} + this.callback = callback || function(item){ console.log(item) } + this.$options.empty() + options.forEach(function(opt){ + this.lookup[String(opt.id)] = opt + var t = this.template.replace(/{{id}}/, opt.id) + .replace(/{{label}}/, opt.label) + this.$options.append(t) + }.bind(this)) + this.$el.show() + app.curtain.show("white") + this.visible = true + }, + + hide: function(){ + this.lookup = this.callback = null + this.$el.hide() + app.curtain.hide() + this.visible = false + }, + + pick: function(e){ + var $option = $(e.currentTarget) + var id = String($option.data("id")) + var selection = this.lookup[id] + + this.callback( selection ) + this.hide() + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/products/filters/CategoryFilter.js b/StoneIsland/platforms/android/assets/www/js/lib/products/filters/CategoryFilter.js new file mode 100755 index 00000000..4e6baf62 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/products/filters/CategoryFilter.js @@ -0,0 +1,40 @@ +var CategoryFilter = View.extend({ + + initialize: function(opt){ + this.parent = opt.parent + }, + + filter: function(){ + var cats = this.parent.data.SearchResponseFull.Refinements.Filters.Categories.map(function(cat){ + return { + id: cat.Id, + label: cat.Value + } + }) + if (this.last_choice) { + cats.push({ + id: "__remove_filter", + label: "REMOVE FILTER", + }) + } + app.selector.select(cats, this.pick.bind(this)) + }, + + last_choice: null, + + pick: function(choice){ + this.parent.$content.empty() + if (choice.id == "__remove_filter") { + this.last_choice = null + this.parent.data.SearchResponseFull.Results.Items.forEach(this.parent.append.bind(this.parent)) + } + else { + this.last_choice = choice + this.parent.data.SearchResponseFull.Results.Items.filter(function(item){ + return item.MacroCategory == choice.label + }).forEach(this.parent.append.bind(this.parent)) + } + this.parent.deferScrollToTop() + }, + +}) diff --git a/StoneIsland/platforms/android/assets/www/js/lib/view/Router.js b/StoneIsland/platforms/android/assets/www/js/lib/view/Router.js new file mode 100755 index 00000000..a8ec331f --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/view/Router.js @@ -0,0 +1,75 @@ +var Router = View.extend({ + + routeByHash: false, + + go: function(url){ + this.parseRoute(url) + }, + + route: function(){ + var path = this.routeByHash ? window.location.hash.substr(0) : window.location.pathname + path = path || "/" + this.originalPath = path + this.parseRoute(path) + }, + + parseRoute: function(pathname){ + + pathname = pathname.replace(/^#/, "") + + if (pathname[0] !== "/") { pathname = "/" + pathname } + + var routes = this.routes, + path = pathname.split("/"); + + for (var i = 0; i < path.length; i++) { + if (! path[i].length) { + path[i] = null + } + } + + if (pathname in routes) { + this[this.routes[pathname]]() + return + } + + if (path[path.length-1] == null) { + path.pop() + } + + for (var route in routes) { + var routePath = route.split("/") + if (routePath[1] == path[1]) { + if (routePath[2] && routePath[2].indexOf(":") !== -1 && path[2] && (path[3] === routePath[3]) ) { + this[this.routes[route]](path[2]) + return + } + else if (routePath[2] == path[2]) { + if (routePath[3] && path[3]) { + if (routePath[3].indexOf(":") !== -1) { + this[this.routes[route]](path[3]) + return + } + else if (routePath[3] == path[3]) { + this[this.routes[route]]() + return + } + } + else if (! routePath[3] && ! path[3]) { + this[this.routes[route]]() + return + } + } + else if (! routePath[2] && (! path[2].length || ! path[2])) { + this[this.routes[route]]() + return + } + } + } + + if (is_mobile) { + window.location.href = "/" + } + } + +}) diff --git a/StoneIsland/platforms/android/assets/www/js/lib/view/Scrollable.js b/StoneIsland/platforms/android/assets/www/js/lib/view/Scrollable.js new file mode 100755 index 00000000..d06ed590 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/view/Scrollable.js @@ -0,0 +1,27 @@ +var ScrollableView = View.extend({ + + events: { + "load img": "deferRefresh", + }, + + deferScrollToTop: function(){ + setTimeout(this.scrollToTop.bind(this), 0) + }, + + refreshScroller: function(){ + this.scroller.refresh() + clearTimeout( this.scrollerRefreshTimeout ) + }, + + scrollerRefreshTimeout: null, + deferRefresh: function(){ + clearTimeout( this.scrollerRefreshTimeout ) + this.scrollerRefreshTimeout = setTimeout(this.refreshScroller.bind(this)) + }, + + scrollToTop: function(){ + this.scroller.refresh() + app.collection.scroller.scrollTo(0, 0) + }, + +}) \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/lib/view/Serializable.js b/StoneIsland/platforms/android/assets/www/js/lib/view/Serializable.js new file mode 100755 index 00000000..98aa8ce3 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/view/Serializable.js @@ -0,0 +1,164 @@ +var SerializableView = View.extend({ + + events: { + "change select": "update_select", + "change [type=date]": "update_date", + "focus input": "focus_input", + "click .date-wrapper": "focus_date", + "submit form": "save", + }, + + preload: function(data){ + if (! data && sdk.env == "production") { return } + data = data || this.test_data + if (! data) { return } + this.load_data(data) + }, + + load_data: function(data){ + Object.keys(data).forEach(function(key){ + var value = data[key] + var $el = this.$("[name=" + key + "]") + + if ($el.attr("type") == "checkbox") { + $el.prop("checked", value) + } + if ($el.attr("type") == "date") { + $el.val( value ) + this.update_date({ currentTarget: $el }) + } + else if ($el.prop("tagName") == "SELECT") { + $el.val( value ) + this.update_select({ currentTarget: $el }) + } + else { + $el.val( value ) + } + }.bind(this)) + }, + + serialize: function(){ + var fields = {} + this.$("input[name], select[name], textarea[name]").each( function(){ + if (this.type == "checkbox") { + if ($(this).prop("checked")) { + fields[this.name] = this.value + } + } + else { + fields[this.name] = this.value + } + }) + return fields + }, + + deserialize: function(data){ + this.$("input[name], textarea[name]").val("") + Object.keys(data).forEach(function(k){ + this.$("[" + k + "]").val(data[k]) + }) + }, + + focus_input: function(e){ + $(e.currentTarget).removeClass("error_hilite") + }, + + focus_date: function(e){ + $(e.currentTarget).find("input").focus() + }, + + update_select: function(e){ + var $target = $(e.currentTarget), value = $target.val() + var label = $target.find("option").filter(function(){ return this.value === value }).html() + $target.parent().addClass("picked") + $target.parent().find("span").html(label) + }, + + update_date: function(e){ + var $target = $(e.currentTarget), value = $target.val() + var label = moment(value).format("MM/DD/YYYY") + $target.parent().addClass("picked") + $target.parent().find("span").html(label) + }, + + validate: function(data, errors){ + var data = data || this.serialize() + var errors = errors || [] + var presence_msgs = this.validate_presence || {} + if (! this.disabled) { + Object.keys(presence_msgs).forEach(function(k){ + if (! data[k]) errors.push( [ k, presence_msgs[k] ] ) + }) + } + this.validate_fields && this.validate_fields(data, errors) + this.cc && this.cc.validate(data, errors) + this.address && this.address.validate(data, errors) + return { errors: errors, data: data } + }, + + show_errors: function(errors){ + console.log(errors) + var msgs = [] + errors.forEach(function(e, i){ + if (i > 0) { return } + this.$("[name=" + e[0] + "]").addClass('error_hilite') + msgs.push(e[1]) + }.bind(this)) + this.$msg.html(msgs.join("
")) + this.$msg.addClass('alert-notice') + }, + + hide_errors: function(){ + this.$msg.removeClass('alert-notice') + this.$msg.html("") + }, + + finalize: function(data){ + return data + }, + + save: function(e){ + e && e.preventDefault() + + var valid = this.validate() + if (valid.errors.length) { + this.show_errors(valid.errors) + return + } + else { + this.hide_errors() + } + + var finalized_data = this.finalize(valid.data) + this.submit( finalized_data ) + }, + + submit: function(data){ + if (! data) { + return + } + app.curtain.show("loading") + this.action({ + data: data, + success: function(data){ + app.curtain.hide("loading") + this.success(data) + }.bind(this), + error: function(data){ + app.curtain.hide("loading") + this.error(data) + }.bind(this), + }) + }, + + success: function(data){ + console.log("SUCCESS", data) + }, + + error: function(data){ + console.log("FAIL", data) + }, + +}) + +var FormView = View.extend(SerializableView.prototype).extend(ScrollableView.prototype) diff --git a/StoneIsland/platforms/android/assets/www/js/lib/view/View.js b/StoneIsland/platforms/android/assets/www/js/lib/view/View.js new file mode 100755 index 00000000..41638ab7 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/lib/view/View.js @@ -0,0 +1,147 @@ +var View = (function($, _){ + + var View = function(options) { + this._id = _.uniqueId('view') + this.type = "view" + options || (options = {}); + _.extend(this, _.pick(options, viewOptions)) + this._ensureElement() + this.initialize.apply(this, arguments) + this.delegateEvents() + } + + var delegateEventSplitter = /^(\S+)\s*(.*)$/; + + var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; + + _.extend(View.prototype, { + + // The default `tagName` of a View's element is `"div"`. + tagName: 'div', + + $: function(selector) { + return this.$el.find(selector); + }, + + initialize: function(){}, + + setElement: function(element, delegate) { + if (this.$el) this.undelegateEvents(); + this.$el = element instanceof $ ? element : $(element); + this.el = this.$el[0]; + if (delegate !== false) this.delegateEvents(); + return this; + }, + + // Set callbacks, where `this.events` is a hash of + // + // *{"event selector": "callback"}* + // + // { + // 'mousedown .title': 'edit', + // 'click .button': 'save', + // 'click .open': function(e) { ... } + // } + // + // pairs. Callbacks will be bound to the view, with `this` set properly. + // Uses event delegation for efficiency. + // Omitting the selector binds the event to `this.el`. + // This only works for delegate-able events: not `focus`, `blur`, and + // not `change`, `submit`, and `reset` in Internet Explorer. + delegateEvents: function(events) { + if (!(events || (events = _.result(this, 'events')))) return this; + this.undelegateEvents(); + for (var key in events) { + var method = events[key]; + if (!_.isFunction(method)) method = this[events[key]]; + if (!method) continue; + + var match = key.match(delegateEventSplitter); + var eventName = match[1], selector = match[2]; + method = _.bind(method, this); + eventName += '.delegateEvents' + this._id; + if (is_mobile) { + if (eventName === 'mouseenter' || eventName === 'mouseleave') { + continue + } +// if (eventName === 'click') { +// eventName = 'tap' +// } + } + if (selector === '') { + this.$el.on(eventName, method); + } else { + this.$el.on(eventName, selector, method); + } + } + return this; + }, + + // Clears all callbacks previously bound to the view with `delegateEvents`. + undelegateEvents: function() { + this.$el.off('.delegateEvents' + this._id); + return this; + }, + + // Ensure that the View has a DOM element to render into. + // If `this.el` is a string, pass it through `$()`, take the first + // matching element, and re-assign it to `el`. Otherwise, create + // an element from the `id`, `className` and `tagName` properties. + _ensureElement: function() { + this.setElement(_.result(this, 'el'), false); + }, + + preventDefault: function(e){ + e && e.preventDefault() + }, + + stopPropagation: function(e){ + e && e.stopPropagation() + }, + + }); + + + var extend = function(protoProps, staticProps) { + var staticProps = staticProps || {} + var parent = this; + var child; + var childEvents = {}; + + // The constructor function for the new subclass is either defined by you + // (the "constructor" property in your `extend` definition), or defaulted + // by us to simply call the parent's constructor. + if (protoProps && _.has(protoProps, 'constructor')) { + child = protoProps.constructor; + } else { + child = function(){ return parent.apply(this, arguments); }; + } + + // Extend events so we can subclass views + _.extend(childEvents, parent.prototype.events, protoProps.events) + + // Add static properties to the constructor function, if supplied. + _.extend(child, parent, staticProps); + + // Set the prototype chain to inherit from `parent`, without calling + // `parent`'s constructor function. + var Surrogate = function(){ this.constructor = child; }; + Surrogate.prototype = parent.prototype; + child.prototype = new Surrogate; + + // Add prototype properties (instance properties) to the subclass, + // if supplied. + if (protoProps) _.extend(child.prototype, protoProps); + + // Set a convenience property in case the parent's prototype is needed + // later. + child.prototype.__super__ = parent.prototype; + child.prototype.events = childEvents + + return child; + }; + + View.extend = extend; + + return View; +})(jQuery, _) diff --git a/StoneIsland/platforms/android/assets/www/js/sdk/_sdk.js b/StoneIsland/platforms/android/assets/www/js/sdk/_sdk.js new file mode 100755 index 00000000..b7880e50 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/sdk/_sdk.js @@ -0,0 +1,38 @@ +var sdk = (function(){ + var sdk = {} + + sdk.env = "development" + + var endpoint = "https://secure.api.yoox.biz/" + // var endpoint = "http://api.yoox.biz/" + + sdk.init = function(opt){ + switch (sdk.env = opt.env || "development") { + case 'test': + endpoint = "http://lvh.me:9090/" + break + default: + case 'development': + endpoint = "/" + break + case 'production': + endpoint = "https://secure.api.yoox.biz/" + break + } + } + + sdk.path = function(api, path){ + return endpoint + api + "/STONEISLAND_US/" + path + } + + sdk.image = function(code, size){ + return "http://cdn.yoox.biz/" + code.substr(0,2) + "/" + code.substr(0,8) + "_" + size + ".jpg" + } + + $.ajaxSetup({ + // possibly: application/json; charset=utf-8" + contentType: "application/json", + }) + + return sdk +})() \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/sdk/account.js b/StoneIsland/platforms/android/assets/www/js/sdk/account.js new file mode 100755 index 00000000..3eb3f3bd --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/sdk/account.js @@ -0,0 +1,133 @@ +sdk.account = (function(){ + + var user_id, access_token + + // https://gist.github.com/fanfare/d18498e7fa25acbd4486 + var account = {} + account.signup = function(opt){ + return $.ajax({ + method: "POST", + url: sdk.path("Account.API/1.5", "users.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-api-key": auth.apikey, + }, + data: JSON.stringify( opt.data ), + success: function(data){ + user_id = data['UserAccount']['UserId'] + access_token = data['UserAccount']['AccessToken'] + + auth.set_user(user_id, access_token) + + opt.success(data) + }, + error: opt.error, + }) + } + + account.login = function(opt){ + return $.ajax({ + method: "POST", + url: sdk.path("Account.API/1.5", "authfull.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-account-token": auth.access_token, + }, + data: JSON.stringify( opt.data ), + success: function(data){ + auth.user = data['UserFull'] + user_id = data['UserFull']['idUser'] + access_token = data['UserFull']['AccessToken'] + + auth.set_user(user_id, access_token) + + opt.success(data) + }, + error: opt.error, + }) + } + + account.checkin = function(opt){ + return $.ajax({ + method: "GET", + url: sdk.path("Account.API/1.5", "users/" + auth.user_id + ".json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-account-token": auth.access_token, + }, + data: "{}", + success: function(data){ + auth.user = data.User + opt.success(data) + }, + error: opt.error, + }) + } + + account.update = function(opt){ + return $.ajax({ + method: "PUT", + url: sdk.path("Account.API/1.5", "users/" + auth.user_id + ".json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-account-token": auth.access_token, + }, + data: JSON.stringify( opt.data ), + success: function(data){ + opt.success(data) + }, + error: opt.error, + }) + } + + account.update_mail_and_password = function(opt){ + return $.ajax({ + method: "PUT", + url: sdk.path("Account.API/1.5", "auth/" + auth.user_id + ".json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-account-token": auth.access_token, + }, + data: JSON.stringify( opt.data ), + success: function(data){ + opt.success(data) + }, + error: opt.error, + }) + } + + account.fetch_orders = function(opt){ + return $.ajax({ + method: "GET", + url: sdk.path("Account.API/1.5", "users/" + auth.user_id + "/orders.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-account-token": auth.access_token, + }, + data: JSON.stringify( opt.data ), + success: function(data){ + opt.success(data) + }, + error: opt.error, + }) + } + + account.fetch_single_order = function(opt){ + return $.ajax({ + method: "GET", + url: sdk.path("Account.API/1.5", "users/" + auth.user_id + "/orders/" + opt.id + ".json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-account-token": auth.access_token, + }, + data: JSON.stringify( opt.data ), + success: function(data){ + opt.success(data) + }, + error: opt.error, + }) + } + + return account + +})() diff --git a/StoneIsland/platforms/android/assets/www/js/sdk/address.js b/StoneIsland/platforms/android/assets/www/js/sdk/address.js new file mode 100755 index 00000000..4fb12ad0 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/sdk/address.js @@ -0,0 +1,74 @@ +sdk.address = (function(){ + var address = {} + + address.list = function(opt){ + return $.ajax({ + method: "GET", + url: sdk.path("Account.API/1.5", "users/" + auth.user_id + "/addressBook.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-account-token": auth.access_token, + }, + data: opt.data, + success: function(data){ + // console.log(data) + opt.success(data) + }, + error: opt.error, + }) + } + + address.add = function(opt){ + return $.ajax({ + method: "POST", + url: sdk.path("Account.API/1.5", "users/" + auth.user_id + "/addressBook/item.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-account-token": auth.access_token, + }, + data: JSON.stringify( opt.data ), + success: function(data){ + // console.log(data) + opt.success(data) + }, + error: opt.error, + }) + } + + address.update = function(opt){ + return $.ajax({ + method: "PUT", + url: sdk.path("Account.API/1.5", "users/" + auth.user_id + "/addressBook/item.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-account-token": auth.access_token, + }, + data: JSON.stringify( opt.data ), + success: function(data){ + // console.log(data) + opt.success(data) + }, + error: opt.error, + }) + } + + address.destroy = function(opt){ + return $.ajax({ + method: "DELETE", + url: sdk.path("Account.API/1.5", "users/" + auth.user_id + "/" + opt.id + "/addressBook.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-account-token": auth.access_token, + }, + data: JSON.stringify( opt.data ), + success: function(data){ + // console.log(data) + opt.success(data) + }, + error: opt.error, + }) + } + + return address + +})() \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/sdk/auth.js b/StoneIsland/platforms/android/assets/www/js/sdk/auth.js new file mode 100755 index 00000000..87ce60ea --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/sdk/auth.js @@ -0,0 +1,129 @@ +/* + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-account-token": auth.access_token, + "x-yoox-device": auth.device, + "x-yoox-api-key": auth.apikey, + }, +*/ + +var auth = sdk.auth = (function(){ + var auth = {} + + auth.appname = is_iphone ? "native-iphone-stoneisland/1.0.0" : "native-android-stoneisland/1.0.0" + auth.apikey = "U2FsdGVkX18fThqg9bF0/ZgE9Jg948hn8O9EXli4B2729nAESCQaexv//M5+7+za" + auth.device = "smartphone" + + auth.access_token = "" + auth.user_id = -1 + + auth.next_view = null + auth.deferred_product = null + + // ios: integrate keychain api + // android: cordova.file.externalRootDirectory api + + auth.init = function(fn){ + console.log("AUTH INIT") + auth.get_user(function(){ + if (auth.logged_in()) { + sdk.account.checkin({ + success: function(data){ + fn && fn( auth.logged_in() ) + } + }) + auth.get_cart() + } + else { + fn && fn( auth.logged_in() ) + } + }) + } + + auth.set_user = function(user_id, access_token, cb){ + auth.access_token = access_token + auth.user_id = user_id + + localStorage.setItem("yoox.access_token", access_token) + localStorage.setItem("yoox.user_id", user_id) + cb && cb() + } + auth.get_user = function(cb){ + auth.access_token = localStorage.getItem("yoox.access_token") || "" + auth.user_id = localStorage.getItem("yoox.user_id") || -1 + cb && cb() + } + auth.clear_user = function(cb){ + auth.access_token = "" + auth.user_id = -1 + localStorage.removeItem("yoox.access_token") + localStorage.removeItem("yoox.user_id") + cb && cb() + } + + auth.set_cart = function(cart_id, cart_token, cb){ + localStorage.setItem("yoox.cart_token", cart_token) + localStorage.setItem("yoox.cart_id", cart_id) + cb && cb() + } + auth.get_cart = function(cb){ + sdk.cart.token = localStorage.getItem("yoox.cart_token") || "" + sdk.cart.id = localStorage.getItem("yoox.cart_id") || -1 + cb && cb() + } + auth.clear_cart = function(cb){ + sdk.cart.token = "" + sdk.cart.id = -1 + localStorage.removeItem("yoox.cart_token") + localStorage.removeItem("yoox.cart_id") + cb && cb() + } + auth.create_cart = function(cb){ + if (auth.has_cart()) { return cb() } + sdk.cart.initialize({ + success: function(data){ + sdk.cart.set_user({ + success: function(){ + auth.set_cart(sdk.cart.id, sdk.cart.token, function(){ + cb && cb() + }) + } + }) + } + }) + } + auth.add_deferred_product_to_cart = function(cb){ + // auth.deferred_product + if (! auth.deferred_product) { + console.log("VV NO DEF PROD") + cb && cb() + return + } + sdk.cart.add_item({ + data: auth.deferred_product, + success: function(){ + console.log("ADDED ITEM") + cb && cb() + }, + error: function(data){ + console.log("ERROR ADDING ITEM", data) + cb && cb() + }, + }) + auth.deferred_product = null + app.header.increment_cart_count() + } + + auth.log_out = function(){ + auth.clear_user() + auth.clear_cart() + } + auth.logged_in = function(){ + return (auth.user_id && auth.user_id !== -1 && auth.user_id !== "undefined") + } + auth.has_cart = function(){ + return (sdk.cart.id && sdk.cart.id !== -1 && sdk.cart.id !== "undefined") + } + + return auth +})() \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/sdk/cart.js b/StoneIsland/platforms/android/assets/www/js/sdk/cart.js new file mode 100755 index 00000000..3ff2e1d2 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/sdk/cart.js @@ -0,0 +1,248 @@ +sdk.cart = (function(){ + var cart = {} + + cart.id = "" + cart.token = "" + + // https://gist.github.com/fanfare/9a50c524aea417d0bf3e + cart.initialize = function(opt){ + return $.ajax({ + method: "POST", + url: sdk.path("Cart.API/1.6", "carts.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-device": auth.device, + }, + data: "{}", + // data: opt.data, + success: function(data){ + cart.id = data["CartSession"]["CartId"] + cart.token = data["CartSession"]["CartToken"] + auth.set_cart( cart.id, cart.token ) + opt.success(data) + }, + error: opt.error, + }) + } + + cart.set_user = function(opt){ + return $.ajax({ + method: "PUT", + url: sdk.path("Cart.API/1.6", "carts/" + cart.id + "/user.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-cart-token": cart.token, + }, + data: JSON.stringify({ + "UserId": auth.user_id, + "UserToken": auth.access_token, + }), + success: function(data){ + opt.success(data) + }, + error: opt.error, + }) + } + + // Code10, Size, Section + cart.add_item = function(opt){ + return $.ajax({ + method: "POST", + url: sdk.path("Cart.API/1.6", "carts/" + cart.id + "/items.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-cart-token": cart.token, + }, + data: JSON.stringify( opt.data ), + success: function(data){ + // console.log(data) + opt.success(data) + }, + error: opt.error, + }) + } + + cart.delete_item = function(opt){ + return $.ajax({ + method: "DELETE", + url: sdk.path("Cart.API/1.6", "carts/" + cart.id + + "/items/" + opt.data.Code10 + + "/" + opt.data.Size + ".json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-cart-token": cart.token, + }, + data: "{}", + success: function(data){ + // console.log(data) + opt.success(data) + }, + error: opt.error, + }) + } + + cart.get_status = function(opt){ + if (! cart.id) { + return opt.error({ error: "no cart" }) + } + return $.ajax({ + method: "GET", + url: sdk.path("Cart.API/1.6", "carts/" + cart.id + ".json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-cart-token": cart.token, + "x-yoox-device": auth.device, + }, + success: function(data){ + if (data['Error']) { + opt.error && opt.error(data) + } + else { + opt.success(data) + } + }, + error: opt.error, + }) + } + + cart.set_shipping_address = function(opt){ + return $.ajax({ + method: "PUT", + url: sdk.path("Cart.API/1.6", "carts/" + cart.id + "/receiver.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-cart-token": cart.token, + }, + data: JSON.stringify(opt.data), + success: function(data){ + // console.log(data) + opt.success(data) + }, + error: opt.error, + }) + } + + // NB: Payment type may simply be 1 (credit card) + cart.set_payment_type = function(opt){ + return $.ajax({ + method: "PUT", + url: sdk.path("Cart.API/1.6", "carts/" + cart.id + "/paymentType.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-cart-token": cart.token, + }, + data: JSON.stringify( opt.data ), + success: function(data){ + // console.log(data) + opt.success(data) + }, + error: opt.error, + }) + } + + cart.get_card_types = function(opt){ + return $.ajax({ + method: "GET", + url: sdk.path("Cart.API/1.6", "cardTypes.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-cart-token": cart.token, + }, + data: "", + success: function(data){ + opt.success(data) + }, + error: opt.error, + }) + } + + // use with full CC data if not storing it in wallet + cart.set_credit_card = function(opt){ + return $.ajax({ + method: "PUT", + url: sdk.path("Cart.API/1.6", "carts/" + cart.id + "/creditCard.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-cart-token": cart.token, + }, + data: JSON.stringify( opt.data ), + success: function(data){ + // console.log(data) + opt.success(data) + }, + error: opt.error, + }) + } + + // use with a stored GUID + // NB: if "verification number" is 1, use CVV/CID/CVC security code + // if "verification number" is 2, use "Issue Number" + cart.use_stored_credit_card = function(opt){ + var data = { + "Guid": opt.data.guid, + "UserId": auth.user_id, + "AccessToken": auth.access_token, + } + if (opt.data.cvv) { + data["Cvv"] = opt.data.cvv + } + if (opt.data.issue) { + data["Issue"] = opt.data.issue + } + return $.ajax({ + method: "PUT", + url: sdk.path("Cart.API/1.6", "carts/" + cart.id + "/userCreditCard.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-cart-token": cart.token, + }, + data: JSON.stringify(data), + success: function(data){ + // console.log(data) + opt.success(data) + }, + error: opt.error, + }) + } + + cart.secure_finalize = function(opt){ + return $.ajax({ + method: "POST", + url: sdk.path("Cart.API/1.6", "carts/" + cart.id + "/secureFinalizer.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-cart-token": cart.token, + "x-yoox-device": auth.device, + }, + data: JSON.stringify( opt.data || {} ), + success: function(data){ + console.log(data) + // order number is: + // "Info": "2905Y07FA13020" + opt.success(data) + }, + error: opt.error, + }) + } + + cart.finalize = function(opt){ + return $.ajax({ + method: "POST", + url: sdk.path("Cart.API/1.6", "carts/" + cart.id + "/finalizer.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-cart-token": cart.token, + }, + data: JSON.stringify( opt.data || {} ), + success: function(data){ + console.log(data) + // order number is: + // "Info": "2905Y07FA13020" + opt.success(data) + }, + error: opt.error, + }) + } + + return cart +})() \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/sdk/payment.js b/StoneIsland/platforms/android/assets/www/js/sdk/payment.js new file mode 100755 index 00000000..283fee92 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/sdk/payment.js @@ -0,0 +1,72 @@ +sdk.payment = (function(){ + var payment = {} + + payment.add_credit_card = function(opt){ + return $.ajax({ + method: "POST", + url: sdk.path("Account.API/1.5", "users/" + auth.user_id + "/cards.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-account-token": auth.access_token, + }, + data: JSON.stringify( opt.data ), + success: function(data){ + // console.log(data) + opt.success(data) + }, + error: opt.error, + }) + } + + payment.list_credit_cards = function(opt){ + return $.ajax({ + method: "GET", + url: sdk.path("Account.API/1.5", "users/" + auth.user_id + "/cards.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-account-token": auth.access_token, + }, + data: opt.data, + success: function(data){ + opt.success(data) + }, + error: opt.error, + }) + } + + payment.delete_credit_card = function(opt){ + return $.ajax({ + method: "DELETE", + url: sdk.path("Account.API/1.5", "users/" + auth.user_id + "/cards/" + opt.guid + ".json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-account-token": auth.access_token, + }, + data: "{}", + success: function(data){ + // console.log(data) + opt.success(data) + }, + error: opt.error, + }) + } + + payment.get_payment_types = function(opt){ + return $.ajax({ + method: "GET", + url: sdk.path("Cart.API/1.6", "availablePaymentTypes.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-device": auth.device, + }, + data: opt.data, + success: function(data){ + // console.log(data) + opt.success(data) + }, + error: opt.error, + }) + } + + return payment +})() \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/sdk/product.js b/StoneIsland/platforms/android/assets/www/js/sdk/product.js new file mode 100755 index 00000000..55f1940a --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/sdk/product.js @@ -0,0 +1,37 @@ +sdk.product = (function(){ + var product = {} + + var default_gallery = 31617 + + product.collection = function(opt){ + return $.ajax({ + method: "GET", + url: sdk.path("Search.API/1.2", "search.json"), + data: { format: "full", gallery: opt.gallery_id || default_gallery, productsPerPage: 100 }, + success: opt.success, + error: opt.error, + }) + } + + // https://gist.github.com/fanfare/2d25d1b36944188948ff + product.item = function(opt){ + return $.ajax({ + method: "GET", + url: sdk.path("Item.API/1.0", "item/" + opt.code + ".json"), + success: opt.success, + error: opt.error, + }) + } + + product.search = function(opt){ + return $.ajax({ + method: "GET", + url: sdk.path("Search.API/1.2", "search.json"), + data: { format: "full", gallery: opt.gallery_id || default_gallery, textSearch: opt.query, productsPerPage: 100 }, + success: opt.success, + error: opt.error, + }) + } + + return product +})() \ No newline at end of file diff --git a/StoneIsland/platforms/android/assets/www/js/sdk/shipping.js b/StoneIsland/platforms/android/assets/www/js/sdk/shipping.js new file mode 100755 index 00000000..28a0db76 --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/sdk/shipping.js @@ -0,0 +1,85 @@ +sdk.shipping = (function() { + var shipping = {} + + + // https://gist.github.com/fanfare/edb524128461b573d833 + + // BOX TYPE + + shipping.get_box_types = function(opt){ + return $.ajax({ + method: "GET", + url: sdk.path("Cart.API/1.6", "carts/" + sdk.cart.id + "/availableBoxTypes.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-cart-token": sdk.cart.token, + }, + success: function(data){ + // console.log(data) + opt.success(data) + }, + error: opt.error, + }) + } + + shipping.set_box_type = function(opt){ + return $.ajax({ + method: "PUT", + url: sdk.path("Cart.API/1.6", "carts/" + sdk.cart.id + "/boxType.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-cart-token": sdk.cart.token, + }, + data: JSON.stringify({ + "Type": opt.type, + }), + success: function(data){ + // console.log(data) + opt.success(data) + }, + error: opt.error, + }) + } + + + // DELIVERY TYPES + + // The response is different than described in the API reference.. + // https://gist.github.com/fanfare/15dfbca6a16ae6bed503 + + shipping.get_delivery_types = function(opt){ + return $.ajax({ + method: "GET", + url: sdk.path("Cart.API/1.6", "carts/" + sdk.cart.id + "/availableDeliveryTypes.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-cart-token": sdk.cart.token, + }, + success: function(data){ + opt.success(data) + }, + error: opt.error, + }) + } + + shipping.set_delivery_type = function(opt){ + return $.ajax({ + method: "PUT", + url: sdk.path("Cart.API/1.6", "carts/" + sdk.cart.id + "/deliveryType.json"), + headers: { + "x-yoox-appname": auth.appname, + "x-yoox-cart-token": sdk.cart.token, + }, + data: JSON.stringify({ + "Id": opt.id, + }), + success: function(data){ + //console.log(data) + opt.success(data) + }, + error: opt.error, + }) + } + + return shipping +})() diff --git a/StoneIsland/platforms/android/assets/www/js/vendor/fastclick.js b/StoneIsland/platforms/android/assets/www/js/vendor/fastclick.js new file mode 100755 index 00000000..9c746c2b --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/vendor/fastclick.js @@ -0,0 +1,790 @@ +/** + * @preserve FastClick: polyfill to remove click delays on browsers with touch UIs. + * + * @version 1.0.1 + * @codingstandard ftlabs-jsv2 + * @copyright The Financial Times Limited [All Rights Reserved] + * @license MIT License (see LICENSE.txt) + */ + +/*jslint browser:true, node:true*/ +/*global define, Event, Node*/ + + +/** + * Instantiate fast-clicking listeners on the specified layer. + * + * @constructor + * @param {Element} layer The layer to listen on + * @param {Object} options The options to override the defaults + */ +function FastClick(layer, options) { + 'use strict'; + var oldOnClick; + + options = options || {}; + + /** + * Whether a click is currently being tracked. + * + * @type boolean + */ + this.trackingClick = false; + + + /** + * Timestamp for when click tracking started. + * + * @type number + */ + this.trackingClickStart = 0; + + + /** + * The element being tracked for a click. + * + * @type EventTarget + */ + this.targetElement = null; + + + /** + * X-coordinate of touch start event. + * + * @type number + */ + this.touchStartX = 0; + + + /** + * Y-coordinate of touch start event. + * + * @type number + */ + this.touchStartY = 0; + + + /** + * ID of the last touch, retrieved from Touch.identifier. + * + * @type number + */ + this.lastTouchIdentifier = 0; + + + /** + * Touchmove boundary, beyond which a click will be cancelled. + * + * @type number + */ + this.touchBoundary = options.touchBoundary || 10; + + + /** + * The FastClick layer. + * + * @type Element + */ + this.layer = layer; + + /** + * The minimum time between tap(touchstart and touchend) events + * + * @type number + */ + this.tapDelay = options.tapDelay || 200; + + if (FastClick.notNeeded(layer)) { + return; + } + + // Some old versions of Android don't have Function.prototype.bind + function bind(method, context) { + return function() { return method.apply(context, arguments); }; + } + + + var methods = ['onMouse', 'onClick', 'onTouchStart', 'onTouchMove', 'onTouchEnd', 'onTouchCancel']; + var context = this; + for (var i = 0, l = methods.length; i < l; i++) { + context[methods[i]] = bind(context[methods[i]], context); + } + + // Set up event handlers as required + if (deviceIsAndroid) { + layer.addEventListener('mouseover', this.onMouse, true); + layer.addEventListener('mousedown', this.onMouse, true); + layer.addEventListener('mouseup', this.onMouse, true); + } + + layer.addEventListener('click', this.onClick, true); + layer.addEventListener('touchstart', this.onTouchStart, false); + layer.addEventListener('touchmove', this.onTouchMove, false); + layer.addEventListener('touchend', this.onTouchEnd, false); + layer.addEventListener('touchcancel', this.onTouchCancel, false); + + // Hack is required for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2) + // which is how FastClick normally stops click events bubbling to callbacks registered on the FastClick + // layer when they are cancelled. + if (!Event.prototype.stopImmediatePropagation) { + layer.removeEventListener = function(type, callback, capture) { + var rmv = Node.prototype.removeEventListener; + if (type === 'click') { + rmv.call(layer, type, callback.hijacked || callback, capture); + } else { + rmv.call(layer, type, callback, capture); + } + }; + + layer.addEventListener = function(type, callback, capture) { + var adv = Node.prototype.addEventListener; + if (type === 'click') { + adv.call(layer, type, callback.hijacked || (callback.hijacked = function(event) { + if (!event.propagationStopped) { + callback(event); + } + }), capture); + } else { + adv.call(layer, type, callback, capture); + } + }; + } + + // If a handler is already declared in the element's onclick attribute, it will be fired before + // FastClick's onClick handler. Fix this by pulling out the user-defined handler function and + // adding it as listener. + if (typeof layer.onclick === 'function') { + + // Android browser on at least 3.2 requires a new reference to the function in layer.onclick + // - the old one won't work if passed to addEventListener directly. + oldOnClick = layer.onclick; + layer.addEventListener('click', function(event) { + oldOnClick(event); + }, false); + layer.onclick = null; + } +} + + +/** + * Android requires exceptions. + * + * @type boolean + */ +var deviceIsAndroid = navigator.userAgent.indexOf('Android') > 0; + + +/** + * iOS requires exceptions. + * + * @type boolean + */ +var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent); + + +/** + * iOS 4 requires an exception for select elements. + * + * @type boolean + */ +var deviceIsIOS4 = deviceIsIOS && (/OS 4_\d(_\d)?/).test(navigator.userAgent); + + +/** + * iOS 6.0(+?) requires the target element to be manually derived + * + * @type boolean + */ +var deviceIsIOSWithBadTarget = deviceIsIOS && (/OS ([6-9]|\d{2})_\d/).test(navigator.userAgent); + + +/** + * Determine whether a given element requires a native click. + * + * @param {EventTarget|Element} target Target DOM element + * @returns {boolean} Returns true if the element needs a native click + */ +FastClick.prototype.needsClick = function(target) { + 'use strict'; + switch (target.nodeName.toLowerCase()) { + + // Don't send a synthetic click to disabled inputs (issue #62) + case 'button': + case 'select': + case 'textarea': + if (target.disabled) { + return true; + } + + break; + case 'input': + + // File inputs need real clicks on iOS 6 due to a browser bug (issue #68) + if ((deviceIsIOS && target.type === 'file') || target.disabled) { + return true; + } + + break; + case 'label': + case 'video': + return true; + } + + return (/\bneedsclick\b/).test(target.className); +}; + + +/** + * Determine whether a given element requires a call to focus to simulate click into element. + * + * @param {EventTarget|Element} target Target DOM element + * @returns {boolean} Returns true if the element requires a call to focus to simulate native click. + */ +FastClick.prototype.needsFocus = function(target) { + 'use strict'; + switch (target.nodeName.toLowerCase()) { + case 'textarea': + return true; + case 'select': + return !deviceIsAndroid; + case 'input': + switch (target.type) { + case 'button': + case 'checkbox': + case 'file': + case 'image': + case 'radio': + case 'submit': + return false; + } + + // No point in attempting to focus disabled inputs + return !target.disabled && !target.readOnly; + default: + return (/\bneedsfocus\b/).test(target.className); + } +}; + + +/** + * Send a click event to the specified element. + * + * @param {EventTarget|Element} targetElement + * @param {Event} event + */ +FastClick.prototype.sendClick = function(targetElement, event) { + 'use strict'; + var clickEvent, touch; + + // On some Android devices activeElement needs to be blurred otherwise the synthetic click will have no effect (#24) + if (document.activeElement && document.activeElement !== targetElement) { + document.activeElement.blur(); + } + + touch = event.changedTouches[0]; + + // Synthesise a click event, with an extra attribute so it can be tracked + clickEvent = document.createEvent('MouseEvents'); + clickEvent.initMouseEvent(this.determineEventType(targetElement), true, true, window, 1, touch.screenX, touch.screenY, touch.clientX, touch.clientY, false, false, false, false, 0, null); + clickEvent.forwardedTouchEvent = true; + targetElement.dispatchEvent(clickEvent); +}; + +FastClick.prototype.determineEventType = function(targetElement) { + 'use strict'; + + //Issue #159: Android Chrome Select Box does not open with a synthetic click event + if (deviceIsAndroid && targetElement.tagName.toLowerCase() === 'select') { + return 'mousedown'; + } + + return 'click'; +}; + + +/** + * @param {EventTarget|Element} targetElement + */ +FastClick.prototype.focus = function(targetElement) { + 'use strict'; + var length; + + // Issue #160: on iOS 7, some input elements (e.g. date datetime) throw a vague TypeError on setSelectionRange. These elements don't have an integer value for the selectionStart and selectionEnd properties, but unfortunately that can't be used for detection because accessing the properties also throws a TypeError. Just check the type instead. Filed as Apple bug #15122724. + if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date') !== 0 && targetElement.type !== 'time') { + length = targetElement.value.length; + targetElement.setSelectionRange(length, length); + } else { + targetElement.focus(); + } +}; + + +/** + * Check whether the given target element is a child of a scrollable layer and if so, set a flag on it. + * + * @param {EventTarget|Element} targetElement + */ +FastClick.prototype.updateScrollParent = function(targetElement) { + 'use strict'; + var scrollParent, parentElement; + + scrollParent = targetElement.fastClickScrollParent; + + // Attempt to discover whether the target element is contained within a scrollable layer. Re-check if the + // target element was moved to another parent. + if (!scrollParent || !scrollParent.contains(targetElement)) { + parentElement = targetElement; + do { + if (parentElement.scrollHeight > parentElement.offsetHeight) { + scrollParent = parentElement; + targetElement.fastClickScrollParent = parentElement; + break; + } + + parentElement = parentElement.parentElement; + } while (parentElement); + } + + // Always update the scroll top tracker if possible. + if (scrollParent) { + scrollParent.fastClickLastScrollTop = scrollParent.scrollTop; + } +}; + + +/** + * @param {EventTarget} targetElement + * @returns {Element|EventTarget} + */ +FastClick.prototype.getTargetElementFromEventTarget = function(eventTarget) { + 'use strict'; + + // On some older browsers (notably Safari on iOS 4.1 - see issue #56) the event target may be a text node. + if (eventTarget.nodeType === Node.TEXT_NODE) { + return eventTarget.parentNode; + } + + return eventTarget; +}; + + +/** + * On touch start, record the position and scroll offset. + * + * @param {Event} event + * @returns {boolean} + */ +FastClick.prototype.onTouchStart = function(event) { + 'use strict'; + var targetElement, touch, selection; + + // Ignore multiple touches, otherwise pinch-to-zoom is prevented if both fingers are on the FastClick element (issue #111). + if (event.targetTouches.length > 1) { + return true; + } + + targetElement = this.getTargetElementFromEventTarget(event.target); + touch = event.targetTouches[0]; + + if (deviceIsIOS) { + + // Only trusted events will deselect text on iOS (issue #49) + selection = window.getSelection(); + if (selection.rangeCount && !selection.isCollapsed) { + return true; + } + + if (!deviceIsIOS4) { + + // Weird things happen on iOS when an alert or confirm dialog is opened from a click event callback (issue #23): + // when the user next taps anywhere else on the page, new touchstart and touchend events are dispatched + // with the same identifier as the touch event that previously triggered the click that triggered the alert. + // Sadly, there is an issue on iOS 4 that causes some normal touch events to have the same identifier as an + // immediately preceeding touch event (issue #52), so this fix is unavailable on that platform. + if (touch.identifier === this.lastTouchIdentifier) { + event.preventDefault(); + return false; + } + + this.lastTouchIdentifier = touch.identifier; + + // If the target element is a child of a scrollable layer (using -webkit-overflow-scrolling: touch) and: + // 1) the user does a fling scroll on the scrollable layer + // 2) the user stops the fling scroll with another tap + // then the event.target of the last 'touchend' event will be the element that was under the user's finger + // when the fling scroll was started, causing FastClick to send a click event to that layer - unless a check + // is made to ensure that a parent layer was not scrolled before sending a synthetic click (issue #42). + this.updateScrollParent(targetElement); + } + } + + this.trackingClick = true; + this.trackingClickStart = event.timeStamp; + this.targetElement = targetElement; + + this.touchStartX = touch.pageX; + this.touchStartY = touch.pageY; + + // Prevent phantom clicks on fast double-tap (issue #36) + if ((event.timeStamp - this.lastClickTime) < this.tapDelay) { + event.preventDefault(); + } + + return true; +}; + + +/** + * Based on a touchmove event object, check whether the touch has moved past a boundary since it started. + * + * @param {Event} event + * @returns {boolean} + */ +FastClick.prototype.touchHasMoved = function(event) { + 'use strict'; + var touch = event.changedTouches[0], boundary = this.touchBoundary; + + if (Math.abs(touch.pageX - this.touchStartX) > boundary || Math.abs(touch.pageY - this.touchStartY) > boundary) { + return true; + } + + return false; +}; + + +/** + * Update the last position. + * + * @param {Event} event + * @returns {boolean} + */ +FastClick.prototype.onTouchMove = function(event) { + 'use strict'; + if (!this.trackingClick) { + return true; + } + + // If the touch has moved, cancel the click tracking + if (this.targetElement !== this.getTargetElementFromEventTarget(event.target) || this.touchHasMoved(event)) { + this.trackingClick = false; + this.targetElement = null; + } + + return true; +}; + + +/** + * Attempt to find the labelled control for the given label element. + * + * @param {EventTarget|HTMLLabelElement} labelElement + * @returns {Element|null} + */ +FastClick.prototype.findControl = function(labelElement) { + 'use strict'; + + // Fast path for newer browsers supporting the HTML5 control attribute + if (labelElement.control !== undefined) { + return labelElement.control; + } + + // All browsers under test that support touch events also support the HTML5 htmlFor attribute + if (labelElement.htmlFor) { + return document.getElementById(labelElement.htmlFor); + } + + // If no for attribute exists, attempt to retrieve the first labellable descendant element + // the list of which is defined here: http://www.w3.org/TR/html5/forms.html#category-label + return labelElement.querySelector('button, input:not([type=hidden]), keygen, meter, output, progress, select, textarea'); +}; + + +/** + * On touch end, determine whether to send a click event at once. + * + * @param {Event} event + * @returns {boolean} + */ +FastClick.prototype.onTouchEnd = function(event) { + 'use strict'; + var forElement, trackingClickStart, targetTagName, scrollParent, touch, targetElement = this.targetElement; + + if (!this.trackingClick) { + return true; + } + + // Prevent phantom clicks on fast double-tap (issue #36) + if ((event.timeStamp - this.lastClickTime) < this.tapDelay) { + this.cancelNextClick = true; + return true; + } + + // Reset to prevent wrong click cancel on input (issue #156). + this.cancelNextClick = false; + + this.lastClickTime = event.timeStamp; + + trackingClickStart = this.trackingClickStart; + this.trackingClick = false; + this.trackingClickStart = 0; + + // On some iOS devices, the targetElement supplied with the event is invalid if the layer + // is performing a transition or scroll, and has to be re-detected manually. Note that + // for this to function correctly, it must be called *after* the event target is checked! + // See issue #57; also filed as rdar://13048589 . + if (deviceIsIOSWithBadTarget) { + touch = event.changedTouches[0]; + + // In certain cases arguments of elementFromPoint can be negative, so prevent setting targetElement to null + targetElement = document.elementFromPoint(touch.pageX - window.pageXOffset, touch.pageY - window.pageYOffset) || targetElement; + targetElement.fastClickScrollParent = this.targetElement.fastClickScrollParent; + } + + targetTagName = targetElement.tagName.toLowerCase(); + if (targetTagName === 'label') { + forElement = this.findControl(targetElement); + if (forElement) { + this.focus(targetElement); + if (deviceIsAndroid) { + return false; + } + + targetElement = forElement; + } + } else if (this.needsFocus(targetElement)) { + + // Case 1: If the touch started a while ago (best guess is 100ms based on tests for issue #36) then focus will be triggered anyway. Return early and unset the target element reference so that the subsequent click will be allowed through. + // Case 2: Without this exception for input elements tapped when the document is contained in an iframe, then any inputted text won't be visible even though the value attribute is updated as the user types (issue #37). + if ((event.timeStamp - trackingClickStart) > 100 || (deviceIsIOS && window.top !== window && targetTagName === 'input')) { + this.targetElement = null; + return false; + } + + this.focus(targetElement); + this.sendClick(targetElement, event); + + // Select elements need the event to go through on iOS 4, otherwise the selector menu won't open. + // Also this breaks opening selects when VoiceOver is active on iOS6, iOS7 (and possibly others) + if (!deviceIsIOS || targetTagName !== 'select') { + this.targetElement = null; + event.preventDefault(); + } + + return false; + } + + if (deviceIsIOS && !deviceIsIOS4) { + + // Don't send a synthetic click event if the target element is contained within a parent layer that was scrolled + // and this tap is being used to stop the scrolling (usually initiated by a fling - issue #42). + scrollParent = targetElement.fastClickScrollParent; + if (scrollParent && scrollParent.fastClickLastScrollTop !== scrollParent.scrollTop) { + return true; + } + } + + // Prevent the actual click from going though - unless the target node is marked as requiring + // real clicks or if it is in the whitelist in which case only non-programmatic clicks are permitted. + if (!this.needsClick(targetElement)) { + event.preventDefault(); + this.sendClick(targetElement, event); + } + + return false; +}; + + +/** + * On touch cancel, stop tracking the click. + * + * @returns {void} + */ +FastClick.prototype.onTouchCancel = function() { + 'use strict'; + this.trackingClick = false; + this.targetElement = null; +}; + + +/** + * Determine mouse events which should be permitted. + * + * @param {Event} event + * @returns {boolean} + */ +FastClick.prototype.onMouse = function(event) { + 'use strict'; + + // If a target element was never set (because a touch event was never fired) allow the event + if (!this.targetElement) { + return true; + } + + if (event.forwardedTouchEvent) { + return true; + } + + // Programmatically generated events targeting a specific element should be permitted + if (!event.cancelable) { + return true; + } + + // Derive and check the target element to see whether the mouse event needs to be permitted; + // unless explicitly enabled, prevent non-touch click events from triggering actions, + // to prevent ghost/doubleclicks. + if (!this.needsClick(this.targetElement) || this.cancelNextClick) { + + // Prevent any user-added listeners declared on FastClick element from being fired. + if (event.stopImmediatePropagation) { + event.stopImmediatePropagation(); + } else { + + // Part of the hack for browsers that don't support Event#stopImmediatePropagation (e.g. Android 2) + event.propagationStopped = true; + } + + // Cancel the event + event.stopPropagation(); + event.preventDefault(); + + return false; + } + + // If the mouse event is permitted, return true for the action to go through. + return true; +}; + + +/** + * On actual clicks, determine whether this is a touch-generated click, a click action occurring + * naturally after a delay after a touch (which needs to be cancelled to avoid duplication), or + * an actual click which should be permitted. + * + * @param {Event} event + * @returns {boolean} + */ +FastClick.prototype.onClick = function(event) { + 'use strict'; + var permitted; + + // It's possible for another FastClick-like library delivered with third-party code to fire a click event before FastClick does (issue #44). In that case, set the click-tracking flag back to false and return early. This will cause onTouchEnd to return early. + if (this.trackingClick) { + this.targetElement = null; + this.trackingClick = false; + return true; + } + + // Very odd behaviour on iOS (issue #18): if a submit element is present inside a form and the user hits enter in the iOS simulator or clicks the Go button on the pop-up OS keyboard the a kind of 'fake' click event will be triggered with the submit-type input element as the target. + if (event.target.type === 'submit' && event.detail === 0) { + return true; + } + + permitted = this.onMouse(event); + + // Only unset targetElement if the click is not permitted. This will ensure that the check for !targetElement in onMouse fails and the browser's click doesn't go through. + if (!permitted) { + this.targetElement = null; + } + + // If clicks are permitted, return true for the action to go through. + return permitted; +}; + + +/** + * Remove all FastClick's event listeners. + * + * @returns {void} + */ +FastClick.prototype.destroy = function() { + 'use strict'; + var layer = this.layer; + + if (deviceIsAndroid) { + layer.removeEventListener('mouseover', this.onMouse, true); + layer.removeEventListener('mousedown', this.onMouse, true); + layer.removeEventListener('mouseup', this.onMouse, true); + } + + layer.removeEventListener('click', this.onClick, true); + layer.removeEventListener('touchstart', this.onTouchStart, false); + layer.removeEventListener('touchmove', this.onTouchMove, false); + layer.removeEventListener('touchend', this.onTouchEnd, false); + layer.removeEventListener('touchcancel', this.onTouchCancel, false); +}; + + +/** + * Check whether FastClick is needed. + * + * @param {Element} layer The layer to listen on + */ +FastClick.notNeeded = function(layer) { + 'use strict'; + var metaViewport; + var chromeVersion; + + // Devices that don't support touch don't need FastClick + if (typeof window.ontouchstart === 'undefined') { + return true; + } + + // Chrome version - zero for other browsers + chromeVersion = +(/Chrome\/([0-9]+)/.exec(navigator.userAgent) || [,0])[1]; + + if (chromeVersion) { + + if (deviceIsAndroid) { + metaViewport = document.querySelector('meta[name=viewport]'); + + if (metaViewport) { + // Chrome on Android with user-scalable="no" doesn't need FastClick (issue #89) + if (metaViewport.content.indexOf('user-scalable=no') !== -1) { + return true; + } + // Chrome 32 and above with width=device-width or less don't need FastClick + if (chromeVersion > 31 && document.documentElement.scrollWidth <= window.outerWidth) { + return true; + } + } + + // Chrome desktop doesn't need FastClick (issue #15) + } else { + return true; + } + } + + // IE10 with -ms-touch-action: none, which disables double-tap-to-zoom (issue #97) + if (layer.style.msTouchAction === 'none') { + return true; + } + + return false; +}; + + +/** + * Factory method for creating a FastClick object + * + * @param {Element} layer The layer to listen on + * @param {Object} options The options to override the defaults + */ +FastClick.attach = function(layer, options) { + 'use strict'; + return new FastClick(layer, options); +}; + + +if (typeof define !== 'undefined' && define.amd) { + + // AMD. Register as an anonymous module. + define(function() { + 'use strict'; + return FastClick; + }); +} else if (typeof module !== 'undefined' && module.exports) { + module.exports = FastClick.attach; + module.exports.FastClick = FastClick; +} else { + window.FastClick = FastClick; +} diff --git a/StoneIsland/platforms/android/assets/www/js/vendor/flickity.pkgd.js b/StoneIsland/platforms/android/assets/www/js/vendor/flickity.pkgd.js new file mode 100755 index 00000000..0471fa5b --- /dev/null +++ b/StoneIsland/platforms/android/assets/www/js/vendor/flickity.pkgd.js @@ -0,0 +1,5090 @@ +/*! + * Flickity PACKAGED v1.0.1 + * Touch, responsive, flickable galleries + * + * Licensed GPLv3 for open source use + * or Flickity Commercial License for commercial use + * + * http://flickity.metafizzy.co + * Copyright 2015 Metafizzy + */ + +/** + * Bridget makes jQuery widgets + * v1.1.0 + * MIT license + */ + +( function( window ) { + + + +// -------------------------- utils -------------------------- // + +var slice = Array.prototype.slice; + +function noop() {} + +// -------------------------- definition -------------------------- // + +function defineBridget( $ ) { + +// bail if no jQuery +if ( !$ ) { + return; +} + +// -------------------------- addOptionMethod -------------------------- // + +/** + * adds option method -> $().plugin('option', {...}) + * @param {Function} PluginClass - constructor class + */ +function addOptionMethod( PluginClass ) { + // don't overwrite original option method + if ( PluginClass.prototype.option ) { + return; + } + + // option setter + PluginClass.prototype.option = function( opts ) { + // bail out if not an object + if ( !$.isPlainObject( opts ) ){ + return; + } + this.options = $.extend( true, this.options, opts ); + }; +} + +// -------------------------- plugin bridge -------------------------- // + +// helper function for logging errors +// $.error breaks jQuery chaining +var logError = typeof console === 'undefined' ? noop : + function( message ) { + console.error( message ); + }; + +/** + * jQuery plugin bridge, access methods like $elem.plugin('method') + * @param {String} namespace - plugin name + * @param {Function} PluginClass - constructor class + */ +function bridge( namespace, PluginClass ) { + // add to jQuery fn namespace + $.fn[ namespace ] = function( options ) { + if ( typeof options === 'string' ) { + // call plugin method when first argument is a string + // get arguments for method + var args = slice.call( arguments, 1 ); + + for ( var i=0, len = this.length; i < len; i++ ) { + var elem = this[i]; + var instance = $.data( elem, namespace ); + if ( !instance ) { + logError( "cannot call methods on " + namespace + " prior to initialization; " + + "attempted to call '" + options + "'" ); + continue; + } + if ( !$.isFunction( instance[options] ) || options.charAt(0) === '_' ) { + logError( "no such method '" + options + "' for " + namespace + " instance" ); + continue; + } + + // trigger method with arguments + var returnValue = instance[ options ].apply( instance, args ); + + // break look and return first value if provided + if ( returnValue !== undefined ) { + return returnValue; + } + } + // return this if no return value + return this; + } else { + return this.each( function() { + var instance = $.data( this, namespace ); + if ( instance ) { + // apply options & init + instance.option( options ); + instance._init(); + } else { + // initialize new instance + instance = new PluginClass( this, options ); + $.data( this, namespace, instance ); + } + }); + } + }; + +} + +// -------------------------- bridget -------------------------- // + +/** + * converts a Prototypical class into a proper jQuery plugin + * the class must have a ._init method + * @param {String} namespace - plugin name, used in $().pluginName + * @param {Function} PluginClass - constructor class + */ +$.bridget = function( namespace, PluginClass ) { + addOptionMethod( PluginClass ); + bridge( namespace, PluginClass ); +}; + +return $.bridget; + +} + +// transport +if ( typeof define === 'function' && define.amd ) { + // AMD + define( 'jquery-bridget/jquery.bridget',[ 'jquery' ], defineBridget ); +} else if ( typeof exports === 'object' ) { + defineBridget( require('jquery') ); +} else { + // get jquery from browser global + defineBridget( window.jQuery ); +} + +})( window ); + +/*! + * classie v1.0.1 + * class helper functions + * from bonzo https://github.com/ded/bonzo + * MIT license + * + * classie.has( elem, 'my-class' ) -> true/false + * classie.add( elem, 'my-new-class' ) + * classie.remove( elem, 'my-unwanted-class' ) + * classie.toggle( elem, 'my-class' ) + */ + +/*jshint browser: true, strict: true, undef: true, unused: true */ +/*global define: false, module: false */ + +( function( window ) { + + + +// class helper functions from bonzo https://github.com/ded/bonzo + +function classReg( className ) { + return new RegExp("(^|\\s+)" + className + "(\\s+|$)"); +} + +// classList support for class management +// altho to be fair, the api sucks because it won't accept multiple classes at once +var hasClass, addClass, removeClass; + +if ( 'classList' in document.documentElement ) { + hasClass = function( elem, c ) { + return elem.classList.contains( c ); + }; + addClass = function( elem, c ) { + elem.classList.add( c ); + }; + removeClass = function( elem, c ) { + elem.classList.remove( c ); + }; +} +else { + hasClass = function( elem, c ) { + return classReg( c ).test( elem.className ); + }; + addClass = function( elem, c ) { + if ( !hasClass( elem, c ) ) { + elem.className = elem.className + ' ' + c; + } + }; + removeClass = function( elem, c ) { + elem.className = elem.className.replace( classReg( c ), ' ' ); + }; +} + +function toggleClass( elem, c ) { + var fn = hasClass( elem, c ) ? removeClass : addClass; + fn( elem, c ); +} + +var classie = { + // full names + hasClass: hasClass, + addClass: addClass, + removeClass: removeClass, + toggleClass: toggleClass, + // short names + has: hasClass, + add: addClass, + remove: removeClass, + toggle: toggleClass +}; + +// transport +if ( typeof define === 'function' && define.amd ) { + // AMD + define( 'classie/classie',classie ); +} else if ( typeof exports === 'object' ) { + // CommonJS + module.exports = classie; +} else { + // browser global + window.classie = classie; +} + +})( window ); + +/*! + * EventEmitter v4.2.11 - git.io/ee + * Unlicense - http://unlicense.org/ + * Oliver Caldwell - http://oli.me.uk/ + * @preserve + */ + +;(function () { + + + /** + * Class for managing events. + * Can be extended to provide event functionality in other classes. + * + * @class EventEmitter Manages event registering and emitting. + */ + function EventEmitter() {} + + // Shortcuts to improve speed and size + var proto = EventEmitter.prototype; + var exports = this; + var originalGlobalValue = exports.EventEmitter; + + /** + * Finds the index of the listener for the event in its storage array. + * + * @param {Function[]} listeners Array of listeners to search through. + * @param {Function} listener Method to look for. + * @return {Number} Index of the specified listener, -1 if not found + * @api private + */ + function indexOfListener(listeners, listener) { + var i = listeners.length; + while (i--) { + if (listeners[i].listener === listener) { + return i; + } + } + + return -1; + } + + /** + * Alias a method while keeping the context correct, to allow for overwriting of target method. + * + * @param {String} name The name of the target method. + * @return {Function} The aliased method + * @api private + */ + function alias(name) { + return function aliasClosure() { + return this[name].apply(this, arguments); + }; + } + + /** + * Returns the listener array for the specified event. + * Will initialise the event object and listener arrays if required. + * Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them. + * Each property in the object response is an array of listener functions. + * + * @param {String|RegExp} evt Name of the event to return the listeners from. + * @return {Function[]|Object} All listener functions for the event. + */ + proto.getListeners = function getListeners(evt) { + var events = this._getEvents(); + var response; + var key; + + // Return a concatenated array of all matching events if + // the selector is a regular expression. + if (evt instanceof RegExp) { + response = {}; + for (key in events) { + if (events.hasOwnProperty(key) && evt.test(key)) { + response[key] = events[key]; + } + } + } + else { + response = events[evt] || (events[evt] = []); + } + + return response; + }; + + /** + * Takes a list of listener objects and flattens it into a list of listener functions. + * + * @param {Object[]} listeners Raw listener objects. + * @return {Function[]} Just the listener functions. + */ + proto.flattenListeners = function flattenListeners(listeners) { + var flatListeners = []; + var i; + + for (i = 0; i < listeners.length; i += 1) { + flatListeners.push(listeners[i].listener); + } + + return flatListeners; + }; + + /** + * Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful. + * + * @param {String|RegExp} evt Name of the event to return the listeners from. + * @return {Object} All listener functions for an event in an object. + */ + proto.getListenersAsObject = function getListenersAsObject(evt) { + var listeners = this.getListeners(evt); + var response; + + if (listeners instanceof Array) { + response = {}; + response[evt] = listeners; + } + + return response || listeners; + }; + + /** + * Adds a listener function to the specified event. + * The listener will not be added if it is a duplicate. + * If the listener returns true then it will be removed after it is called. + * If you pass a regular expression as the event name then the listener will be added to all events that match it. + * + * @param {String|RegExp} evt Name of the event to attach the listener to. + * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.addListener = function addListener(evt, listener) { + var listeners = this.getListenersAsObject(evt); + var listenerIsWrapped = typeof listener === 'object'; + var key; + + for (key in listeners) { + if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) { + listeners[key].push(listenerIsWrapped ? listener : { + listener: listener, + once: false + }); + } + } + + return this; + }; + + /** + * Alias of addListener + */ + proto.on = alias('addListener'); + + /** + * Semi-alias of addListener. It will add a listener that will be + * automatically removed after its first execution. + * + * @param {String|RegExp} evt Name of the event to attach the listener to. + * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.addOnceListener = function addOnceListener(evt, listener) { + return this.addListener(evt, { + listener: listener, + once: true + }); + }; + + /** + * Alias of addOnceListener. + */ + proto.once = alias('addOnceListener'); + + /** + * Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad. + * You need to tell it what event names should be matched by a regex. + * + * @param {String} evt Name of the event to create. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.defineEvent = function defineEvent(evt) { + this.getListeners(evt); + return this; + }; + + /** + * Uses defineEvent to define multiple events. + * + * @param {String[]} evts An array of event names to define. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.defineEvents = function defineEvents(evts) { + for (var i = 0; i < evts.length; i += 1) { + this.defineEvent(evts[i]); + } + return this; + }; + + /** + * Removes a listener function from the specified event. + * When passed a regular expression as the event name, it will remove the listener from all events that match it. + * + * @param {String|RegExp} evt Name of the event to remove the listener from. + * @param {Function} listener Method to remove from the event. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.removeListener = function removeListener(evt, listener) { + var listeners = this.getListenersAsObject(evt); + var index; + var key; + + for (key in listeners) { + if (listeners.hasOwnProperty(key)) { + index = indexOfListener(listeners[key], listener); + + if (index !== -1) { + listeners[key].splice(index, 1); + } + } + } + + return this; + }; + + /** + * Alias of removeListener + */ + proto.off = alias('removeListener'); + + /** + * Adds listeners in bulk using the manipulateListeners method. + * If you pass an object as the second argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added. + * You can also pass it a regular expression to add the array of listeners to all events that match it. + * Yeah, this function does quite a bit. That's probably a bad thing. + * + * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once. + * @param {Function[]} [listeners] An optional array of listener functions to add. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.addListeners = function addListeners(evt, listeners) { + // Pass through to manipulateListeners + return this.manipulateListeners(false, evt, listeners); + }; + + /** + * Removes listeners in bulk using the manipulateListeners method. + * If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. + * You can also pass it an event name and an array of listeners to be removed. + * You can also pass it a regular expression to remove the listeners from all events that match it. + * + * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once. + * @param {Function[]} [listeners] An optional array of listener functions to remove. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.removeListeners = function removeListeners(evt, listeners) { + // Pass through to manipulateListeners + return this.manipulateListeners(true, evt, listeners); + }; + + /** + * Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level. + * The first argument will determine if the listeners are removed (true) or added (false). + * If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. + * You can also pass it an event name and an array of listeners to be added/removed. + * You can also pass it a regular expression to manipulate the listeners of all events that match it. + * + * @param {Boolean} remove True if you want to remove listeners, false if you want to add. + * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once. + * @param {Function[]} [listeners] An optional array of listener functions to add/remove. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) { + var i; + var value; + var single = remove ? this.removeListener : this.addListener; + var multiple = remove ? this.removeListeners : this.addListeners; + + // If evt is an object then pass each of its properties to this method + if (typeof evt === 'object' && !(evt instanceof RegExp)) { + for (i in evt) { + if (evt.hasOwnProperty(i) && (value = evt[i])) { + // Pass the single listener straight through to the singular method + if (typeof value === 'function') { + single.call(this, i, value); + } + else { + // Otherwise pass back to the multiple function + multiple.call(this, i, value); + } + } + } + } + else { + // So evt must be a string + // And listeners must be an array of listeners + // Loop over it and pass each one to the multiple method + i = listeners.length; + while (i--) { + single.call(this, evt, listeners[i]); + } + } + + return this; + }; + + /** + * Removes all listeners from a specified event. + * If you do not specify an event then all listeners will be removed. + * That means every event will be emptied. + * You can also pass a regex to remove all events that match it. + * + * @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.removeEvent = function removeEvent(evt) { + var type = typeof evt; + var events = this._getEvents(); + var key; + + // Remove different things depending on the state of evt + if (type === 'string') { + // Remove all listeners for the specified event + delete events[evt]; + } + else if (evt instanceof RegExp) { + // Remove all events matching the regex. + for (key in events) { + if (events.hasOwnProperty(key) && evt.test(key)) { + delete events[key]; + } + } + } + else { + // Remove all listeners in all events + delete this._events; + } + + return this; + }; + + /** + * Alias of removeEvent. + * + * Added to mirror the node API. + */ + proto.removeAllListeners = alias('removeEvent'); + + /** + * Emits an event of your choice. + * When emitted, every listener attached to that event will be executed. + * If you pass the optional argument array then those arguments will be passed to every listener upon execution. + * Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately. + * So they will not arrive within the array on the other side, they will be separate. + * You can also pass a regular expression to emit to all events that match it. + * + * @param {String|RegExp} evt Name of the event to emit and execute listeners for. + * @param {Array} [args] Optional array of arguments to be passed to each listener. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.emitEvent = function emitEvent(evt, args) { + var listeners = this.getListenersAsObject(evt); + var listener; + var i; + var key; + var response; + + for (key in listeners) { + if (listeners.hasOwnProperty(key)) { + i = listeners[key].length; + + while (i--) { + // If the listener returns true then it shall be removed from the event + // The function is executed either with a basic call or an apply if there is an args array + listener = listeners[key][i]; + + if (listener.once === true) { + this.removeListener(evt, listener.listener); + } + + response = listener.listener.apply(this, args || []); + + if (response === this._getOnceReturnValue()) { + this.removeListener(evt, listener.listener); + } + } + } + } + + return this; + }; + + /** + * Alias of emitEvent + */ + proto.trigger = alias('emitEvent'); + + /** + * Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on. + * As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it. + * + * @param {String|RegExp} evt Name of the event to emit and execute listeners for. + * @param {...*} Optional additional arguments to be passed to each listener. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.emit = function emit(evt) { + var args = Array.prototype.slice.call(arguments, 1); + return this.emitEvent(evt, args); + }; + + /** + * Sets the current value to check against when executing listeners. If a + * listeners return value matches the one set here then it will be removed + * after execution. This value defaults to true. + * + * @param {*} value The new value to check for when executing listeners. + * @return {Object} Current instance of EventEmitter for chaining. + */ + proto.setOnceReturnValue = function setOnceReturnValue(value) { + this._onceReturnValue = value; + return this; + }; + + /** + * Fetches the current value to check against when executing listeners. If + * the listeners return value matches this one then it should be removed + * automatically. It will return true by default. + * + * @return {*|Boolean} The current value to check for or the default, true. + * @api private + */ + proto._getOnceReturnValue = function _getOnceReturnValue() { + if (this.hasOwnProperty('_onceReturnValue')) { + return this._onceReturnValue; + } + else { + return true; + } + }; + + /** + * Fetches the events object and creates one if required. + * + * @return {Object} The events storage object. + * @api private + */ + proto._getEvents = function _getEvents() { + return this._events || (this._events = {}); + }; + + /** + * Reverts the global {@link EventEmitter} to its previous value and returns a reference to this version. + * + * @return {Function} Non conflicting EventEmitter class. + */ + EventEmitter.noConflict = function noConflict() { + exports.EventEmitter = originalGlobalValue; + return EventEmitter; + }; + + // Expose the class either via AMD, CommonJS or the global object + if (typeof define === 'function' && define.amd) { + define('eventEmitter/EventEmitter',[],function () { + return EventEmitter; + }); + } + else if (typeof module === 'object' && module.exports){ + module.exports = EventEmitter; + } + else { + exports.EventEmitter = EventEmitter; + } +}.call(this)); + +/*! + * eventie v1.0.6 + * event binding helper + * eventie.bind( elem, 'click', myFn ) + * eventie.unbind( elem, 'click', myFn ) + * MIT license + */ + +/*jshint browser: true, undef: true, unused: true */ +/*global define: false, module: false */ + +( function( window ) { + + + +var docElem = document.documentElement; + +var bind = function() {}; + +function getIEEvent( obj ) { + var event = window.event; + // add event.target + event.target = event.target || event.srcElement || obj; + return event; +} + +if ( docElem.addEventListener ) { + bind = function( obj, type, fn ) { + obj.addEventListener( type, fn, false ); + }; +} else if ( docElem.attachEvent ) { + bind = function( obj, type, fn ) { + obj[ type + fn ] = fn.handleEvent ? + function() { + var event = getIEEvent( obj ); + fn.handleEvent.call( fn, event ); + } : + function() { + var event = getIEEvent( obj ); + fn.call( obj, event ); + }; + obj.attachEvent( "on" + type, obj[ type + fn ] ); + }; +} + +var unbind = function() {}; + +if ( docElem.removeEventListener ) { + unbind = function( obj, type, fn ) { + obj.removeEventListener( type, fn, false ); + }; +} else if ( docElem.detachEvent ) { + unbind = function( obj, type, fn ) { + obj.detachEvent( "on" + type, obj[ type + fn ] ); + try { + delete obj[ type + fn ]; + } catch ( err ) { + // can't delete window object properties + obj[ type + fn ] = undefined; + } + }; +} + +var eventie = { + bind: bind, + unbind: unbind +}; + +// ----- module definition ----- // + +if ( typeof define === 'function' && define.amd ) { + // AMD + define( 'eventie/eventie',eventie ); +} else if ( typeof exports === 'object' ) { + // CommonJS + module.exports = eventie; +} else { + // browser global + window.eventie = eventie; +} + +})( window ); + +/*! + * getStyleProperty v1.0.4 + * original by kangax + * http://perfectionkills.com/feature-testing-css-properties/ + * MIT license + */ + +/*jshint browser: true, strict: true, undef: true */ +/*global define: false, exports: false, module: false */ + +( function( window ) { + + + +var prefixes = 'Webkit Moz ms Ms O'.split(' '); +var docElemStyle = document.documentElement.style; + +function getStyleProperty( propName ) { + if ( !propName ) { + return; + } + + // test standard property first + if ( typeof docElemStyle[ propName ] === 'string' ) { + return propName; + } + + // capitalize + propName = propName.charAt(0).toUpperCase() + propName.slice(1); + + // test vendor specific properties + var prefixed; + for ( var i=0, len = prefixes.length; i < len; i++ ) { + prefixed = prefixes[i] + propName; + if ( typeof docElemStyle[ prefixed ] === 'string' ) { + return prefixed; + } + } +} + +// transport +if ( typeof define === 'function' && define.amd ) { + // AMD + define( 'get-style-property/get-style-property',[],function() { + return getStyleProperty; + }); +} else if ( typeof exports === 'object' ) { + // CommonJS for Component + module.exports = getStyleProperty; +} else { + // browser global + window.getStyleProperty = getStyleProperty; +} + +})( window ); + +/*! + * getSize v1.2.2 + * measure size of elements + * MIT license + */ + +/*jshint browser: true, strict: true, undef: true, unused: true */ +/*global define: false, exports: false, require: false, module: false, console: false */ + +( function( window, undefined ) { + + + +// -------------------------- helpers -------------------------- // + +// get a number from a string, not a percentage +function getStyleSize( value ) { + var num = parseFloat( value ); + // not a percent like '100%', and a number + var isValid = value.indexOf('%') === -1 && !isNaN( num ); + return isValid && num; +} + +function noop() {} + +var logError = typeof console === 'undefined' ? noop : + function( message ) { + console.error( message ); + }; + +// -------------------------- measurements -------------------------- // + +var measurements = [ + 'paddingLeft', + 'paddingRight', + 'paddingTop', + 'paddingBottom', + 'marginLeft', + 'marginRight', + 'marginTop', + 'marginBottom', + 'borderLeftWidth', + 'borderRightWidth', + 'borderTopWidth', + 'borderBottomWidth' +]; + +function getZeroSize() { + var size = { + width: 0, + height: 0, + innerWidth: 0, + innerHeight: 0, + outerWidth: 0, + outerHeight: 0 + }; + for ( var i=0, len = measurements.length; i < len; i++ ) { + var measurement = measurements[i]; + size[ measurement ] = 0; + } + return size; +} + + + +function defineGetSize( getStyleProperty ) { + +// -------------------------- setup -------------------------- // + +var isSetup = false; + +var getStyle, boxSizingProp, isBoxSizeOuter; + +/** + * setup vars and functions + * do it on initial getSize(), rather than on script load + * For Firefox bug https://bugzilla.mozilla.org/show_bug.cgi?id=548397 + */ +function setup() { + // setup once + if ( isSetup ) { + return; + } + isSetup = true; + + var getComputedStyle = window.getComputedStyle; + getStyle = ( function() { + var getStyleFn = getComputedStyle ? + function( elem ) { + return getComputedStyle( elem, null ); + } : + function( elem ) { + return elem.currentStyle; + }; + + return function getStyle( elem ) { + var style = getStyleFn( elem ); + if ( !style ) { + logError( 'Style returned ' + style + + '. Are you running this code in a hidden iframe on Firefox? ' + + 'See http://bit.ly/getsizebug1' ); + } + return style; + }; + })(); + + // -------------------------- box sizing -------------------------- // + + boxSizingProp = getStyleProperty('boxSizing'); + + /** + * WebKit measures the outer-width on style.width on border-box elems + * IE & Firefox measures the inner-width + */ + if ( boxSizingProp ) { + var div = document.createElement('div'); + div.style.width = '200px'; + div.style.padding = '1px 2px 3px 4px'; + div.style.borderStyle = 'solid'; + div.style.borderWidth = '1px 2px 3px 4px'; + div.style[ boxSizingProp ] = 'border-box'; + + var body = document.body || document.documentElement; + body.appendChild( div ); + var style = getStyle( div ); + + isBoxSizeOuter = getStyleSize( style.width ) === 200; + body.removeChild( div ); + } + +} + +// -------------------------- getSize -------------------------- // + +function getSize( elem ) { + setup(); + + // use querySeletor if elem is string + if ( typeof elem === 'string' ) { + elem = document.querySelector( elem ); + } + + // do not proceed on non-objects + if ( !elem || typeof elem !== 'object' || !elem.nodeType ) { + return; + } + + var style = getStyle( elem ); + + // if hidden, everything is 0 + if ( style.display === 'none' ) { + return getZeroSize(); + } + + var size = {}; + size.width = elem.offsetWidth; + size.height = elem.offsetHeight; + + var isBorderBox = size.isBorderBox = !!( boxSizingProp && + style[ boxSizingProp ] && style[ boxSizingProp ] === 'border-box' ); + + // get all measurements + for ( var i=0, len = measurements.length; i < len; i++ ) { + var measurement = measurements[i]; + var value = style[ measurement ]; + value = mungeNonPixel( elem, value ); + var num = parseFloat( value ); + // any 'auto', 'medium' value will be 0 + size[ measurement ] = !isNaN( num ) ? num : 0; + } + + var paddingWidth = size.paddingLeft + size.paddingRight; + var paddingHeight = size.paddingTop + size.paddingBottom; + var marginWidth = size.marginLeft + size.marginRight; + var marginHeight = size.marginTop + size.marginBottom; + var borderWidth = size.borderLeftWidth + size.borderRightWidth; + var borderHeight = size.borderTopWidth + size.borderBottomWidth; + + var isBorderBoxSizeOuter = isBorderBox && isBoxSizeOuter; + + // overwrite width and height if we can get it from style + var styleWidth = getStyleSize( style.width ); + if ( styleWidth !== false ) { + size.width = styleWidth + + // add padding and border unless it's already including it + ( isBorderBoxSizeOuter ? 0 : paddingWidth + borderWidth ); + } + + var styleHeight = getStyleSize( style.height ); + if ( styleHeight !== false ) { + size.height = styleHeight + + // add padding and border unless it's already including it + ( isBorderBoxSizeOuter ? 0 : paddingHeight + borderHeight ); + } + + size.innerWidth = size.width - ( paddingWidth + borderWidth ); + size.innerHeight = size.height - ( paddingHeight + borderHeight ); + + size.outerWidth = size.width + marginWidth; + size.outerHeight = size.height + marginHeight; + + return size; +} + +// IE8 returns percent values, not pixels +// taken from jQuery's curCSS +function mungeNonPixel( elem, value ) { + // IE8 and has percent value + if ( window.getComputedStyle || value.indexOf('%') === -1 ) { + return value; + } + var style = elem.style; + // Remember the original values + var left = style.left; + var rs = elem.runtimeStyle; + var rsLeft = rs && rs.left; + + // Put in the new values to get a computed value out + if ( rsLeft ) { + rs.left = elem.currentStyle.left; + } + style.left = value; + value = style.pixelLeft; + + // Revert the changed values + style.left = left; + if ( rsLeft ) { + rs.left = rsLeft; + } + + return value; +} + +return getSize; + +} + +// transport +if ( typeof define === 'function' && define.amd ) { + // AMD for RequireJS + define( 'get-size/get-size',[ 'get-style-property/get-style-property' ], defineGetSize ); +} else if ( typeof exports === 'object' ) { + // CommonJS for Component + module.exports = defineGetSize( require('desandro-get-style-property') ); +} else { + // browser global + window.getSize = defineGetSize( window.getStyleProperty ); +} + +})( window ); + +/*! + * docReady v1.0.4 + * Cross browser DOMContentLoaded event emitter + * MIT license + */ + +/*jshint browser: true, strict: true, undef: true, unused: true*/ +/*global define: false, require: false, module: false */ + +( function( window ) { + + + +var document = window.document; +// collection of functions to be triggered on ready +var queue = []; + +function docReady( fn ) { + // throw out non-functions + if ( typeof fn !== 'function' ) { + return; + } + + if ( docReady.isReady ) { + // ready now, hit it + fn(); + } else { + // queue function when ready + queue.push( fn ); + } +} + +docReady.isReady = false; + +// triggered on various doc ready events +function onReady( event ) { + // bail if already triggered or IE8 document is not ready just yet + var isIE8NotReady = event.type === 'readystatechange' && document.readyState !== 'complete'; + if ( docReady.isReady || isIE8NotReady ) { + return; + } + + trigger(); +} + +function trigger() { + docReady.isReady = true; + // process queue + for ( var i=0, len = queue.length; i < len; i++ ) { + var fn = queue[i]; + fn(); + } +} + +function defineDocReady( eventie ) { + // trigger ready if page is ready + if ( document.readyState === 'complete' ) { + trigger(); + } else { + // listen for events + eventie.bind( document, 'DOMContentLoaded', onReady ); + eventie.bind( document, 'readystatechange', onReady ); + eventie.bind( window, 'load', onReady ); + } + + return docReady; +} + +// transport +if ( typeof define === 'function' && define.amd ) { + // AMD + define( 'doc-ready/doc-ready',[ 'eventie/eventie' ], defineDocReady ); +} else if ( typeof exports === 'object' ) { + module.exports = defineDocReady( require('eventie') ); +} else { + // browser global + window.docReady = defineDocReady( window.eventie ); +} + +})( window ); + +/** + * matchesSelector v1.0.3 + * matchesSelector( element, '.selector' ) + * MIT license + */ + +/*jshint browser: true, strict: true, undef: true, unused: true */ +/*global define: false, module: false */ + +( function( ElemProto ) { + + + + var matchesMethod = ( function() { + // check for the standard method name first + if ( ElemProto.matches ) { + return 'matches'; + } + // check un-prefixed + if ( ElemProto.matchesSelector ) { + return 'matchesSelector'; + } + // check vendor prefixes + var prefixes = [ 'webkit', 'moz', 'ms', 'o' ]; + + for ( var i=0, len = prefixes.length; i < len; i++ ) { + var prefix = prefixes[i]; + var method = prefix + 'MatchesSelector'; + if ( ElemProto[ method ] ) { + return method; + } + } + })(); + + // ----- match ----- // + + function match( elem, selector ) { + return elem[ matchesMethod ]( selector ); + } + + // ----- appendToFragment ----- // + + function checkParent( elem ) { + // not needed if already has parent + if ( elem.parentNode ) { + return; + } + var fragment = document.createDocumentFragment(); + fragment.appendChild( elem ); + } + + // ----- query ----- // + + // fall back to using QSA + // thx @jonathantneal https://gist.github.com/3062955 + function query( elem, selector ) { + // append to fragment if no parent + checkParent( elem ); + + // match elem with all selected elems of parent + var elems = elem.parentNode.querySelectorAll( selector ); + for ( var i=0, len = elems.length; i < len; i++ ) { + // return true if match + if ( elems[i] === elem ) { + return true; + } + } + // otherwise return false + return false; + } + + // ----- matchChild ----- // + + function matchChild( elem, selector ) { + checkParent( elem ); + return match( elem, selector ); + } + + // ----- matchesSelector ----- // + + var matchesSelector; + + if ( matchesMethod ) { + // IE9 supports matchesSelector, but doesn't work on orphaned elems + // check for that + var div = document.createElement('div'); + var supportsOrphans = match( div, 'div' ); + matchesSelector = supportsOrphans ? match : matchChild; + } else { + matchesSelector = query; + } + + // transport + if ( typeof define === 'function' && define.amd ) { + // AMD + define( 'matches-selector/matches-selector',[],function() { + return matchesSelector; + }); + } else if ( typeof exports === 'object' ) { + module.exports = matchesSelector; + } + else { + // browser global + window.matchesSelector = matchesSelector; + } + +})( Element.prototype ); + +/** + * Fizzy UI utils v1.0.1 + * MIT license + */ + +/*jshint browser: true, undef: true, unused: true, strict: true */ + +( function( window, factory ) { + /*global define: false, module: false, require: false */ + + // universal module definition + + if ( typeof define == 'function' && define.amd ) { + // AMD + define( 'fizzy-ui-utils/utils',[ + 'doc-ready/doc-ready', + 'matches-selector/matches-selector' + ], function( docReady, matchesSelector ) { + return factory( window, docReady, matchesSelector ); + }); + } else if ( typeof exports == 'object' ) { + // CommonJS + module.exports = factory( + window, + require('doc-ready'), + require('desandro-matches-selector') + ); + } else { + // browser global + window.fizzyUIUtils = factory( + window, + window.docReady, + window.matchesSelector + ); + } + +}( window, function factory( window, docReady, matchesSelector ) { + + + +var utils = {}; + +// ----- extend ----- // + +// extends objects +utils.extend = function( a, b ) { + for ( var prop in b ) { + a[ prop ] = b[ prop ]; + } + return a; +}; + +// ----- modulo ----- // + +utils.modulo = function( num, div ) { + return ( ( num % div ) + div ) % div; +}; + +// ----- isArray ----- // + +var objToString = Object.prototype.toString; +utils.isArray = function( obj ) { + return objToString.call( obj ) == '[object Array]'; +}; + +// ----- makeArray ----- // + +// turn element or nodeList into an array +utils.makeArray = function( obj ) { + var ary = []; + if ( utils.isArray( obj ) ) { + // use object if already an array + ary = obj; + } else if ( obj && typeof obj.length == 'number' ) { + // convert nodeList to array + for ( var i=0, len = obj.length; i < len; i++ ) { + ary.push( obj[i] ); + } + } else { + // array of single index + ary.push( obj ); + } + return ary; +}; + +// ----- indexOf ----- // + +// index of helper cause IE8 +utils.indexOf = Array.prototype.indexOf ? function( ary, obj ) { + return ary.indexOf( obj ); + } : function( ary, obj ) { + for ( var i=0, len = ary.length; i < len; i++ ) { + if ( ary[i] === obj ) { + return i; + } + } + return -1; + }; + +// ----- removeFrom ----- // + +utils.removeFrom = function( ary, obj ) { + var index = utils.indexOf( ary, obj ); + if ( index != -1 ) { + ary.splice( index, 1 ); + } +}; + +// ----- isElement ----- // + +// http://stackoverflow.com/a/384380/182183 +utils.isElement = ( typeof HTMLElement == 'function' || typeof HTMLElement == 'object' ) ? + function isElementDOM2( obj ) { + return obj instanceof HTMLElement; + } : + function isElementQuirky( obj ) { + return obj && typeof obj == 'object' && + obj.nodeType == 1 && typeof obj.nodeName == 'string'; + }; + +// ----- setText ----- // + +utils.setText = ( function() { + var setTextProperty; + function setText( elem, text ) { + // only check setTextProperty once + setTextProperty = setTextProperty || ( document.documentElement.textContent !== undefined ? 'textContent' : 'innerText' ); + elem[ setTextProperty ] = text; + } + return setText; +})(); + +// ----- getParent ----- // + +utils.getParent = function( elem, selector ) { + while ( elem != document.body ) { + elem = elem.parentNode; + if ( matchesSelector( elem, selector ) ) { + return elem; + } + } +}; + +// ----- getQueryElement ----- // + +// use element as selector string +utils.getQueryElement = function( elem ) { + if ( typeof elem == 'string' ) { + return document.querySelector( elem ); + } + return elem; +}; + +// ----- handleEvent ----- // + +// enable .ontype to trigger from .addEventListener( elem, 'type' ) +utils.handleEvent = function( event ) { + var method = 'on' + event.type; + if ( this[ method ] ) { + this[ method ]( event ); + } +}; + +// ----- filterFindElements ----- // + +utils.filterFindElements = function( elems, selector ) { + // make array of elems + elems = utils.makeArray( elems ); + var ffElems = []; + + for ( var i=0, len = elems.length; i < len; i++ ) { + var elem = elems[i]; + // check that elem is an actual element + if ( !utils.isElement( elem ) ) { + continue; + } + // filter & find items if we have a selector + if ( selector ) { + // filter siblings + if ( matchesSelector( elem, selector ) ) { + ffElems.push( elem ); + } + // find children + var childElems = elem.querySelectorAll( selector ); + // concat childElems to filterFound array + for ( var j=0, jLen = childElems.length; j < jLen; j++ ) { + ffElems.push( childElems[j] ); + } + } else { + ffElems.push( elem ); + } + } + + return ffElems; +}; + +// ----- debounceMethod ----- // + +utils.debounceMethod = function( _class, methodName, threshold ) { + // original method + var method = _class.prototype[ methodName ]; + var timeoutName = methodName + 'Timeout'; + + _class.prototype[ methodName ] = function() { + var timeout = this[ timeoutName ]; + if ( timeout ) { + clearTimeout( timeout ); + } + var args = arguments; + + var _this = this; + this[ timeoutName ] = setTimeout( function() { + method.apply( _this, args ); + delete _this[ timeoutName ]; + }, threshold || 100 ); + }; +}; + +// ----- htmlInit ----- // + +// http://jamesroberts.name/blog/2010/02/22/string-functions-for-javascript-trim-to-camel-case-to-dashed-and-to-underscore/ +utils.toDashed = function( str ) { + return str.replace( /(.)([A-Z])/g, function( match, $1, $2 ) { + return $1 + '-' + $2; + }).toLowerCase(); +}; + +var console = window.console; +/** + * allow user to initialize classes via .js-namespace class + * htmlInit( Widget, 'widgetName' ) + * options are parsed from data-namespace-option attribute + */ +utils.htmlInit = function( WidgetClass, namespace ) { + docReady( function() { + var dashedNamespace = utils.toDashed( namespace ); + var elems = document.querySelectorAll( '.js-' + dashedNamespace ); + var dataAttr = 'data-' + dashedNamespace + '-options'; + + for ( var i=0, len = elems.length; i < len; i++ ) { + var elem = elems[i]; + var attr = elem.getAttribute( dataAttr ); + var options; + try { + options = attr && JSON.parse( attr ); + } catch ( error ) { + // log error, do not initialize + if ( console ) { + console.error( 'Error parsing ' + dataAttr + ' on ' + + elem.nodeName.toLowerCase() + ( elem.id ? '#' + elem.id : '' ) + ': ' + + error ); + } + continue; + } + // initialize + var instance = new WidgetClass( elem, options ); + // make available via $().data('layoutname') + var jQuery = window.jQuery; + if ( jQuery ) { + jQuery.data( elem, namespace, instance ); + } + } + }); +}; + +// ----- ----- // + +return utils; + +})); + +( function( window, factory ) { + + // universal module definition + + if ( typeof define == 'function' && define.amd ) { + // AMD + define( 'flickity/js/cell',[ + 'get-size/get-size' + ], function( getSize ) { + return factory( window, getSize ); + }); + } else if ( typeof exports == 'object' ) { + // CommonJS + module.exports = factory( + window, + require('get-size') + ); + } else { + // browser global + window.Flickity = window.Flickity || {}; + window.Flickity.Cell = factory( + window, + window.getSize + ); + } + +}( window, function factory( window, getSize ) { + + + +function Cell( elem, parent ) { + this.element = elem; + this.parent = parent; + + this.create(); +} + +var isIE8 = 'attachEvent' in window; + +Cell.prototype.create = function() { + this.element.style.position = 'absolute'; + // IE8 prevent child from changing focus http://stackoverflow.com/a/17525223/182183 + if ( isIE8 ) { + this.element.setAttribute( 'unselectable', 'on' ); + } + this.x = 0; + this.shift = 0; +}; + +Cell.prototype.destroy = function() { + // reset style + this.element.style.position = ''; + var side = this.parent.originSide; + this.element.style[ side ] = ''; +}; + +Cell.prototype.getSize = function() { + this.size = getSize( this.element ); +}; + +Cell.prototype.setPosition = function( x ) { + this.x = x; + this.setDefaultTarget(); + this.renderPosition( x ); +}; + +Cell.prototype.setDefaultTarget = function() { + var marginProperty = this.parent.originSide == 'left' ? 'marginLeft' : 'marginRight'; + this.target = this.x + this.size[ marginProperty ] + + this.size.width * this.parent.cellAlign; +}; + +Cell.prototype.renderPosition = function( x ) { + // render position of cell with in slider + var side = this.parent.originSide; + this.element.style[ side ] = this.parent.getPositionValue( x ); +}; + +/** + * @param {Integer} factor - 0, 1, or -1 +**/ +Cell.prototype.wrapShift = function( shift ) { + this.shift = shift; + this.renderPosition( this.x + this.parent.slideableWidth * shift ); +}; + +Cell.prototype.remove = function() { + this.element.parentNode.removeChild( this.element ); +}; + +return Cell; + +})); + +( function( window, factory ) { + + // universal module definition + + if ( typeof define == 'function' && define.amd ) { + // AMD + define( 'flickity/js/animate',[ + 'get-style-property/get-style-property', + 'fizzy-ui-utils/utils' + ], function( getStyleProperty, utils ) { + return factory( window, getStyleProperty, utils ); + }); + } else if ( typeof exports == 'object' ) { + // CommonJS + module.exports = factory( + window, + require('desandro-get-style-property'), + require('fizzy-ui-utils') + ); + } else { + // browser global + window.Flickity = window.Flickity || {}; + window.Flickity.animatePrototype = factory( + window, + window.getStyleProperty, + window.fizzyUIUtils + ); + } + +}( window, function factory( window, getStyleProperty, utils ) { + + + +// -------------------------- requestAnimationFrame -------------------------- // + +// https://gist.github.com/1866474 + +var lastTime = 0; +var prefixes = 'webkit moz ms o'.split(' '); +// get unprefixed rAF and cAF, if present +var requestAnimationFrame = window.requestAnimationFrame; +var cancelAnimationFrame = window.cancelAnimationFrame; +// loop through vendor prefixes and get prefixed rAF and cAF +var prefix; +for( var i = 0; i < prefixes.length; i++ ) { + if ( requestAnimationFrame && cancelAnimationFrame ) { + break; + } + prefix = prefixes[i]; + requestAnimationFrame = requestAnimationFrame || window[ prefix + 'RequestAnimationFrame' ]; + cancelAnimationFrame = cancelAnimationFrame || window[ prefix + 'CancelAnimationFrame' ] || + window[ prefix + 'CancelRequestAnimationFrame' ]; +} + +// fallback to setTimeout and clearTimeout if either request/cancel is not supported +if ( !requestAnimationFrame || !cancelAnimationFrame ) { + requestAnimationFrame = function( callback ) { + var currTime = new Date().getTime(); + var timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) ); + var id = window.setTimeout( function() { + callback( currTime + timeToCall ); + }, timeToCall ); + lastTime = currTime + timeToCall; + return id; + }; + + cancelAnimationFrame = function( id ) { + window.clearTimeout( id ); + }; +} + +// -------------------------- animate -------------------------- // + +var proto = {}; + +proto.startAnimation = function() { + if ( this.isAnimating ) { + return; + } + + this.isAnimating = true; + this.restingFrames = 0; + this.animate(); +}; + +proto.animate = function() { + this.applySelectedAttraction(); + + var previousX = this.x; + + this.integratePhysics(); + this.positionSlider(); + this.settle( previousX ); + // animate next frame + if ( this.isAnimating ) { + var _this = this; + requestAnimationFrame( function animateFrame() { + _this.animate(); + }); + } + + /** / + // log animation frame rate + var now = new Date(); + if ( this.then ) { + console.log( ~~( 1000 / (now-this.then)) + 'fps' ) + } + this.then = now; + /**/ +}; + + +var transformProperty = getStyleProperty('transform'); +var is3d = !!getStyleProperty('perspective'); + +proto.positionSlider = function() { + var x = this.x; + // wrap position around + if ( this.options.wrapAround && this.cells.length > 1 ) { + x = utils.modulo( x, this.slideableWidth ); + x = x - this.slideableWidth; + this.shiftWrapCells( x ); + } + + x = x + this.cursorPosition; + + // reverse if right-to-left and using transform + x = this.options.rightToLeft && transformProperty ? -x : x; + + var value = this.getPositionValue( x ); + + if ( transformProperty ) { + // use 3D tranforms for hardware acceleration on iOS + // but use 2D when settled, for better font-rendering + this.slider.style[ transformProperty ] = is3d && this.isAnimating ? + 'translate3d(' + value + ',0,0)' : 'translateX(' + value + ')'; + } else { + this.slider.style[ this.originSide ] = value; + } +}; + +proto.positionSliderAtSelected = function() { + if ( !this.cells.length ) { + return; + } + var selectedCell = this.cells[ this.selectedIndex ]; + this.x = -selectedCell.target; + this.positionSlider(); +}; + +proto.getPositionValue = function( position ) { + if ( this.options.percentPosition ) { + // percent position, round to 2 digits, like 12.34% + return ( Math.round( ( position / this.size.innerWidth ) * 10000 ) * 0.01 )+ '%'; + } else { + // pixel positioning + return Math.round( position ) + 'px'; + } +}; + +proto.settle = function( previousX ) { + // keep track of frames where x hasn't moved + if ( !this.isPointerDown && Math.round( this.x * 100 ) == Math.round( previousX * 100 ) ) { + this.restingFrames++; + } + // stop animating if resting for 3 or more frames + if ( this.restingFrames > 2 ) { + this.isAnimating = false; + delete this.isFreeScrolling; + // render position with translateX when settled + if ( is3d ) { + this.positionSlider(); + } + this.dispatchEvent('settle'); + } +}; + +proto.shiftWrapCells = function( x ) { + // shift before cells + var beforeGap = this.cursorPosition + x; + this._shiftCells( this.beforeShiftCells, beforeGap, -1 ); + // shift after cells + var afterGap = this.size.innerWidth - ( x + this.slideableWidth + this.cursorPosition ); + this._shiftCells( this.afterShiftCells, afterGap, 1 ); +}; + +proto._shiftCells = function( cells, gap, shift ) { + for ( var i=0, len = cells.length; i < len; i++ ) { + var cell = cells[i]; + var cellShift = gap > 0 ? shift : 0; + cell.wrapShift( cellShift ); + gap -= cell.size.outerWidth; + } +}; + +proto._unshiftCells = function( cells ) { + if ( !cells || !cells.length ) { + return; + } + for ( var i=0, len = cells.length; i < len; i++ ) { + cells[i].wrapShift( 0 ); + } +}; + +// -------------------------- physics -------------------------- // + +proto.integratePhysics = function() { + this.velocity += this.accel; + this.x += this.velocity; + this.velocity *= this.getFrictionFactor(); + // reset acceleration + this.accel = 0; +}; + +proto.applyForce = function( force ) { + this.accel += force; +}; + +proto.getFrictionFactor = function() { + return 1 - this.options[ this.isFreeScrolling ? 'freeScrollFriction' : 'friction' ]; +}; + + +proto.getRestingPosition = function() { + // my thanks to Steven Wittens, who simplified this math greatly + return this.x + this.velocity / ( 1 - this.getFrictionFactor() ); +}; + + +proto.applySelectedAttraction = function() { + // do not attract if pointer down or no cells + var len = this.cells.length; + if ( this.isPointerDown || this.isFreeScrolling || !len ) { + return; + } + var cell = this.cells[ this.selectedIndex ]; + var wrap = this.options.wrapAround && len > 1 ? + this.slideableWidth * Math.floor( this.selectedIndex / len ) : 0; + var distance = ( cell.target + wrap ) * -1 - this.x; + var force = distance * this.options.selectedAttraction; + this.applyForce( force ); +}; + +return proto; + +})); + +/*! + * Flickity v1.0.1 + * Touch, responsive, flickable galleries + * + * Licensed GPLv3 for open source use + * or Flickity Commercial License for commercial use + * + * http://flickity.metafizzy.co + * Copyright 2015 Metafizzy + */ + +( function( window, factory ) { + + // universal module definition + + if ( typeof define == 'function' && define.amd ) { + // AMD + define( 'flickity/js/flickity',[ + 'classie/classie', + 'eventEmitter/EventEmitter', + 'eventie/eventie', + 'get-size/get-size', + 'fizzy-ui-utils/utils', + './cell', + './animate' + ], function( classie, EventEmitter, eventie, getSize, utils, Cell, animatePrototype ) { + return factory( window, classie, EventEmitter, eventie, getSize, utils, Cell, animatePrototype ); + }); + } else if ( typeof exports == 'object' ) { + // CommonJS + module.exports = factory( + window, + require('desandro-classie'), + require('wolfy87-eventemitter'), + require('eventie'), + require('get-size'), + require('fizzy-ui-utils'), + require('./cell'), + require('./animate') + ); + } else { + // browser global + var _Flickity = window.Flickity; + + window.Flickity = factory( + window, + window.classie, + window.EventEmitter, + window.eventie, + window.getSize, + window.fizzyUIUtils, + _Flickity.Cell, + _Flickity.animatePrototype + ); + } + +}( window, function factory( window, classie, EventEmitter, eventie, getSize, + utils, Cell, animatePrototype ) { + + + +// vars +var jQuery = window.jQuery; +var getComputedStyle = window.getComputedStyle; +var console = window.console; + +function moveElements( elems, toElem ) { + elems = utils.makeArray( elems ); + while ( elems.length ) { + toElem.appendChild( elems.shift() ); + } +} + +// -------------------------- Flickity -------------------------- // + +// globally unique identifiers +var GUID = 0; +// internal store of all Flickity intances +var instances = {}; + +function Flickity( element, options ) { + var queryElement = utils.getQueryElement( element ); + if ( !queryElement ) { + if ( console ) { + console.error( 'Bad element for Flickity: ' + ( queryElement || element ) ); + } + return; + } + this.element = queryElement; + // add jQuery + if ( jQuery ) { + this.$element = jQuery( this.element ); + } + // options + this.options = utils.extend( {}, this.constructor.defaults ); + this.option( options ); + + // kick things off + this._create(); +} + +Flickity.defaults = { + accessibility: true, + cellAlign: 'center', + // cellSelector: undefined, + // contain: false, + freeScrollFriction: 0.075, // friction when free-scrolling + friction: 0.28, // friction when selecting + // initialIndex: 0, + percentPosition: true, + resize: true, + selectedAttraction: 0.025, + setGallerySize: true + // watchCSS: false, + // wrapAround: false +}; + +// hash of methods triggered on _create() +Flickity.createMethods = []; + +// inherit EventEmitter +utils.extend( Flickity.prototype, EventEmitter.prototype ); + +Flickity.prototype._create = function() { + // add id for Flickity.data + var id = this.guid = ++GUID; + this.element.flickityGUID = id; // expando + instances[ id ] = this; // associate via id + // initial properties + this.selectedIndex = this.options.initialIndex || 0; + // how many frames slider has been in same position + this.restingFrames = 0; + // initial physics properties + this.x = 0; + this.velocity = 0; + this.accel = 0; + this.originSide = this.options.rightToLeft ? 'right' : 'left'; + // create viewport & slider + this.viewport = document.createElement('div'); + this.viewport.className = 'flickity-viewport'; + Flickity.setUnselectable( this.viewport ); + this._createSlider(); + + if ( this.options.resize || this.options.watchCSS ) { + eventie.bind( window, 'resize', this ); + this.isResizeBound = true; + } + + for ( var i=0, len = Flickity.createMethods.length; i < len; i++ ) { + var method = Flickity.createMethods[i]; + this[ method ](); + } + + if ( this.options.watchCSS ) { + this.watchCSS(); + } else { + this.activate(); + } + +}; + +/** + * set options + * @param {Object} opts + */ +Flickity.prototype.option = function( opts ) { + utils.extend( this.options, opts ); +}; + +Flickity.prototype.activate = function() { + if ( this.isActive ) { + return; + } + this.isActive = true; + classie.add( this.element, 'flickity-enabled' ); + if ( this.options.rightToLeft ) { + classie.add( this.element, 'flickity-rtl' ); + } + + // move initial cell elements so they can be loaded as cells + var cellElems = this._filterFindCellElements( this.element.children ); + moveElements( cellElems, this.slider ); + this.viewport.appendChild( this.slider ); + this.element.appendChild( this.viewport ); + + this.getSize(); + // get cells from children + this.reloadCells(); + + if ( this.options.accessibility ) { + // allow element to focusable + this.element.tabIndex = 0; + // listen for key presses + eventie.bind( this.element, 'keydown', this ); + } + + this.emit('activate'); + + this.positionSliderAtSelected(); + this.select( this.selectedIndex ); +}; + +// slider positions the cells +Flickity.prototype._createSlider = function() { + // slider element does all the positioning + var slider = document.createElement('div'); + slider.className = 'flickity-slider'; + slider.style[ this.originSide ] = 0; + this.slider = slider; +}; + +Flickity.prototype._filterFindCellElements = function( elems ) { + return utils.filterFindElements( elems, this.options.cellSelector ); +}; + +// goes through all children +Flickity.prototype.reloadCells = function() { + // collection of item elements + this.cells = this._makeCells( this.slider.children ); + this.positionCells(); + this._getWrapShiftCells(); + this.setGallerySize(); +}; + +/** + * turn elements into Flickity.Cells + * @param {Array or NodeList or HTMLElement} elems + * @returns {Array} items - collection of new Flickity Cells + */ +Flickity.prototype._makeCells = function( elems ) { + var cellElems = this._filterFindCellElements( elems ); + + // create new Flickity for collection + var cells = []; + for ( var i=0, len = cellElems.length; i < len; i++ ) { + var elem = cellElems[i]; + var cell = new Cell( elem, this ); + cells.push( cell ); + } + + return cells; +}; + +Flickity.prototype.getLastCell = function() { + return this.cells[ this.cells.length - 1 ]; +}; + +// positions all cells +Flickity.prototype.positionCells = function() { + // size all cells + this._sizeCells( this.cells ); + // position all cells + this._positionCells( 0 ); +}; + +/** + * position certain cells + * @param {Integer} index - which cell to start with + */ +Flickity.prototype._positionCells = function( index ) { + // also measure maxCellHeight + // start 0 if positioning all cells + this.maxCellHeight = index ? this.maxCellHeight || 0 : 0; + var cellX = 0; + // get cellX + if ( index > 0 ) { + var startCell = this.cells[ index - 1 ]; + cellX = startCell.x + startCell.size.outerWidth; + } + var cell; + for ( var len = this.cells.length, i=index; i < len; i++ ) { + cell = this.cells[i]; + cell.setPosition( cellX ); + cellX += cell.size.outerWidth; + this.maxCellHeight = Math.max( cell.size.outerHeight, this.maxCellHeight ); + } + // keep track of cellX for wrap-around + this.slideableWidth = cellX; + // contain cell target + this._containCells(); +}; + +/** + * cell.getSize() on multiple cells + * @param {Array} cells + */ +Flickity.prototype._sizeCells = function( cells ) { + for ( var i=0, len = cells.length; i < len; i++ ) { + var cell = cells[i]; + cell.getSize(); + } +}; + +// alias _init for jQuery plugin .flickity() +Flickity.prototype._init = +Flickity.prototype.reposition = function() { + this.positionCells(); + this.positionSliderAtSelected(); +}; + +Flickity.prototype.getSize = function() { + this.size = getSize( this.element ); + this.setCellAlign(); + this.cursorPosition = this.size.innerWidth * this.cellAlign; +}; + +var cellAlignShorthands = { + // cell align, then based on origin side + center: { + left: 0.5, + right: 0.5 + }, + left: { + left: 0, + right: 1 + }, + right: { + right: 0, + left: 1 + } +}; + +Flickity.prototype.setCellAlign = function() { + var shorthand = cellAlignShorthands[ this.options.cellAlign ]; + this.cellAlign = shorthand ? shorthand[ this.originSide ] : this.options.cellAlign; +}; + +Flickity.prototype.setGallerySize = function() { + if ( this.options.setGallerySize ) { + this.viewport.style.height = this.maxCellHeight + 'px'; + } +}; + +Flickity.prototype._getWrapShiftCells = function() { + // only for wrap-around + if ( !this.options.wrapAround ) { + return; + } + // unshift previous cells + this._unshiftCells( this.beforeShiftCells ); + this._unshiftCells( this.afterShiftCells ); + // get before cells + // initial gap + var gapX = this.cursorPosition; + var cellIndex = this.cells.length - 1; + this.beforeShiftCells = this._getGapCells( gapX, cellIndex, -1 ); + // get after cells + // ending gap between last cell and end of gallery viewport + gapX = this.size.innerWidth - this.cursorPosition; + // start cloning at first cell, working forwards + this.afterShiftCells = this._getGapCells( gapX, 0, 1 ); +}; + +Flickity.prototype._getGapCells = function( gapX, cellIndex, increment ) { + // keep adding cells until the cover the initial gap + var cells = []; + while ( gapX > 0 ) { + var cell = this.cells[ cellIndex ]; + if ( !cell ) { + break; + } + cells.push( cell ); + cellIndex += increment; + gapX -= cell.size.outerWidth; + } + return cells; +}; + +// ----- contain ----- // + +// contain cell targets so no excess sliding +Flickity.prototype._containCells = function() { + if ( !this.options.contain || this.options.wrapAround || !this.cells.length ) { + return; + } + var startMargin = this.options.rightToLeft ? 'marginRight' : 'marginLeft'; + var endMargin = this.options.rightToLeft ? 'marginLeft' : 'marginRight'; + var firstCellStartMargin = this.cells[0].size[ startMargin ]; + var lastCell = this.getLastCell(); + var contentWidth = this.slideableWidth - lastCell.size[ endMargin ]; + var endLimit = contentWidth - this.size.innerWidth * ( 1 - this.cellAlign ); + // content is less than gallery size + var isContentSmaller = contentWidth < this.size.innerWidth; + // contain each cell target + for ( var i=0, len = this.cells.length; i < len; i++ ) { + var cell = this.cells[i]; + // reset default target + cell.setDefaultTarget(); + if ( isContentSmaller ) { + // all cells fit inside gallery + cell.target = contentWidth * this.cellAlign; + } else { + // contain to bounds + cell.target = Math.max( cell.target, this.cursorPosition + firstCellStartMargin ); + cell.target = Math.min( cell.target, endLimit ); + } + } +}; + +// ----- ----- // + +/** + * emits events via eventEmitter and jQuery events + * @param {String} type - name of event + * @param {Event} event - original event + * @param {Array} args - extra arguments + */ +Flickity.prototype.dispatchEvent = function( type, event, args ) { + var emitArgs = [ event ].concat( args ); + this.emitEvent( type, emitArgs ); + + if ( jQuery && this.$element ) { + if ( event ) { + // create jQuery event + var $event = jQuery.Event( event ); + $event.type = type; + this.$element.trigger( $event, args ); + } else { + // just trigger with type if no event available + this.$element.trigger( type, args ); + } + } +}; + +// -------------------------- select -------------------------- // + +/** + * @param {Integer} index - index of the cell + * @param {Boolean} isWrap - will wrap-around to last/first if at the end + */ +Flickity.prototype.select = function( index, isWrap ) { + if ( !this.isActive ) { + return; + } + // wrap position so slider is within normal area + var len = this.cells.length; + if ( this.options.wrapAround && len > 1 ) { + if ( index < 0 ) { + this.x -= this.slideableWidth; + } else if ( index >= len ) { + this.x += this.slideableWidth; + } + } + + if ( this.options.wrapAround || isWrap ) { + index = utils.modulo( index, len ); + } + + if ( this.cells[ index ] ) { + this.selectedIndex = index; + this.setSelectedCell(); + this.startAnimation(); + this.dispatchEvent('cellSelect'); + } +}; + +Flickity.prototype.previous = function( isWrap ) { + this.select( this.selectedIndex - 1, isWrap ); +}; + +Flickity.prototype.next = function( isWrap ) { + this.select( this.selectedIndex + 1, isWrap ); +}; + +Flickity.prototype.setSelectedCell = function() { + this._removeSelectedCellClass(); + this.selectedCell = this.cells[ this.selectedIndex ]; + this.selectedElement = this.selectedCell.element; + classie.add( this.selectedElement, 'is-selected' ); +}; + +Flickity.prototype._removeSelectedCellClass = function() { + if ( this.selectedCell ) { + classie.remove( this.selectedCell.element, 'is-selected' ); + } +}; + +// -------------------------- get cells -------------------------- // + +/** + * get Flickity.Cell, given an Element + * @param {Element} elem + * @returns {Flickity.Cell} item + */ +Flickity.prototype.getCell = function( elem ) { + // loop through cells to get the one that matches + for ( var i=0, len = this.cells.length; i < len; i++ ) { + var cell = this.cells[i]; + if ( cell.element == elem ) { + return cell; + } + } +}; + +/** + * get collection of Flickity.Cells, given Elements + * @param {Element, Array, NodeList} elems + * @returns {Array} cells - Flickity.Cells + */ +Flickity.prototype.getCells = function( elems ) { + elems = utils.makeArray( elems ); + var cells = []; + for ( var i=0, len = elems.length; i < len; i++ ) { + var elem = elems[i]; + var cell = this.getCell( elem ); + if ( cell ) { + cells.push( cell ); + } + } + return cells; +}; + +/** + * get cell elements + * @returns {Array} cellElems + */ +Flickity.prototype.getCellElements = function() { + var cellElems = []; + for ( var i=0, len = this.cells.length; i < len; i++ ) { + cellElems.push( this.cells[i].element ); + } + return cellElems; +}; + +/** + * get parent cell from an element + * @param {Element} elem + * @returns {Flickit.Cell} cell + */ +Flickity.prototype.getParentCell = function( elem ) { + // first check if elem is cell + var cell = this.getCell( elem ); + if ( cell ) { + return cell; + } + // try to get parent cell elem + elem = utils.getParent( elem, '.flickity-slider > *' ); + return this.getCell( elem ); +}; + +// -------------------------- events -------------------------- // + +Flickity.prototype.uiChange = function() { + this.emit('uiChange'); +}; + +Flickity.prototype.childUIPointerDown = function( event ) { + this.emitEvent( 'childUIPointerDown', [ event ] ); +}; + +// ----- resize ----- // + +Flickity.prototype.onresize = function() { + this.watchCSS(); + this.resize(); +}; + +utils.debounceMethod( Flickity, 'onresize', 150 ); + +Flickity.prototype.resize = function() { + if ( !this.isActive ) { + return; + } + this.getSize(); + // wrap values + if ( this.options.wrapAround ) { + this.x = utils.modulo( this.x, this.slideableWidth ); + } + this.positionCells(); + this._getWrapShiftCells(); + this.setGallerySize(); + this.positionSliderAtSelected(); +}; + +var supportsConditionalCSS = Flickity.supportsConditionalCSS = ( function() { + var supports; + return function checkSupport() { + if ( supports !== undefined ) { + return supports; + } + if ( !getComputedStyle ) { + supports = false; + return; + } + // style body's :after and check that + var style = document.createElement('style'); + var cssText = document.createTextNode('body:after { content: "foo"; display: none; }'); + style.appendChild( cssText ); + document.head.appendChild( style ); + var afterContent = getComputedStyle( document.body, ':after' ).content; + // check if able to get :after content + supports = afterContent.indexOf('foo') != -1; + document.head.removeChild( style ); + return supports; + }; +})(); + +// watches the :after property, activates/deactivates +Flickity.prototype.watchCSS = function() { + var watchOption = this.options.watchCSS; + if ( !watchOption ) { + return; + } + var supports = supportsConditionalCSS(); + if ( !supports ) { + // activate if watch option is fallbackOn + var method = watchOption == 'fallbackOn' ? 'activate' : 'deactivate'; + this[ method ](); + return; + } + + var afterContent = getComputedStyle( this.element, ':after' ).content; + // activate if :after { content: 'flickity' } + if ( afterContent.indexOf('flickity') != -1 ) { + this.activate(); + } else { + this.deactivate(); + } +}; + +// ----- keydown ----- // + +// go previous/next if left/right keys pressed +Flickity.prototype.onkeydown = function( event ) { + // only work if element is in focus + if ( !this.options.accessibility || + ( document.activeElement && document.activeElement != this.element ) ) { + return; + } + + if ( event.keyCode == 37 ) { + // go left + var leftMethod = this.options.rightToLeft ? 'next' : 'previous'; + this.uiChange(); + this[ leftMethod ](); + } else if ( event.keyCode == 39 ) { + // go right + var rightMethod = this.options.rightToLeft ? 'previous' : 'next'; + this.uiChange(); + this[ rightMethod ](); + } +}; + +// -------------------------- destroy -------------------------- // + +// deactivate all Flickity functionality, but keep stuff available +Flickity.prototype.deactivate = function() { + if ( !this.isActive ) { + return; + } + classie.remove( this.element, 'flickity-enabled' ); + classie.remove( this.element, 'flickity-rtl' ); + // destroy cells + for ( var i=0, len = this.cells.length; i < len; i++ ) { + var cell = this.cells[i]; + cell.destroy(); + } + this._removeSelectedCellClass(); + this.element.removeChild( this.viewport ); + // move child elements back into element + moveElements( this.slider.children, this.element ); + if ( this.options.accessibility ) { + this.element.removeAttribute('tabIndex'); + eventie.unbind( this.element, 'keydown', this ); + } + // set flags + this.isActive = false; + this.emit('deactivate'); +}; + +Flickity.prototype.destroy = function() { + this.deactivate(); + if ( this.isResizeBound ) { + eventie.unbind( window, 'resize', this ); + } + this.emit('destroy'); + if ( jQuery && this.$element ) { + jQuery.removeData( this.element, 'flickity' ); + } + delete this.element.flickityGUID; + delete instances[ this.guid ]; +}; + +// -------------------------- prototype -------------------------- // + +utils.extend( Flickity.prototype, animatePrototype ); + +// -------------------------- extras -------------------------- // + +// quick check for IE8 +var isIE8 = 'attachEvent' in window; + +Flickity.setUnselectable = function( elem ) { + if ( !isIE8 ) { + return; + } + // IE8 prevent child from changing focus http://stackoverflow.com/a/17525223/182183 + elem.setAttribute( 'unselectable', 'on' ); +}; + +/** + * get Flickity instance from element + * @param {Element} elem + * @returns {Flickity} + */ +Flickity.data = function( elem ) { + elem = utils.getQueryElement( elem ); + var id = elem && elem.flickityGUID; + return id && instances[ id ]; +}; + +utils.htmlInit( Flickity, 'flickity' ); + +if ( jQuery && jQuery.bridget ) { + jQuery.bridget( 'flickity', Flickity ); +} + +Flickity.Cell = Cell; + +return Flickity; + +})); + +/*! + * Unipointer v1.1.0 + * base class for doing one thing with pointer event + * MIT license + */ + +/*jshint browser: true, undef: true, unused: true, strict: true */ +/*global define: false, module: false, require: false */ + +( function( window, factory ) { + + // universal module definition + + if ( typeof define == 'function' && define.amd ) { + // AMD + define( 'unipointer/unipointer',[ + 'eventEmitter/EventEmitter', + 'eventie/eventie' + ], function( EventEmitter, eventie ) { + return factory( window, EventEmitter, eventie ); + }); + } else if ( typeof exports == 'object' ) { + // CommonJS + module.exports = factory( + window, + require('wolfy87-eventemitter'), + require('eventie') + ); + } else { + // browser global + window.Unipointer = factory( + window, + window.EventEmitter, + window.eventie + ); + } + +}( window, function factory( window, EventEmitter, eventie ) { + + + +function noop() {} + +function Unipointer() {} + +// inherit EventEmitter +Unipointer.prototype = new EventEmitter(); + +Unipointer.prototype.bindStartEvent = function( elem ) { + this._bindStartEvent( elem, true ); +}; + +Unipointer.prototype.unbindStartEvent = function( elem ) { + this._bindStartEvent( elem, false ); +}; + +/** + * works as unbinder, as you can ._bindStart( false ) to unbind + * @param {Boolean} isBind - will unbind if falsey + */ +Unipointer.prototype._bindStartEvent = function( elem, isBind ) { + // munge isBind, default to true + isBind = isBind === undefined ? true : !!isBind; + var bindMethod = isBind ? 'bind' : 'unbind'; + + if ( window.navigator.pointerEnabled ) { + // W3C Pointer Events, IE11. See https://coderwall.com/p/mfreca + eventie[ bindMethod ]( elem, 'pointerdown', this ); + } else if ( window.navigator.msPointerEnabled ) { + // IE10 Pointer Events + eventie[ bindMethod ]( elem, 'MSPointerDown', this ); + } else { + // listen for both, for devices like Chrome Pixel + eventie[ bindMethod ]( elem, 'mousedown', this ); + eventie[ bindMethod ]( elem, 'touchstart', this ); + } +}; + +// trigger handler methods for events +Unipointer.prototype.handleEvent = function( event ) { + var method = 'on' + event.type; + if ( this[ method ] ) { + this[ method ]( event ); + } +}; + +// returns the touch that we're keeping track of +Unipointer.prototype.getTouch = function( touches ) { + for ( var i=0, len = touches.length; i < len; i++ ) { + var touch = touches[i]; + if ( touch.identifier == this.pointerIdentifier ) { + return touch; + } + } +}; + +// ----- start event ----- // + +Unipointer.prototype.onmousedown = function( event ) { + // dismiss clicks from right or middle buttons + var button = event.button; + if ( button && ( button !== 0 && button !== 1 ) ) { + return; + } + this._pointerDown( event, event ); +}; + +Unipointer.prototype.ontouchstart = function( event ) { + this._pointerDown( event, event.changedTouches[0] ); +}; + +Unipointer.prototype.onMSPointerDown = +Unipointer.prototype.onpointerdown = function( event ) { + this._pointerDown( event, event ); +}; + +/** + * pointer start + * @param {Event} event + * @param {Event or Touch} pointer + */ +Unipointer.prototype._pointerDown = function( event, pointer ) { + // dismiss other pointers + if ( this.isPointerDown ) { + return; + } + + this.isPointerDown = true; + // save pointer identifier to match up touch events + this.pointerIdentifier = pointer.pointerId !== undefined ? + // pointerId for pointer events, touch.indentifier for touch events + pointer.pointerId : pointer.identifier; + + this.pointerDown( event, pointer ); +}; + +Unipointer.prototype.pointerDown = function( event, pointer ) { + this._bindPostStartEvents( event ); + this.emitEvent( 'pointerDown', [ event, pointer ] ); +}; + +// hash of events to be bound after start event +var postStartEvents = { + mousedown: [ 'mousemove', 'mouseup' ], + touchstart: [ 'touchmove', 'touchend', 'touchcancel' ], + pointerdown: [ 'pointermove', 'pointerup', 'pointercancel' ], + MSPointerDown: [ 'MSPointerMove', 'MSPointerUp', 'MSPointerCancel' ] +}; + +Unipointer.prototype._bindPostStartEvents = function( event ) { + if ( !event ) { + return; + } + // get proper events to match start event + var events = postStartEvents[ event.type ]; + // IE8 needs to be bound to document + var node = event.preventDefault ? window : document; + // bind events to node + for ( var i=0, len = events.length; i < len; i++ ) { + var evnt = events[i]; + eventie.bind( node, evnt, this ); + } + // save these arguments + this._boundPointerEvents = { + events: events, + node: node + }; +}; + +Unipointer.prototype._unbindPostStartEvents = function() { + var args = this._boundPointerEvents; + // IE8 can trigger dragEnd twice, check for _boundEvents + if ( !args || !args.events ) { + return; + } + + for ( var i=0, len = args.events.length; i < len; i++ ) { + var event = args.events[i]; + eventie.unbind( args.node, event, this ); + } + delete this._boundPointerEvents; +}; + +// ----- move event ----- // + +Unipointer.prototype.onmousemove = function( event ) { + this._pointerMove( event, event ); +}; + +Unipointer.prototype.onMSPointerMove = +Unipointer.prototype.onpointermove = function( event ) { + if ( event.pointerId == this.pointerIdentifier ) { + this._pointerMove( event, event ); + } +}; + +Unipointer.prototype.ontouchmove = function( event ) { + var touch = this.getTouch( event.changedTouches ); + if ( touch ) { + this._pointerMove( event, touch ); + } +}; + +/** + * pointer move + * @param {Event} event + * @param {Event or Touch} pointer + * @private + */ +Unipointer.prototype._pointerMove = function( event, pointer ) { + this.pointerMove( event, pointer ); +}; + +// public +Unipointer.prototype.pointerMove = function( event, pointer ) { + this.emitEvent( 'pointerMove', [ event, pointer ] ); +}; + +// ----- end event ----- // + + +Unipointer.prototype.onmouseup = function( event ) { + this._pointerUp( event, event ); +}; + +Unipointer.prototype.onMSPointerUp = +Unipointer.prototype.onpointerup = function( event ) { + if ( event.pointerId == this.pointerIdentifier ) { + this._pointerUp( event, event ); + } +}; + +Unipointer.prototype.ontouchend = function( event ) { + var touch = this.getTouch( event.changedTouches ); + if ( touch ) { + this._pointerUp( event, touch ); + } +}; + +/** + * pointer up + * @param {Event} event + * @param {Event or Touch} pointer + * @private + */ +Unipointer.prototype._pointerUp = function( event, pointer ) { + this._pointerDone(); + this.pointerUp( event, pointer ); +}; + +// public +Unipointer.prototype.pointerUp = function( event, pointer ) { + this.emitEvent( 'pointerUp', [ event, pointer ] ); +}; + +// ----- pointer done ----- // + +// triggered on pointer up & pointer cancel +Unipointer.prototype._pointerDone = function() { + // reset properties + this.isPointerDown = false; + delete this.pointerIdentifier; + // remove events + this._unbindPostStartEvents(); + this.pointerDone(); +}; + +Unipointer.prototype.pointerDone = noop; + +// ----- pointer cancel ----- // + +Unipointer.prototype.onMSPointerCancel = +Unipointer.prototype.onpointercancel = function( event ) { + if ( event.pointerId == this.pointerIdentifier ) { + this._pointerCancel( event, event ); + } +}; + +Unipointer.prototype.ontouchcancel = function( event ) { + var touch = this.getTouch( event.changedTouches ); + if ( touch ) { + this._pointerCancel( event, touch ); + } +}; + +/** + * pointer cancel + * @param {Event} event + * @param {Event or Touch} pointer + * @private + */ +Unipointer.prototype._pointerCancel = function( event, pointer ) { + this._pointerDone(); + this.pointerCancel( event, pointer ); +}; + +// public +Unipointer.prototype.pointerCancel = function( event, pointer ) { + this.emitEvent( 'pointerCancel', [ event, pointer ] ); +}; + +// ----- ----- // + +// utility function for getting x/y cooridinates from event, because IE8 +Unipointer.getPointerPoint = function( pointer ) { + return { + x: pointer.pageX !== undefined ? pointer.pageX : pointer.clientX, + y: pointer.pageY !== undefined ? pointer.pageY : pointer.clientY + }; +}; + +// ----- ----- // + +return Unipointer; + +})); + +/*! + * Unidragger v1.1.3 + * Draggable base class + * MIT license + */ + +/*jshint browser: true, unused: true, undef: true, strict: true */ + +( function( window, factory ) { + /*global define: false, module: false, require: false */ + + // universal module definition + + if ( typeof define == 'function' && define.amd ) { + // AMD + define( 'unidragger/unidragger',[ + 'eventie/eventie', + 'unipointer/unipointer' + ], function( eventie, Unipointer ) { + return factory( window, eventie, Unipointer ); + }); + } else if ( typeof exports == 'object' ) { + // CommonJS + module.exports = factory( + window, + require('eventie'), + require('unipointer') + ); + } else { + // browser global + window.Unidragger = factory( + window, + window.eventie, + window.Unipointer + ); + } + +}( window, function factory( window, eventie, Unipointer ) { + + + +// ----- ----- // + +function noop() {} + +// handle IE8 prevent default +function preventDefaultEvent( event ) { + if ( event.preventDefault ) { + event.preventDefault(); + } else { + event.returnValue = false; + } +} + +// -------------------------- Unidragger -------------------------- // + +function Unidragger() {} + +// inherit Unipointer & EventEmitter +Unidragger.prototype = new Unipointer(); + +// ----- bind start ----- // + +Unidragger.prototype.bindHandles = function() { + this._bindHandles( true ); +}; + +Unidragger.prototype.unbindHandles = function() { + this._bindHandles( false ); +}; + +var navigator = window.navigator; +/** + * works as unbinder, as you can .bindHandles( false ) to unbind + * @param {Boolean} isBind - will unbind if falsey + */ +Unidragger.prototype._bindHandles = function( isBind ) { + // munge isBind, default to true + isBind = isBind === undefined ? true : !!isBind; + // extra bind logic + var binderExtra; + if ( navigator.pointerEnabled ) { + binderExtra = function( handle ) { + // disable scrolling on the element + handle.style.touchAction = isBind ? 'none' : ''; + }; + } else if ( navigator.msPointerEnabled ) { + binderExtra = function( handle ) { + // disable scrolling on the element + handle.style.msTouchAction = isBind ? 'none' : ''; + }; + } else { + binderExtra = function() { + // TODO re-enable img.ondragstart when unbinding + if ( isBind ) { + disableImgOndragstart( handle ); + } + }; + } + // bind each handle + var bindMethod = isBind ? 'bind' : 'unbind'; + for ( var i=0, len = this.handles.length; i < len; i++ ) { + var handle = this.handles[i]; + this._bindStartEvent( handle, isBind ); + binderExtra( handle ); + eventie[ bindMethod ]( handle, 'click', this ); + } +}; + +// remove default dragging interaction on all images in IE8 +// IE8 does its own drag thing on images, which messes stuff up + +function noDragStart() { + return false; +} + +// TODO replace this with a IE8 test +var isIE8 = 'attachEvent' in document.documentElement; + +// IE8 only +var disableImgOndragstart = !isIE8 ? noop : function( handle ) { + + if ( handle.nodeName == 'IMG' ) { + handle.ondragstart = noDragStart; + } + + var images = handle.querySelectorAll('img'); + for ( var i=0, len = images.length; i < len; i++ ) { + var img = images[i]; + img.ondragstart = noDragStart; + } +}; + +// ----- start event ----- // + +/** + * pointer start + * @param {Event} event + * @param {Event or Touch} pointer + */ +Unidragger.prototype.pointerDown = function( event, pointer ) { + this._dragPointerDown( event, pointer ); + // kludge to blur focused inputs in dragger + var focused = document.activeElement; + if ( focused && focused.blur ) { + focused.blur(); + } + // bind move and end events + this._bindPostStartEvents( event ); + this.emitEvent( 'pointerDown', [ event, pointer ] ); +}; + +// base pointer down logic +Unidragger.prototype._dragPointerDown = function( event, pointer ) { + // track to see when dragging starts + this.pointerDownPoint = Unipointer.getPointerPoint( pointer ); + + // prevent default, unless touchstart or s and ",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";k.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|pointer|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return l.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof n!==U&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,m,o,p=[d||l],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||l,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+n.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},e||!o.trigger||o.trigger.apply(d,c)!==!1)){if(!e&&!o.noBubble&&!n.isWindow(d)){for(i=o.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||l)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:o.bindType||q,m=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),m&&m.apply(g,c),m=k&&g[k],m&&m.apply&&n.acceptData(g)&&(b.result=m.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!n.acceptData(d)||k&&n.isFunction(d[q])&&!n.isWindow(d)&&(h=d[k],h&&(d[k]=null),n.event.triggered=q,d[q](),n.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>=0:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h]*)\/>/gi,ba=/<([\w:]+)/,ca=/<|&#?\w+;/,da=/<(?:script|style|link)/i,ea=/checked\s*(?:[^=]|=\s*.checked.)/i,fa=/^$|\/(?:java|ecma)script/i,ga=/^true\/(.*)/,ha=/^\s*\s*$/g,ia={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ia.optgroup=ia.option,ia.tbody=ia.tfoot=ia.colgroup=ia.caption=ia.thead,ia.th=ia.td;function ja(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function ka(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function la(a){var b=ga.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function ma(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function na(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=n.extend({},h),M.set(b,i))}}function oa(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function pa(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}n.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=oa(h),f=oa(a),d=0,e=f.length;e>d;d++)pa(f[d],g[d]);if(b)if(c)for(f=f||oa(a),g=g||oa(h),d=0,e=f.length;e>d;d++)na(f[d],g[d]);else na(a,h);return g=oa(h,"script"),g.length>0&&ma(g,!i&&oa(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,o=a.length;o>m;m++)if(e=a[m],e||0===e)if("object"===n.type(e))n.merge(l,e.nodeType?[e]:e);else if(ca.test(e)){f=f||k.appendChild(b.createElement("div")),g=(ba.exec(e)||["",""])[1].toLowerCase(),h=ia[g]||ia._default,f.innerHTML=h[1]+e.replace(aa,"<$1>")+h[2],j=h[0];while(j--)f=f.lastChild;n.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===n.inArray(e,d))&&(i=n.contains(e.ownerDocument,e),f=oa(k.appendChild(e),"script"),i&&ma(f),c)){j=0;while(e=f[j++])fa.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f=n.event.special,g=0;void 0!==(c=a[g]);g++){if(n.acceptData(c)&&(e=c[L.expando],e&&(b=L.cache[e]))){if(b.events)for(d in b.events)f[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);L.cache[e]&&delete L.cache[e]}delete M.cache[c[M.expando]]}}}),n.fn.extend({text:function(a){return J(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=ja(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=ja(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(oa(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&ma(oa(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(oa(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!da.test(a)&&!ia[(ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(aa,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(oa(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(oa(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,m=this,o=l-1,p=a[0],q=n.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&ea.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(c=n.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=n.map(oa(c,"script"),ka),g=f.length;l>j;j++)h=c,j!==o&&(h=n.clone(h,!0,!0),g&&n.merge(f,oa(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,n.map(f,la),j=0;g>j;j++)h=f[j],fa.test(h.type||"")&&!L.access(h,"globalEval")&&n.contains(i,h)&&(h.src?n._evalUrl&&n._evalUrl(h.src):n.globalEval(h.textContent.replace(ha,"")))}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),n(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qa,ra={};function sa(b,c){var d,e=n(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:n.css(e[0],"display");return e.detach(),f}function ta(a){var b=l,c=ra[a];return c||(c=sa(a,b),"none"!==c&&c||(qa=(qa||n("