rmails 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (332) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +20 -0
  3. data/Gemfile +24 -0
  4. data/Gemfile.lock +167 -0
  5. data/LICENSE.txt +20 -0
  6. data/README.markdown +9 -0
  7. data/Rakefile +31 -0
  8. data/Rakefile1 +9 -0
  9. data/Vagrantfile +51 -0
  10. data/app/assets/images/arrow_bottom.gif +0 -0
  11. data/app/assets/images/arrow_right.gif +0 -0
  12. data/app/assets/images/at-sign.png +0 -0
  13. data/app/assets/images/checkerboard.gif +0 -0
  14. data/app/assets/images/glyphicons-halflings-white.png +0 -0
  15. data/app/assets/images/glyphicons-halflings.png +0 -0
  16. data/app/assets/images/icon_draft.gif +0 -0
  17. data/app/assets/images/icon_layout.gif +0 -0
  18. data/app/assets/images/icon_move.gif +0 -0
  19. data/app/assets/images/icon_regular.gif +0 -0
  20. data/app/assets/images/icon_snippet.gif +0 -0
  21. data/app/assets/images/nav_arrow.png +0 -0
  22. data/app/assets/images/x.png +0 -0
  23. data/app/assets/javascripts/application.coffee.erb +27 -0
  24. data/app/assets/javascripts/canjs/can.construct.proxy.js +60 -0
  25. data/app/assets/javascripts/canjs/can.construct.super.js +44 -0
  26. data/app/assets/javascripts/canjs/can.control.plugin.js +245 -0
  27. data/app/assets/javascripts/canjs/can.control.view.js +88 -0
  28. data/app/assets/javascripts/canjs/can.dojo.js +3669 -0
  29. data/app/assets/javascripts/canjs/can.dojo.min.js +66 -0
  30. data/app/assets/javascripts/canjs/can.fixture.js +1020 -0
  31. data/app/assets/javascripts/canjs/can.jquery.js +2995 -0
  32. data/app/assets/javascripts/canjs/can.jquery.min.js +52 -0
  33. data/app/assets/javascripts/canjs/can.mootools.js +3462 -0
  34. data/app/assets/javascripts/canjs/can.mootools.min.js +63 -0
  35. data/app/assets/javascripts/canjs/can.observe.attributes.js +293 -0
  36. data/app/assets/javascripts/canjs/can.observe.backup.js +368 -0
  37. data/app/assets/javascripts/canjs/can.observe.delegate.js +359 -0
  38. data/app/assets/javascripts/canjs/can.observe.setter.js +58 -0
  39. data/app/assets/javascripts/canjs/can.observe.validations.js +374 -0
  40. data/app/assets/javascripts/canjs/can.view.modifiers.js +292 -0
  41. data/app/assets/javascripts/canjs/can.yui.js +3530 -0
  42. data/app/assets/javascripts/canjs/can.yui.min.js +65 -0
  43. data/app/assets/javascripts/canjs/can.zepto.js +3426 -0
  44. data/app/assets/javascripts/canjs/can.zepto.min.js +62 -0
  45. data/app/assets/javascripts/controls/admins.coffee.erb +105 -0
  46. data/app/assets/javascripts/controls/aliases.coffee.erb +91 -0
  47. data/app/assets/javascripts/controls/domains.coffee.erb +115 -0
  48. data/app/assets/javascripts/controls/settings.coffee.erb +47 -0
  49. data/app/assets/javascripts/controls/users.coffee.erb +94 -0
  50. data/app/assets/javascripts/lib/facebox.js +311 -0
  51. data/app/assets/javascripts/lib/html5.js +2 -0
  52. data/app/assets/javascripts/lib/jquery.js +9301 -0
  53. data/app/assets/javascripts/lib/jquery_formparams.js +108 -0
  54. data/app/assets/javascripts/lib/jquery_input_hint.js +20 -0
  55. data/app/assets/javascripts/lib/jquery_paginate.js +120 -0
  56. data/app/assets/javascripts/lib/jquery_ui_custom.js +6 -0
  57. data/app/assets/javascripts/lib/json2.js +487 -0
  58. data/app/assets/javascripts/lib/utils.coffee.erb +48 -0
  59. data/app/assets/javascripts/models/admin.coffee.erb +42 -0
  60. data/app/assets/javascripts/models/alias.coffee.erb +28 -0
  61. data/app/assets/javascripts/models/domain.coffee.erb +39 -0
  62. data/app/assets/javascripts/models/property.coffee.erb +18 -0
  63. data/app/assets/javascripts/models/user.coffee.erb +29 -0
  64. data/app/assets/stylesheets/application.sass +156 -0
  65. data/app/assets/stylesheets/base.css.sass +243 -0
  66. data/app/assets/stylesheets/facebox.css +80 -0
  67. data/app/assets/stylesheets/lib/bootstrap.css +9 -0
  68. data/app/assets/stylesheets/twitter/bootstrap-responsive.scss +1 -0
  69. data/app/assets/stylesheets/twitter/bootstrap.scss +63 -0
  70. data/app/assets/stylesheets/twitter/bootstrap/_accordion.scss +34 -0
  71. data/app/assets/stylesheets/twitter/bootstrap/_alerts.scss +79 -0
  72. data/app/assets/stylesheets/twitter/bootstrap/_breadcrumbs.scss +24 -0
  73. data/app/assets/stylesheets/twitter/bootstrap/_button-groups.scss +229 -0
  74. data/app/assets/stylesheets/twitter/bootstrap/_buttons.scss +228 -0
  75. data/app/assets/stylesheets/twitter/bootstrap/_carousel.scss +158 -0
  76. data/app/assets/stylesheets/twitter/bootstrap/_close.scss +32 -0
  77. data/app/assets/stylesheets/twitter/bootstrap/_code.scss +61 -0
  78. data/app/assets/stylesheets/twitter/bootstrap/_component-animations.scss +22 -0
  79. data/app/assets/stylesheets/twitter/bootstrap/_dropdowns.scss +237 -0
  80. data/app/assets/stylesheets/twitter/bootstrap/_forms.scss +689 -0
  81. data/app/assets/stylesheets/twitter/bootstrap/_grid.scss +21 -0
  82. data/app/assets/stylesheets/twitter/bootstrap/_hero-unit.scss +25 -0
  83. data/app/assets/stylesheets/twitter/bootstrap/_labels-badges.scss +83 -0
  84. data/app/assets/stylesheets/twitter/bootstrap/_layouts.scss +16 -0
  85. data/app/assets/stylesheets/twitter/bootstrap/_media.scss +55 -0
  86. data/app/assets/stylesheets/twitter/bootstrap/_mixins.scss +690 -0
  87. data/app/assets/stylesheets/twitter/bootstrap/_modals.scss +95 -0
  88. data/app/assets/stylesheets/twitter/bootstrap/_navbar.scss +497 -0
  89. data/app/assets/stylesheets/twitter/bootstrap/_navs.scss +409 -0
  90. data/app/assets/stylesheets/twitter/bootstrap/_pager.scss +43 -0
  91. data/app/assets/stylesheets/twitter/bootstrap/_pagination.scss +123 -0
  92. data/app/assets/stylesheets/twitter/bootstrap/_popovers.scss +133 -0
  93. data/app/assets/stylesheets/twitter/bootstrap/_progress-bars.scss +122 -0
  94. data/app/assets/stylesheets/twitter/bootstrap/_reset.scss +216 -0
  95. data/app/assets/stylesheets/twitter/bootstrap/_responsive-1200px-min.scss +28 -0
  96. data/app/assets/stylesheets/twitter/bootstrap/_responsive-767px-max.scss +193 -0
  97. data/app/assets/stylesheets/twitter/bootstrap/_responsive-768px-979px.scss +19 -0
  98. data/app/assets/stylesheets/twitter/bootstrap/_responsive-navbar.scss +189 -0
  99. data/app/assets/stylesheets/twitter/bootstrap/_responsive-utilities.scss +74 -0
  100. data/app/assets/stylesheets/twitter/bootstrap/_scaffolding.scss +53 -0
  101. data/app/assets/stylesheets/twitter/bootstrap/_sprites.scss +197 -0
  102. data/app/assets/stylesheets/twitter/bootstrap/_tables.scss +235 -0
  103. data/app/assets/stylesheets/twitter/bootstrap/_thumbnails.scss +53 -0
  104. data/app/assets/stylesheets/twitter/bootstrap/_tooltip.scss +70 -0
  105. data/app/assets/stylesheets/twitter/bootstrap/_type.scss +247 -0
  106. data/app/assets/stylesheets/twitter/bootstrap/_utilities.scss +45 -0
  107. data/app/assets/stylesheets/twitter/bootstrap/_variables.scss +301 -0
  108. data/app/assets/stylesheets/twitter/bootstrap/_wells.scss +29 -0
  109. data/app/assets/stylesheets/twitter/bootstrap/responsive.scss +48 -0
  110. data/app/controllers/admin_users_controller.rb +62 -0
  111. data/app/controllers/aliases_controller.rb +35 -0
  112. data/app/controllers/application_controller.rb +20 -0
  113. data/app/controllers/domains_controller.rb +48 -0
  114. data/app/controllers/server_controller.rb +28 -0
  115. data/app/controllers/users_controller.rb +35 -0
  116. data/app/helpers/admin_users_helper.rb +11 -0
  117. data/app/helpers/application_helper.rb +2 -0
  118. data/app/helpers/domains_helper.rb +25 -0
  119. data/app/helpers/server_helper.rb +30 -0
  120. data/app/mailers/.gitkeep +0 -0
  121. data/app/models/.gitkeep +0 -0
  122. data/app/models/admin_user.rb +54 -0
  123. data/app/models/certificate_manager.rb +46 -0
  124. data/app/models/property.rb +103 -0
  125. data/app/models/property/awstats.rb +15 -0
  126. data/app/models/property/dovecot.rb +61 -0
  127. data/app/models/property/dspam.rb +45 -0
  128. data/app/models/property/nginx.rb +47 -0
  129. data/app/models/property/postfix.rb +64 -0
  130. data/app/models/property_value_validator.rb +41 -0
  131. data/app/models/system_manager.rb +88 -0
  132. data/app/models/virtual_alias.rb +13 -0
  133. data/app/models/virtual_domain.rb +15 -0
  134. data/app/models/virtual_user.rb +51 -0
  135. data/app/views/admin_users/_form.html.haml +21 -0
  136. data/app/views/admin_users/first.html.haml +12 -0
  137. data/app/views/admin_users/index.html.haml +61 -0
  138. data/app/views/aliases/_form.html.haml +11 -0
  139. data/app/views/aliases/_list.html.haml +0 -0
  140. data/app/views/devise/confirmations/new.html.haml +9 -0
  141. data/app/views/devise/mailer/confirmation_instructions.html.haml +4 -0
  142. data/app/views/devise/mailer/reset_password_instructions.html.haml +6 -0
  143. data/app/views/devise/mailer/unlock_instructions.html.haml +5 -0
  144. data/app/views/devise/passwords/edit.html.haml +14 -0
  145. data/app/views/devise/passwords/new.html.haml +12 -0
  146. data/app/views/devise/registrations/edit.html.haml +18 -0
  147. data/app/views/devise/registrations/new.html.haml +10 -0
  148. data/app/views/devise/sessions/new.html.haml +16 -0
  149. data/app/views/devise/shared/_links.haml +17 -0
  150. data/app/views/devise/unlocks/new.html.haml +11 -0
  151. data/app/views/domains/_fields.html.haml +0 -0
  152. data/app/views/domains/_form.html.haml +7 -0
  153. data/app/views/domains/index.html.haml +133 -0
  154. data/app/views/domains/show.html.haml +1 -0
  155. data/app/views/layouts/_nav.html.haml +3 -0
  156. data/app/views/layouts/application.html.haml +29 -0
  157. data/app/views/server/_certificates.html.haml +10 -0
  158. data/app/views/server/_dovecot.html.haml +27 -0
  159. data/app/views/server/_dspam.html.haml +9 -0
  160. data/app/views/server/_postfix_info.html.haml +5 -0
  161. data/app/views/server/_postfix_test.html.haml +5 -0
  162. data/app/views/server/_status.html.haml +11 -0
  163. data/app/views/server/index.html.haml +36 -0
  164. data/app/views/users/_form.html.haml +11 -0
  165. data/app/views/users/_list.html.haml +0 -0
  166. data/bin/rmails +43 -0
  167. data/config.ru +4 -0
  168. data/config/application.rb +62 -0
  169. data/config/boot.rb +6 -0
  170. data/config/environment.rb +5 -0
  171. data/config/environments/development.rb +37 -0
  172. data/config/environments/production.rb +67 -0
  173. data/config/environments/test.rb +37 -0
  174. data/config/initializers/backtrace_silencers.rb +7 -0
  175. data/config/initializers/devise.rb +240 -0
  176. data/config/initializers/devise_encryptable.rb +37 -0
  177. data/config/initializers/devise_models.rb +86 -0
  178. data/config/initializers/inflections.rb +15 -0
  179. data/config/initializers/mime_types.rb +5 -0
  180. data/config/initializers/secret_token.rb +7 -0
  181. data/config/initializers/session_store.rb +8 -0
  182. data/config/initializers/simple_form.rb +142 -0
  183. data/config/initializers/simple_form_bootstrap.rb +45 -0
  184. data/config/initializers/wrap_parameters.rb +14 -0
  185. data/config/locales/cz.yml +45 -0
  186. data/config/locales/devise.cz.yml +47 -0
  187. data/config/locales/devise.en.yml +60 -0
  188. data/config/locales/en.yml +5 -0
  189. data/config/locales/server/cz.yml +14 -0
  190. data/config/locales/server/en.yml +7 -0
  191. data/config/locales/server/help/dovecot/cz.yml +21 -0
  192. data/config/locales/server/help/dovecot/en.yml +18 -0
  193. data/config/locales/server/help/dspam/cz.yml +10 -0
  194. data/config/locales/server/help/dspam/en.yml +4 -0
  195. data/config/locales/server/key/dovecot/cz.yml +23 -0
  196. data/config/locales/server/key/dovecot/en.yml +20 -0
  197. data/config/locales/server/key/dspam/cz.yml +10 -0
  198. data/config/locales/server/key/dspam/en.yml +4 -0
  199. data/config/locales/simple_form.en.yml +26 -0
  200. data/config/locales/views/admin_users/cz.yml +25 -0
  201. data/config/locales/views/admin_users/en.yml +5 -0
  202. data/config/locales/views/aliases/cz.yml +17 -0
  203. data/config/locales/views/aliases/en.yml +1 -0
  204. data/config/locales/views/devise/cz.yml +26 -0
  205. data/config/locales/views/devise/en.yml +13 -0
  206. data/config/locales/views/domains/cz.yml +15 -0
  207. data/config/locales/views/domains/en.yml +15 -0
  208. data/config/locales/views/server/cz.yml +19 -0
  209. data/config/locales/views/server/en.yml +3 -0
  210. data/config/locales/views/users/cz.yml +18 -0
  211. data/config/locales/views/users/en.yml +1 -0
  212. data/config/routes.rb +80 -0
  213. data/db/migrate/20121112201233_virtual_domain.rb +11 -0
  214. data/db/migrate/20121112201247_virtual_alias.rb +10 -0
  215. data/db/migrate/20121112201341_virtual_user.rb +34 -0
  216. data/db/migrate/20121112201359_create_admin_user.rb +30 -0
  217. data/db/migrate/20121112201411_server_configuration.rb +13 -0
  218. data/db/migrate/20130304083938_join_domains_users.rb +12 -0
  219. data/db/migrate/20130311214040_create_versions.rb +18 -0
  220. data/db/seeds.rb +45 -0
  221. data/lib/devise-encryptable.rb +1 -0
  222. data/lib/rmails.rb +5 -0
  223. data/lib/rmails/installer.rb +37 -0
  224. data/lib/rmails/version.rb +3 -0
  225. data/lib/tasks/.gitkeep +0 -0
  226. data/lib/templates/haml/scaffold/_form.html.haml +10 -0
  227. data/locals +0 -0
  228. data/log/.gitkeep +0 -0
  229. data/public/404.html +26 -0
  230. data/public/422.html +26 -0
  231. data/public/500.html +25 -0
  232. data/public/favicon.ico +0 -0
  233. data/public/fonts/London.eot +0 -0
  234. data/public/fonts/London.otf +0 -0
  235. data/public/fonts/London.woff +0 -0
  236. data/public/fonts/LondonBold.otf +0 -0
  237. data/public/robots.txt +5 -0
  238. data/rmails.gemspec +35 -0
  239. data/script/prepflog.pl +576 -0
  240. data/script/rails +6 -0
  241. data/system/config/automateit_env.rb +16 -0
  242. data/system/config/fields.yml +48 -0
  243. data/system/config/tags.yml +39 -0
  244. data/system/dist/README_AutomateIt_dist.txt +20 -0
  245. data/system/dist/amavis/spamassassin.cf.erb +85 -0
  246. data/system/dist/amavis/user.erb +33 -0
  247. data/system/dist/awstats/awstats.mail.conf.erb +41 -0
  248. data/system/dist/awstats/prepflog.pl +576 -0
  249. data/system/dist/dovecot/dovecot-sql.conf.ext.erb +14 -0
  250. data/system/dist/dovecot/dovecot.conf.erb +297 -0
  251. data/system/dist/dovecot/old_dovecot.conf.erb +63 -0
  252. data/system/dist/dspam/conf.erb +96 -0
  253. data/system/dist/dspam/pgsql.conf +33 -0
  254. data/system/dist/nginx/awstats.erb +17 -0
  255. data/system/dist/nginx/rmails.erb +40 -0
  256. data/system/dist/postfix/email2email.cf.erb +5 -0
  257. data/system/dist/postfix/main.cf.erb +118 -0
  258. data/system/dist/postfix/master.cf.erb +74 -0
  259. data/system/dist/postfix/sasl.conf.erb +3 -0
  260. data/system/dist/postfix/sender_login_maps.cf.erb +5 -0
  261. data/system/dist/postfix/virtual_alias_maps.cf.erb +5 -0
  262. data/system/dist/postfix/virtual_mailbox_domains.cf.erb +5 -0
  263. data/system/dist/postfix/virtual_mailbox_maps.cf.erb +5 -0
  264. data/system/dist/postgresql/postgresql.conf.erb +54 -0
  265. data/system/dist/rmails/Gemfile.1 +8 -0
  266. data/system/dist/rmails/Gemfile.2 +24 -0
  267. data/system/dist/rmails/database.yml.erb +15 -0
  268. data/system/dist/sudoers +37 -0
  269. data/system/lib/README_AutomateIt_lib.txt +22 -0
  270. data/system/lib/dkim_key.rb +9 -0
  271. data/system/lib/smtpd_key.rb +39 -0
  272. data/system/lib/ssl.rb +23 -0
  273. data/system/recipes/01_prepare_server.rb +84 -0
  274. data/system/recipes/02_setup_database.rb +65 -0
  275. data/system/recipes/03_setup_postfix.rb +124 -0
  276. data/system/recipes/04_setup_dovecot.rb +78 -0
  277. data/system/recipes/05_setup_nginx.rb +29 -0
  278. data/system/recipes/06_setup_dspam.rb +24 -0
  279. data/system/recipes/07_setup_amavis.rb +16 -0
  280. data/system/recipes/08_setup_spamassassin.rb +22 -0
  281. data/system/recipes/09_setup_awstats.rb +49 -0
  282. data/system/recipes/XX_start_services.rb +5 -0
  283. data/test/fixtures/.gitkeep +0 -0
  284. data/test/functional/.gitkeep +0 -0
  285. data/test/functional/aliases_controller_test.rb +7 -0
  286. data/test/functional/domains_controller_test.rb +7 -0
  287. data/test/functional/users_controller_test.rb +7 -0
  288. data/test/integration/.gitkeep +0 -0
  289. data/test/performance/browsing_test.rb +12 -0
  290. data/test/test_helper.rb +13 -0
  291. data/test/unit/.gitkeep +0 -0
  292. data/test/unit/helpers/aliases_helper_test.rb +4 -0
  293. data/test/unit/helpers/domains_helper_test.rb +4 -0
  294. data/test/unit/helpers/users_helper_test.rb +4 -0
  295. data/vendor/assets/javascripts/.gitkeep +0 -0
  296. data/vendor/assets/javascripts/canjs/can.construct.proxy.js +60 -0
  297. data/vendor/assets/javascripts/canjs/can.construct.super.js +44 -0
  298. data/vendor/assets/javascripts/canjs/can.control.plugin.js +245 -0
  299. data/vendor/assets/javascripts/canjs/can.control.view.js +88 -0
  300. data/vendor/assets/javascripts/canjs/can.dojo.js +3669 -0
  301. data/vendor/assets/javascripts/canjs/can.dojo.min.js +66 -0
  302. data/vendor/assets/javascripts/canjs/can.fixture.js +1020 -0
  303. data/vendor/assets/javascripts/canjs/can.jquery.js +2995 -0
  304. data/vendor/assets/javascripts/canjs/can.jquery.min.js +52 -0
  305. data/vendor/assets/javascripts/canjs/can.mootools.js +3462 -0
  306. data/vendor/assets/javascripts/canjs/can.mootools.min.js +63 -0
  307. data/vendor/assets/javascripts/canjs/can.observe.attributes.js +293 -0
  308. data/vendor/assets/javascripts/canjs/can.observe.backup.js +368 -0
  309. data/vendor/assets/javascripts/canjs/can.observe.delegate.js +359 -0
  310. data/vendor/assets/javascripts/canjs/can.observe.setter.js +58 -0
  311. data/vendor/assets/javascripts/canjs/can.observe.validations.js +374 -0
  312. data/vendor/assets/javascripts/canjs/can.view.modifiers.js +292 -0
  313. data/vendor/assets/javascripts/canjs/can.yui.js +3530 -0
  314. data/vendor/assets/javascripts/canjs/can.yui.min.js +65 -0
  315. data/vendor/assets/javascripts/canjs/can.zepto.js +3426 -0
  316. data/vendor/assets/javascripts/canjs/can.zepto.min.js +62 -0
  317. data/vendor/assets/javascripts/twitter/bootstrap-affix.js +104 -0
  318. data/vendor/assets/javascripts/twitter/bootstrap-alert.js +90 -0
  319. data/vendor/assets/javascripts/twitter/bootstrap-button.js +96 -0
  320. data/vendor/assets/javascripts/twitter/bootstrap-carousel.js +176 -0
  321. data/vendor/assets/javascripts/twitter/bootstrap-collapse.js +158 -0
  322. data/vendor/assets/javascripts/twitter/bootstrap-dropdown.js +150 -0
  323. data/vendor/assets/javascripts/twitter/bootstrap-modal.js +239 -0
  324. data/vendor/assets/javascripts/twitter/bootstrap-popover.js +103 -0
  325. data/vendor/assets/javascripts/twitter/bootstrap-scrollspy.js +151 -0
  326. data/vendor/assets/javascripts/twitter/bootstrap-tab.js +135 -0
  327. data/vendor/assets/javascripts/twitter/bootstrap-tooltip.js +275 -0
  328. data/vendor/assets/javascripts/twitter/bootstrap-transition.js +60 -0
  329. data/vendor/assets/javascripts/twitter/bootstrap-typeahead.js +300 -0
  330. data/vendor/assets/javascripts/twitter/my/bootstrap-typeahead.js +311 -0
  331. data/vendor/assets/stylesheets/.gitkeep +0 -0
  332. metadata +470 -0
@@ -0,0 +1,65 @@
1
+ (function(c,m,k){YUI().add("can",function(j){c.Y=j;c.addEvent=function(a,b){this.__bindEvents||(this.__bindEvents={});var d=a.split(".")[0];this.__bindEvents[d]||(this.__bindEvents[d]=[]);this.__bindEvents[d].push({handler:b,name:a});return this};c.removeEvent=function(a,b){if(this.__bindEvents){for(var d=0,c=this.__bindEvents[a.split(".")[0]],f;d<c.length;)f=c[d],b&&f.handler===b||!b&&f.name===a?c.splice(d,1):d++;return this}};c.dispatch=function(a){if(this.__bindEvents){var b=(this.__bindEvents[a.type.split(".")[0]]||
2
+ []).slice(0),d=this,e=[a].concat(a.data||[]);c.each(b,function(b){a.data=e.slice(1);b.handler.apply(d,e)})}};c.each=function(a,b,d){var c=0,f;if(a)if("number"==typeof a.length&&a.pop){a.attr&&a.attr("length");for(f=a.length;c<f&&!1!==b.call(d||a[c],a[c],c,a);c++);}else for(f in a)if(!1===b.call(d||a[c],a[f],f,a))break;return a};j=c.Y=c.Y||YUI().use("*");c.trim=function(a){return j.Lang.trim(a)};c.makeArray=function(a){return j.Array(a)};c.isArray=j.Lang.isArray;c.inArray=function(a,b){return j.Array.indexOf(b,
3
+ a)};c.map=function(a,b){return j.Array.map(c.makeArray(a||[]),b)};c.extend=function(a){for(var b=!0===a?1:0,d=arguments[b],c=b+1,f;f=arguments[c];c++)j.mix(d,f,!0,null,null,!!b);return d};c.param=function(a){return j.QueryString.stringify(a,{arrayKey:!0})};c.isEmptyObject=function(a){return j.Object.isEmpty(a)};c.proxy=function(a,b){return j.bind.apply(j,arguments)};c.isFunction=function(a){return j.Lang.isFunction(a)};var S=function(a){a.each(function(b,d){a[d]=b.getDOMNode()});a.length=a.size();
4
+ return a};c.$=function(a){return a===m?m:a instanceof j.NodeList?S(a):"object"===typeof a&&!c.isArray(a)&&"undefined"===typeof a.nodeType&&!a.getDOMNode?a:S(j.all(a))};c.get=function(a,b){return a._nodes[b]};c.buildFragment=function(a,b){var d=j.Node.create(a,b&&b.ownerDocument),d=d&&d.getDOMNode()||document.createDocumentFragment();if(11!==d.nodeType){var c=document.createDocumentFragment();c.appendChild(d);d=c}return d};c.append=function(a,b){a.each(function(a){"string"===typeof b&&(b=c.buildFragment(b,
5
+ a));a.append(b)})};c.addClass=function(a,b){return a.addClass(b)};c.data=function(a,b,d){return d===k?a.item(0).getData(b):a.item(0).setData(b,d)};c.remove=function(a){return a.remove()&&a.destroy()};c._yNodeDestroy=c._yNodeDestroy||j.Node.prototype.destroy;j.Node.prototype.destroy=function(){c.trigger(this,"destroyed",[],!1);c._yNodeDestroy.apply(this,arguments)};j.NodeList.addMethod("destroy",j.Node.prototype.destroy);var T={type:"method",success:k,error:k},H=function(a,b){if(a&&a.io){var d=a.io,
6
+ c;for(c in d)b[c]="function"==typeof b[c]?function(){d[c].apply(d,arguments)}:c[d]}};c.ajax=function(a){var b=c.Deferred(),d=c.extend({},a),e;for(e in T)d[e]!==k&&(d[T[e]]=d[e],delete d[e]);d.sync=!a.async;var f=a.success,g=a.error;d.on={success:function(d,c){var e=c.responseText;"json"===a.dataType&&(e=eval("("+e+")"));H(h,b);b.resolve(e,"success",h);f&&f(e,"success",h)},failure:function(){H(h,b);b.reject(h,"error");g&&g(h,"error")}};var h=j.io(d.url,d);H(h,b);return b};var U=0,V=function(a,b,d,
7
+ e){if(a instanceof j.NodeList||!a.on||a.getDOMNode)a.each(function(a){var a=c.$(a),f=c.data(a,"events"),i=d+":"+b;f||c.data(a,"events",f={});f[i]||(f[i]={});e.__bindingsIds===k&&(e.__bindingsIds=U++);f[i][e.__bindingsIds]=b?a.item(0).delegate(d,e,b):a.item(0).on(d,e)});else{var f=a.__canEvents=a.__canEvents||{};f[d]||(f[d]={});e.__bindingsIds===k&&(e.__bindingsIds=U++);f[d][e.__bindingsIds]=a.on(d,e)}},W=function(a,b,d,e){if(a instanceof j.NodeList||!a.on||a.getDOMNode)a.each(function(a){var a=c.$(a),
8
+ a=c.data(a,"events"),f=a[d+":"+b];f[e.__bindingsIds].detach();delete f[e.__bindingsIds];c.isEmptyObject(f)&&delete a[d];c.isEmptyObject(a)});else{var a=a.__canEvents||{},f=a[d];f[e.__bindingsIds].detach();delete f[e.__bindingsIds];c.isEmptyObject(f)&&delete a[d];c.isEmptyObject(a)}};c.bind=function(a,b){this.bind&&this.bind!==c.bind?this.bind(a,b):this.on||this.nodeType?V(c.$(this),k,a,b):this.addEvent?this.addEvent(a,b):c.addEvent.call(this,a,b);return this};c.unbind=function(a,b){this.unbind&&this.unbind!==
9
+ c.unbind?this.unbind(a,b):this.on||this.nodeType?W(c.$(this),k,a,b):c.removeEvent.call(this,a,b);return this};c.trigger=function(a,b,d,e){a instanceof j.NodeList&&(a=a.item(0));a.getDOMNode&&(a=a.getDOMNode());if(a.nodeName){a=j.Node(a);if(!1===e)a.once(b,function(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=!0;a._stopper&&a._stopper()});wa(a.getDOMNode(),b,{})}else"string"===typeof b&&(b={type:b}),b.target=b.target||a,b.data=d,c.dispatch.call(a,b)};j.mix(j.Node.DOM_EVENTS,{destroyed:!0});
10
+ c.delegate=function(a,b,d){this.on||this.nodeType?V(c.$(this),a,b,d):this.delegate&&this.delegate(a,b,d);return this};c.undelegate=function(a,b,d){this.on||this.nodeType?W(c.$(this),a,b,d):this.undelegate&&this.undelegate(a,b,d);return this};var xa=/mouse(enter|leave)/,ya=function(a,b){return"mouse"+("enter"==b?"over":"out")},wa=document.createEvent?function(a,b,d){var e=document.createEvent("HTMLEvents"),b=b.replace(xa,ya);e.initEvent(b,!0,!0);d&&c.extend(e,d);a.dispatchEvent(e)}:function(a,b,d){var e=
11
+ "on"+b,f=!1;b.toLowerCase();try{a.fireEvent(e)}catch(g){d=c.extend({type:b,target:a,faux:!0,_stopper:function(){f=this.cancelBubble}},d);for(X(a,b,d);!f&&a!==document&&a.parentNode;)a=a.parentNode,X(a,b,d)}},X=function(a,b,d){a=j.Node(a);if(b=c.Y.Event.getListeners(a._yuid,b))for(a=0;a<b.length;a++)b[a].fire(d)},w=function(a){if(!(this instanceof w))return new w;this._doneFuncs=[];this._failFuncs=[];this._resultArgs=null;this._status="";a&&a.call(this,this)};c.Deferred=w;c.when=w.when=function(){var a=
12
+ c.makeArray(arguments);if(2>a.length){var b=a[0];return b&&c.isFunction(b.isResolved)&&c.isFunction(b.isRejected)?b:w().resolve(b)}var d=w(),e=0,f=[];c.each(a,function(b,c){b.done(function(){f[c]=2>arguments.length?arguments[0]:arguments;++e==a.length&&d.resolve.apply(d,f)}).fail(function(){d.reject(arguments)})});return d};var C=function(a,b){return function(d){var c=this._resultArgs=1<arguments.length?arguments[1]:[];return this.exec(d,this[a],c,b)}},v=function(a,b){return function(){var d=this;
13
+ c.each(Array.prototype.slice.call(arguments),function(c,f,g){c&&(c.constructor===Array?g.callee.apply(d,c):(d._status===b&&c.apply(d,d._resultArgs||[]),d[a].push(c)))});return this}};c.extend(w.prototype,{pipe:function(a,b){var d=c.Deferred();this.done(function(){d.resolve(a.apply(this,arguments))});this.fail(function(){b?d.reject(b.apply(this,arguments)):d.reject.apply(d,arguments)});return d},resolveWith:C("_doneFuncs","rs"),rejectWith:C("_failFuncs","rj"),done:v("_doneFuncs","rs"),fail:v("_failFuncs",
14
+ "rj"),always:function(){var a=c.makeArray(arguments);a.length&&a[0]&&this.done(a[0]).fail(a[0]);return this},then:function(){var a=c.makeArray(arguments);1<a.length&&a[1]&&this.fail(a[1]);a.length&&a[0]&&this.done(a[0]);return this},isResolved:function(){return"rs"===this._status},isRejected:function(){return"rj"===this._status},reject:function(){return this.rejectWith(this,arguments)},resolve:function(){return this.resolveWith(this,arguments)},exec:function(a,b,d,e){if(""!==this._status)return this;
15
+ this._status=e;c.each(b,function(b){b.apply(a,d)});return this}});var za=/==/,Aa=/([A-Z]+)([A-Z][a-z])/g,Ba=/([a-z\d])([A-Z])/g,Ca=/([a-z\d])([A-Z])/g,Y=/\{([^\}]+)\}/g,t=/"/g,Da=/'/g;c.extend(c,{esc:function(a){return(""+a).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(t,"&#34;").replace(Da,"&#39;")},getObject:function(a,b,d){var a=a?a.split("."):[],e=a.length,f,g=0,h,i,b=c.isArray(b)?b:[b||m];if(!e)return b[0];for(;f=b[g++];){for(i=0;i<e-1&&/^f|^o/.test(typeof f);i++)f=
16
+ a[i]in f?f[a[i]]:d&&(f[a[i]]={});if(/^f|^o/.test(typeof f)&&(h=a[i]in f?f[a[i]]:d&&(f[a[i]]={}),h!==k))return!1===d&&delete f[a[i]],h}},capitalize:function(a){return a.charAt(0).toUpperCase()+a.slice(1)},underscore:function(a){return a.replace(za,"/").replace(Aa,"$1_$2").replace(Ba,"$1_$2").replace(Ca,"_").toLowerCase()},sub:function(a,b,d){var e=[];e.push(a.replace(Y,function(a,g){var h=c.getObject(g,b,d===k?d:!d);return/^f|^o/.test(typeof h)?(e.push(h),""):""+h}));return 1>=e.length?e[0]:e},replacer:Y,
17
+ undHash:/_|-/});var I=0;c.Construct=function(){if(arguments.length)return c.Construct.extend.apply(c.Construct,arguments)};c.extend(c.Construct,{newInstance:function(){var a=this.instance(),b;a.setup&&(b=a.setup.apply(a,arguments));a.init&&a.init.apply(a,b||arguments);return a},_inherit:function(a,b,d){c.extend(d||a,a||{})},_overwrite:function(a,b,c,e){a[c]=e},setup:function(a){this.defaults=c.extend(!0,{},a.defaults,this.defaults)},instance:function(){I=1;var a=new this;I=0;return a},extend:function(a,
18
+ b,d){function e(){if(!I)return this.constructor!==e&&arguments.length?arguments.callee.extend.apply(arguments.callee,arguments):this.constructor.newInstance.apply(this.constructor,arguments)}"string"!=typeof a&&(d=b,b=a,a=null);d||(d=b,b=null);var d=d||{},f=this.prototype,g,h,i,n;n=this.instance();c.Construct._inherit(d,f,n);for(g in this)this.hasOwnProperty(g)&&(e[g]=this[g]);c.Construct._inherit(b,this,e);if(a){i=a.split(".");h=i.pop();i=f=c.getObject(i.join("."),m,!0);var p=c.underscore(a.replace(/\./g,
19
+ "_")),k=c.underscore(h);f[h]=e}c.extend(e,{constructor:e,prototype:n,namespace:i,shortName:h,_shortName:k,fullName:a,_fullName:p});e.prototype.constructor=e;h=[this].concat(c.makeArray(arguments));n=e.setup.apply(e,h);e.init&&e.init.apply(e,n||h);return e}});var r=function(a){return a&&"object"===typeof a&&!(a instanceof Date)},J=function(a,b){return c.each(a,function(a){a&&a.unbind&&a.unbind("change"+b)})},K=function(a,b,d){a instanceof x?J([a],d._namespace):a=c.isArray(a)?new x.List(a):new x(a);
20
+ a.bind("change"+d._namespace,function(e,f){var g=c.makeArray(arguments),e=g.shift();g[0]="*"===b?d.indexOf(a)+"."+g[0]:b+"."+g[0];e.triggeredNS=e.triggeredNS||{};e.triggeredNS[d._namespace]||(e.triggeredNS[d._namespace]=!0,c.trigger(d,e,g),c.trigger(d,g[0],g))});return a},Z=0,y=k,$=function(){if(!y)return y=[],!0},q=function(a,b,d){if(!a._init)if(y)y.push([a,{type:b,batchNum:aa},d]);else return c.trigger(a,b,d)},aa=1,ba=function(){var a=y.slice(0);y=k;aa++;c.each(a,function(a){c.trigger.apply(c,a)})},
21
+ E=function(a,b,d){a.each(function(a,f){d[f]=r(a)&&c.isFunction(a[b])?a[b]():a});return d},v=function(a){return function(){return c[a].apply(this,arguments)}},C=v("addEvent"),v=v("removeEvent"),L=function(a){return c.isArray(a)?a:(""+a).split(".")},x=c.Construct("can.Observe",{setup:function(){c.Construct.setup.apply(this,arguments)},bind:C,unbind:v,id:"id"},{setup:function(a){this._data={};this._namespace=".observe"+ ++Z;this._init=1;this.attr(a);delete this._init},attr:function(a,b){if(~"ns".indexOf((typeof a).charAt(0))){if(b===
22
+ k)return x.__reading&&x.__reading(this,a),this._get(a);this._set(a,b);return this}return this._attrs(a,b)},each:function(){return c.each.apply(k,[this.__get()].concat(c.makeArray(arguments)))},removeAttr:function(a){var a=L(a),b=a.shift(),c=this._data[b];if(a.length)return c.removeAttr(a);delete this._data[b];b in this.constructor.prototype||delete this[b];q(this,"change",[b,"remove",k,c]);q(this,b,[k,c]);return c},_get:function(a){var a=L(a),b=this.__get(a.shift());return a.length?b?b._get(a):k:
23
+ b},__get:function(a){return a?this._data[a]:this._data},_set:function(a,b){var c=L(a),e=c.shift(),f=this.__get(e);if(r(f)&&c.length)f._set(c,b);else{if(c.length)throw"can.Observe: Object does not exist";this.__convert&&(b=this.__convert(e,b));this.__set(e,b,f)}},__set:function(a,b,c){if(b!==c){var e=this.__get().hasOwnProperty(a)?"set":"add";this.___set(a,r(b)?K(b,a,this):b);q(this,"change",[a,e,b,c]);q(this,a,[b,c]);c&&J([c],this._namespace)}},___set:function(a,b){this._data[a]=b;a in this.constructor.prototype||
24
+ (this[a]=b)},bind:C,unbind:v,serialize:function(){return E(this,"serialize",{})},_attrs:function(a,b){if(a===k)return E(this,"attr",{});var a=c.extend(!0,{},a),d,e=$(),f=this,g;this.each(function(c,d){g=a[d];g===k?b&&f.removeAttr(d):(r(c)&&r(g)?c.attr(g,b):c!=g&&f._set(d,g),delete a[d])});for(d in a)g=a[d],this._set(d,g);e&&ba();return this}}),Ea=[].splice,M=x("can.Observe.List",{setup:function(a,b){this.length=0;this._namespace=".observe"+ ++Z;this._init=1;this.bind("change",c.proxy(this._changes,
25
+ this));this.push.apply(this,c.makeArray(a||[]));c.extend(this,b);delete this._init},_changes:function(a,b,c,e,f){~b.indexOf(".")||("add"===c?(q(this,c,[e,+b]),q(this,"length",[this.length])):"remove"===c?(q(this,c,[f,+b]),q(this,"length",[this.length])):q(this,c,[e,+b]))},__get:function(a){return a?this[a]:this},___set:function(a,b){this[a]=b;+a>=this.length&&(this.length=+a+1)},serialize:function(){return E(this,"serialize",[])},splice:function(a,b){var d=c.makeArray(arguments),e;for(e=2;e<d.length;e++){var f=
26
+ d[e];r(f)&&(d[e]=K(f,"*",this))}b===k&&(b=d[1]=this.length-a);e=Ea.apply(this,d);0<b&&(q(this,"change",[""+a,"remove",k,e]),J(e,this._namespace));2<d.length&&q(this,"change",[""+a,"add",d.slice(2),e]);return e},_attrs:function(a,b){if(a===k)return E(this,"attr",[]);var a=a.slice(0),c=Math.min(a.length,this.length),e=$(),f;for(f=0;f<c;f++){var g=this[f],h=a[f];r(g)&&r(h)?g.attr(h,b):g!=h&&this._set(f,h)}a.length>this.length?this.push(a.slice(this.length)):a.length<this.length&&b&&this.splice(a.length);
27
+ e&&ba()}});c.each({push:"length",unshift:0},function(a,b){M.prototype[b]=function(){for(var d=arguments[0]&&c.isArray(arguments[0])?arguments[0]:c.makeArray(arguments),e=a?this.length:0,f=0;f<d.length;f++){var g=d[f];r(g)&&(d[f]=K(g,"*",this))}f=[][b].apply(this,d);(!this.comparator||!d.length)&&q(this,"change",[""+e,"add",d,k]);return f}});c.each({pop:"length",shift:0},function(a,b){M.prototype[b]=function(){var d=arguments[0]&&c.isArray(arguments[0])?arguments[0]:c.makeArray(arguments),e=a&&this.length?
28
+ this.length-1:0,d=[][b].apply(this,d);q(this,"change",[""+e,"remove",k,[d]]);d&&d.unbind&&d.unbind("change"+this._namespace);return d}});M.prototype.indexOf=[].indexOf||function(a){return c.inArray(a,this)};var Fa=function(a,b,d){var e=new c.Deferred;a.then(function(){arguments[0]=b[d](arguments[0]);e.resolve.apply(e,arguments)},function(){e.rejectWith.apply(this,arguments)});return e},Ga=0,ca=/change.observe\d+/,da=function(a,b,c,e,f){var g;g=[a.serialize()];var h=a.constructor,i;"destroy"==b&&g.shift();
29
+ "create"!==b&&g.unshift(a[a.constructor.id]);i=h[b].apply(h,g);g=i.pipe(function(c){a[f||b+"d"](c,i);return a});i.abort&&(g.abort=function(){i.abort()});return g.then(c,e)},Ha={create:{url:"_shortName",type:"post"},update:{data:function(a,b){var b=b||{},d=this.id;b[d]&&b[d]!==a&&(b["new"+c.capitalize(a)]=b[d],delete b[d]);b[d]=a;return b},type:"put"},destroy:{type:"delete",data:function(a){var b={};b[this.id]=a;return b}},findAll:{url:"_shortName"},findOne:{}},ea=function(a,b){return function(d){var d=
30
+ a.data?a.data.apply(this,arguments):d,e=b||this[a.url||"_url"],f=d,g=a.type||"get";if("string"==typeof e){var h=e.split(" "),e={url:h.pop()};h.length&&(e.type=h.pop())}e.data="object"==typeof f&&!c.isArray(f)?c.extend(e.data||{},f):f;e.url=c.sub(e.url,e.data,!0);return c.ajax(c.extend({type:g||"post",dataType:"json",success:void 0,error:void 0},e))}};c.Observe("can.Model",{setup:function(a){c.Observe.apply(this,arguments);if(this!==c.Model){var b=this,d=c.proxy(this._clean,b);c.each(Ha,function(e,
31
+ f){c.isFunction(b[f])||(b[f]=ea(e,b[f]));if(b["make"+c.capitalize(f)]){var g=b["make"+c.capitalize(f)](b[f]);c.Construct._overwrite(b,a,f,function(){this._super;this._reqs++;return g.apply(this,arguments).then(d,d)})}});if(!b.fullName||b.fullName==a.fullName)b.fullName=b._shortName="Model"+ ++Ga;this.store={};this._reqs=0;this._url=this._shortName+"/{"+this.id+"}"}},_ajax:ea,_clean:function(){this._reqs--;if(!this._reqs)for(var a in this.store)this.store[a]._bindings||delete this.store[a]},models:function(a){if(a){if(a instanceof
32
+ this.List)return a;var b=this,d=new (b.List||fa),e=c.isArray(a),f=a instanceof fa,f=e?a:f?a.serialize():a.data;c.each(f,function(a){d.push(b.model(a))});e||c.each(a,function(a,b){"data"!==b&&(d[b]=a)});return d}},model:function(a){if(a){a instanceof this&&(a=a.serialize());var b=this.store[a[this.id]]?this.store[a[this.id]].attr(a):new this(a);this._reqs&&(this.store[a[this.id]]=b);return b}}},{isNew:function(){var a=this[this.constructor.id];return!(a||0===a)},save:function(a,b){return da(this,this.isNew()?
33
+ "create":"update",a,b)},destroy:function(a,b){return da(this,"destroy",a,b,"destroyed")},bind:function(a){ca.test(a)||(this._bindings||(this.constructor.store[this[this.constructor.id]]=this,this._bindings=0),this._bindings++);return c.Observe.prototype.bind.apply(this,arguments)},unbind:function(a){ca.test(a)||(this._bindings--,this._bindings||delete this.constructor.store[this[this.constructor.id]]);return c.Observe.prototype.unbind.apply(this,arguments)},___set:function(a,b){c.Observe.prototype.___set.call(this,
34
+ a,b);a===this.constructor.id&&this._bindings&&(this.constructor.store[this[this.constructor.id]]=this)}});c.each({makeFindAll:"models",makeFindOne:"model"},function(a,b){c.Model[b]=function(b){return function(c,f,g){return Fa(b.call(this,c),this,a).then(f,g)}}});c.each(["created","updated","destroyed"],function(a){c.Model.prototype[a]=function(b){var d=this.constructor;b&&"object"==typeof b&&this.attr(b.attr?b.attr():b);c.trigger(this,a);c.trigger(this,"change",a);c.trigger(d,a,this)}});var fa=c.Observe.List("can.Model.List",
35
+ {setup:function(){c.Observe.List.prototype.setup.apply(this,arguments);var a=this;this.bind("change",function(b,c){/\w+\.destroyed/.test(c)&&a.splice(a.indexOf(b.target),1)})}}),Ia=/^\d+$/,Ja=/([^\[\]]+)|(\[\])/g,Ka=/([^?#]*)(#.*)?$/,ga=function(a){return decodeURIComponent(a.replace(/\+/g," "))};c.extend(c,{deparam:function(a){var b={},d;a&&Ka.test(a)&&(a=a.split("&"),c.each(a,function(a){var a=a.split("="),c=ga(a.shift()),g=ga(a.join("="));current=b;for(var a=c.match(Ja),c=0,h=a.length-1;c<h;c++)current[a[c]]||
36
+ (current[a[c]]=Ia.test(a[c+1])||"[]"==a[c+1]?[]:{}),current=current[a[c]];d=a.pop();"[]"==d?current.push(g):current[d]=g}));return b}});var ha=/\:([\w\.]+)/g,ia=/^(?:&[^=]+=[^&]*)+/,La=function(a){var b=[];c.each(a,function(a,e){b.push(("className"===e?"class":e)+'="'+("href"===e?a:c.esc(a))+'"')});return b.join(" ")},ja=function(a,b){var c=0,e=0,f={},g;for(g in a.defaults)a.defaults[g]===b[g]&&(f[g]=1,c++);for(;e<a.names.length;e++){if(!b.hasOwnProperty(a.names[e]))return-1;f[a.names[e]]||c++}return c},
37
+ ka=!0,N=m.location,z=c.each,u=c.extend;c.route=function(a,b){var b=b||{},d=[],e=a.replace(ha,function(c,e,h){d.push(e);return"([^\\"+(a.substr(h+c.length,1)||"&")+"]"+(b[e]?"*":"+")+")"});c.route.routes[a]={test:RegExp("^"+e+"($|&)"),route:a,names:d,defaults:b,length:a.split("/").length};return c.route};u(c.route,{param:function(a,b){var d,e=0,f,g=a.route,h=0;delete a.route;z(a,function(){h++});z(c.route.routes,function(c){f=ja(c,a);f>e&&(d=c,e=f);if(f>=h)return!1});c.route.routes[g]&&ja(c.route.routes[g],
38
+ a)===e&&(d=c.route.routes[g]);if(d){var i=u({},a),g=d.route.replace(ha,function(c,b){delete i[b];return a[b]===d.defaults[b]?"":encodeURIComponent(a[b])}),n;z(d.defaults,function(a,c){i[c]===a&&delete i[c]});n=c.param(i);b&&c.route.attr("route",d.route);return g+(n?"&"+n:"")}return c.isEmptyObject(a)?"":"&"+c.param(a)},deparam:function(a){var b={length:-1};z(c.route.routes,function(c){c.test.test(a)&&c.length>b.length&&(b=c)});if(-1<b.length){var d=a.match(b.test),e=d.shift(),f=(e=a.substr(e.length-
39
+ ("&"===d[d.length-1]?1:0)))&&ia.test(e)?c.deparam(e.slice(1)):{},f=u(!0,{},b.defaults,f);z(d,function(a,c){a&&"&"!==a&&(f[b.names[c]]=decodeURIComponent(a))});f.route=b.route;return f}"&"!==a.charAt(0)&&(a="&"+a);return ia.test(a)?c.deparam(a.slice(1)):{}},data:new c.Observe({}),routes:{},ready:function(a){!1===a&&(ka=a);(!0===a||!0===ka)&&la();return c.route},url:function(a,b){b&&(a=u({},O,a));return"#!"+c.route.param(a)},link:function(a,b,d,e){return"<a "+La(u({href:c.route.url(b,e)},d))+">"+a+
40
+ "</a>"},current:function(a){return N.hash=="#!"+c.route.param(a)}});z("bind unbind delegate undelegate attr removeAttr".split(" "),function(a){c.route[a]=function(){return c.route.data[a].apply(c.route.data,arguments)}});var ma,O,la=function(){var a=N.href.split(/#!?/)[1]||"";O=c.route.deparam(a);(!P||a!==na)&&c.route.attr(O,!0)},na,P;c.bind.call(m,"hashchange",la);c.route.bind("change",function(){P=1;clearTimeout(ma);ma=setTimeout(function(){P=0;var a=c.route.data.serialize();N.hash="#!"+(na=c.route.param(a,
41
+ !0))},1)});c.bind.call(document,"ready",c.route.ready);(function(){var a=function(a,b,d){c.bind.call(a,b,d);return function(){c.unbind.call(a,b,d)}},b=c.isFunction,d=c.extend,e=c.each,f=[].slice,g=/\{([^\}]+)\}/g,h=c.getObject("$.event.special")||{},i=function(a,b,d,e){c.delegate.call(a,b,d,e);return function(){c.undelegate.call(a,b,d,e)}},n=function(a,d){var e="string"==typeof d?a[d]:d;b(e)||(e=a[e]);return function(){a.called=d;return e.apply(a,[this.nodeName?c.$(this):this].concat(f.call(arguments,
42
+ 0)))}},p;c.Construct("can.Control",{setup:function(){c.Construct.setup.apply(this,arguments);if(this!==c.Control){var a;this.actions={};for(a in this.prototype)this._isAction(a)&&(this.actions[a]=this._action(a))}},_isAction:function(a){var c=this.prototype[a],d=typeof c;return"constructor"!==a&&("function"==d||"string"==d&&b(this.prototype[c]))&&!(!h[a]&&!j[a]&&!/[^\w]/.test(a))},_action:function(a,b){g.lastIndex=0;if(b||!g.test(a)){var d=b?c.sub(a,[b,m]):a,e=c.isArray(d),f=(e?d[1]:d).match(/^(?:(.*?)\s)?([\w\.\:>]+)$/);
43
+ return{processor:j[f[2]]||p,parts:f,delegate:e?d[0]:k}}},processors:{},defaults:{}},{setup:function(a,b){var e=this.constructor,f=e.pluginName||e._fullName;this.element=c.$(a);f&&"can_control"!==f&&this.element.addClass(f);(f=c.data(this.element,"controls"))||c.data(this.element,"controls",f=[]);f.push(this);this.options=d({},e.defaults,b);this.on();return[this.element,this.options]},on:function(b,d,e,f){if(!b){this.off();var b=this.constructor,d=this._bindings,e=b.actions,f=this.element,g=n(this,
44
+ "destroy"),h,p;for(h in e)e.hasOwnProperty(h)&&(p=e[h]||b._action(h,this.options),d.push(p.processor(p.delegate||f,p.parts[2],p.parts[1],h,this)));c.bind.call(f,"destroyed",g);d.push(function(a){c.unbind.call(a,"destroyed",g)});return d.length}"string"==typeof b&&(f=e,e=d,d=b,b=this.element);"string"==typeof f&&(f=n(this,f));this._bindings.push(d?i(b,c.trim(d),e,f):a(b,e,f));return this._bindings.length},off:function(){var a=this.element[0];e(this._bindings||[],function(b){b(a)});this._bindings=[]},
45
+ destroy:function(){var a=this.constructor,a=a.pluginName||a._fullName;this.off();a&&"can_control"!==a&&this.element.removeClass(a);a=c.data(this.element,"controls");a.splice(c.inArray(this,a),1);c.trigger(this,"destroyed");this.element=null}});var j=c.Control.processors;p=function(b,d,e,f,g){f=n(g,f);return e?i(b,c.trim(e),d,f):a(b,d,f)};e("change click contextmenu dblclick keydown keyup keypress mousedown mousemove mouseout mouseover mouseup reset resize scroll select submit focusin focusout mouseenter mouseleave".split(" "),
46
+ function(a){j[a]=p})})();c.Control.processors.route=function(a,b,d,e,f){c.route(d||"");var g,h=function(a){if(c.route.attr("route")===(d||"")&&(a.batchNum===k||a.batchNum!==g))if(g=a.batchNum,a=c.route.attr(),delete a.route,c.isFunction(f[e]))f[e](a);else f[f[e]](a)};c.route.bind("change",h);return function(){c.route.unbind("change",h)}};var F=c.isFunction,Ma=c.makeArray,oa=1,l=c.view=function(a,b,d,e){a=l.render(a,b,d,e);return c.isDeferred(a)?a.pipe(function(a){return l.frag(a)}):l.frag(a)};c.extend(l,
47
+ {frag:function(a,b){return l.hookup(l.fragment(a),b)},fragment:function(a){a=c.buildFragment(a,document.body);a.childNodes.length||a.appendChild(document.createTextNode(""));return a},toId:function(a){return c.map(a.toString().split(/\/|\./g),function(a){if(a)return a}).join("_")},hookup:function(a,b){var d=[],e,f,g,h=0;for(c.each(a.childNodes?c.makeArray(a.childNodes):a,function(a){1===a.nodeType&&(d.push(a),d.push.apply(d,c.makeArray(a.getElementsByTagName("*"))))});g=d[h++];)if(g.getAttribute&&
48
+ (e=g.getAttribute("data-view-id"))&&(f=l.hookups[e]))f(g,b,e),delete l.hookups[e],g.removeAttribute("data-view-id");return a},hookups:{},hook:function(a){l.hookups[++oa]=a;return" data-view-id='"+oa+"'"},cached:{},cache:!0,register:function(a){this.types["."+a.suffix]=a},types:{},ext:".ejs",registerScript:function(){},preload:function(){},render:function(a,b,d,e){F(d)&&(e=d,d=k);var f=Na(b);if(f.length){var g=new c.Deferred;f.push(pa(a,!0));c.when.apply(c,f).then(function(a){var f=Ma(arguments),h=
49
+ f.pop();if(c.isDeferred(b))b=qa(a);else for(var k in b)c.isDeferred(b[k])&&(b[k]=qa(f.shift()));f=h(b,d);g.resolve(f);e&&e(f)});return g}var h,f=F(e),g=pa(a,f);f?(h=g,g.then(function(a){e(a(b,d))})):g.then(function(a){h=a(b,d)});return h}});c.isDeferred=function(a){return a&&F(a.then)&&F(a.pipe)};var ra=function(a,b){if(!a.length)throw"can.view: No template or empty template:"+b;},pa=function(a,b){var d=a.match(/\.[\w\d]+$/),e,f,g,h=function(a){var a=e.renderer(g,a),b=new c.Deferred;b.resolve(a);
50
+ l.cache&&(l.cached[g]=b);return b};a.match(/^#/)&&(a=a.substr(1));if(f=document.getElementById(a))d="."+f.type.match(/\/(x\-)?(.+)/)[2];!d&&!l.cached[a]&&(a+=d=l.ext);c.isArray(d)&&(d=d[0]);g=c.view.toId(a);if(a.match(/^\/\//))var i=a.substr(2),a=!m.steal?"/"+i:steal.root.mapJoin(i);e=l.types[d];if(l.cached[g])return l.cached[g];if(f)return h(f.innerHTML);var n=new c.Deferred;c.ajax({async:b,url:a,dataType:"text",error:function(b){ra("",a);n.reject(b)},success:function(b){ra(b,a);n.resolve(e.renderer(g,
51
+ b));l.cache&&(l.cached[g]=n)}});return n},Na=function(a){var b=[];if(c.isDeferred(a))return[a];for(var d in a)c.isDeferred(a[d])&&b.push(a[d]);return b},qa=function(a){return c.isArray(a)&&"success"===a[1]?a[0]:a};m.steal&&steal.type("view js",function(a,b){var d=c.view.types["."+a.type],e=c.view.toId(a.rootSrc);a.text="steal('"+(d.plugin||"can/view/"+a.type)+"').then(function($){can.view.preload('"+e+"',"+a.text+");\n})";b()});c.extend(c.view,{register:function(a){this.types["."+a.suffix]=a;m.steal&&
52
+ steal.type(a.suffix+" view js",function(a,d){var e=c.view.types["."+a.type],f=c.view.toId(a.rootSrc+"");a.text=e.script(f,a.text);d()});c.view[a.suffix]=function(b,c){l.preload(b,a.renderer(b,c))}},registerScript:function(a,b,c){return"can.view.preload('"+b+"',"+l.types["."+a].script(b,c)+");"},preload:function(a,b){c.view.cached[a]=(new c.Deferred).resolve(function(a,c){return b.call(a,a,c)})}});var Oa=function(a,b){var d;c.Observe&&(d=c.Observe.__reading,c.Observe.__reading=function(a,b){e.push({obj:a,
53
+ attr:b})});var e=[],f=a.call(b);c.Observe&&(c.Observe.__reading=d);return{value:f,observed:e}},sa=function(a,b,d){var e={},f=!0,g={value:k,teardown:function(){for(var a in e){var b=e[a];b.observe.obj.unbind(b.observe.attr,h);delete e[a]}}},h=function(){var a=g.value,b=i();g.value=b;b!==a&&d(b,a)},i=function(){var d=Oa(a,b),g=d.observed,d=d.value;f=!f;c.each(g,function(a){e[a.obj._namespace+"|"+a.attr]?e[a.obj._namespace+"|"+a.attr].matched=f:(e[a.obj._namespace+"|"+a.attr]={matched:f,observe:a},a.obj.bind(a.attr,
54
+ h))});for(var i in e)g=e[i],g.matched!==f&&(g.observe.obj.unbind(g.observe.attr,h),delete e[i]);return d};g.value=i();g.isListening=!c.isEmptyObject(e);return g};c.compute=function(a,b){if(a.isComputed)return a;var d,e=0,f,g=!0;"function"===typeof a?f=function(c){return c===k?d?d.value:a.call(b||this):a.apply(b||this,arguments)}:(f=function(b){if(b===k)return a;var d=a;a=b;d!==b&&c.trigger(f,"change",[b,d]);return b},g=!1);f.isComputed=!0;f.bind=function(h,i){c.addEvent.apply(f,arguments);e===0&&
55
+ g&&(d=sa(a,b||this,function(a,b){c.trigger(f,"change",[a,b])}));e++};f.unbind=function(a,b){c.removeEvent.apply(f,arguments);e--;e===0&&g&&d.teardown()};return f};c.compute.binder=sa;var Pa=function(a){eval(a)},u=c.extend,ta=/\s*\(([\$\w]+)\)\s*->([^\n]*)/,ua=/([^\s]+)=$/,Qa=/(\r|\n)+/g,Ra=/__!!__/g,Sa={"":"span",table:"tr",tr:"td",ol:"li",ul:"li",tbody:"tr",thead:"tr",tfoot:"tr"},D={"class":"className"},va=c.each(["checked","disabled","readonly","required"],function(a){D[a]=a}),Q=function(a,b,d){D[b]?
56
+ a[D[b]]=-1<c.inArray(b,va)?!0:d:a.setAttribute(b,d)},Ta=function(a){return"string"==typeof a||"number"==typeof a?c.esc(a):R(a)},R=function(a){if("string"==typeof a)return a;if(!a&&0!=a)return"";var b=a.hookup&&function(b,c){a.hookup.call(a,b,c)}||"function"==typeof a&&a;return b?(A.push(b),""):""+a},o=function(a){if(this.constructor!=o){var b=new o(a);return function(a,c){return b.render(a,c)}}"function"==typeof a?this.template={fn:a}:(u(this,a),this.template=Ua(this.text,this.name))};c.EJS=o;o.prototype.render=
57
+ function(a,b){a=a||{};return this.template.fn.call(a,a,new o.Helpers(a,b||{}))};u(o,{txt:function(a,b,d,e,f){var g=c.compute.binder(f,e,function(a,b){p(a,b)});if(!g.isListening)return(a||0!==d?Ta:R)(g.value);var h,i=function(a){c.bind.call(a,"destroyed",g.teardown);h=a},j=function(a){a||(g.teardown(),c.unbind.call(h,"destroyed",g.teardown))},b=Sa[b]||"span",p;if(0==d)return"<"+b+c.view.hook(a?function(a,b){p=function(a){d.nodeValue=""+a;j(d.parentNode)};var c=b&&11===a.parentNode.nodeType?b:a.parentNode,
58
+ d=document.createTextNode(g.value);c.insertBefore(d,a);c.removeChild(a);i(c)}:function(a,b){p=function(a){e[0].parentNode&&(e=d(a,e));j(e[0].parentNode)};var b=b&&11===a.parentNode.nodeType?b:a.parentNode,d=function(a,d){var e=c.view.frag(a,b),f=c.map(e.childNodes,function(a){return a}),g=d[d.length-1];g.nextSibling?g.parentNode.insertBefore(e,g.nextSibling):g.parentNode.appendChild(e);c.remove(c.$(d));return f},e=d(g.value,[a]);i(b)})+"></"+b+">";if(1===d){var l=g.value.replace(/['"]/g,"").split("=")[0];
59
+ A.push(function(a){p=function(b){var b=(b||"").replace(/['"]/g,"").split("="),d=b[0];if(d!=l&&l){var e=l;-1<c.inArray(e,va)?a[e]=!1:a.removeAttribute(e)}d&&(Q(a,d,b[1]),l=d)};i(a)});return g.value}A.push(function(a){p=function(){Q(a,d,h.render())};var b=c.$(a),e;(e=c.data(b,"hooks"))||c.data(b,"hooks",e={});var f=D[d]?a[D[d]]:a.getAttribute(d),b=f.split("__!!__"),h;e[d]?e[d].bindings.push(g):e[d]={render:function(){var a=0;return f.replace(Ra,function(){return R(h.bindings[a++].value)})},bindings:[g],
60
+ batchNum:k};h=e[d];b.splice(1,0,g.value);Q(a,d,b.join(""));i(a)});return"__!!__"},pending:function(){if(A.length){var a=A.slice(0);A=[];return c.view.hook(function(b){c.each(a,function(a){a(b)})})}return""}});var Va=RegExp("(<%%|%%>|<%==|<%=|<%#|<%|%>|<|>|\"|')","g"),B=null,G=t=null,A=[],Ua=function(a,b){var c=[],e=0,a=a.replace(Qa,"\n");a.replace(Va,function(b,f,g){g>e&&c.push(a.substring(e,g));c.push(f);e=g+f.length});e<a.length&&c.push(a.substr(e));var f="",g=["var ___v1ew = [];"],h=function(a,
61
+ b){g.push("___v1ew.push(",'"',a.split("\\").join("\\\\").split("\n").join("\\n").split('"').join('\\"').split("\t").join("\\t"),'"'+(b||"")+");")},i=[],j,l=null,q=!1,m="",o=[],r=0,s;for(B=t=G=null;(s=c[r++])!==k;){if(null===l)switch(s){case "<%":case "<%=":case "<%==":q=1;case "<%#":l=s;f.length&&h(f);f="";break;case "<%%":f+="<%";break;case "<":0!==c[r].indexOf("!--")&&(B=1,q=0);f+=s;break;case ">":B=0;q?(h(f,',can.EJS.pending(),">"'),f=""):f+=s;"/"==j.substr(-1)&&(o.pop(),m=o[o.length-1]);break;
62
+ case "'":case '"':B&&(t&&t===s?t=null:null===t&&(t=s,G=j));default:"<"===j&&(m=s.split(" ")[0],0===m.indexOf("/")&&o.pop()===m.substr(1)?m=o[o.length-1]||m.substr(1):o.push(m)),f+=s}else switch(s){case "%>":switch(l){case "<%":j=--f.split("{").length- --f.split("}").length;1==j?(g.push("___v1ew.push(","can.EJS.txt(0,'"+m+"',"+(t?"'"+G.match(ua)[1]+"'":B?1:0)+",this,function(){","var ___v1ew = [];",f),i.push({before:"",after:"return ___v1ew.join('')}));\n"})):(e=i.length&&-1==j?i.pop():{after:";"},
63
+ e.before&&g.push(e.before),g.push(f,";",e.after));break;case "<%=":case "<%==":(j=--f.split("{").length- --f.split("}").length)&&i.push({before:"return ___v1ew.join('')",after:"}));"}),ta.test(f)&&(f=f.match(ta),f="function(__){var "+f[1]+"=can.$(__);"+f[2]+"}"),g.push("___v1ew.push(","can.EJS.txt("+("<%="===l?1:0)+",'"+m+"',"+(t?"'"+G.match(ua)[1]+"'":B?1:0)+",this,function(){ return ",f,j?"var ___v1ew = [];":"}));")}l=null;f="";break;case "<%%":f+="<%";break;default:f+=s}j=s}f.length&&h(f);g.push(";");
64
+ h={out:"with(_VIEW) { with (_CONTEXT) {"+g.join("")+" return ___v1ew.join('')}}"};Pa.call(h,"this.fn = (function(_CONTEXT,_VIEW){"+h.out+"});\r\n//@ sourceURL="+b+".js");return h};o.Helpers=function(a,b){this._data=a;this._extras=b;u(this,b)};o.Helpers.prototype={list:function(a,b){c.each(a,function(c,e){b(c,e,a)})}};c.view.register({suffix:"ejs",script:function(a,b){return"can.EJS(function(_CONTEXT,_VIEW) { "+(new o({text:b,name:a})).template.out+" })"},renderer:function(a,b){return o({text:b,name:a})}});
65
+ "function"===typeof define&&define.amd?define("can",[],function(){return c}):m.can=c},"0.0.1",{requires:["node","io-base","querystring","event-focus","array-extras"],optional:["selector-css2","selector-css3"]})})(can={},this);
@@ -0,0 +1,3426 @@
1
+ (function(can, window, undefined){
2
+ // data.js
3
+ // ---------
4
+ // _jQuery-like data methods._
5
+ var data = {}, dataAttr = $.fn.data,
6
+ uuid = $.uuid = +new Date(),
7
+ exp = $.expando = 'Zepto' + uuid;
8
+
9
+ function getData(node, name) {
10
+ var id = node[exp], store = id && data[id];
11
+ return name === undefined ? store || setData(node) :
12
+ (store && store[name]) || dataAttr.call($(node), name);
13
+ }
14
+
15
+ function setData(node, name, value) {
16
+ var id = node[exp] || (node[exp] = ++uuid),
17
+ store = data[id] || (data[id] = {});
18
+ if (name !== undefined) store[name] = value;
19
+ return store;
20
+ };
21
+
22
+ $.fn.data = function(name, value) {
23
+ return value === undefined ?
24
+ this.length == 0 ? undefined : getData(this[0], name) :
25
+ this.each(function(idx){
26
+ setData(this, name, $.isFunction(value) ?
27
+ value.call(this, idx, getData(this, name)) : value);
28
+ });
29
+ };
30
+ $.cleanData = function(elems){
31
+ for ( var i = 0, elem;
32
+ (elem = elems[i]) !== undefined; i++ ) {
33
+ can.trigger(elem,"destroyed",[],false)
34
+ var id = elem[exp]
35
+ delete data[id];
36
+ }
37
+ }
38
+ ;
39
+
40
+ // event.js
41
+ // ---------
42
+ // _Basic event wrapper._
43
+ can.addEvent = function(event, fn){
44
+ if(!this.__bindEvents){
45
+ this.__bindEvents = {};
46
+ }
47
+ var eventName = event.split(".")[0];
48
+
49
+ if(!this.__bindEvents[eventName]){
50
+ this.__bindEvents[eventName] = [];
51
+ }
52
+ this.__bindEvents[eventName].push({
53
+ handler: fn,
54
+ name: event
55
+ });
56
+ return this;
57
+ };
58
+ can.removeEvent = function(event, fn){
59
+ if(!this.__bindEvents){
60
+ return;
61
+ }
62
+ var i =0,
63
+ events = this.__bindEvents[event.split(".")[0]],
64
+ ev;
65
+ while(i < events.length){
66
+ ev = events[i]
67
+ if((fn && ev.handler === fn) || (!fn && ev.name === event)){
68
+ events.splice(i, 1);
69
+ } else {
70
+ i++;
71
+ }
72
+ }
73
+ return this;
74
+ };
75
+ can.dispatch = function(event){
76
+ if(!this.__bindEvents){
77
+ return;
78
+ }
79
+
80
+ var eventName = event.type.split(".")[0],
81
+ handlers = (this.__bindEvents[eventName] || []).slice(0),
82
+ self= this,
83
+ args = [event].concat(event.data || []);
84
+
85
+ can.each(handlers, function(ev){
86
+ event.data = args.slice(1);
87
+ ev.handler.apply(self, args);
88
+ });
89
+ }
90
+
91
+ ;
92
+
93
+ // fragment.js
94
+ // ---------
95
+ // _DOM Fragment support._
96
+
97
+ var table = document.createElement('table'),
98
+ tableRow = document.createElement('tr'),
99
+ containers = {
100
+ 'tr': document.createElement('tbody'),
101
+ 'tbody': table, 'thead': table, 'tfoot': table,
102
+ 'td': tableRow, 'th': tableRow,
103
+ '*': document.createElement('div')
104
+ },
105
+ fragmentRE = /^\s*<(\w+)[^>]*>/,
106
+ fragment = function(html, name) {
107
+ if (name === undefined) {
108
+ name = fragmentRE.test(html) && RegExp.$1;
109
+ }
110
+ if (!(name in containers)) name = '*';
111
+ var container = containers[name];
112
+ // IE's parser will strip any `<tr><td>` tags when `innerHTML`
113
+ // is called on a `tbody`. To get around this, we construct a
114
+ // valid table with a `tbody` that has the `innerHTML` we want.
115
+ // Then the container is the `firstChild` of the `tbody`.
116
+ // [source](http://www.ericvasilik.com/2006/07/code-karma.html).
117
+ if(name === "tr") {
118
+ var temp = document.createElement('div');
119
+ temp.innerHTML = "<table><tbody>" + html + "</tbody></table>";
120
+ container = temp.firstChild.firstChild;
121
+ } else {
122
+ container.innerHTML = '' + html;
123
+ }
124
+ // IE8 barfs if you pass slice a `childNodes` object, so make a copy.
125
+ var tmp = {},
126
+ children = container.childNodes;
127
+ tmp.length = children.length;
128
+ for(var i=0; i<children.length; i++){
129
+ tmp[i] = children[i];
130
+ }
131
+ return [].slice.call(tmp);
132
+ }
133
+
134
+ can.buildFragment = function(html, nodes){
135
+ var parts = fragment(html),
136
+ frag = document.createDocumentFragment();
137
+ parts.forEach(function(part){
138
+ frag.appendChild(part);
139
+ })
140
+ return frag;
141
+ };
142
+
143
+ // zepto.js
144
+ // ---------
145
+ // _Zepto node list._
146
+
147
+ // Extend what you can out of Zepto.
148
+ $.extend(can,Zepto);
149
+
150
+ var arrHas = function(obj, name){
151
+ return obj[0] && obj[0][name] || obj[name]
152
+ }
153
+
154
+ // Do what's similar for jQuery.
155
+ can.trigger = function(obj, event, args, bubble){
156
+ if(obj.trigger){
157
+ obj.trigger(event, args)
158
+ } else if(arrHas(obj, "dispatchEvent")){
159
+ if(bubble === false){
160
+ $([obj]).triggerHandler(event, args)
161
+ } else {
162
+ $([obj]).trigger(event, args)
163
+ }
164
+
165
+ } else {
166
+ if(typeof event == "string"){
167
+ event = {type: event}
168
+ }
169
+ event.target = event.target || obj;
170
+ event.data = args;
171
+ can.dispatch.call(obj, event)
172
+ }
173
+
174
+ }
175
+
176
+ can.$ = Zepto
177
+
178
+ can.bind = function( ev, cb){
179
+ // If we can bind to it...
180
+ if(this.bind){
181
+ this.bind(ev, cb)
182
+ } else if(arrHas(this, "addEventListener")){
183
+ $([this]).bind(ev, cb)
184
+ } else {
185
+ can.addEvent.call(this, ev, cb)
186
+ }
187
+ return this;
188
+ }
189
+ can.unbind = function(ev, cb){
190
+ // If we can bind to it...
191
+ if(this.unbind){
192
+ this.unbind(ev, cb)
193
+ } else if(arrHas(this, "addEventListener")){
194
+ $([this]).unbind(ev, cb)
195
+ } else {
196
+ can.removeEvent.call(this, ev, cb)
197
+ }
198
+ return this;
199
+ }
200
+ can.delegate = function(selector,ev, cb){
201
+ if(this.delegate){
202
+ this.delegate(selector, ev, cb)
203
+ } else {
204
+ $([this]).delegate(selector,ev, cb)
205
+ }
206
+ }
207
+ can.undelegate = function(selector,ev, cb){
208
+ if(this.undelegate){
209
+ this.undelegate(selector, ev, cb)
210
+ } else {
211
+ $([this]).undelegate(selector,ev, cb)
212
+ }
213
+ }
214
+
215
+ $.each(["append","filter","addClass","remove","data"], function(i,name){
216
+ can[name] = function(wrapped){
217
+ return wrapped[name].apply(wrapped, can.makeArray(arguments).slice(1))
218
+ }
219
+ })
220
+
221
+ can.makeArray = function(arr){
222
+ var ret = []
223
+ can.each(arr, function(a, i){
224
+ ret[i] = a
225
+ })
226
+ return ret;
227
+ };
228
+ can.inArray =function(item, arr){
229
+ return arr.indexOf(item)
230
+ }
231
+
232
+ can.proxy = function(f, ctx){
233
+ return function(){
234
+ return f.apply(ctx, arguments)
235
+ }
236
+ }
237
+
238
+ // Make ajax.
239
+ var XHR = $.ajaxSettings.xhr;
240
+ $.ajaxSettings.xhr = function(){
241
+ var xhr = XHR()
242
+ var open = xhr.open;
243
+ xhr.open = function(type, url, async){
244
+ open.call(this, type, url, ASYNC === undefined ? true : ASYNC)
245
+ }
246
+ return xhr;
247
+ }
248
+ var ASYNC;
249
+ var AJAX = $.ajax;
250
+ var updateDeferred = function(xhr, d){
251
+ for(var prop in xhr){
252
+ if(typeof d[prop] == 'function'){
253
+ d[prop] = function(){
254
+ xhr[prop].apply(xhr, arguments)
255
+ }
256
+ } else {
257
+ d[prop] = prop[xhr]
258
+ }
259
+ }
260
+ }
261
+ can.ajax = function(options){
262
+
263
+ var success = options.success,
264
+ error = options.error;
265
+ var d = can.Deferred();
266
+
267
+ options.success = function(){
268
+
269
+ updateDeferred(xhr, d);
270
+ d.resolve.apply(d, arguments);
271
+ success && success.apply(this,arguments);
272
+ }
273
+ options.error = function(){
274
+ updateDeferred(xhr, d);
275
+ d.reject.apply(d, arguments);
276
+ error && error.apply(this,arguments);
277
+ }
278
+ if(options.async === false){
279
+ ASYNC = false
280
+ }
281
+ var xhr = AJAX(options);
282
+ ASYNC = undefined;
283
+ updateDeferred(xhr, d);
284
+ return d;
285
+ };
286
+
287
+
288
+
289
+
290
+
291
+
292
+ // Make destroyed and empty work.
293
+ $.fn.empty = function(){
294
+ return this.each(function(){
295
+ $.cleanData(this.getElementsByTagName('*'))
296
+ this.innerHTML = ''
297
+ })
298
+ }
299
+
300
+ $.fn.remove= function () {
301
+ $.cleanData(this);
302
+ this.each(function () {
303
+ if (this.parentNode != null) {
304
+ // might be a text node
305
+ this.getElementsByTagName && $.cleanData(this.getElementsByTagName('*'))
306
+ this.parentNode.removeChild(this);
307
+ }
308
+ });
309
+ return this;
310
+ }
311
+
312
+
313
+ can.trim = function(str){
314
+ return str.trim();
315
+ }
316
+ can.isEmptyObject = function(object){
317
+ var name;
318
+ for(name in object){};
319
+ return name === undefined;
320
+ }
321
+
322
+ // Make extend handle `true` for deep.
323
+ can.extend = function(first){
324
+ if(first === true){
325
+ var args = can.makeArray(arguments);
326
+ args.shift();
327
+ return $.extend.apply($, args)
328
+ }
329
+ return $.extend.apply($, arguments)
330
+ }
331
+
332
+ can.get = function(wrapped, index){
333
+ return wrapped[index];
334
+ }
335
+
336
+
337
+ ;
338
+
339
+ // deferred.js
340
+ // ---------
341
+ // _Lightweight, jQuery style deferreds._
342
+
343
+ var Deferred = function( func ) {
344
+ if ( ! ( this instanceof Deferred ))
345
+ return new Deferred();
346
+
347
+ this._doneFuncs = [];
348
+ this._failFuncs = [];
349
+ this._resultArgs = null;
350
+ this._status = "";
351
+
352
+ // Check for option `function` -- call it with this as context and as first
353
+ // parameter, as specified in jQuery API.
354
+ func && func.call(this, this);
355
+ };
356
+ can.Deferred = Deferred;
357
+ can.when = Deferred.when = function() {
358
+ var args = can.makeArray( arguments );
359
+ if (args.length < 2) {
360
+ var obj = args[0];
361
+ if (obj && ( can.isFunction( obj.isResolved ) && can.isFunction( obj.isRejected ))) {
362
+ return obj;
363
+ } else {
364
+ return Deferred().resolve(obj);
365
+ }
366
+ } else {
367
+
368
+ var df = Deferred(),
369
+ done = 0,
370
+ // Resolve params -- params of each resolve, we need to track them down
371
+ // to be able to pass them in the correct order if the master
372
+ // needs to be resolved.
373
+ rp = [];
374
+
375
+ can.each(args, function(arg, j){
376
+ arg.done(function() {
377
+ rp[j] = (arguments.length < 2) ? arguments[0] : arguments;
378
+ if (++done == args.length) {
379
+ df.resolve.apply(df, rp);
380
+ }
381
+ }).fail(function() {
382
+ df.reject(arguments);
383
+ });
384
+ });
385
+
386
+ return df;
387
+
388
+ }
389
+ }
390
+
391
+ var resolveFunc = function(type, _status){
392
+ return function(context){
393
+ var args = this._resultArgs = (arguments.length > 1) ? arguments[1] : [];
394
+ return this.exec(context, this[type], args, _status);
395
+ }
396
+ },
397
+ doneFunc = function(type, _status){
398
+ return function(){
399
+ var self = this;
400
+ // In Safari, the properties of the `arguments` object are not enumerable,
401
+ // so we have to convert arguments to an `Array` that allows `can.each` to loop over them.
402
+ can.each(Array.prototype.slice.call(arguments), function( v, i, args ) {
403
+ if ( ! v )
404
+ return;
405
+ if ( v.constructor === Array ) {
406
+ args.callee.apply(self, v)
407
+ } else {
408
+ // Immediately call the `function` if the deferred has been resolved.
409
+ if (self._status === _status)
410
+ v.apply(self, self._resultArgs || []);
411
+
412
+ self[type].push(v);
413
+ }
414
+ });
415
+ return this;
416
+ }
417
+ };
418
+
419
+ can.extend( Deferred.prototype, {
420
+ pipe : function(done, fail){
421
+ var d = can.Deferred();
422
+ this.done(function(){
423
+ d.resolve( done.apply(this, arguments) );
424
+ });
425
+
426
+ this.fail(function(){
427
+ if(fail){
428
+ d.reject( fail.apply(this, arguments) );
429
+ } else {
430
+ d.reject.apply(d, arguments);
431
+ }
432
+ });
433
+ return d;
434
+ },
435
+ resolveWith : resolveFunc("_doneFuncs","rs"),
436
+ rejectWith : resolveFunc("_failFuncs","rj"),
437
+ done : doneFunc("_doneFuncs","rs"),
438
+ fail : doneFunc("_failFuncs","rj"),
439
+ always : function() {
440
+ var args = can.makeArray(arguments);
441
+ if (args.length && args[0])
442
+ this.done(args[0]).fail(args[0]);
443
+
444
+ return this;
445
+ },
446
+
447
+ then : function() {
448
+ var args = can.makeArray( arguments );
449
+ // Fail `function`(s)
450
+ if (args.length > 1 && args[1])
451
+ this.fail(args[1]);
452
+
453
+ // Done `function`(s)
454
+ if (args.length && args[0])
455
+ this.done(args[0]);
456
+
457
+ return this;
458
+ },
459
+
460
+ isResolved : function() {
461
+ return this._status === "rs";
462
+ },
463
+
464
+ isRejected : function() {
465
+ return this._status === "rj";
466
+ },
467
+
468
+ reject : function() {
469
+ return this.rejectWith(this, arguments);
470
+ },
471
+
472
+ resolve : function() {
473
+ return this.resolveWith(this, arguments);
474
+ },
475
+
476
+ exec : function(context, dst, args, st) {
477
+ if (this._status !== "")
478
+ return this;
479
+
480
+ this._status = st;
481
+
482
+ can.each(dst, function(d){
483
+ d.apply(context, args);
484
+ });
485
+
486
+ return this;
487
+ }
488
+ });
489
+
490
+ can.each = function (elements, callback, context) {
491
+ var i = 0,
492
+ key;
493
+ if (elements) {
494
+ if (typeof elements.length == 'number' && elements.pop) {
495
+ elements.attr && elements.attr('length');
496
+ for (var len = elements.length; i < len; i++) {
497
+ if (callback.call(context || elements[i], elements[i], i, elements) === false) {
498
+ break;
499
+ }
500
+ }
501
+ } else {
502
+ for (key in elements) {
503
+ if (callback.call(context || elements[i], elements[key], key, elements) === false) {
504
+ break;
505
+ }
506
+ }
507
+ }
508
+ }
509
+ return elements;
510
+ }
511
+ ;
512
+
513
+ // ##string.js
514
+ // _Miscellaneous string utility functions._
515
+
516
+ // Several of the methods in this plugin use code adapated from Prototype
517
+ // Prototype JavaScript framework, version 1.6.0.1.
518
+ // © 2005-2007 Sam Stephenson
519
+ var undHash = /_|-/,
520
+ colons = /==/,
521
+ words = /([A-Z]+)([A-Z][a-z])/g,
522
+ lowUp = /([a-z\d])([A-Z])/g,
523
+ dash = /([a-z\d])([A-Z])/g,
524
+ replacer = /\{([^\}]+)\}/g,
525
+ quote = /"/g,
526
+ singleQuote = /'/g,
527
+
528
+ // Returns the `prop` property from `obj`.
529
+ // If `add` is true and `prop` doesn't exist in `obj`, create it as an
530
+ // empty object.
531
+ getNext = function( obj, prop, add ) {
532
+ return prop in obj ?
533
+ obj[ prop ] :
534
+ ( add && ( obj[ prop ] = {} ));
535
+ },
536
+
537
+ // Returns `true` if the object can have properties (no `null`s).
538
+ isContainer = function( current ) {
539
+ return /^f|^o/.test( typeof current );
540
+ };
541
+
542
+ can.extend(can, {
543
+ // Escapes strings for HTML.
544
+ esc : function( content ) {
545
+ return ( "" + content )
546
+ .replace(/&/g, '&amp;')
547
+ .replace(/</g, '&lt;')
548
+ .replace(/>/g, '&gt;')
549
+ .replace(quote, '&#34;')
550
+ .replace(singleQuote, "&#39;");
551
+ },
552
+
553
+ getObject : function( name, roots, add ) {
554
+
555
+ // The parts of the name we are looking up
556
+ // `['App','Models','Recipe']`
557
+ var parts = name ? name.split('.') : [],
558
+ length = parts.length,
559
+ current,
560
+ r = 0,
561
+ ret, i;
562
+
563
+ // Make sure roots is an `array`.
564
+ roots = can.isArray(roots) ? roots : [roots || window];
565
+
566
+ if ( ! length ) {
567
+ return roots[0];
568
+ }
569
+
570
+ // For each root, mark it as current.
571
+ while( current = roots[r++] ) {
572
+
573
+ // Walk current to the 2nd to last object or until there
574
+ // is not a container.
575
+ for (i =0; i < length - 1 && isContainer( current ); i++ ) {
576
+ current = getNext( current, parts[i], add );
577
+ }
578
+
579
+ // If we can get a property from the 2nd to last object...
580
+ if( isContainer(current) ) {
581
+
582
+ // Get (and possibly set) the property.
583
+ ret = getNext(current, parts[i], add);
584
+
585
+ // If there is a value, we exit.
586
+ if ( ret !== undefined ) {
587
+ // If `add` is `false`, delete the property
588
+ if ( add === false ) {
589
+ delete current[parts[i]];
590
+ }
591
+ return ret;
592
+
593
+ }
594
+ }
595
+ }
596
+ },
597
+ // Capitalizes a string.
598
+ capitalize: function( s, cache ) {
599
+ // Used to make newId.
600
+ return s.charAt(0).toUpperCase() + s.slice(1);
601
+ },
602
+
603
+ // Underscores a string.
604
+ underscore: function( s ) {
605
+ return s
606
+ .replace(colons, '/')
607
+ .replace(words, '$1_$2')
608
+ .replace(lowUp, '$1_$2')
609
+ .replace(dash, '_')
610
+ .toLowerCase();
611
+ },
612
+ // Micro-templating.
613
+ sub: function( str, data, remove ) {
614
+
615
+ var obs = [];
616
+
617
+ obs.push( str.replace( replacer, function( whole, inside ) {
618
+
619
+ // Convert inside to type.
620
+ var ob = can.getObject( inside, data, remove === undefined? remove : !remove );
621
+
622
+ // If a container, push into objs (which will return objects found).
623
+ if ( isContainer( ob ) ) {
624
+ obs.push( ob );
625
+ return "";
626
+ } else {
627
+ return "" + ob;
628
+ }
629
+ }));
630
+
631
+ return obs.length <= 1 ? obs[0] : obs;
632
+ },
633
+
634
+ // These regex's are used throughout the rest of can, so let's make
635
+ // them available.
636
+ replacer : replacer,
637
+ undHash : undHash
638
+ });
639
+
640
+ // ## construct.js
641
+ // `can.Construct`
642
+ // _This is a modified version of
643
+ // [John Resig's class](http://ejohn.org/blog/simple-javascript-inheritance/).
644
+ // It provides class level inheritance and callbacks._
645
+
646
+ // A private flag used to initialize a new class instance without
647
+ // initializing it's bindings.
648
+ var initializing = 0;
649
+
650
+ can.Construct = function() {
651
+ if (arguments.length) {
652
+ return can.Construct.extend.apply(can.Construct, arguments);
653
+ }
654
+ };
655
+
656
+ can.extend(can.Construct, {
657
+ newInstance: function() {
658
+ // Get a raw instance object (`init` is not called).
659
+ var inst = this.instance(),
660
+ arg = arguments,
661
+ args;
662
+
663
+ // Call `setup` if there is a `setup`
664
+ if ( inst.setup ) {
665
+ args = inst.setup.apply(inst, arguments);
666
+ }
667
+
668
+ // Call `init` if there is an `init`
669
+ // If `setup` returned `args`, use those as the arguments
670
+ if ( inst.init ) {
671
+ inst.init.apply(inst, args || arguments);
672
+ }
673
+
674
+ return inst;
675
+ },
676
+ // Overwrites an object with methods. Used in the `super` plugin.
677
+ // `newProps` - New properties to add.
678
+ // `oldProps` - Where the old properties might be (used with `super`).
679
+ // `addTo` - What we are adding to.
680
+ _inherit: function( newProps, oldProps, addTo ) {
681
+ can.extend(addTo || newProps, newProps || {})
682
+ },
683
+ // used for overwriting a single property.
684
+ // this should be used for patching other objects
685
+ // the super plugin overwrites this
686
+ _overwrite : function(what, oldProps, propName, val){
687
+ what[propName] = val;
688
+ },
689
+ // Set `defaults` as the merger of the parent `defaults` and this
690
+ // object's `defaults`. If you overwrite this method, make sure to
691
+ // include option merging logic.
692
+ setup: function( base, fullName ) {
693
+ this.defaults = can.extend(true,{}, base.defaults, this.defaults);
694
+ },
695
+ // Create's a new `class` instance without initializing by setting the
696
+ // `initializing` flag.
697
+ instance: function() {
698
+
699
+ // Prevents running `init`.
700
+ initializing = 1;
701
+
702
+ var inst = new this();
703
+
704
+ // Allow running `init`.
705
+ initializing = 0;
706
+
707
+ return inst;
708
+ },
709
+ // Extends classes.
710
+ extend: function( fullName, klass, proto ) {
711
+ // Figure out what was passed and normalize it.
712
+ if ( typeof fullName != 'string' ) {
713
+ proto = klass;
714
+ klass = fullName;
715
+ fullName = null;
716
+ }
717
+
718
+ if ( ! proto ) {
719
+ proto = klass;
720
+ klass = null;
721
+ }
722
+ proto = proto || {};
723
+
724
+ var _super_class = this,
725
+ _super = this.prototype,
726
+ name, shortName, namespace, prototype;
727
+
728
+ // Instantiate a base class (but only create the instance,
729
+ // don't run the init constructor).
730
+ prototype = this.instance();
731
+
732
+ // Copy the properties over onto the new prototype.
733
+ can.Construct._inherit(proto, _super, prototype);
734
+
735
+ // The dummy class constructor.
736
+ function Constructor() {
737
+ // All construction is actually done in the init method.
738
+ if ( ! initializing ) {
739
+ return this.constructor !== Constructor && arguments.length ?
740
+ // We are being called without `new` or we are extending.
741
+ arguments.callee.extend.apply(arguments.callee, arguments) :
742
+ // We are being called with `new`.
743
+ this.constructor.newInstance.apply(this.constructor, arguments);
744
+ }
745
+ }
746
+
747
+ // Copy old stuff onto class (can probably be merged w/ inherit)
748
+ for ( name in _super_class ) {
749
+ if ( _super_class.hasOwnProperty(name) ) {
750
+ Constructor[name] = _super_class[name];
751
+ }
752
+ }
753
+
754
+ // Copy new static properties on class.
755
+ can.Construct._inherit(klass, _super_class, Constructor);
756
+
757
+ // Setup namespaces.
758
+ if ( fullName ) {
759
+
760
+ var parts = fullName.split('.'),
761
+ shortName = parts.pop(),
762
+ current = can.getObject(parts.join('.'), window, true),
763
+ namespace = current,
764
+ _fullName = can.underscore(fullName.replace(/\./g, "_")),
765
+ _shortName = can.underscore(shortName);
766
+
767
+ //@steal-remove-start
768
+ if(current[shortName]){
769
+
770
+ }
771
+ //@steal-remove-end
772
+
773
+ current[shortName] = Constructor;
774
+ }
775
+
776
+ // Set things that shouldn't be overwritten.
777
+ can.extend(Constructor, {
778
+ constructor: Constructor,
779
+ prototype: prototype,
780
+ namespace: namespace,
781
+ shortName: shortName,
782
+ _shortName : _shortName,
783
+ fullName: fullName,
784
+ _fullName: _fullName
785
+ });
786
+
787
+ // Make sure our prototype looks nice.
788
+ Constructor.prototype.constructor = Constructor;
789
+
790
+
791
+ // Call the class `setup` and `init`
792
+ var t = [_super_class].concat(can.makeArray(arguments)),
793
+ args = Constructor.setup.apply(Constructor, t );
794
+
795
+ if ( Constructor.init ) {
796
+ Constructor.init.apply(Constructor, args || t );
797
+ }
798
+
799
+ return Constructor;
800
+ //
801
+ //
802
+ }
803
+
804
+ });
805
+
806
+ // ## observe.js
807
+ // `can.Observe`
808
+ // _Provides the observable pattern for JavaScript Objects._
809
+ //
810
+ // Returns `true` if something is an object with properties of its own.
811
+ var canMakeObserve = function( obj ) {
812
+ return obj && typeof obj === 'object' && !(obj instanceof Date);
813
+ },
814
+
815
+ // Removes all listeners.
816
+ unhookup = function(items, namespace){
817
+ return can.each(items, function(item){
818
+ if(item && item.unbind){
819
+ item.unbind("change" + namespace);
820
+ }
821
+ });
822
+ },
823
+ // Listens to changes on `val` and "bubbles" the event up.
824
+ // `val` - The object to listen for changes on.
825
+ // `prop` - The property name is at on.
826
+ // `parent` - The parent object of prop.
827
+ hookupBubble = function( val, prop, parent ) {
828
+ // If it's an `array` make a list, otherwise a val.
829
+ if (val instanceof Observe){
830
+ // We have an `observe` already...
831
+ // Make sure it is not listening to this already
832
+ unhookup([val], parent._namespace);
833
+ } else if ( can.isArray(val) ) {
834
+ val = new Observe.List(val);
835
+ } else {
836
+ val = new Observe(val);
837
+ }
838
+
839
+ // Listen to all changes and `batchTrigger` upwards.
840
+ val.bind("change" + parent._namespace, function( ev, attr ) {
841
+ // `batchTrigger` the type on this...
842
+ var args = can.makeArray(arguments),
843
+ ev = args.shift();
844
+ args[0] = prop === "*" ?
845
+ parent.indexOf(val)+"." + args[0] :
846
+ prop + "." + args[0];
847
+ // track objects dispatched on this observe
848
+ ev.triggeredNS = ev.triggeredNS || {};
849
+ // if it has already been dispatched exit
850
+ if (ev.triggeredNS[parent._namespace]) {
851
+ return;
852
+ }
853
+ ev.triggeredNS[parent._namespace] = true;
854
+
855
+ can.trigger(parent, ev, args);
856
+ can.trigger(parent,args[0],args);
857
+ });
858
+
859
+ return val;
860
+ },
861
+
862
+ // An `id` to track events for a given observe.
863
+ observeId = 0,
864
+ // A reference to an `array` of events that will be dispatched.
865
+ collecting = undefined,
866
+ // Call to start collecting events (`Observe` sends all events at
867
+ // once).
868
+ collect = function() {
869
+ if (!collecting ) {
870
+ collecting = [];
871
+ return true;
872
+ }
873
+ },
874
+ // Creates an event on item, but will not send immediately
875
+ // if collecting events.
876
+ // `item` - The item the event should happen on.
877
+ // `event` - The event name, ex: `change`.
878
+ // `args` - Tn array of arguments.
879
+ batchTrigger = function( item, event, args ) {
880
+ // Don't send events if initalizing.
881
+ if ( ! item._init) {
882
+ if (!collecting ) {
883
+ return can.trigger(item, event, args);
884
+ } else {
885
+ collecting.push([
886
+ item,
887
+ {
888
+ type: event,
889
+ batchNum : batchNum
890
+ },
891
+ args ] );
892
+ }
893
+ }
894
+ },
895
+ // Which batch of events this is for -- might not want to send multiple
896
+ // messages on the same batch. This is mostly for event delegation.
897
+ batchNum = 1,
898
+ // Sends all pending events.
899
+ sendCollection = function() {
900
+ var items = collecting.slice(0);
901
+ collecting = undefined;
902
+ batchNum++;
903
+ can.each(items, function( item ) {
904
+ can.trigger.apply(can, item)
905
+ })
906
+
907
+ },
908
+ // A helper used to serialize an `Observe` or `Observe.List`.
909
+ // `observe` - The observable.
910
+ // `how` - To serialize with `attr` or `serialize`.
911
+ // `where` - To put properties, in an `{}` or `[]`.
912
+ serialize = function( observe, how, where ) {
913
+ // Go through each property.
914
+ observe.each(function( val, name ) {
915
+ // If the value is an `object`, and has an `attrs` or `serialize` function.
916
+ where[name] = canMakeObserve(val) && can.isFunction( val[how] ) ?
917
+ // Call `attrs` or `serialize` to get the original data back.
918
+ val[how]() :
919
+ // Otherwise return the value.
920
+ val
921
+ })
922
+ return where;
923
+ },
924
+ $method = function( name ) {
925
+ return function() {
926
+ return can[name].apply(this, arguments );
927
+ }
928
+ },
929
+ bind = $method('addEvent'),
930
+ unbind = $method('removeEvent'),
931
+ attrParts = function(attr){
932
+ return can.isArray(attr) ? attr : (""+attr).split(".")
933
+ };
934
+ var Observe = can.Construct('can.Observe', {
935
+ // keep so it can be overwritten
936
+ setup : function(){
937
+ can.Construct.setup.apply(this, arguments)
938
+ },
939
+ bind : bind,
940
+ unbind: unbind,
941
+ id: "id"
942
+ },
943
+ {
944
+ setup: function( obj ) {
945
+ // `_data` is where we keep the properties.
946
+ this._data = {};
947
+ // The namespace this `object` uses to listen to events.
948
+ this._namespace = ".observe" + (++observeId);
949
+ // Sets all `attrs`.
950
+ this._init = 1;
951
+ this.attr(obj);
952
+ delete this._init;
953
+ },
954
+ attr: function( attr, val ) {
955
+ // This is super obfuscated for space -- basically, we're checking
956
+ // if the type of the attribute is not a `number` or a `string`.
957
+ if ( !~ "ns".indexOf((typeof attr).charAt(0))) {
958
+ return this._attrs(attr, val)
959
+ } else if ( val === undefined ) {// If we are getting a value.
960
+ // Let people know we are reading.
961
+ Observe.__reading && Observe.__reading(this, attr)
962
+ return this._get(attr)
963
+ } else {
964
+ // Otherwise we are setting.
965
+ this._set(attr, val);
966
+ return this;
967
+ }
968
+ },
969
+ each: function() {
970
+ return can.each.apply(undefined, [this.__get()].concat(can.makeArray(arguments)))
971
+ },
972
+ removeAttr: function( attr ) {
973
+ // Convert the `attr` into parts (if nested).
974
+ var parts = attrParts(attr),
975
+ // The actual property to remove.
976
+ prop = parts.shift(),
977
+ // The current value.
978
+ current = this._data[prop];
979
+
980
+ // If we have more parts, call `removeAttr` on that part.
981
+ if ( parts.length ) {
982
+ return current.removeAttr(parts)
983
+ } else {
984
+ // Otherwise, `delete`.
985
+ delete this._data[prop];
986
+ // Create the event.
987
+ if (!(prop in this.constructor.prototype)) {
988
+ delete this[prop]
989
+ }
990
+ batchTrigger(this, "change", [prop, "remove", undefined, current]);
991
+ batchTrigger(this, prop, [undefined, current]);
992
+ return current;
993
+ }
994
+ },
995
+ // Reads a property from the `object`.
996
+ _get: function( attr ) {
997
+ var parts = attrParts(attr),
998
+ current = this.__get(parts.shift());
999
+ return parts.length ? current ? current._get(parts) : undefined : current;
1000
+ },
1001
+ // Reads a property directly if an `attr` is provided, otherwise
1002
+ // returns the "real" data object itself.
1003
+ __get: function( attr ) {
1004
+ return attr ? this._data[attr] : this._data;
1005
+ },
1006
+ // Sets `attr` prop as value on this object where.
1007
+ // `attr` - Is a string of properties or an array of property values.
1008
+ // `value` - The raw value to set.
1009
+ _set: function( attr, value ) {
1010
+ // Convert `attr` to attr parts (if it isn't already).
1011
+ var parts = attrParts(attr),
1012
+ // The immediate prop we are setting.
1013
+ prop = parts.shift(),
1014
+ // The current value.
1015
+ current = this.__get(prop);
1016
+
1017
+ // If we have an `object` and remaining parts.
1018
+ if ( canMakeObserve(current) && parts.length ) {
1019
+ // That `object` should set it (this might need to call attr).
1020
+ current._set(parts, value)
1021
+ } else if (!parts.length ) {
1022
+ // We're in "real" set territory.
1023
+ if(this.__convert){
1024
+ value = this.__convert(prop, value)
1025
+ }
1026
+ this.__set(prop, value, current)
1027
+
1028
+ } else {
1029
+ throw "can.Observe: Object does not exist"
1030
+ }
1031
+ },
1032
+ __set : function(prop, value, current){
1033
+
1034
+ // Otherwise, we are setting it on this `object`.
1035
+ // TODO: Check if value is object and transform
1036
+ // are we changing the value.
1037
+ if ( value !== current ) {
1038
+
1039
+ // Check if we are adding this for the first time --
1040
+ // if we are, we need to create an `add` event.
1041
+ var changeType = this.__get().hasOwnProperty(prop) ? "set" : "add";
1042
+
1043
+ // Set the value on data.
1044
+ this.___set(prop,
1045
+
1046
+ // If we are getting an object.
1047
+ canMakeObserve(value) ?
1048
+
1049
+ // Hook it up to send event.
1050
+ hookupBubble(value, prop, this) :
1051
+ // Value is normal.
1052
+ value);
1053
+
1054
+ // `batchTrigger` the change event.
1055
+ batchTrigger(this, "change", [prop, changeType, value, current]);
1056
+ batchTrigger(this, prop, [value, current]);
1057
+ // If we can stop listening to our old value, do it.
1058
+ current && unhookup([current], this._namespace);
1059
+ }
1060
+
1061
+ },
1062
+ // Directly sets a property on this `object`.
1063
+ ___set: function( prop, val ) {
1064
+ this._data[prop] = val;
1065
+ // Add property directly for easy writing.
1066
+ // Check if its on the `prototype` so we don't overwrite methods like `attrs`.
1067
+ if (!(prop in this.constructor.prototype)) {
1068
+ this[prop] = val
1069
+ }
1070
+ },
1071
+ bind: bind,
1072
+ unbind: unbind,
1073
+ serialize: function() {
1074
+ return serialize(this, 'serialize', {});
1075
+ },
1076
+ _attrs: function( props, remove ) {
1077
+ if ( props === undefined ) {
1078
+ return serialize(this, 'attr', {})
1079
+ }
1080
+
1081
+ props = can.extend(true, {}, props);
1082
+ var prop,
1083
+ collectingStarted = collect(),
1084
+ self = this,
1085
+ newVal;
1086
+
1087
+ this.each(function(curVal, prop){
1088
+ newVal = props[prop];
1089
+
1090
+ // If we are merging...
1091
+ if ( newVal === undefined ) {
1092
+ remove && self.removeAttr(prop);
1093
+ return;
1094
+ }
1095
+ if ( canMakeObserve(curVal) && canMakeObserve(newVal) ) {
1096
+ curVal.attr(newVal, remove)
1097
+ } else if ( curVal != newVal ) {
1098
+ self._set(prop, newVal)
1099
+ } else {
1100
+
1101
+ }
1102
+ delete props[prop];
1103
+ })
1104
+ // Add remaining props.
1105
+ for ( var prop in props ) {
1106
+ newVal = props[prop];
1107
+ this._set(prop, newVal)
1108
+ }
1109
+ if ( collectingStarted ) {
1110
+ sendCollection();
1111
+ }
1112
+ return this;
1113
+ }
1114
+ });
1115
+ // Helpers for `observable` lists.
1116
+ var splice = [].splice,
1117
+ list = Observe('can.Observe.List',
1118
+ {
1119
+ setup: function( instances, options ) {
1120
+ this.length = 0;
1121
+ this._namespace = ".observe" + (++observeId);
1122
+ this._init = 1;
1123
+ this.bind('change',can.proxy(this._changes,this));
1124
+ this.push.apply(this, can.makeArray(instances || []));
1125
+ can.extend(this, options);
1126
+ delete this._init;
1127
+ },
1128
+ _changes : function(ev, attr, how, newVal, oldVal){
1129
+ // `batchTrigger` direct add and remove events...
1130
+ if ( !~ attr.indexOf('.')){
1131
+
1132
+ if( how === 'add' ) {
1133
+ batchTrigger(this, how, [newVal,+attr]);
1134
+ batchTrigger(this,'length',[this.length]);
1135
+ } else if( how === 'remove' ) {
1136
+ batchTrigger(this, how, [oldVal, +attr]);
1137
+ batchTrigger(this,'length',[this.length]);
1138
+ } else {
1139
+ batchTrigger(this,how,[newVal, +attr])
1140
+ }
1141
+
1142
+ }
1143
+ },
1144
+ __get : function(attr){
1145
+ return attr ? this[attr] : this;
1146
+ },
1147
+ ___set : function(attr, val){
1148
+ this[attr] = val;
1149
+ if(+attr >= this.length){
1150
+ this.length = (+attr+1)
1151
+ }
1152
+ },
1153
+ // Returns the serialized form of this list.
1154
+ serialize: function() {
1155
+ return serialize(this, 'serialize', []);
1156
+ },
1157
+ //
1158
+ splice: function( index, howMany ) {
1159
+ var args = can.makeArray(arguments),
1160
+ i;
1161
+
1162
+ for ( i = 2; i < args.length; i++ ) {
1163
+ var val = args[i];
1164
+ if ( canMakeObserve(val) ) {
1165
+ args[i] = hookupBubble(val, "*", this)
1166
+ }
1167
+ }
1168
+ if ( howMany === undefined ) {
1169
+ howMany = args[1] = this.length - index;
1170
+ }
1171
+ var removed = splice.apply(this, args);
1172
+ if ( howMany > 0 ) {
1173
+ batchTrigger(this, "change", [""+index, "remove", undefined, removed]);
1174
+ unhookup(removed, this._namespace);
1175
+ }
1176
+ if ( args.length > 2 ) {
1177
+ batchTrigger(this, "change", [""+index, "add", args.slice(2), removed]);
1178
+ }
1179
+ return removed;
1180
+ },
1181
+ _attrs: function( props, remove ) {
1182
+ if ( props === undefined ) {
1183
+ return serialize(this, 'attr', []);
1184
+ }
1185
+
1186
+ // Create a copy.
1187
+ props = props.slice(0);
1188
+
1189
+ var len = Math.min(props.length, this.length),
1190
+ collectingStarted = collect(),
1191
+ prop;
1192
+
1193
+ for ( var prop = 0; prop < len; prop++ ) {
1194
+ var curVal = this[prop],
1195
+ newVal = props[prop];
1196
+
1197
+ if ( canMakeObserve(curVal) && canMakeObserve(newVal) ) {
1198
+ curVal.attr(newVal, remove)
1199
+ } else if ( curVal != newVal ) {
1200
+ this._set(prop, newVal)
1201
+ } else {
1202
+
1203
+ }
1204
+ }
1205
+ if ( props.length > this.length ) {
1206
+ // Add in the remaining props.
1207
+ this.push(props.slice(this.length))
1208
+ } else if ( props.length < this.length && remove ) {
1209
+ this.splice(props.length)
1210
+ }
1211
+
1212
+ if ( collectingStarted ) {
1213
+ sendCollection()
1214
+ }
1215
+ }
1216
+ }),
1217
+
1218
+ // Converts to an `array` of arguments.
1219
+ getArgs = function( args ) {
1220
+ return args[0] && can.isArray(args[0]) ?
1221
+ args[0] :
1222
+ can.makeArray(args);
1223
+ };
1224
+ // Create `push`, `pop`, `shift`, and `unshift`
1225
+ can.each({
1226
+ push: "length",
1227
+ unshift: 0
1228
+ },
1229
+ // Adds a method
1230
+ // `name` - The method name.
1231
+ // `where` - Where items in the `array` should be added.
1232
+ function( where, name ) {
1233
+ list.prototype[name] = function() {
1234
+ // Get the items being added.
1235
+ var args = getArgs(arguments),
1236
+ // Where we are going to add items.
1237
+ len = where ? this.length : 0;
1238
+
1239
+ // Go through and convert anything to an `observe` that needs to be converted.
1240
+ for ( var i = 0; i < args.length; i++ ) {
1241
+ var val = args[i];
1242
+ if ( canMakeObserve(val) ) {
1243
+ args[i] = hookupBubble(val, "*", this)
1244
+ }
1245
+ }
1246
+
1247
+ // Call the original method.
1248
+ var res = [][name].apply(this, args);
1249
+
1250
+ if ( !this.comparator || !args.length ) {
1251
+ batchTrigger(this, "change", [""+len, "add", args, undefined])
1252
+ }
1253
+
1254
+ return res;
1255
+ }
1256
+ });
1257
+
1258
+ can.each({
1259
+ pop: "length",
1260
+ shift: 0
1261
+ },
1262
+ // Creates a `remove` type method
1263
+ function( where, name ) {
1264
+ list.prototype[name] = function() {
1265
+
1266
+ var args = getArgs(arguments),
1267
+ len = where && this.length ? this.length - 1 : 0;
1268
+
1269
+ var res = [][name].apply(this, args)
1270
+
1271
+ // Create a change where the args are
1272
+ // `*` - Change on potentially multiple properties.
1273
+ // `remove` - Items removed.
1274
+ // `undefined` - The new values (there are none).
1275
+ // `res` - The old, removed values (should these be unbound).
1276
+ // `len` - Where these items were removed.
1277
+ batchTrigger(this, "change", [""+len, "remove", undefined, [res]])
1278
+
1279
+ if ( res && res.unbind ) {
1280
+ res.unbind("change" + this._namespace)
1281
+ }
1282
+ return res;
1283
+ }
1284
+ });
1285
+
1286
+ list.prototype.
1287
+ indexOf = [].indexOf || function(item){
1288
+ return can.inArray(item, this)
1289
+ };
1290
+
1291
+
1292
+ // ## model.js
1293
+ // `can.Model`
1294
+ // _A `can.Observe` that connects to a RESTful interface._
1295
+ //
1296
+ // Generic deferred piping function
1297
+ var pipe = function( def, model, func ) {
1298
+ var d = new can.Deferred();
1299
+ def.then(function(){
1300
+ arguments[0] = model[func](arguments[0])
1301
+ d.resolve.apply(d, arguments)
1302
+ },function(){
1303
+ d.rejectWith.apply(this,arguments)
1304
+ })
1305
+ return d;
1306
+ },
1307
+ modelNum = 0,
1308
+ ignoreHookup = /change.observe\d+/,
1309
+ getId = function( inst ) {
1310
+ return inst[inst.constructor.id]
1311
+ },
1312
+ // Ajax `options` generator function
1313
+ ajax = function( ajaxOb, data, type, dataType, success, error ) {
1314
+
1315
+
1316
+ // If we get a string, handle it.
1317
+ if ( typeof ajaxOb == "string" ) {
1318
+ // If there's a space, it's probably the type.
1319
+ var parts = ajaxOb.split(" ")
1320
+ ajaxOb = {
1321
+ url : parts.pop()
1322
+ };
1323
+ if(parts.length){
1324
+ ajaxOb.type = parts.pop();
1325
+ }
1326
+ }
1327
+
1328
+ // If we are a non-array object, copy to a new attrs.
1329
+ ajaxOb.data = typeof data == "object" && !can.isArray(data) ?
1330
+ can.extend(ajaxOb.data || {}, data) : data;
1331
+
1332
+
1333
+ // Get the url with any templated values filled out.
1334
+ ajaxOb.url = can.sub(ajaxOb.url, ajaxOb.data, true);
1335
+
1336
+ return can.ajax(can.extend({
1337
+ type: type || "post",
1338
+ dataType: dataType ||"json",
1339
+ success : success,
1340
+ error: error
1341
+ }, ajaxOb ));
1342
+ },
1343
+ makeRequest = function( self, type, success, error, method ) {
1344
+ var deferred ,
1345
+ args = [self.serialize()],
1346
+ // The model.
1347
+ model = self.constructor,
1348
+ jqXHR;
1349
+
1350
+ // `destroy` does not need data.
1351
+ if ( type == 'destroy' ) {
1352
+ args.shift();
1353
+ }
1354
+ // `update` and `destroy` need the `id`.
1355
+ if ( type !== 'create' ) {
1356
+ args.unshift(getId(self))
1357
+ }
1358
+
1359
+ jqXHR = model[type].apply(model, args);
1360
+
1361
+ deferred = jqXHR.pipe(function(data){
1362
+ self[method || type + "d"](data, jqXHR);
1363
+ return self
1364
+ })
1365
+
1366
+ // Hook up `abort`
1367
+ if(jqXHR.abort){
1368
+ deferred.abort = function(){
1369
+ jqXHR.abort();
1370
+ }
1371
+ }
1372
+
1373
+ return deferred.then(success,error);
1374
+ },
1375
+
1376
+ // This object describes how to make an ajax request for each ajax method.
1377
+ // The available properties are:
1378
+ // `url` - The default url to use as indicated as a property on the model.
1379
+ // `type` - The default http request type
1380
+ // `data` - A method that takes the `arguments` and returns `data` used for ajax.
1381
+ //
1382
+ //
1383
+ //
1384
+ ajaxMethods = {
1385
+ create : {
1386
+ url : "_shortName",
1387
+ type :"post"
1388
+ },
1389
+ update : {
1390
+ data : function(id, attrs){
1391
+ attrs = attrs || {};
1392
+ var identity = this.id;
1393
+ if ( attrs[identity] && attrs[identity] !== id ) {
1394
+ attrs["new" + can.capitalize(id)] = attrs[identity];
1395
+ delete attrs[identity];
1396
+ }
1397
+ attrs[identity] = id;
1398
+ return attrs;
1399
+ },
1400
+ type : "put"
1401
+ },
1402
+ destroy : {
1403
+ type : "delete",
1404
+ data : function(id){
1405
+ var args = {};
1406
+ args[this.id] = id;
1407
+ return args;
1408
+ }
1409
+ },
1410
+ findAll : {
1411
+ url : "_shortName"
1412
+ },
1413
+ findOne: {}
1414
+ },
1415
+ // Makes an ajax request `function` from a string.
1416
+ // `ajaxMethod` - The `ajaxMethod` object defined above.
1417
+ // `str` - The string the user provided. Ex: `findAll: "/recipes.json"`.
1418
+ ajaxMaker = function(ajaxMethod, str){
1419
+ // Return a `function` that serves as the ajax method.
1420
+ return function(data){
1421
+ // If the ajax method has it's own way of getting `data`, use that.
1422
+ data = ajaxMethod.data ?
1423
+ ajaxMethod.data.apply(this, arguments) :
1424
+ // Otherwise use the data passed in.
1425
+ data;
1426
+ // Return the ajax method with `data` and the `type` provided.
1427
+ return ajax(str || this[ajaxMethod.url || "_url"], data, ajaxMethod.type || "get")
1428
+ }
1429
+ }
1430
+
1431
+
1432
+
1433
+ can.Observe("can.Model",{
1434
+ setup : function(base){
1435
+ can.Observe.apply(this, arguments);
1436
+ if(this === can.Model){
1437
+ return;
1438
+ }
1439
+ var self = this,
1440
+ clean = can.proxy(this._clean, self);
1441
+
1442
+ can.each(ajaxMethods, function(method, name){
1443
+ if ( ! can.isFunction( self[name] )) {
1444
+ self[name] = ajaxMaker(method, self[name]);
1445
+ }
1446
+ if (self["make"+can.capitalize(name)]){
1447
+ var newMethod = self["make"+can.capitalize(name)](self[name]);
1448
+ can.Construct._overwrite(self, base, name,function(){
1449
+ this._super;
1450
+ this._reqs++;
1451
+ return newMethod.apply(this, arguments).then(clean, clean);
1452
+ })
1453
+ }
1454
+ });
1455
+
1456
+ if(!self.fullName || self.fullName == base.fullName){
1457
+ self.fullName = self._shortName = "Model"+(++modelNum);
1458
+ }
1459
+ // Ddd ajax converters.
1460
+ this.store = {};
1461
+ this._reqs = 0;
1462
+ this._url = this._shortName+"/{"+this.id+"}"
1463
+ },
1464
+ _ajax : ajaxMaker,
1465
+ _clean : function(){
1466
+ this._reqs--;
1467
+ if(!this._reqs){
1468
+ for(var id in this.store) {
1469
+ if(!this.store[id]._bindings){
1470
+ delete this.store[id];
1471
+ }
1472
+ }
1473
+ }
1474
+ },
1475
+ models: function( instancesRawData ) {
1476
+
1477
+ if ( ! instancesRawData ) {
1478
+ return;
1479
+ }
1480
+
1481
+ if ( instancesRawData instanceof this.List ) {
1482
+ return instancesRawData;
1483
+ }
1484
+
1485
+ // Get the list type.
1486
+ var self = this,
1487
+ res = new( self.List || ML),
1488
+ // Did we get an `array`?
1489
+ arr = can.isArray(instancesRawData),
1490
+
1491
+ // Did we get a model list?
1492
+ ml = (instancesRawData instanceof ML),
1493
+
1494
+ // Get the raw `array` of objects.
1495
+ raw = arr ?
1496
+
1497
+ // If an `array`, return the `array`.
1498
+ instancesRawData :
1499
+
1500
+ // Otherwise if a model list.
1501
+ (ml ?
1502
+
1503
+ // Get the raw objects from the list.
1504
+ instancesRawData.serialize() :
1505
+
1506
+ // Get the object's data.
1507
+ instancesRawData.data),
1508
+ i = 0;
1509
+
1510
+
1511
+
1512
+ can.each(raw, function( rawPart ) {
1513
+ res.push( self.model( rawPart ));
1514
+ });
1515
+
1516
+ if ( ! arr ) { // Push other stuff onto `array`.
1517
+ can.each(instancesRawData, function(val, prop){
1518
+ if ( prop !== 'data' ) {
1519
+ res[prop] = val;
1520
+ }
1521
+ })
1522
+ }
1523
+ return res;
1524
+ },
1525
+ model: function( attributes ) {
1526
+ if (!attributes ) {
1527
+ return;
1528
+ }
1529
+ if ( attributes instanceof this ) {
1530
+ attributes = attributes.serialize();
1531
+ }
1532
+ var model = this.store[attributes[this.id]] ? this.store[attributes[this.id]].attr(attributes) : new this( attributes );
1533
+ if(this._reqs){
1534
+ this.store[attributes[this.id]] = model;
1535
+ }
1536
+ return model;
1537
+ }
1538
+ },
1539
+ {
1540
+ isNew: function() {
1541
+ var id = getId(this);
1542
+ return ! ( id || id === 0 ); // If `null` or `undefined`
1543
+ },
1544
+ save: function( success, error ) {
1545
+ return makeRequest(this, this.isNew() ? 'create' : 'update', success, error);
1546
+ },
1547
+ destroy: function( success, error ) {
1548
+ return makeRequest(this, 'destroy', success, error, 'destroyed');
1549
+ },
1550
+ bind : function(eventName){
1551
+ if ( ! ignoreHookup.test( eventName )) {
1552
+ if ( ! this._bindings ) {
1553
+ this.constructor.store[getId(this)] = this;
1554
+ this._bindings = 0;
1555
+ }
1556
+ this._bindings++;
1557
+ }
1558
+
1559
+ return can.Observe.prototype.bind.apply( this, arguments );
1560
+ },
1561
+ unbind : function(eventName){
1562
+ if(!ignoreHookup.test(eventName)) {
1563
+ this._bindings--;
1564
+ if(!this._bindings){
1565
+ delete this.constructor.store[getId(this)];
1566
+ }
1567
+ }
1568
+ return can.Observe.prototype.unbind.apply(this, arguments);
1569
+ },
1570
+ // Change `id`.
1571
+ ___set: function( prop, val ) {
1572
+ can.Observe.prototype.___set.call(this,prop, val)
1573
+ // If we add an `id`, move it to the store.
1574
+ if(prop === this.constructor.id && this._bindings){
1575
+ this.constructor.store[getId(this)] = this;
1576
+ }
1577
+ }
1578
+ });
1579
+
1580
+
1581
+
1582
+
1583
+ can.each({makeFindAll : "models", makeFindOne: "model"}, function(method, name){
1584
+ can.Model[name] = function(oldFind){
1585
+ return function(params, success, error){
1586
+ return pipe( oldFind.call( this, params ),
1587
+ this,
1588
+ method ).then(success,error)
1589
+ }
1590
+ };
1591
+ });
1592
+
1593
+ can.each([
1594
+ "created",
1595
+ "updated",
1596
+ "destroyed"], function( funcName ) {
1597
+ can.Model.prototype[funcName] = function( attrs ) {
1598
+ var stub,
1599
+ constructor = this.constructor;
1600
+
1601
+ // Update attributes if attributes have been passed
1602
+ stub = attrs && typeof attrs == 'object' && this.attr(attrs.attr ? attrs.attr() : attrs);
1603
+
1604
+ // Call event on the instance
1605
+ can.trigger(this,funcName);
1606
+ can.trigger(this,"change",funcName)
1607
+
1608
+
1609
+ // Call event on the instance's Class
1610
+ can.trigger(constructor,funcName, this);
1611
+ };
1612
+ });
1613
+
1614
+ // Model lists are just like `Observe.List` except that when their items are
1615
+ // destroyed, it automatically gets removed from the list.
1616
+ var ML = can.Observe.List('can.Model.List',{
1617
+ setup : function(){
1618
+ can.Observe.List.prototype.setup.apply(this, arguments );
1619
+ // Send destroy events.
1620
+ var self = this;
1621
+ this.bind('change', function(ev, how){
1622
+ if(/\w+\.destroyed/.test(how)){
1623
+ self.splice(self.indexOf(ev.target),1);
1624
+ }
1625
+ })
1626
+ }
1627
+ })
1628
+
1629
+ ;
1630
+
1631
+
1632
+ // ## deparam.js
1633
+ // `can.deparam`
1634
+ // _Takes a string of name value pairs and returns a Object literal that represents those params._
1635
+ var digitTest = /^\d+$/,
1636
+ keyBreaker = /([^\[\]]+)|(\[\])/g,
1637
+ paramTest = /([^?#]*)(#.*)?$/,
1638
+ prep = function( str ) {
1639
+ return decodeURIComponent( str.replace(/\+/g, " ") );
1640
+ }
1641
+
1642
+
1643
+ can.extend(can, {
1644
+ deparam: function(params){
1645
+
1646
+ var data = {},
1647
+ pairs, lastPart;
1648
+
1649
+ if ( params && paramTest.test( params )) {
1650
+
1651
+ pairs = params.split('&'),
1652
+
1653
+ can.each( pairs, function( pair ) {
1654
+
1655
+ var parts = pair.split('='),
1656
+ key = prep( parts.shift() ),
1657
+ value = prep( parts.join("=") );
1658
+
1659
+ current = data;
1660
+ parts = key.match(keyBreaker);
1661
+
1662
+ for ( var j = 0, l = parts.length - 1; j < l; j++ ) {
1663
+ if (!current[parts[j]] ) {
1664
+ // If what we are pointing to looks like an `array`
1665
+ current[parts[j]] = digitTest.test(parts[j+1]) || parts[j+1] == "[]" ? [] : {}
1666
+ }
1667
+ current = current[parts[j]];
1668
+ }
1669
+ lastPart = parts.pop()
1670
+ if ( lastPart == "[]" ) {
1671
+ current.push(value)
1672
+ } else {
1673
+ current[lastPart] = value;
1674
+ }
1675
+ });
1676
+ }
1677
+ return data;
1678
+ }
1679
+ });
1680
+
1681
+ // ## route.js
1682
+ // `can.route`
1683
+ // _Helps manage browser history (and client state) by synchronizing the
1684
+ // `window.location.hash` with a `can.Observe`._
1685
+ //
1686
+ // Helper methods used for matching routes.
1687
+ var
1688
+ // `RegExp` used to match route variables of the type ':name'.
1689
+ // Any word character or a period is matched.
1690
+ matcher = /\:([\w\.]+)/g,
1691
+ // Regular expression for identifying &amp;key=value lists.
1692
+ paramsMatcher = /^(?:&[^=]+=[^&]*)+/,
1693
+ // Converts a JS Object into a list of parameters that can be
1694
+ // inserted into an html element tag.
1695
+ makeProps = function( props ) {
1696
+ var tags = [];
1697
+ can.each(props, function(val, name){
1698
+ tags.push( ( name === 'className' ? 'class' : name )+ '="' +
1699
+ (name === "href" ? val : can.esc(val) ) + '"');
1700
+ });
1701
+ return tags.join(" ");
1702
+ },
1703
+ // Checks if a route matches the data provided. If any route variable
1704
+ // is not present in the data, the route does not match. If all route
1705
+ // variables are present in the data, the number of matches is returned
1706
+ // to allow discerning between general and more specific routes.
1707
+ matchesData = function(route, data) {
1708
+ var count = 0, i = 0, defaults = {};
1709
+ // look at default values, if they match ...
1710
+ for( var name in route.defaults ) {
1711
+ if(route.defaults[name] === data[name]){
1712
+ // mark as matched
1713
+ defaults[name] = 1;
1714
+ count++;
1715
+ }
1716
+ }
1717
+ for (; i < route.names.length; i++ ) {
1718
+ if (!data.hasOwnProperty(route.names[i]) ) {
1719
+ return -1;
1720
+ }
1721
+ if(!defaults[route.names[i]]){
1722
+ count++;
1723
+ }
1724
+
1725
+ }
1726
+
1727
+ return count;
1728
+ },
1729
+ onready = !0,
1730
+ location = window.location,
1731
+ each = can.each,
1732
+ extend = can.extend;
1733
+
1734
+ can.route = function( url, defaults ) {
1735
+ defaults = defaults || {}
1736
+ // Extract the variable names and replace with `RegExp` that will match
1737
+ // an atual URL with values.
1738
+ var names = [],
1739
+ test = url.replace(matcher, function( whole, name, i ) {
1740
+ names.push(name);
1741
+ var next = "\\"+( url.substr(i+whole.length,1) || "&" )
1742
+ // a name without a default value HAS to have a value
1743
+ // a name that has a default value can be empty
1744
+ // The `\\` is for string-escaping giving single `\` for `RegExp` escaping.
1745
+ return "([^" +next+"]"+(defaults[name] ? "*" : "+")+")"
1746
+ });
1747
+
1748
+ // Add route in a form that can be easily figured out.
1749
+ can.route.routes[url] = {
1750
+ // A regular expression that will match the route when variable values
1751
+ // are present; i.e. for `:page/:type` the `RegExp` is `/([\w\.]*)/([\w\.]*)/` which
1752
+ // will match for any value of `:page` and `:type` (word chars or period).
1753
+ test: new RegExp("^" + test+"($|&)"),
1754
+ // The original URL, same as the index for this entry in routes.
1755
+ route: url,
1756
+ // An `array` of all the variable names in this route.
1757
+ names: names,
1758
+ // Default values provided for the variables.
1759
+ defaults: defaults,
1760
+ // The number of parts in the URL separated by `/`.
1761
+ length: url.split('/').length
1762
+ }
1763
+ return can.route;
1764
+ };
1765
+
1766
+ extend(can.route, {
1767
+ param: function( data , _setRoute ) {
1768
+ // Check if the provided data keys match the names in any routes;
1769
+ // Get the one with the most matches.
1770
+ var route,
1771
+ // Need to have at least 1 match.
1772
+ matches = 0,
1773
+ matchCount,
1774
+ routeName = data.route,
1775
+ propCount = 0;
1776
+
1777
+ delete data.route;
1778
+
1779
+ each(data, function(){propCount++});
1780
+ // Otherwise find route.
1781
+ each(can.route.routes, function(temp, name){
1782
+ // best route is the first with all defaults matching
1783
+
1784
+
1785
+ matchCount = matchesData(temp, data);
1786
+ if ( matchCount > matches ) {
1787
+ route = temp;
1788
+ matches = matchCount
1789
+ }
1790
+ if(matchCount >= propCount){
1791
+ return false;
1792
+ }
1793
+ });
1794
+ // If we have a route name in our `can.route` data, and it's
1795
+ // just as good as what currently matches, use that
1796
+ if (can.route.routes[routeName] && matchesData(can.route.routes[routeName], data ) === matches) {
1797
+ route = can.route.routes[routeName];
1798
+ }
1799
+ // If this is match...
1800
+ if ( route ) {
1801
+ var cpy = extend({}, data),
1802
+ // Create the url by replacing the var names with the provided data.
1803
+ // If the default value is found an empty string is inserted.
1804
+ res = route.route.replace(matcher, function( whole, name ) {
1805
+ delete cpy[name];
1806
+ return data[name] === route.defaults[name] ? "" : encodeURIComponent( data[name] );
1807
+ }),
1808
+ after;
1809
+ // Remove matching default values
1810
+ each(route.defaults, function(val,name){
1811
+ if(cpy[name] === val) {
1812
+ delete cpy[name]
1813
+ }
1814
+ })
1815
+
1816
+ // The remaining elements of data are added as
1817
+ // `&amp;` separated parameters to the url.
1818
+ after = can.param(cpy);
1819
+ // if we are paraming for setting the hash
1820
+ // we also want to make sure the route value is updated
1821
+ if(_setRoute){
1822
+ can.route.attr('route',route.route);
1823
+ }
1824
+ return res + (after ? "&" + after : "")
1825
+ }
1826
+ // If no route was found, there is no hash URL, only paramters.
1827
+ return can.isEmptyObject(data) ? "" : "&" + can.param(data);
1828
+ },
1829
+ deparam: function( url ) {
1830
+ // See if the url matches any routes by testing it against the `route.test` `RegExp`.
1831
+ // By comparing the URL length the most specialized route that matches is used.
1832
+ var route = {
1833
+ length: -1
1834
+ };
1835
+ each(can.route.routes, function(temp, name){
1836
+ if ( temp.test.test(url) && temp.length > route.length ) {
1837
+ route = temp;
1838
+ }
1839
+ });
1840
+ // If a route was matched.
1841
+ if ( route.length > -1 ) {
1842
+ var // Since `RegExp` backreferences are used in `route.test` (parens)
1843
+ // the parts will contain the full matched string and each variable (back-referenced) value.
1844
+ parts = url.match(route.test),
1845
+ // Start will contain the full matched string; parts contain the variable values.
1846
+ start = parts.shift(),
1847
+ // The remainder will be the `&amp;key=value` list at the end of the URL.
1848
+ remainder = url.substr(start.length - (parts[parts.length-1] === "&" ? 1 : 0) ),
1849
+ // If there is a remainder and it contains a `&amp;key=value` list deparam it.
1850
+ obj = (remainder && paramsMatcher.test(remainder)) ? can.deparam( remainder.slice(1) ) : {};
1851
+
1852
+ // Add the default values for this route.
1853
+ obj = extend(true, {}, route.defaults, obj);
1854
+ // Overwrite each of the default values in `obj` with those in
1855
+ // parts if that part is not empty.
1856
+ each(parts,function(part, i){
1857
+ if ( part && part !== '&') {
1858
+ obj[route.names[i]] = decodeURIComponent( part );
1859
+ }
1860
+ });
1861
+ obj.route = route.route;
1862
+ return obj;
1863
+ }
1864
+ // If no route was matched, it is parsed as a `&amp;key=value` list.
1865
+ if ( url.charAt(0) !== '&' ) {
1866
+ url = '&' + url;
1867
+ }
1868
+ return paramsMatcher.test(url) ? can.deparam( url.slice(1) ) : {};
1869
+ },
1870
+ data: new can.Observe({}),
1871
+ routes: {},
1872
+ ready: function(val) {
1873
+ if( val === false ) {
1874
+ onready = val;
1875
+ }
1876
+ if( val === true || onready === true ) {
1877
+ setState();
1878
+ }
1879
+ return can.route;
1880
+ },
1881
+ url: function( options, merge ) {
1882
+ if (merge) {
1883
+ options = extend({}, curParams, options)
1884
+ }
1885
+ return "#!" + can.route.param(options)
1886
+ },
1887
+ link: function( name, options, props, merge ) {
1888
+ return "<a " + makeProps(
1889
+ extend({
1890
+ href: can.route.url(options, merge)
1891
+ }, props)) + ">" + name + "</a>";
1892
+ },
1893
+ current: function( options ) {
1894
+ return location.hash == "#!" + can.route.param(options)
1895
+ }
1896
+ });
1897
+
1898
+
1899
+ // The functions in the following list applied to `can.route` (e.g. `can.route.attr('...')`) will
1900
+ // instead act on the `can.route.data` observe.
1901
+ each(['bind','unbind','delegate','undelegate','attr','removeAttr'], function(name){
1902
+ can.route[name] = function(){
1903
+ return can.route.data[name].apply(can.route.data, arguments)
1904
+ }
1905
+ })
1906
+
1907
+ var // A ~~throttled~~ debounced function called multiple times will only fire once the
1908
+ // timer runs down. Each call resets the timer.
1909
+ timer,
1910
+ // Intermediate storage for `can.route.data`.
1911
+ curParams,
1912
+ // Deparameterizes the portion of the hash of interest and assign the
1913
+ // values to the `can.route.data` removing existing values no longer in the hash.
1914
+ // setState is called typically by hashchange which fires asynchronously
1915
+ // So it's possible that someone started changing the data before the
1916
+ // hashchange event fired. For this reason, it will not set the route data
1917
+ // if the data is changing and the hash already matches the hash that was set.
1918
+ setState = function() {
1919
+ var hash = location.href.split(/#!?/)[1] || ""
1920
+ curParams = can.route.deparam( hash );
1921
+
1922
+
1923
+ // if the hash data is currently changing, and
1924
+ // the hash is what we set it to anyway, do NOT change the hash
1925
+ if(!changingData || hash !== lastHash){
1926
+ can.route.attr(curParams, true);
1927
+ }
1928
+ },
1929
+ // The last hash caused by a data change
1930
+ lastHash,
1931
+ // Are data changes pending that haven't yet updated the hash
1932
+ changingData;
1933
+
1934
+ // If the hash changes, update the `can.route.data`.
1935
+ can.bind.call(window,'hashchange', setState);
1936
+
1937
+ // If the `can.route.data` changes, update the hash.
1938
+ // Using `.serialize()` retrieves the raw data contained in the `observable`.
1939
+ // This function is ~~throttled~~ debounced so it only updates once even if multiple values changed.
1940
+ // This might be able to use batchNum and avoid this.
1941
+ can.route.bind("change", function(ev, attr) {
1942
+ // indicate that data is changing
1943
+ changingData = 1;
1944
+ clearTimeout( timer );
1945
+ timer = setTimeout(function() {
1946
+ // indicate that the hash is set to look like the data
1947
+ changingData = 0;
1948
+ var serialized = can.route.data.serialize();
1949
+ location.hash = "#!" + (lastHash = can.route.param(serialized, true))
1950
+ }, 1);
1951
+ });
1952
+ // `onready` event...
1953
+ can.bind.call(document,"ready",can.route.ready);
1954
+
1955
+ (function() {
1956
+
1957
+
1958
+ // ## control.js
1959
+ // `can.Control`
1960
+ // _Controller_
1961
+
1962
+ // Binds an element, returns a function that unbinds.
1963
+ var bind = function( el, ev, callback ) {
1964
+
1965
+ can.bind.call( el, ev, callback )
1966
+
1967
+ return function() {
1968
+ can.unbind.call(el, ev, callback);
1969
+ };
1970
+ },
1971
+ isFunction = can.isFunction,
1972
+ extend = can.extend,
1973
+ each = can.each,
1974
+ slice = [].slice,
1975
+ paramReplacer = /\{([^\}]+)\}/g,
1976
+ special = can.getObject("$.event.special") || {},
1977
+
1978
+ // Binds an element, returns a function that unbinds.
1979
+ delegate = function( el, selector, ev, callback ) {
1980
+ can.delegate.call(el, selector, ev, callback)
1981
+ return function() {
1982
+ can.undelegate.call(el, selector, ev, callback);
1983
+ };
1984
+ },
1985
+
1986
+ // Calls bind or unbind depending if there is a selector.
1987
+ binder = function( el, ev, callback, selector ) {
1988
+ return selector ?
1989
+ delegate( el, can.trim( selector ), ev, callback ) :
1990
+ bind( el, ev, callback );
1991
+ },
1992
+
1993
+ // Moves `this` to the first argument, wraps it with `jQuery` if it's an element
1994
+ shifter = function shifter(context, name) {
1995
+ var method = typeof name == "string" ? context[name] : name;
1996
+ if(!isFunction(method)){
1997
+ method = context[method];
1998
+ }
1999
+ return function() {
2000
+ context.called = name;
2001
+ return method.apply(context, [this.nodeName ? can.$(this) : this].concat( slice.call(arguments, 0)));
2002
+ };
2003
+ },
2004
+ basicProcessor;
2005
+
2006
+ can.Construct("can.Control",
2007
+ {
2008
+ // Setup pre-processes which methods are event listeners.
2009
+ setup: function() {
2010
+
2011
+ // Allow contollers to inherit "defaults" from super-classes as it
2012
+ // done in `can.Construct`
2013
+ can.Construct.setup.apply( this, arguments );
2014
+
2015
+ // If you didn't provide a name, or are `control`, don't do anything.
2016
+ if ( this !== can.Control ) {
2017
+
2018
+ // Cache the underscored names.
2019
+ var control = this,
2020
+ funcName;
2021
+
2022
+ // Calculate and cache actions.
2023
+ control.actions = {};
2024
+ for ( funcName in control.prototype ) {
2025
+ if ( control._isAction(funcName) ) {
2026
+ control.actions[funcName] = control._action(funcName);
2027
+ }
2028
+ }
2029
+ }
2030
+ },
2031
+ // Return `true` if is an action.
2032
+ _isAction: function( methodName ) {
2033
+
2034
+ var val = this.prototype[methodName],
2035
+ type = typeof val;
2036
+ // if not the constructor
2037
+ return (methodName !== 'constructor') &&
2038
+ // and is a function or links to a function
2039
+ ( type == "function" || (type == "string" && isFunction(this.prototype[val] ) ) ) &&
2040
+ // and is in special, a processor, or has a funny character
2041
+ !! ( special[methodName] || processors[methodName] || /[^\w]/.test(methodName) );
2042
+ },
2043
+ // Takes a method name and the options passed to a control
2044
+ // and tries to return the data necessary to pass to a processor
2045
+ // (something that binds things).
2046
+ _action: function( methodName, options ) {
2047
+
2048
+ // If we don't have options (a `control` instance), we'll run this
2049
+ // later.
2050
+ paramReplacer.lastIndex = 0;
2051
+ if ( options || ! paramReplacer.test( methodName )) {
2052
+ // If we have options, run sub to replace templates `{}` with a
2053
+ // value from the options or the window
2054
+ var convertedName = options ? can.sub(methodName, [options, window]) : methodName,
2055
+
2056
+ // If a `{}` resolves to an object, `convertedName` will be
2057
+ // an array
2058
+ arr = can.isArray(convertedName),
2059
+
2060
+ // Get the parts of the function
2061
+ // `[convertedName, delegatePart, eventPart]`
2062
+ // `/^(?:(.*?)\s)?([\w\.\:>]+)$/` - Breaker `RegExp`.
2063
+ parts = (arr ? convertedName[1] : convertedName).match(/^(?:(.*?)\s)?([\w\.\:>]+)$/);
2064
+
2065
+ var event = parts[2],
2066
+ processor = processors[event] || basicProcessor;
2067
+ return {
2068
+ processor: processor,
2069
+ parts: parts,
2070
+ delegate : arr ? convertedName[0] : undefined
2071
+ };
2072
+ }
2073
+ },
2074
+ // An object of `{eventName : function}` pairs that Control uses to
2075
+ // hook up events auto-magically.
2076
+ processors: {},
2077
+ // A object of name-value pairs that act as default values for a
2078
+ // control instance
2079
+ defaults: {}
2080
+ },
2081
+ {
2082
+ // Sets `this.element`, saves the control in `data, binds event
2083
+ // handlers.
2084
+ setup: function( element, options ) {
2085
+
2086
+ var cls = this.constructor,
2087
+ pluginname = cls.pluginName || cls._fullName,
2088
+ arr;
2089
+
2090
+ // Want the raw element here.
2091
+ this.element = can.$(element)
2092
+
2093
+ if ( pluginname && pluginname !== 'can_control') {
2094
+ // Set element and `className` on element.
2095
+ this.element.addClass(pluginname);
2096
+ }
2097
+
2098
+ (arr = can.data(this.element,"controls")) || can.data(this.element,"controls",arr = []);
2099
+ arr.push(this);
2100
+
2101
+ // Option merging.
2102
+ this.options = extend({}, cls.defaults, options);
2103
+
2104
+ // Bind all event handlers.
2105
+ this.on();
2106
+
2107
+ // Get's passed into `init`.
2108
+ return [this.element, this.options];
2109
+ },
2110
+ on: function( el, selector, eventName, func ) {
2111
+
2112
+ if ( ! el ) {
2113
+
2114
+ // Adds bindings.
2115
+ this.off();
2116
+
2117
+ // Go through the cached list of actions and use the processor
2118
+ // to bind
2119
+ var cls = this.constructor,
2120
+ bindings = this._bindings,
2121
+ actions = cls.actions,
2122
+ element = this.element,
2123
+ destroyCB = shifter(this,"destroy"),
2124
+ funcName, ready;
2125
+
2126
+ for ( funcName in actions ) {
2127
+ if ( actions.hasOwnProperty( funcName )) {
2128
+ ready = actions[funcName] || cls._action(funcName, this.options);
2129
+ bindings.push(
2130
+ ready.processor(ready.delegate || element,
2131
+ ready.parts[2],
2132
+ ready.parts[1],
2133
+ funcName,
2134
+ this));
2135
+ }
2136
+ }
2137
+
2138
+
2139
+ // Setup to be destroyed...
2140
+ // don't bind because we don't want to remove it.
2141
+ can.bind.call(element,"destroyed", destroyCB);
2142
+ bindings.push(function( el ) {
2143
+ can.unbind.call(el,"destroyed", destroyCB);
2144
+ });
2145
+ return bindings.length;
2146
+ }
2147
+
2148
+ if ( typeof el == 'string' ) {
2149
+ func = eventName;
2150
+ eventName = selector;
2151
+ selector = el;
2152
+ el = this.element;
2153
+ }
2154
+
2155
+ if ( typeof func == 'string' ) {
2156
+ func = shifter(this,func);
2157
+ }
2158
+
2159
+ this._bindings.push( binder( el, eventName, func, selector ));
2160
+
2161
+ return this._bindings.length;
2162
+ },
2163
+ // Unbinds all event handlers on the controller.
2164
+ off : function(){
2165
+ var el = this.element[0]
2166
+ each(this._bindings || [], function( value ) {
2167
+ value(el);
2168
+ });
2169
+ // Adds bindings.
2170
+ this._bindings = [];
2171
+ },
2172
+ // Prepares a `control` for garbage collection
2173
+ destroy: function() {
2174
+ var Class = this.constructor,
2175
+ pluginName = Class.pluginName || Class._fullName,
2176
+ controls;
2177
+
2178
+ // Unbind bindings.
2179
+ this.off();
2180
+
2181
+ if(pluginName && pluginName !== 'can_control'){
2182
+ // Remove the `className`.
2183
+ this.element.removeClass(pluginName);
2184
+ }
2185
+
2186
+ // Remove from `data`.
2187
+ controls = can.data(this.element,"controls");
2188
+ controls.splice(can.inArray(this, controls),1);
2189
+
2190
+ can.trigger( this, "destroyed"); // In case we want to know if the `control` is removed.
2191
+
2192
+ this.element = null;
2193
+ }
2194
+ });
2195
+
2196
+ var processors = can.Control.processors,
2197
+
2198
+ // Processors do the binding.
2199
+ // They return a function that unbinds when called.
2200
+ //
2201
+ // The basic processor that binds events.
2202
+ basicProcessor = function( el, event, selector, methodName, control ) {
2203
+ return binder( el, event, shifter(control, methodName), selector);
2204
+ };
2205
+
2206
+ // Set common events to be processed as a `basicProcessor`
2207
+ each(["change", "click", "contextmenu", "dblclick", "keydown", "keyup",
2208
+ "keypress", "mousedown", "mousemove", "mouseout", "mouseover",
2209
+ "mouseup", "reset", "resize", "scroll", "select", "submit", "focusin",
2210
+ "focusout", "mouseenter", "mouseleave"], function( v ) {
2211
+ processors[v] = basicProcessor;
2212
+ });
2213
+
2214
+ }());
2215
+
2216
+
2217
+ // ## control/route.js
2218
+ // _Controller route integration._
2219
+
2220
+ can.Control.processors.route = function( el, event, selector, funcName, controller ) {
2221
+ can.route( selector || "" )
2222
+ var batchNum,
2223
+ check = function( ev, attr, how ) {
2224
+ if ( can.route.attr('route') === ( selector || "" ) &&
2225
+ ( ev.batchNum === undefined || ev.batchNum !== batchNum ) ) {
2226
+
2227
+ batchNum = ev.batchNum;
2228
+
2229
+ var d = can.route.attr();
2230
+ delete d.route;
2231
+ if(can.isFunction(controller[funcName])){
2232
+ controller[funcName]( d )
2233
+ }else {
2234
+ controller[controller[funcName]](d)
2235
+ }
2236
+
2237
+ }
2238
+ }
2239
+ can.route.bind( 'change', check );
2240
+ return function() {
2241
+ can.route.unbind( 'change', check )
2242
+ }
2243
+ }
2244
+ ;
2245
+
2246
+ // ## view.js
2247
+ // `can.view`
2248
+ // _Templating abstraction._
2249
+
2250
+ var isFunction = can.isFunction,
2251
+ makeArray = can.makeArray,
2252
+ // Used for hookup `id`s.
2253
+ hookupId = 1,
2254
+ $view = can.view = function(view, data, helpers, callback){
2255
+ // Get the result.
2256
+ var result = $view.render(view, data, helpers, callback);
2257
+ if(can.isDeferred(result)){
2258
+ return result.pipe(function(result){
2259
+ return $view.frag(result);
2260
+ })
2261
+ }
2262
+
2263
+ // Convert it into a dom frag.
2264
+ return $view.frag(result);
2265
+ };
2266
+
2267
+ can.extend( $view, {
2268
+ // creates a frag and hooks it up all at once
2269
+ frag: function(result, parentNode ){
2270
+ return $view.hookup( $view.fragment(result), parentNode );
2271
+ },
2272
+ // simply creates a frag
2273
+ // this is used internally to create a frag
2274
+ // insert it
2275
+ // then hook it up
2276
+ fragment: function(result){
2277
+ var frag = can.buildFragment(result,document.body);
2278
+ // If we have an empty frag...
2279
+ if(!frag.childNodes.length) {
2280
+ frag.appendChild(document.createTextNode(''))
2281
+ }
2282
+ return frag;
2283
+ },
2284
+ // Convert a path like string into something that's ok for an `element` ID.
2285
+ toId : function( src ) {
2286
+ return can.map(src.toString().split(/\/|\./g), function( part ) {
2287
+ // Dont include empty strings in toId functions
2288
+ if ( part ) {
2289
+ return part;
2290
+ }
2291
+ }).join("_");
2292
+ },
2293
+ hookup: function(fragment, parentNode ){
2294
+ var hookupEls = [],
2295
+ id,
2296
+ func,
2297
+ el,
2298
+ i=0;
2299
+
2300
+ // Get all `childNodes`.
2301
+ can.each(fragment.childNodes ? can.makeArray(fragment.childNodes) : fragment, function(node){
2302
+ if(node.nodeType === 1){
2303
+ hookupEls.push(node)
2304
+ hookupEls.push.apply(hookupEls, can.makeArray( node.getElementsByTagName('*')))
2305
+ }
2306
+ });
2307
+ // Filter by `data-view-id` attribute.
2308
+ for (; el = hookupEls[i++]; ) {
2309
+
2310
+ if ( el.getAttribute && (id = el.getAttribute('data-view-id')) && (func = $view.hookups[id]) ) {
2311
+ func(el, parentNode, id);
2312
+ delete $view.hookups[id];
2313
+ el.removeAttribute('data-view-id');
2314
+ }
2315
+ }
2316
+ return fragment;
2317
+ },
2318
+ hookups: {},
2319
+ hook: function( cb ) {
2320
+ $view.hookups[++hookupId] = cb;
2321
+ return " data-view-id='"+hookupId+"'";
2322
+ },
2323
+ cached: {},
2324
+ cache: true,
2325
+ register: function( info ) {
2326
+ this.types["." + info.suffix] = info;
2327
+ },
2328
+ types: {},
2329
+ ext: ".ejs",
2330
+ registerScript: function() {},
2331
+ preload: function( ) {},
2332
+ render: function( view, data, helpers, callback ) {
2333
+ // If helpers is a `function`, it is actually a callback.
2334
+ if ( isFunction( helpers )) {
2335
+ callback = helpers;
2336
+ helpers = undefined;
2337
+ }
2338
+
2339
+ // See if we got passed any deferreds.
2340
+ var deferreds = getDeferreds(data);
2341
+
2342
+
2343
+ if ( deferreds.length ) { // Does data contain any deferreds?
2344
+ // The deferred that resolves into the rendered content...
2345
+ var deferred = new can.Deferred();
2346
+
2347
+ // Add the view request to the list of deferreds.
2348
+ deferreds.push(get(view, true))
2349
+
2350
+ // Wait for the view and all deferreds to finish...
2351
+ can.when.apply(can, deferreds).then(function( resolved ) {
2352
+ // Get all the resolved deferreds.
2353
+ var objs = makeArray(arguments),
2354
+ // Renderer is the last index of the data.
2355
+ renderer = objs.pop(),
2356
+ // The result of the template rendering with data.
2357
+ result;
2358
+
2359
+ // Make data look like the resolved deferreds.
2360
+ if ( can.isDeferred(data) ) {
2361
+ data = usefulPart(resolved);
2362
+ }
2363
+ else {
2364
+ // Go through each prop in data again and
2365
+ // replace the defferreds with what they resolved to.
2366
+ for ( var prop in data ) {
2367
+ if ( can.isDeferred(data[prop]) ) {
2368
+ data[prop] = usefulPart(objs.shift());
2369
+ }
2370
+ }
2371
+ }
2372
+ // Get the rendered result.
2373
+ result = renderer(data, helpers);
2374
+
2375
+ // Resolve with the rendered view.
2376
+ deferred.resolve(result);
2377
+ // If there's a `callback`, call it back with the result.
2378
+ callback && callback(result);
2379
+ });
2380
+ // Return the deferred...
2381
+ return deferred;
2382
+ }
2383
+ else {
2384
+ // No deferreds! Render this bad boy.
2385
+ var response,
2386
+ // If there's a `callback` function
2387
+ async = isFunction( callback ),
2388
+ // Get the `view` type
2389
+ deferred = get(view, async);
2390
+
2391
+ // If we are `async`...
2392
+ if ( async ) {
2393
+ // Return the deferred
2394
+ response = deferred;
2395
+ // And fire callback with the rendered result.
2396
+ deferred.then(function( renderer ) {
2397
+ callback(renderer(data, helpers))
2398
+ })
2399
+ } else {
2400
+ // Otherwise, the deferred is complete, so
2401
+ // set response to the result of the rendering.
2402
+ deferred.then(function( renderer ) {
2403
+ response = renderer(data, helpers);
2404
+ });
2405
+ }
2406
+
2407
+ return response;
2408
+ }
2409
+ }
2410
+ });
2411
+ // Returns `true` if something looks like a deferred.
2412
+ can.isDeferred = function( obj ) {
2413
+ return obj && isFunction(obj.then) && isFunction(obj.pipe) // Check if `obj` is a `can.Deferred`.
2414
+ }
2415
+ // Makes sure there's a template, if not, have `steal` provide a warning.
2416
+ var checkText = function( text, url ) {
2417
+ if ( ! text.length ) {
2418
+ //@steal-remove-start
2419
+ //@steal-remove-end
2420
+ throw "can.view: No template or empty template:" + url;
2421
+ }
2422
+ },
2423
+ // `Returns a `view` renderer deferred.
2424
+ // `url` - The url to the template.
2425
+ // `async` - If the ajax request should be asynchronous.
2426
+ // Returns a deferred.
2427
+ get = function( url, async ) {
2428
+
2429
+
2430
+ var suffix = url.match(/\.[\w\d]+$/),
2431
+ type,
2432
+ // If we are reading a script element for the content of the template,
2433
+ // `el` will be set to that script element.
2434
+ el,
2435
+ // A unique identifier for the view (used for caching).
2436
+ // This is typically derived from the element id or
2437
+ // the url for the template.
2438
+ id,
2439
+ // The ajax request used to retrieve the template content.
2440
+ jqXHR,
2441
+ // Used to generate the response.
2442
+ response = function( text ) {
2443
+ // Get the renderer function.
2444
+ var func = type.renderer(id, text),
2445
+ d = new can.Deferred();
2446
+ d.resolve(func)
2447
+ // Cache if we are caching.
2448
+ if ( $view.cache ) {
2449
+ $view.cached[id] = d;
2450
+ }
2451
+ // Return the objects for the response's `dataTypes`
2452
+ // (in this case view).
2453
+ return d;
2454
+ };
2455
+
2456
+ //If the url has a #, we assume we want to use an inline template
2457
+ //from a script element and not current page's HTML
2458
+ if( url.match(/^#/) ) {
2459
+ url = url.substr(1);
2460
+ }
2461
+ // If we have an inline template, derive the suffix from the `text/???` part.
2462
+ // This only supports `<script>` tags.
2463
+ if ( el = document.getElementById(url) ) {
2464
+ suffix = "."+el.type.match(/\/(x\-)?(.+)/)[2];
2465
+ }
2466
+
2467
+ // If there is no suffix, add one.
2468
+ if (!suffix && !$view.cached[url] ) {
2469
+ url += ( suffix = $view.ext );
2470
+ }
2471
+
2472
+ if ( can.isArray( suffix )) {
2473
+ suffix = suffix[0]
2474
+ }
2475
+
2476
+ // Convert to a unique and valid id.
2477
+ id = can.view.toId(url);
2478
+
2479
+ // If an absolute path, use `steal` to get it.
2480
+ // You should only be using `//` if you are using `steal`.
2481
+ if ( url.match(/^\/\//) ) {
2482
+ var sub = url.substr(2);
2483
+ url = ! window.steal ?
2484
+ "/" + sub :
2485
+ steal.root.mapJoin(sub);
2486
+ }
2487
+
2488
+ // Set the template engine type.
2489
+ type = $view.types[suffix];
2490
+
2491
+ // If it is cached,
2492
+ if ( $view.cached[id] ) {
2493
+ // Return the cached deferred renderer.
2494
+ return $view.cached[id];
2495
+
2496
+ // Otherwise if we are getting this from a `<script>` element.
2497
+ } else if ( el ) {
2498
+ // Resolve immediately with the element's `innerHTML`.
2499
+ return response(el.innerHTML);
2500
+ } else {
2501
+ // Make an ajax request for text.
2502
+ var d = new can.Deferred();
2503
+ can.ajax({
2504
+ async: async,
2505
+ url: url,
2506
+ dataType: "text",
2507
+ error: function(jqXHR) {
2508
+ checkText("", url);
2509
+ d.reject(jqXHR);
2510
+ },
2511
+ success: function( text ) {
2512
+ // Make sure we got some text back.
2513
+ checkText(text, url);
2514
+ d.resolve(type.renderer(id, text))
2515
+ // Cache if if we are caching.
2516
+ if ( $view.cache ) {
2517
+ $view.cached[id] = d;
2518
+ }
2519
+
2520
+ }
2521
+ });
2522
+ return d;
2523
+ }
2524
+ },
2525
+ // Gets an `array` of deferreds from an `object`.
2526
+ // This only goes one level deep.
2527
+ getDeferreds = function( data ) {
2528
+ var deferreds = [];
2529
+
2530
+ // pull out deferreds
2531
+ if ( can.isDeferred(data) ) {
2532
+ return [data]
2533
+ } else {
2534
+ for ( var prop in data ) {
2535
+ if ( can.isDeferred(data[prop]) ) {
2536
+ deferreds.push(data[prop]);
2537
+ }
2538
+ }
2539
+ }
2540
+ return deferreds;
2541
+ },
2542
+ // Gets the useful part of a resolved deferred.
2543
+ // This is for `model`s and `can.ajax` that resolve to an `array`.
2544
+ usefulPart = function( resolved ) {
2545
+ return can.isArray(resolved) && resolved[1] === 'success' ? resolved[0] : resolved
2546
+ };
2547
+
2548
+
2549
+ if ( window.steal ) {
2550
+ steal.type("view js", function( options, success, error ) {
2551
+ var type = can.view.types["." + options.type],
2552
+ id = can.view.toId(options.rootSrc);
2553
+
2554
+ options.text = "steal('" + (type.plugin || "can/view/" + options.type) + "').then(function($){" + "can.view.preload('" + id + "'," + options.text + ");\n})";
2555
+ success();
2556
+ })
2557
+ }
2558
+
2559
+ //!steal-pluginify-remove-start
2560
+ can.extend(can.view, {
2561
+ register: function( info ) {
2562
+ this.types["." + info.suffix] = info;
2563
+
2564
+ if ( window.steal ) {
2565
+ steal.type(info.suffix + " view js", function( options, success, error ) {
2566
+ var type = can.view.types["." + options.type],
2567
+ id = can.view.toId(options.rootSrc+'');
2568
+
2569
+ options.text = type.script(id, options.text)
2570
+ success();
2571
+ })
2572
+ }
2573
+ can.view[info.suffix] = function(id, text){
2574
+ $view.preload(id, info.renderer(id, text) )
2575
+ }
2576
+ },
2577
+ registerScript: function( type, id, src ) {
2578
+ return "can.view.preload('" + id + "'," + $view.types["." + type].script(id, src) + ");";
2579
+ },
2580
+ preload: function( id, renderer ) {
2581
+ can.view.cached[id] = new can.Deferred().resolve(function( data, helpers ) {
2582
+ return renderer.call(data, data, helpers);
2583
+ });
2584
+ }
2585
+
2586
+ });
2587
+ //!steal-pluginify-remove-end
2588
+
2589
+
2590
+ // returns the
2591
+ // - observes and attr methods are called by func
2592
+ // - the value returned by func
2593
+ // ex: `{value: 100, observed: [{obs: o, attr: "completed"}]}`
2594
+ var getValueAndObserved = function(func, self){
2595
+
2596
+ var oldReading;
2597
+ if (can.Observe) {
2598
+ // Set a callback on can.Observe to know
2599
+ // when an attr is read.
2600
+ // Keep a reference to the old reader
2601
+ // if there is one. This is used
2602
+ // for nested live binding.
2603
+ oldReading = can.Observe.__reading;
2604
+ can.Observe.__reading = function(obj, attr){
2605
+ // Add the observe and attr that was read
2606
+ // to `observed`
2607
+ observed.push({
2608
+ obj: obj,
2609
+ attr: attr
2610
+ });
2611
+ }
2612
+ }
2613
+
2614
+ var observed = [],
2615
+ // Call the "wrapping" function to get the value. `observed`
2616
+ // will have the observe/attribute pairs that were read.
2617
+ value = func.call(self);
2618
+
2619
+ // Set back so we are no longer reading.
2620
+ if(can.Observe){
2621
+ can.Observe.__reading = oldReading;
2622
+ }
2623
+ return {
2624
+ value : value,
2625
+ observed : observed
2626
+ }
2627
+ },
2628
+ // Calls `callback(newVal, oldVal)` everytime an observed property
2629
+ // called within `getterSetter` is changed and creates a new result of `getterSetter`.
2630
+ // Also returns an object that can teardown all event handlers.
2631
+ computeBinder = function(getterSetter, context, callback){
2632
+ // track what we are observing
2633
+ var observing = {},
2634
+ // a flag indicating if this observe/attr pair is already bound
2635
+ matched = true,
2636
+ // the data to return
2637
+ data = {
2638
+ // we will maintain the value while live-binding is taking place
2639
+ value : undefined,
2640
+ // a teardown method that stops listening
2641
+ teardown: function(){
2642
+ for ( var name in observing ) {
2643
+ var ob = observing[name];
2644
+ ob.observe.obj.unbind(ob.observe.attr, onchanged);
2645
+ delete observing[name];
2646
+ }
2647
+ }
2648
+ };
2649
+
2650
+ // when a property value is cahnged
2651
+ var onchanged = function(){
2652
+ // store the old value
2653
+ var oldValue = data.value,
2654
+ // get the new value
2655
+ newvalue = getValueAndBind();
2656
+ // update the value reference (in case someone reads)
2657
+ data.value = newvalue
2658
+ // if a change happened
2659
+ if(newvalue !== oldValue){
2660
+ callback(newvalue, oldValue);
2661
+ };
2662
+ };
2663
+
2664
+ // gets the value returned by `getterSetter` and also binds to any attributes
2665
+ // read by the call
2666
+ var getValueAndBind = function(){
2667
+ var info = getValueAndObserved( getterSetter, context ),
2668
+ newObserveSet = info.observed;
2669
+
2670
+ var value = info.value;
2671
+ matched = !matched;
2672
+
2673
+ // go through every attribute read by this observe
2674
+ can.each(newObserveSet, function(ob){
2675
+ // if the observe/attribute pair is being observed
2676
+ if(observing[ob.obj._namespace+"|"+ob.attr]){
2677
+ // mark at as observed
2678
+ observing[ob.obj._namespace+"|"+ob.attr].matched = matched;
2679
+ } else {
2680
+ // otherwise, set the observe/attribute on oldObserved, marking it as being observed
2681
+ observing[ob.obj._namespace+"|"+ob.attr] = {
2682
+ matched: matched,
2683
+ observe: ob
2684
+ };
2685
+ ob.obj.bind(ob.attr, onchanged)
2686
+ }
2687
+ });
2688
+
2689
+ // Iterate through oldObserved, looking for observe/attributes
2690
+ // that are no longer being bound and unbind them
2691
+ for ( var name in observing ) {
2692
+ var ob = observing[name];
2693
+ if(ob.matched !== matched){
2694
+ ob.observe.obj.unbind(ob.observe.attr, onchanged);
2695
+ delete observing[name];
2696
+ }
2697
+ }
2698
+ return value;
2699
+ }
2700
+ // set the initial value
2701
+ data.value = getValueAndBind();
2702
+ data.isListening = ! can.isEmptyObject(observing);
2703
+ return data;
2704
+ }
2705
+
2706
+ // if no one is listening ... we can not calculate every time
2707
+ can.compute = function(getterSetter, context){
2708
+ if(getterSetter.isComputed){
2709
+ return getterSetter;
2710
+ }
2711
+ // get the value right away
2712
+ // TODO: eventually we can defer this until a bind or a read
2713
+ var computedData,
2714
+ bindings = 0,
2715
+ computed,
2716
+ canbind = true;
2717
+ if(typeof getterSetter === "function"){
2718
+ computed = function(value){
2719
+ if(value === undefined){
2720
+ // we are reading
2721
+ if(computedData){
2722
+ return computedData.value;
2723
+ } else {
2724
+ return getterSetter.call(context || this)
2725
+ }
2726
+ } else {
2727
+ return getterSetter.apply(context || this, arguments)
2728
+ }
2729
+ }
2730
+
2731
+ } else {
2732
+ // we just gave it a value
2733
+ computed = function(val){
2734
+ if(val === undefined){
2735
+ return getterSetter;
2736
+ } else {
2737
+ var old = getterSetter;
2738
+ getterSetter = val;
2739
+ if( old !== val){
2740
+ can.trigger(computed, "change",[val, old]);
2741
+ }
2742
+
2743
+ return val;
2744
+ }
2745
+
2746
+ }
2747
+ canbind = false;
2748
+ }
2749
+ computed.isComputed = true;
2750
+
2751
+
2752
+ computed.bind = function(ev, handler){
2753
+ can.addEvent.apply(computed, arguments);
2754
+ if( bindings === 0 && canbind){
2755
+ // setup live-binding
2756
+ computedData = computeBinder(getterSetter, context || this, function(newValue, oldValue){
2757
+ can.trigger(computed, "change",[newValue, oldValue])
2758
+ });
2759
+ }
2760
+ bindings++;
2761
+ }
2762
+ computed.unbind = function(ev, handler){
2763
+ can.removeEvent.apply(computed, arguments);
2764
+ bindings--;
2765
+ if( bindings === 0 && canbind){
2766
+ computedData.teardown();
2767
+ }
2768
+
2769
+ };
2770
+ return computed;
2771
+ };
2772
+ can.compute.binder = computeBinder;
2773
+
2774
+ // ## ejs.js
2775
+ // `can.EJS`
2776
+ // _Embedded JavaScript Templates._
2777
+
2778
+ // Helper methods.
2779
+ var myEval = function( script ) {
2780
+ eval(script);
2781
+ },
2782
+ extend = can.extend,
2783
+ // Regular expressions for caching.
2784
+ quickFunc = /\s*\(([\$\w]+)\)\s*->([^\n]*)/,
2785
+ attrReg = /([^\s]+)=$/,
2786
+ newLine = /(\r|\n)+/g,
2787
+ attributeReplace = /__!!__/g,
2788
+ tagMap = {
2789
+ "": "span",
2790
+ table: "tr",
2791
+ tr: "td",
2792
+ ol: "li",
2793
+ ul: "li",
2794
+ tbody: "tr",
2795
+ thead: "tr",
2796
+ tfoot: "tr"
2797
+ },
2798
+ // Escapes characters starting with `\`.
2799
+ clean = function( content ) {
2800
+ return content
2801
+ .split('\\').join("\\\\")
2802
+ .split("\n").join("\\n")
2803
+ .split('"').join('\\"')
2804
+ .split("\t").join("\\t");
2805
+ },
2806
+ bracketNum = function(content){
2807
+ return (--content.split("{").length) - (--content.split("}").length);
2808
+ },
2809
+ // Cross-browser attribute methods.
2810
+ // These should be mapped to the underlying library.
2811
+ attrMap = {
2812
+ "class" : "className"
2813
+ },
2814
+ bool = can.each(["checked","disabled","readonly","required"], function(n){
2815
+ attrMap[n] = n;
2816
+ }),
2817
+ setAttr = function(el, attrName, val){
2818
+ attrMap[attrName] ?
2819
+ (el[attrMap[attrName]] = can.inArray(attrName,bool) > -1? true : val):
2820
+ el.setAttribute(attrName, val);
2821
+ },
2822
+ getAttr = function(el, attrName){
2823
+ return attrMap[attrName]?
2824
+ el[attrMap[attrName]]:
2825
+ el.getAttribute(attrName);
2826
+ },
2827
+ removeAttr = function(el, attrName){
2828
+ if(can.inArray(attrName,bool) > -1){
2829
+ el[attrName] = false;
2830
+ } else{
2831
+ el.removeAttribute(attrName)
2832
+ }
2833
+ },
2834
+ // a helper to get the parentNode for a given element el
2835
+ // if el is in a documentFragment, it will return defaultParentNode
2836
+ getParentNode = function(el, defaultParentNode){
2837
+ return defaultParentNode && el.parentNode.nodeType === 11 ? defaultParentNode : el.parentNode;
2838
+ },
2839
+ // helper to know if property is not an expando on oldObserved's list of observes
2840
+ // this should probably be removed and oldObserved should just have a
2841
+ // property with observes
2842
+ observeProp = function(name){
2843
+ return name.indexOf("|") >= 0;
2844
+ },
2845
+ // Returns escaped/sanatized content for anything other than a live-binding
2846
+ contentEscape = function( txt ) {
2847
+ return (typeof txt == 'string' || typeof txt == 'number') ?
2848
+ can.esc( txt ) :
2849
+ contentText(txt);
2850
+ },
2851
+ // Returns text content for anything other than a live-binding
2852
+ contentText = function( input ) {
2853
+
2854
+ // If it's a string, return.
2855
+ if ( typeof input == 'string' ) {
2856
+ return input;
2857
+ }
2858
+ // If has no value, return an empty string.
2859
+ if ( !input && input != 0 ) {
2860
+ return '';
2861
+ }
2862
+
2863
+ // If it's an object, and it has a hookup method.
2864
+ var hook = (input.hookup &&
2865
+
2866
+ // Make a function call the hookup method.
2867
+ function( el, id ) {
2868
+ input.hookup.call(input, el, id);
2869
+ }) ||
2870
+
2871
+ // Or if it's a `function`, just use the input.
2872
+ (typeof input == 'function' && input);
2873
+
2874
+ // Finally, if there is a `function` to hookup on some dom,
2875
+ // add it to pending hookups.
2876
+ if ( hook ) {
2877
+ pendingHookups.push(hook);
2878
+ return '';
2879
+ }
2880
+
2881
+ // Finally, if all else is `false`, `toString()` it.
2882
+ return "" + input;
2883
+ },
2884
+ // The EJS constructor function
2885
+ EJS = function( options ) {
2886
+ // Supports calling EJS without the constructor
2887
+ // This returns a function that renders the template.
2888
+ if ( this.constructor != EJS ) {
2889
+ var ejs = new EJS(options);
2890
+ return function( data, helpers ) {
2891
+ return ejs.render(data, helpers);
2892
+ };
2893
+ }
2894
+ // If we get a `function` directly, it probably is coming from
2895
+ // a `steal`-packaged view.
2896
+ if ( typeof options == "function" ) {
2897
+ this.template = {
2898
+ fn: options
2899
+ };
2900
+ return;
2901
+ }
2902
+ // Set options on self.
2903
+ extend(this, options);
2904
+ this.template = scan(this.text, this.name);
2905
+ };
2906
+
2907
+ can.EJS = EJS;
2908
+ EJS.prototype.
2909
+ render = function( object, extraHelpers ) {
2910
+ object = object || {};
2911
+ return this.template.fn.call(object, object, new EJS.Helpers(object, extraHelpers || {}));
2912
+ };
2913
+ extend(EJS, {
2914
+ // Called to return the content within a magic tag like `<%= %>`.
2915
+ // - escape - if the content returned should be escaped
2916
+ // - tagName - the tag name the magic tag is within or the one that proceeds the magic tag
2917
+ // - status - where the tag is in. The status can be:
2918
+ // - _STRING_ - The name of the attribute the magic tag is within
2919
+ // - `1` - The magic tag is within a tag like `<div <%= %>>`
2920
+ // - `0` - The magic tag is outside (or between) tags like `<div><%= %></div>`
2921
+ // - self - the `this` the template was called with
2922
+ // - func - the "wrapping" function. For example: `<%= task.attr('name') %>` becomes
2923
+ // `(function(){return task.attr('name')})
2924
+ txt : function(escape, tagName, status, self, func){
2925
+ // call the "wrapping" function and get the binding information
2926
+ var binding = can.compute.binder(func, self, function(newVal, oldVal){
2927
+ // call the update method we will define for each
2928
+ // type of attribute
2929
+ update(newVal, oldVal)
2930
+ });
2931
+
2932
+ // If we had no observes just return the value returned by func.
2933
+ if(!binding.isListening){
2934
+ return (escape || status !== 0? contentEscape : contentText)(binding.value);
2935
+ }
2936
+ // The following are helper methods or varaibles that will
2937
+ // be defined by one of the various live-updating schemes.
2938
+
2939
+ // The parent element we are listening to for teardown
2940
+ var parentElement,
2941
+ // if the parent element is removed, teardown the binding
2942
+ setupTeardownOnDestroy = function(el){
2943
+ can.bind.call(el,'destroyed', binding.teardown)
2944
+ parentElement = el;
2945
+ },
2946
+ // if there is no parent, undo bindings
2947
+ teardownCheck = function(parent){
2948
+ if(!parent){
2949
+ binding.teardown();
2950
+ can.unbind.call(parentElement,'destroyed', binding.teardown)
2951
+ }
2952
+ },
2953
+ // the tag type to insert
2954
+ tag = (tagMap[tagName] || "span"),
2955
+ // this will be filled in if binding.isListening
2956
+ update;
2957
+
2958
+
2959
+ // The magic tag is outside or between tags.
2960
+ if(status == 0){
2961
+ // Return an element tag with a hookup in place of the content
2962
+ return "<" +tag+can.view.hook(
2963
+ escape ?
2964
+ // If we are escaping, replace the parentNode with
2965
+ // a text node who's value is `func`'s return value.
2966
+ function(el, parentNode){
2967
+ // updates the text of the text node
2968
+ update = function(newVal){
2969
+ node.nodeValue = ""+newVal;
2970
+ teardownCheck(node.parentNode);
2971
+ };
2972
+
2973
+ var parent = getParentNode(el, parentNode),
2974
+ node = document.createTextNode(binding.value);
2975
+
2976
+ parent.insertBefore(node, el);
2977
+ parent.removeChild(el);
2978
+ setupTeardownOnDestroy(parent);
2979
+ }
2980
+ :
2981
+ // If we are not escaping, replace the parentNode with a
2982
+ // documentFragment created as with `func`'s return value.
2983
+ function(span, parentNode){
2984
+ // updates the elements with the new content
2985
+ update = function(newVal){
2986
+ // is this still part of the DOM?
2987
+ var attached = nodes[0].parentNode;
2988
+ // update the nodes in the DOM with the new rendered value
2989
+ if( attached ) {
2990
+ nodes = makeAndPut(newVal, nodes);
2991
+ }
2992
+ teardownCheck(nodes[0].parentNode)
2993
+ }
2994
+
2995
+ // make sure we have a valid parentNode
2996
+ parentNode = getParentNode(span, parentNode)
2997
+ // A helper function to manage inserting the contents
2998
+ // and removing the old contents
2999
+ var makeAndPut = function(val, remove){
3000
+ // create the fragment, but don't hook it up
3001
+ // we need to insert it into the document first
3002
+
3003
+ var frag = can.view.frag(val, parentNode),
3004
+ // keep a reference to each node
3005
+ nodes = can.map(frag.childNodes,function(node){
3006
+ return node;
3007
+ }),
3008
+ last = remove[remove.length - 1];
3009
+
3010
+ // Insert it in the `document` or `documentFragment`
3011
+ if( last.nextSibling ){
3012
+ last.parentNode.insertBefore(frag, last.nextSibling)
3013
+ } else {
3014
+ last.parentNode.appendChild(frag)
3015
+ }
3016
+ // Remove the old content.
3017
+ can.remove( can.$(remove) );
3018
+
3019
+ return nodes;
3020
+ },
3021
+ // nodes are the nodes that any updates will replace
3022
+ // at this point, these nodes could be part of a documentFragment
3023
+ nodes = makeAndPut(binding.value, [span]);
3024
+
3025
+
3026
+ setupTeardownOnDestroy(parentNode);
3027
+
3028
+ }) + "></" +tag+">";
3029
+ // In a tag, but not in an attribute
3030
+ } else if(status === 1){
3031
+ // remember the old attr name
3032
+ var attrName = binding.value.replace(/['"]/g, '').split('=')[0];
3033
+ pendingHookups.push(function(el) {
3034
+ update = function(newVal){
3035
+ var parts = (newVal|| "").replace(/['"]/g, '').split('='),
3036
+ newAttrName = parts[0];
3037
+
3038
+ // Remove if we have a change and used to have an `attrName`.
3039
+ if((newAttrName != attrName) && attrName){
3040
+ removeAttr(el,attrName)
3041
+ }
3042
+ // Set if we have a new `attrName`.
3043
+ if(newAttrName){
3044
+ setAttr(el, newAttrName, parts[1]);
3045
+ attrName = newAttrName;
3046
+ }
3047
+ }
3048
+ setupTeardownOnDestroy(el);
3049
+ });
3050
+
3051
+ return binding.value;
3052
+ } else { // In an attribute...
3053
+ pendingHookups.push(function(el){
3054
+ // update will call this attribute's render method
3055
+ // and set the attribute accordingly
3056
+ update = function(){
3057
+ setAttr(el, status, hook.render())
3058
+ }
3059
+
3060
+ var wrapped = can.$(el),
3061
+ hooks;
3062
+
3063
+ // Get the list of hookups or create one for this element.
3064
+ // Hooks is a map of attribute names to hookup `data`s.
3065
+ // Each hookup data has:
3066
+ // `render` - A `function` to render the value of the attribute.
3067
+ // `funcs` - A list of hookup `function`s on that attribute.
3068
+ // `batchNum` - The last event `batchNum`, used for performance.
3069
+ (hooks = can.data(wrapped,'hooks')) || can.data(wrapped, 'hooks', hooks = {});
3070
+
3071
+ // Get the attribute value.
3072
+ var attr = getAttr(el, status),
3073
+ // Split the attribute value by the template.
3074
+ parts = attr.split("__!!__"),
3075
+ hook;
3076
+
3077
+
3078
+ // If we already had a hookup for this attribute...
3079
+ if(hooks[status]) {
3080
+ // Just add to that attribute's list of `function`s.
3081
+ hooks[status].bindings.push(binding);
3082
+ }
3083
+ else {
3084
+ // Create the hookup data.
3085
+ hooks[status] = {
3086
+ render: function() {
3087
+ var i =0,
3088
+ newAttr = attr.replace(attributeReplace, function() {
3089
+ return contentText( hook.bindings[i++].value );
3090
+ });
3091
+ return newAttr;
3092
+ },
3093
+ bindings: [binding],
3094
+ batchNum : undefined
3095
+ };
3096
+ };
3097
+
3098
+ // Save the hook for slightly faster performance.
3099
+ hook = hooks[status];
3100
+
3101
+ // Insert the value in parts.
3102
+ parts.splice(1,0,binding.value);
3103
+
3104
+ // Set the attribute.
3105
+ setAttr(el, status, parts.join(""));
3106
+
3107
+ // Bind on change.
3108
+ //liveBind(observed, el, binder,oldObserved);
3109
+ setupTeardownOnDestroy(el)
3110
+ })
3111
+ return "__!!__";
3112
+ }
3113
+ },
3114
+ pending: function() {
3115
+ if(pendingHookups.length) {
3116
+ var hooks = pendingHookups.slice(0);
3117
+
3118
+ pendingHookups = [];
3119
+ return can.view.hook(function(el){
3120
+ can.each(hooks, function(fn){
3121
+ fn(el);
3122
+ })
3123
+ });
3124
+ }else {
3125
+ return "";
3126
+ }
3127
+ }
3128
+ });
3129
+ // Start scanning code.
3130
+ var tokenReg = new RegExp("(" +[ "<%%", "%%>", "<%==", "<%=",
3131
+ "<%#", "<%", "%>", "<", ">", '"', "'"].join("|")+")","g"),
3132
+ // Commands for caching.
3133
+ startTxt = 'var ___v1ew = [];',
3134
+ finishTxt = "return ___v1ew.join('')",
3135
+ put_cmd = "___v1ew.push(",
3136
+ insert_cmd = put_cmd,
3137
+ // Global controls (used by other functions to know where we are).
3138
+ //
3139
+ // Are we inside a tag?
3140
+ htmlTag = null,
3141
+ // Are we within a quote within a tag?
3142
+ quote = null,
3143
+ // What was the text before the current quote? (used to get the `attr` name)
3144
+ beforeQuote = null,
3145
+ // Used to mark where the element is.
3146
+ status = function(){
3147
+ // `t` - `1`.
3148
+ // `h` - `0`.
3149
+ // `q` - String `beforeQuote`.
3150
+ return quote ? "'"+beforeQuote.match(attrReg)[1]+"'" : (htmlTag ? 1 : 0)
3151
+ },
3152
+ pendingHookups = [],
3153
+ scan = function(source, name){
3154
+ var tokens = [],
3155
+ last = 0;
3156
+
3157
+ source = source.replace(newLine, "\n");
3158
+ source.replace(tokenReg, function(whole, part, offset){
3159
+ // if the next token starts after the last token ends
3160
+ // push what's in between
3161
+ if(offset > last){
3162
+ tokens.push( source.substring(last, offset) );
3163
+ }
3164
+ // push the token
3165
+ tokens.push(part);
3166
+ // update the position of the last part of the last token
3167
+ last = offset+part.length;
3168
+ })
3169
+ // if there's something at the end, add it
3170
+ if(last < source.length){
3171
+ tokens.push(source.substr(last))
3172
+ }
3173
+
3174
+ var content = '',
3175
+ buff = [startTxt],
3176
+ // Helper `function` for putting stuff in the view concat.
3177
+ put = function( content, bonus ) {
3178
+ buff.push(put_cmd, '"', clean(content), '"'+(bonus||'')+');');
3179
+ },
3180
+ // A stack used to keep track of how we should end a bracket
3181
+ // `}`.
3182
+ // Once we have a `<%= %>` with a `leftBracket`,
3183
+ // we store how the file should end here (either `))` or `;`).
3184
+ endStack =[],
3185
+ // The last token, used to remember which tag we are in.
3186
+ lastToken,
3187
+ // The corresponding magic tag.
3188
+ startTag = null,
3189
+ // Was there a magic tag inside an html tag?
3190
+ magicInTag = false,
3191
+ // The current tag name.
3192
+ tagName = '',
3193
+ // stack of tagNames
3194
+ tagNames = [],
3195
+ // Declared here.
3196
+ bracketCount,
3197
+ i = 0,
3198
+ token;
3199
+
3200
+ // Reinitialize the tag state goodness.
3201
+ htmlTag = quote = beforeQuote = null;
3202
+
3203
+ for (; (token = tokens[i++]) !== undefined;) {
3204
+
3205
+ if ( startTag === null ) {
3206
+ switch ( token ) {
3207
+ case '<%':
3208
+ case '<%=':
3209
+ case '<%==':
3210
+ magicInTag = 1;
3211
+ case '<%#':
3212
+ // A new line -- just add whatever content within a clean.
3213
+ // Reset everything.
3214
+ startTag = token;
3215
+ if ( content.length ) {
3216
+ put(content);
3217
+ }
3218
+ content = '';
3219
+ break;
3220
+
3221
+ case '<%%':
3222
+ // Replace `<%%` with `<%`.
3223
+ content += '<%';
3224
+ break;
3225
+ case '<':
3226
+ // Make sure we are not in a comment.
3227
+ if(tokens[i].indexOf("!--") !== 0) {
3228
+ htmlTag = 1;
3229
+ magicInTag = 0;
3230
+ }
3231
+ content += token;
3232
+ break;
3233
+ case '>':
3234
+ htmlTag = 0;
3235
+ // TODO: all `<%=` in tags should be added to pending hookups.
3236
+ if(magicInTag){
3237
+ put(content, ",can.EJS.pending(),\">\"");
3238
+ content = '';
3239
+ } else {
3240
+ content += token;
3241
+ }
3242
+ // if it's a tag like <input/>
3243
+ if(lastToken.substr(-1) == "/"){
3244
+ // remove the current tag in the stack
3245
+ tagNames.pop();
3246
+ // set the current tag to the previous parent
3247
+ tagName = tagNames[tagNames.length-1];
3248
+ }
3249
+ break;
3250
+ case "'":
3251
+ case '"':
3252
+ // If we are in an html tag, finding matching quotes.
3253
+ if(htmlTag){
3254
+ // We have a quote and it matches.
3255
+ if(quote && quote === token){
3256
+ // We are exiting the quote.
3257
+ quote = null;
3258
+ // Otherwise we are creating a quote.
3259
+ // TODO: does this handle `\`?
3260
+ } else if(quote === null){
3261
+ quote = token;
3262
+ beforeQuote = lastToken;
3263
+ }
3264
+ }
3265
+ default:
3266
+ // Track the current tag
3267
+ if(lastToken === '<'){
3268
+ tagName = token.split(' ')[0];
3269
+ // If
3270
+ if( tagName.indexOf("/") === 0 && tagNames.pop() === tagName.substr(1) ) {
3271
+ tagName = tagNames[tagNames.length-1]|| tagName.substr(1)
3272
+ } else {
3273
+ tagNames.push(tagName);
3274
+ }
3275
+ }
3276
+ content += token;
3277
+ break;
3278
+ }
3279
+ }
3280
+ else {
3281
+ // We have a start tag.
3282
+ switch ( token ) {
3283
+ case '%>':
3284
+ // `%>`
3285
+ switch ( startTag ) {
3286
+ case '<%':
3287
+ // `<%`
3288
+
3289
+ // Get the number of `{ minus }`
3290
+ bracketCount = bracketNum(content);
3291
+
3292
+ // We are ending a block.
3293
+ if (bracketCount == 1) {
3294
+
3295
+ // We are starting on.
3296
+ buff.push(insert_cmd, "can.EJS.txt(0,'"+tagName+"'," + status() + ",this,function(){", startTxt, content);
3297
+
3298
+ endStack.push({
3299
+ before: "",
3300
+ after: finishTxt+"}));\n"
3301
+ })
3302
+ }
3303
+ else {
3304
+
3305
+ // How are we ending this statement?
3306
+ var last = // If the stack has value and we are ending a block...
3307
+ endStack.length && bracketCount == -1 ? // Use the last item in the block stack.
3308
+ endStack.pop() : // Or use the default ending.
3309
+ {
3310
+ after: ";"
3311
+ };
3312
+
3313
+ // If we are ending a returning block,
3314
+ // add the finish text which returns the result of the
3315
+ // block.
3316
+ if (last.before) {
3317
+ buff.push(last.before)
3318
+ }
3319
+ // Add the remaining content.
3320
+ buff.push(content, ";",last.after);
3321
+ }
3322
+ break;
3323
+ case '<%=':
3324
+ case '<%==':
3325
+ // We have an extra `{` -> `block`.
3326
+ // Get the number of `{ minus }`.
3327
+ bracketCount = bracketNum(content);
3328
+ // If we have more `{`, it means there is a block.
3329
+ if( bracketCount ){
3330
+ // When we return to the same # of `{` vs `}` end with a `doubleParent`.
3331
+ endStack.push({
3332
+ before : finishTxt,
3333
+ after: "}));"
3334
+ })
3335
+ }
3336
+ // Check if its a func like `()->`
3337
+ if(quickFunc.test(content)){
3338
+ var parts = content.match(quickFunc)
3339
+ content = "function(__){var "+parts[1]+"=can.$(__);"+parts[2]+"}"
3340
+ }
3341
+
3342
+ // If we have `<%== a(function(){ %>` then we want
3343
+ // `can.EJS.text(0,this, function(){ return a(function(){ var _v1ew = [];`.
3344
+ buff.push(insert_cmd, "can.EJS.txt("+(startTag === '<%=' ? 1 : 0)+",'"+tagName+"'," + status()+",this,function(){ return ", content,
3345
+ // If we have a block.
3346
+ bracketCount ?
3347
+ // Start with startTxt `"var _v1ew = [];"`.
3348
+ startTxt :
3349
+ // If not, add `doubleParent` to close push and text.
3350
+ "}));"
3351
+ );
3352
+ break;
3353
+ }
3354
+ startTag = null;
3355
+ content = '';
3356
+ break;
3357
+ case '<%%':
3358
+ content += '<%';
3359
+ break;
3360
+ default:
3361
+ content += token;
3362
+ break;
3363
+ }
3364
+
3365
+ }
3366
+ lastToken = token;
3367
+ }
3368
+
3369
+ // Put it together...
3370
+ if ( content.length ) {
3371
+ // Should be `content.dump` in Ruby.
3372
+ put(content)
3373
+ }
3374
+ buff.push(";")
3375
+
3376
+ var template = buff.join(''),
3377
+ out = {
3378
+ out: 'with(_VIEW) { with (_CONTEXT) {' + template + " "+finishTxt+"}}"
3379
+ };
3380
+ // Use `eval` instead of creating a function, because it is easier to debug.
3381
+ myEval.call(out, 'this.fn = (function(_CONTEXT,_VIEW){' + out.out + '});\r\n//@ sourceURL=' + name + ".js");
3382
+ return out;
3383
+ };
3384
+
3385
+
3386
+
3387
+ EJS.Helpers = function( data, extras ) {
3388
+ this._data = data;
3389
+ this._extras = extras;
3390
+ extend(this, extras);
3391
+ };
3392
+ EJS.Helpers.prototype = {
3393
+ // TODO Deprecated!!
3394
+ list : function(list, cb){
3395
+ can.each(list, function(item, i){
3396
+ cb(item, i, list)
3397
+ })
3398
+ }
3399
+ };
3400
+
3401
+ // Options for `steal`'s build.
3402
+ can.view.register({
3403
+ suffix: "ejs",
3404
+ // returns a `function` that renders the view.
3405
+ script: function( id, src ) {
3406
+ return "can.EJS(function(_CONTEXT,_VIEW) { " + new EJS({
3407
+ text: src,
3408
+ name: id
3409
+ }).template.out + " })";
3410
+ },
3411
+ renderer: function( id, text ) {
3412
+ return EJS({
3413
+ text: text,
3414
+ name: id
3415
+ });
3416
+ }
3417
+ });
3418
+
3419
+ // Register as an AMD module if supported, otherwise attach to the window
3420
+ if ( typeof define === "function" && define.amd ) {
3421
+ define( "can", [], function () { return can; } );
3422
+ } else {
3423
+ window.can = can;
3424
+ }
3425
+
3426
+ })(can = {}, this )