diff --git a/.gitignore b/.gitignore index e920c16..613e524 100644 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,7 @@ coverage # Compiled binary addons (http://nodejs.org/api/addons.html) build/Release +dist/ # Dependency directory node_modules diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..a8c99d8 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,31 @@ +language: node_js +node_js: +- '5.8' +addons: + ssh_known_hosts: + - develop.bithub.com + - staging.bithub.com + - production.bithub.com +before_install: +- openssl aes-256-cbc -K $encrypted_34b14dba4b3c_key -iv $encrypted_34b14dba4b3c_iv + -in deploy-key.pem.enc -out deploy-key.pem -d +- export DISPLAY=:99.0 +- sh -e /etc/init.d/xvfb start +deploy: + - provider: script + script: ./.travis/deploy-production.sh + skip_cleanup: true + on: + branch: production + - provider: script + script: ./.travis/deploy-staging.sh + skip_cleanup: true + on: + branch: staging + - provider: script + script: ./.travis/deploy-develop.sh + skip_cleanup: true + on: + branch: develop +notifications: + slack: bitovi:a6EZ5xpLzrpMgCYyvKwfkmN5 diff --git a/.travis/deploy-develop.sh b/.travis/deploy-develop.sh new file mode 100755 index 0000000..32fd51c --- /dev/null +++ b/.travis/deploy-develop.sh @@ -0,0 +1,10 @@ +#!/bin/sh +eval "$(ssh-agent -s)" + +chmod 600 deploy-key.pem +ssh-add deploy-key.pem + +git remote add deploy ssh://bithub@develop.bithub.com/home/bithub/client.git +# Do not change this line. Travis has the ability push back to the repository +# https://docs.travis-ci.com/user/github-oauth-scopes/ +git push -f deploy develop:develop diff --git a/.travis/deploy-production.sh b/.travis/deploy-production.sh new file mode 100755 index 0000000..aec63c8 --- /dev/null +++ b/.travis/deploy-production.sh @@ -0,0 +1,10 @@ +#!/bin/sh +eval "$(ssh-agent -s)" + +chmod 600 deploy-key.pem +ssh-add deploy-key.pem + +git remote add deploy ssh://bithub@production.bithub.com/home/bithub/client.git +# Do not change this line. Travis has the ability push back to the repository +# https://docs.travis-ci.com/user/github-oauth-scopes/ +git push -f deploy production:production diff --git a/.travis/deploy-staging.sh b/.travis/deploy-staging.sh new file mode 100755 index 0000000..5185b92 --- /dev/null +++ b/.travis/deploy-staging.sh @@ -0,0 +1,10 @@ +#!/bin/sh +eval "$(ssh-agent -s)" + +chmod 600 deploy-key.pem +ssh-add deploy-key.pem + +git remote add deploy ssh://bithub@staging.bithub.com/home/bithub/client.git +# Do not change this line. Travis has the ability push back to the repository +# https://docs.travis-ci.com/user/github-oauth-scopes/ +git push -f deploy staging:staging diff --git a/.travis/encrypt-deploy-key.sh b/.travis/encrypt-deploy-key.sh new file mode 100755 index 0000000..b8aea79 --- /dev/null +++ b/.travis/encrypt-deploy-key.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Usage: +# Go to your git project: +# cd my_project +# Then run: +# ./encrypt-deploy-key.sh + +SSH_KEY_PATH=$1 + +if [[ ! $(which travis) ]]; then + gem install travis +fi + +travis login --pro --auto +travis encrypt-file ${SSH_KEY_PATH} --add diff --git a/404.html b/404.html new file mode 100644 index 0000000..9a48320 --- /dev/null +++ b/404.html @@ -0,0 +1,26 @@ + + + + The page you were looking for doesn't exist (404) + + + + + +
+

The page you were looking for doesn't exist.

+

You may have mistyped the address or the page may have moved.

+
+ + diff --git a/422.html b/422.html new file mode 100644 index 0000000..83660ab --- /dev/null +++ b/422.html @@ -0,0 +1,26 @@ + + + + The change you wanted was rejected (422) + + + + + +
+

The change you wanted was rejected.

+

Maybe you tried to change something you didn't have access to.

+
+ + diff --git a/500.html b/500.html new file mode 100644 index 0000000..f3648a0 --- /dev/null +++ b/500.html @@ -0,0 +1,25 @@ + + + + We're sorry, but something went wrong (500) + + + + + +
+

We're sorry, but something went wrong.

+
+ + diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..a9efded --- /dev/null +++ b/Makefile @@ -0,0 +1,67 @@ +all: gitco cleandesktop installdesktop builddesktop buildhomepageembed cleanmobile installmobile buildmobile gitadd gitci + +desktop: gitco cleandesktop installdesktop builddesktop buildhomepageembed gitadd gitci + +mobile: gitco cleanmobile installmobile buildmobile addtogit gitadd gitci + +cleandesktop: + @echo "********************************************************************************" + @echo "* Removing desktop node_modules *" + @echo "********************************************************************************" + rm -rf node_modules + +installdesktop: + @echo "********************************************************************************" + @echo "* Installing desktop node_modules *" + @echo "********************************************************************************" + npm install + +builddesktop: + @echo "********************************************************************************" + @echo "* Building desktop app *" + @echo "********************************************************************************" + ./node_modules/steal-tools/bin/steal build --main=bithub-social; + ./node_modules/steal-tools/bin/steal build --main=bithub-embed + +buildhomepageembed: + @echo "********************************************************************************" + @echo "* Building homepage embed *" + @echo "********************************************************************************" + ./node_modules/steal-tools/bin/steal build --main=homepage_embed/index + +cleanmobile: + @echo "********************************************************************************" + @echo "* Removing mobile node_modules *" + @echo "********************************************************************************" + cd new-bithub-client; rm -rf node_modules + +installmobile: + @echo "********************************************************************************" + @echo "* Installing mobile node_modules *" + @echo "********************************************************************************" + cd new-bithub-client; npm install + +buildmobile: + @echo "********************************************************************************" + @echo "* Building mobile app *" + @echo "********************************************************************************" + cd new-bithub-client; donejs build + +gitco: + @echo "********************************************************************************" + @echo "* Switching to release branch" + @echo "********************************************************************************" + git checkout -b release + +gitadd: + @echo "********************************************************************************" + @echo "* Forcefully adding to git" + @echo "********************************************************************************" + git add --force node_modules dist new-bithub-client/node_modules new-bithub-client/dist + +gitadd: + @echo "********************************************************************************" + @echo "* Forcefully adding to git" + @echo "********************************************************************************" + git ci -m 'Release is out yall!' + diff --git a/README.md b/README.md index c580c55..fab2843 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,2 @@ -# www-client -The desktop and mobile web client for bithub.com. +(develop.bithub) client application [![Build Status](https://travis-ci.org/bithubapp/bithub-admin.svg?branch=develop)](https://travis-ci.org/bithubapp/bithub-admin) +============== diff --git a/bind-model-events.js b/bind-model-events.js new file mode 100644 index 0000000..46732df --- /dev/null +++ b/bind-model-events.js @@ -0,0 +1,31 @@ +import Models from "models/"; + +export default function(appState){ + Models.Service.on('saving', function(ev, service){ + var loadingServices = appState.attr('loadingServices'); + var index = loadingServices.indexOf(service); + + if(index > -1){ + loadingServices.splice(index, 1); + } + + loadingServices.unshift(service); + }); + + + Models.Service.on('errored', function(ev, service){ + var loadingServices = appState.attr('loadingServices'); + var index = loadingServices.indexOf(service); + + loadingServices.splice(index, 1); + }); + + Models.Service.on('destroyed', function(ev, service){ + var loadingServices = appState.attr('loadingServices'); + var index = loadingServices.indexOf(service); + + if(index > -1){ + loadingServices.splice(index, 1); + } + }); +} diff --git a/bit-list/bit-list.js b/bit-list/bit-list.js new file mode 100644 index 0000000..3778dff --- /dev/null +++ b/bit-list/bit-list.js @@ -0,0 +1,50 @@ +import can from "can/"; +import initView from "./bit-list.stache!"; +import InteractionEvent from "models/interaction_event"; + +import "can/construct/super/"; +import "can/construct/proxy/"; +import "bithub-embed/bits_vertical_infinite/"; +import "bithub-embed/bits_vertical_infinite_grouped/"; + +export default can.Control.extend({ + pluginName : 'bh-bits', +}, { + setup : function(el, opts){ + opts = opts || {}; + opts.isLoading = can.compute(false); + opts.hasNextPage = can.compute(true); + return this._super(el, opts); + }, + init : function(){ + this.__timeouts = {}; + + this.currentOffset = can.compute(0); + this.bits = this.options.state.attr('bits'); + + this.element.html(initView({ + isLoading : this.options.isLoading, + state : this.options.state, + bits: this.bits + })); + + + + }, + 'interaction:scroll' : function(el, ev, hubId){ + if(!this.__savedScrollInteraction){ + InteractionEvent.createScrollInteraction(this.options.state.attr('tenant'), hubId); + this.__savedScrollInteraction = true; + } + }, + 'interaction:link' : function(el, ev, hubId, entityId){ + if(!this.options.state.isAdmin()){ + InteractionEvent.createLinkClickedInteraction(this.options.state.attr('tenant'), hubId, entityId); + } + }, + 'interaction:share' : function(el, ev, hubId, entityId, target){ + if(!this.options.state.isAdmin()){ + InteractionEvent.createEntitySharedInteraction(this.options.state.attr('tenant'), hubId, entityId, target); + } + } +}); diff --git a/bit-list/bit-list.stache b/bit-list/bit-list.stache new file mode 100644 index 0000000..639ed09 --- /dev/null +++ b/bit-list/bit-list.stache @@ -0,0 +1,16 @@ +{{#if state.isAdmin}} + {{#if state.isGroupedByDate}} + + {{else}} + + + {{/if}} + +{{else}} + +{{/if}} +{{#if state.showPoweredBy}} +
+ Powered by BitHub +
+{{/if}} diff --git a/bithub-embed.js b/bithub-embed.js new file mode 100644 index 0000000..0056ebb --- /dev/null +++ b/bithub-embed.js @@ -0,0 +1,117 @@ +import AppState from 'models/embed_appstate'; +import Bit from 'models/bit'; +import Hub from 'models/hub'; +import BitList from 'bit-list/'; +import Communicator from 'communicator/'; +import 'can/route/'; +import "style/embed.less!"; +var params = can.deparam(window.location.search.substr(1)); +var isLoadedFromIframe = window.parent !== window; +var appState = new AppState(); + +var bodyClasses = [(isLoadedFromIframe ? 'iframe-context' : 'page-context'), 'embed']; + +var triggerPartition = (function(){ + var partitionTimeout; + return function(bits){ + clearTimeout(partitionTimeout); + partitionTimeout = setTimeout(function(){ + can.trigger(bits, 'partition'); + }, 100); + }; +})(); + +var kickstart = function(hub){ + var communicator = Communicator.bind(window.parent, { + updateAttrs : function(data){ + appState.setAttrs(data); + }, + reset : function(){ + resetApp(); + } + }); + + bodyClasses.push((params.theme || 'light') + '-theme'); + + //can.route.map(appState); + //can.route.ready(); + + + appState.attr('hub', hub); + appState.setAttrs(params); + appState.connectLiveService(); + + if(!appState.isPublic()){ + bodyClasses.push('admin-embed'); + } + + Bit.on('lifecycle', function(ev, bit){ + var serviceIds = bit.attr('service_ids'); + var bits = appState.attr('bits'); + var isLive = appState.isLive(); + + if(appState.isPublic() && isLive && bit.isPublic()){ + bits.place(bit); + } else { + if(isLive && bits.indexOf(bit) === -1 && bit.attr('decision') === appState.attr('decision')){ + bits.unshift(bit); + } + } + + triggerPartition(bits); + + if( serviceIds && (params.view !== 'public') ){ + communicator.send('loadedBits', serviceIds); + } + + }); + + Bit.on('disapproved', function(ev, bit){ + var bits = appState.attr('bits'); + var index = bits.indexOf(bit); + if(appState.isPublic() && index > -1){ + bits.splice(index, 1); + } + }); + + $('body').addClass(bodyClasses.join(' ')); + + var initApp = function(){ + var div = $('
'); + + $('#app-wrapper').html(div); + console.log('INIT APP') + new BitList(div, { + state : appState + }); + }; + + var resetApp = (function(){ + var timeout; + return function(){ + clearTimeout(timeout); + setTimeout(function(){ + appState.reset(); + initApp(); + }, 1); + }; + })(); + + appState.on('view', resetApp); + appState.on('order', resetApp); + appState.on('decision', resetApp); + appState.on('service_id', resetApp); + appState.on('image_only', resetApp); + + appState.on('theme', function(ev, newTheme){ + $('body').removeClass('dark-theme light-theme').addClass(newTheme + '-theme'); + }); + + initApp(); +}; + +Hub.findOne({id: params.hubId}).then(function(hub){ + kickstart(hub); +}, function(){ + kickstart(); +}); diff --git a/bithub-social.html b/bithub-social.html new file mode 100644 index 0000000..94e4a9d --- /dev/null +++ b/bithub-social.html @@ -0,0 +1,12 @@ + + + + + + BitHub + + + +
+ + \ No newline at end of file diff --git a/bithub-social.js b/bithub-social.js new file mode 100644 index 0000000..1eba182 --- /dev/null +++ b/bithub-social.js @@ -0,0 +1,129 @@ +import can from "can/"; +import initView from './bithub-social.stache!'; +import stache from 'can/view/stache/'; +import AppState from 'models/appstate'; +import Models from 'models/'; +import bindModelEvents from './bind-model-events'; +import 'can/map/define/'; +import 'components/'; +import 'components/helpers'; +import 'components/service-config-formatter/'; +import Cookie from 'js-cookie'; + +var kickstart = function(selector){ + var PresetChangeUpdater = can.Control.extend({ + '{appState} preset' : 'updateIframeAttrs', + '{appState} customPreset change' : 'updateIframeAttrs', + '{appState.adminPreset} change' : 'updateIframeAttrs', + updateIframeAttrs : function(){ + var self = this; + clearTimeout(this.__updateIframeAttrs); + this.__updateIframeAttrs = setTimeout(function(){ + self.options.appState.updateIframeAttrs(); + }); + } + }); + + if(/Mobi/.test(navigator.userAgent)){ + if(Cookie.get('redirected-from-new-ui')){ + Cookie.remove('redirected-from-new-ui'); + } else { + window.location = '/new-bithub/'; + return; + } + } + + $.ajaxPrefilter(function( options, originalOptions, jqXHR ) { + if(options.type.toLowerCase() !== 'get'){ + options.data = JSON.stringify(originalOptions.data); + options.contentType = 'application/json'; + } + }); + + $.when(Models.Brand.findOne({}), Models.Subscription.findOne({}), Models.Account.current(), Models.Organization.current()).done(function(brand, subscription, account, organization){ + + var appState = new AppState({ + currentBrand: brand, + currentSubscription: subscription, + currentAccount: account, + currentOrganization: organization, + embedType : 'admin' + }); + + + new PresetChangeUpdater(document.documentElement, { + appState : appState + }); + + can.route('', {page: 'hub-list'}); + can.route(':page'); + can.route(':page/:panel'); + can.route(':page/:panel/:hubId'); + can.route(':page/:panel/:hubId'); + + can.route.map(appState); + + can.route.ready(); + + bindModelEvents(appState); + + stache.registerHelper('ifCanAddHub', function(hubs, opts){ + hubs = can.isFunction(hubs) ? hubs() : hubs; + var canAddHub = appState.attr('currentSubscription').canAddHub(hubs); + return canAddHub ? opts.fn() : opts.inverse(); + }); + + stache.registerHelper('ifCanAddService', function(services, feed, type, opts){ + feed = can.isFunction(feed) ? feed() : feed; + type = can.isFunction(type) ? type() : type; + services = can.isFunction(services) ? services() : services; + var canAddService = appState.attr('currentSubscription').canAddService(services, feed, type); + + return canAddService ? opts.fn() : opts.inverse(); + }); + + + $(selector).html(initView({ + state: appState, + switchOrganization : function(organization){ + Models.Organization.choose(organization.id).then(function(){ + window.location.reload(); + }, function(){ + alert('There was a problem with the organization switching'); + }); + } + }, { + renderIframe : function(iframe, opts){ + iframe = can.isFunction(iframe) ? iframe() : iframe; + return iframe; + }, + renderPage : function(){ + var page = can.route.attr('page') || "hub-list", + template = can.stache(''); + + return template(this); + }, + pageLink : function(page, title){ + page = can.isFunction(page) ? page() : page; + title = can.isFunction(title) ? title() : title; + + var currentPage = can.route.attr('page'); + var props = { + 'class' : 'btn ' + }; + + props['class'] += page === currentPage ? 'btn-default' : 'btn-link'; + + return can.route.link(title, {page: page}, props, false); + }, + serviceStringTitle : function(service){ + service = can.isFunction(service) ? service() : service; + return $(can.stache('')({service: service})).text(); + } + })); + }).fail(function(){ + console.log('FAIL', arguments) + }); +}; + +kickstart('#app'); diff --git a/bithub-social.stache b/bithub-social.stache new file mode 100644 index 0000000..7ba6f2c --- /dev/null +++ b/bithub-social.stache @@ -0,0 +1,95 @@ +{{#if state.isSidebar}} + + + +
+
+
+ {{state.embedTypeTitle}} Mode + {{#unless state.isAdminEmbed}} + - {{state.preset.name}} + {{/unless}} + {{#if state.isAdminEmbed}} +
+ {{#if state.services.length}} + + {{/if}} + +
+ {{/if}} +
+
+ Back to Admin | {{state.hub.name}} +
+
+ {{#if state.isAdminEmbed}} +
+ +
+ {{/if}} +
+ {{renderIframe state.iframe}} +
+
+ +{{else}} + +
+
+

BitHub

+
+ +
+
+
+
+ {{{renderPage}}} +
+
+ +{{/if}} diff --git a/bower.json b/bower.json new file mode 100644 index 0000000..8a666a9 --- /dev/null +++ b/bower.json @@ -0,0 +1,45 @@ +{ + "name": "bithub-social", + "version": "0.0.0", + "homepage": "https://github.com/bitovi/bithub-social", + "authors": [ + "Mihael Konjevic " + ], + "license": "-", + "private": true, + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ], + "dependencies": { + "selectize": "0.12.0", + "steal": "0.10.5", + "canjs": "2.2.6", + "bootstrap": "3.3.0", + "lodash-amd": "3.9.3", + "fontawesome": "4.2.0", + "qunit": "1.18.0", + "moment": "2.9.0", + "Chart.js": "1.0.1", + "randomcolor": "0.2.0", + "system-bower": "0.2.2", + "system-json": "https://github.com/stealjs/system-json.git", + "steal-qunit": "0.0.4", + "jquery.payment": "1.2.3", + "funcunit": "2.0.0", + "js-cookie": "~2.1.0" + }, + "resolutions": { + "steal": "0.10.5", + "jquery": "1.9.1", + "funcunit": "2.0.0", + "js-cookie": "2.0.4", + "canjs": "2.2.6", + "traceur": "0.0.58", + "qunit": "1.18.0" + }, + "main": "bithub-social.js" +} diff --git a/communicator/communicator.js b/communicator/communicator.js new file mode 100644 index 0000000..429f551 --- /dev/null +++ b/communicator/communicator.js @@ -0,0 +1,49 @@ +/* global EMBED_ENDPOINT:true */ +import can from "can/"; + +var preparePayload = function(payload){ + while(payload && can.isFunction(payload.attr)){ + payload = payload.attr(); + } + return payload; +}; + +export default can.Control.extend({ + bind : function(frame, handlers){ + return new this(document.documentElement, { + frame: frame, + handlers : handlers || {} + }); + } +},{ + receive : function(el, ev){ + var event = ev.originalEvent; + var type = event.data.type; + if(event.origin !== 'https://' + EMBED_ENDPOINT){ + return; + } else { + if(this.options.handlers[type]){ + this.options.handlers[type](event.data.payload); + } + } + }, + send : function(type, payload){ + var frame = this.options.frame; + + frame = can.isFunction(frame) ? frame() : frame; + + frame = frame.contentWindow ? frame.contentWindow : frame; + + if(frame && frame.postMessage){ + try { + frame.postMessage({ + type: type, + payload: preparePayload(payload) + }, 'https://' + EMBED_ENDPOINT); + } catch (e) { + console.log( e ); + } + } + }, + '{window} message' : 'receive' +}); diff --git a/components/analytics/analytics.js b/components/analytics/analytics.js new file mode 100644 index 0000000..55bbfcb --- /dev/null +++ b/components/analytics/analytics.js @@ -0,0 +1,18 @@ +import can from "can/"; + +import initView from './analytics.stache!'; + +import "components/crawler_analytics/crawler_analytics"; +import "components/interaction_analytics/interaction_analytics"; +import "./analytics.less!"; + +can.Component.extend({ + tag: 'bh-analytics', + template: initView, + scope: { + tab : 'interaction', + switchTab : function(ctx, el){ + this.attr('tab', el.data('tab')); + } + } +}); diff --git a/components/analytics/analytics.less b/components/analytics/analytics.less new file mode 100644 index 0000000..a6f13bf --- /dev/null +++ b/components/analytics/analytics.less @@ -0,0 +1,6 @@ +bh-analytics { + .nav { + margin: 30px 0; + } + +} diff --git a/components/analytics/analytics.stache b/components/analytics/analytics.stache new file mode 100644 index 0000000..1d32a53 --- /dev/null +++ b/components/analytics/analytics.stache @@ -0,0 +1,19 @@ +{{#if state.hub}} +

{{ state.hub.name }} Analytics

+ + + + {{#eq tab 'interaction'}} + + {{/eq}} + {{#eq tab 'crawler'}} + + {{/eq}} +{{/if}} diff --git a/components/analytics/analytics_test.js b/components/analytics/analytics_test.js new file mode 100644 index 0000000..4518ac9 --- /dev/null +++ b/components/analytics/analytics_test.js @@ -0,0 +1,32 @@ +import "./analytics"; +import QUnit from "steal-qunit"; +import F from "funcunit"; +import $ from "jquery"; + +F.attach(QUnit); +var template = can.stache(""); + +var renderTemplate = function(data){ + $('#qunit-fixture').html(template(data)); +}; + +var State = can.Map.extend(); + +QUnit.module('Analytics Tests'); + +QUnit.test('Clicking on a tab will render a different component', function(){ + renderTemplate({ + state : new State({ + hub : { + name : 'Hub Name' + } + }) + }); + + F('bh-analytics h2').text('Hub Name Analytics', 'Title is rendered'); + F('li.active a[data-tab=interaction]').exists('Interaction analytics tab is active by default'); + F('bh-interaction-analytics').exists('Interaction analytics component is rendered'); + F('[data-tab=crawler]').click(); + F('li.active a[data-tab=crawler]').exists('Crawler analytics tab is activated'); + F('bh-crawler-analytics').exists('Crawler analytics component is rendered'); +}); diff --git a/components/components.js b/components/components.js new file mode 100644 index 0000000..59be535 --- /dev/null +++ b/components/components.js @@ -0,0 +1 @@ +steal('components/hub-list', 'components/payments', 'components/sidebar', 'components/suggestions', 'components/analytics', 'components/organization-settings', 'components/user-settings'); diff --git a/components/crawler_analytics/crawler_analytics.js b/components/crawler_analytics/crawler_analytics.js new file mode 100644 index 0000000..116b32a --- /dev/null +++ b/components/crawler_analytics/crawler_analytics.js @@ -0,0 +1,70 @@ +import can from "can/"; +import initView from "./crawler_analytics.stache!"; +import Chart from "chart.js/Chart"; +import Models from "models/"; + +import "./crawler_analytics.less!"; +import "components/service-config-formatter/"; + +can.Component.extend({ + tag : 'bh-crawler-analytics', + template: initView, + scope : { + resolution: 'hour', + init : function(){ + var self = this; + this.analyticsReq().then(function(analytics){ + self.attr('analytics', analytics); + }); + }, + analyticsReq : function(){ + var hubId = this.attr('state.hubId'); + return Models.Analytics.findAll({ + ownerId: hubId, + sourceType: 'services', + resolution: this.attr('resolution') + }); + }, + reloadAnalytics : function(){ + var self = this; + + this.analyticsReq().then(function(data){ + self.attr('analytics', data); + }); + } + }, + helpers : { + renderGraph : function(type){ + var self = this; + type = can.isFunction(type) ? type() : type; + return function(el){ + setTimeout(function(){ + var ctx = el.getContext('2d'); + new Chart(ctx).Line(self.attr('analytics').graphData(type), { + bezierCurveTension: 0.1, + pointDotRadius: 2, + datasetStrokeWidth: 2, + multiTooltipTemplate: "<%=datasetLabel%> - <%= value %> items", + }); + }, 4); + }; + }, + finalCount : function(timepoints){ + timepoints = can.isFunction(timepoints) ? timepoints() : timepoints; + return (timepoints[timepoints.length - 1] || {volume: '0'}).volume; + }, + hasEnoughData : function(opts){ + var analytics = this.attr('analytics'); + console.log(analytics.graphData('volume')); + if(analytics && analytics.graphData('volume').labels.length > 1){ + return opts.fn(); + } + return opts.inverse(); + } + }, + events : { + '{scope} resolution' : function(){ + this.scope.reloadAnalytics(); + } + } +}); diff --git a/components/crawler_analytics/crawler_analytics.less b/components/crawler_analytics/crawler_analytics.less new file mode 100644 index 0000000..fcd22ee --- /dev/null +++ b/components/crawler_analytics/crawler_analytics.less @@ -0,0 +1,36 @@ +bh-crawler-analytics { + display: block; + position: relative; + + select.form-control { + width: 200px; + margin-bottom: 30px; + } + + h2 { + margin-bottom: 20px; + border-bottom: 1px solid #eee; + padding-bottom: 20px; + } + li { + float: left; + margin-bottom: 5px; + width: 33.3333%; + span { + width: 15px; + height: 15px; + float: left; + margin: 2px 5px 0 0; + border-radius: 2px; + -webkit-border-radius: 2px; + -moz-border-radius: 2px; + } + bh-service-config-formatter { + float: left; + margin-right: 5px; + } + } + canvas { + display: block; + } +} diff --git a/components/crawler_analytics/crawler_analytics.stache b/components/crawler_analytics/crawler_analytics.stache new file mode 100644 index 0000000..bbb997e --- /dev/null +++ b/components/crawler_analytics/crawler_analytics.stache @@ -0,0 +1,26 @@ + +{{#if analytics}} +
    + {{#each analytics}} +
  • + + + ({{finalCount timepoints}} items) +
  • + {{/each}} +
+ {{#hasEnoughData}} +

Total amount of items

+ +
+

Amount of items crawled at time

+ + {{else}} +
We don't have enough data to plot the graph.
+ {{/hasEnoughData}} +{{/if}} diff --git a/components/delete_service_dialog/delete_service_dialog.js b/components/delete_service_dialog/delete_service_dialog.js new file mode 100644 index 0000000..f1c61db --- /dev/null +++ b/components/delete_service_dialog/delete_service_dialog.js @@ -0,0 +1,47 @@ +import can from "can/"; +import initView from "./delete_service_dialog.stache!"; +import "./delete_service_dialog.less!"; +import "can/construct/proxy/"; + +export var DeleteServiceDialogVM = can.Map.extend({ + isDeleting : false, + deleteService : function(){ + var service; + + if(this.attr('isDeleting')){ + return; + } + + service = this.attr('service'); + + this.attr('isDeleting', true); + service.destroy(); + }, + cancelDelete : function(){ + if(this.attr('isDeleting')){ + return; + } + this.clearService(); + }, + clearService : function(){ + this.attr('service', null); + }, + serviceDestroyed : function(){ + can.batch.start(); + this.attr('state').resetEmbed(); + this.attr('isDeleting', false); + this.clearService(); + can.batch.stop(); + } +}); + +can.Component.extend({ + tag: 'bh-delete-service-dialog', + template: initView, + scope : DeleteServiceDialogVM, + events : { + '{scope.service} destroyed' : function(){ + this.scope.serviceDestroyed(); + } + } +}); diff --git a/components/delete_service_dialog/delete_service_dialog.less b/components/delete_service_dialog/delete_service_dialog.less new file mode 100644 index 0000000..1df0406 --- /dev/null +++ b/components/delete_service_dialog/delete_service_dialog.less @@ -0,0 +1,22 @@ +bh-delete-service-dialog { + display: block; + + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: rgba(0,0,0,0.7); + .delete-service-panel { + width: 600px; + position: absolute; + top: 50%; + left: 50%; + margin-left: -300px; + margin-top: -82px; + } + .btn-group { + float: right; + } + +} \ No newline at end of file diff --git a/components/delete_service_dialog/delete_service_dialog.stache b/components/delete_service_dialog/delete_service_dialog.stache new file mode 100644 index 0000000..454ed20 --- /dev/null +++ b/components/delete_service_dialog/delete_service_dialog.stache @@ -0,0 +1,19 @@ +
+
+

Delete Service

+
+
+ Warning! This will delete all the items collected by the service! +
+ +
diff --git a/components/delete_service_dialog/delete_service_dialog_test.js b/components/delete_service_dialog/delete_service_dialog_test.js new file mode 100644 index 0000000..bc3d793 --- /dev/null +++ b/components/delete_service_dialog/delete_service_dialog_test.js @@ -0,0 +1,70 @@ +import {DeleteServiceDialogVM} from "./delete_service_dialog"; +import QUnit from "steal-qunit"; +import F from "funcunit"; +import $ from "jquery"; + +F.attach(QUnit); +var template = can.stache(""); + +var renderTemplate = function(data){ + $('#qunit-fixture').html(template(data)); +}; + +var Service = can.Model.extend({ + destroy : function(){ + ok(true, 'Destroy called'); + } +}); + +var State = can.Map.extend({ + resetEmbed : function(){ + ok(true, 'Reset Embed called'); + } +}); + +var service = new Service(); +QUnit.module("Delete Service Dialog Tests", { + setup() { + renderTemplate({ + service: service + }); + } +}); + +QUnit.test('Alert panel is rendered correctly', function(){ + F('bh-delete-service-dialog h3').text('Delete Service', 'Title is rendered'); + F('bh-delete-service-dialog button[disabled]').missing('Buttons are not disabled'); +}); + +QUnit.test('Clicking delete will destroy the service', 1, function(){ + F('bh-delete-service-dialog [can-click=deleteService]').click(); +}); + +QUnit.test('Clicking cancel will clear the service', function() { + F('bh-delete-service-dialog [can-click=cancelDelete]').click(); + F.wait(1, function() { + equal(can.viewModel($('bh-delete-service-dialog')).attr('service'), null, 'Service is cleared'); + }); +}); + +QUnit.test('Clicking delete will disable the buttons and show the spinner', function(){ + F('bh-delete-service-dialog [can-click=deleteService]').click(); + F('bh-delete-service-dialog button[can-click=cancelDelete][disabled]').exists('Cancel button is disabled'); + F('bh-delete-service-dialog button[can-click=deleteService][disabled]').exists('Delete service button is disabled'); + F('bh-delete-service-dialog .fa-circle-o-notch').exists('Spinner exists'); +}); + +var state = new State(); +QUnit.module("Service and state objects", { + setup() { + renderTemplate({ + service: service, + state: state + }); + } +}); + +QUnit.skip('Triggering destroy on service will clear the service from the VM', function(){ + service.destroyed(); + equal(can.viewModel($('bh-delete-service-dialog')).attr('service'), null, 'Service is cleared'); +}); diff --git a/components/edit_hub_name/edit_hub_name.js b/components/edit_hub_name/edit_hub_name.js new file mode 100644 index 0000000..4acc58f --- /dev/null +++ b/components/edit_hub_name/edit_hub_name.js @@ -0,0 +1,66 @@ +import can from "can/"; +import initView from "./edit_hub_name.stache!"; +import "./edit_hub_name.less!"; + +var KEYMAP = { + 13 : 'ENTER', + 27 : 'ESC' +}; + +export var EditHubNameVM = can.Map.extend({ + isEditing: false, + toggleHubEditing : function(val){ + val = (typeof val === 'undefined') ? !this.attr('isEditing') : val; + this.attr('isEditing', val); + }, + commitNewHubName : function(val){ + var hub = this.attr('hub'); + var name = hub.attr('name'); + if(name !== val){ + hub.attr('name', val); + hub.save(); + } + } +}); + +can.Component.extend({ + tag: 'bh-edit-hub-name', + template: initView, + scope: EditHubNameVM, + events : { + '{scope} isEditing' : function(scope, ev, newVal){ + var self = this; + if(newVal){ + setTimeout(function(){ + if(self.element){ + self.element.find('.hub-name').select().focus(); + } + }, 100); + } + }, + click : function(){ + this.scope.toggleHubEditing(); + }, + "input click" : function(el, ev){ + ev.stopImmediatePropagation(); + }, + "input keyup" : function(el, ev){ + var key = KEYMAP[ev.which]; + if(key === 'ENTER'){ + this.scope.commitNewHubName(el.val()); + } + if(key){ + this.__preventBlur = true; + this.scope.toggleHubEditing(); + } + }, + "input blur" : function(el, ev){ + if(this.__preventBlur){ + delete this.__preventBlur; + } else { + this.scope.commitNewHubName(el.val()); + this.scope.toggleHubEditing(); + } + } + } +}); diff --git a/components/edit_hub_name/edit_hub_name.less b/components/edit_hub_name/edit_hub_name.less new file mode 100644 index 0000000..8eb7dad --- /dev/null +++ b/components/edit_hub_name/edit_hub_name.less @@ -0,0 +1,3 @@ +bh-edit-hub-name { + display: block; +} diff --git a/components/edit_hub_name/edit_hub_name.stache b/components/edit_hub_name/edit_hub_name.stache new file mode 100644 index 0000000..5cf51c0 --- /dev/null +++ b/components/edit_hub_name/edit_hub_name.stache @@ -0,0 +1,10 @@ +
+ Hub Name + {{#if isEditing}} + + {{else}} +

{{ hub.name }}

+ + {{/if}} +
+ diff --git a/components/edit_hub_name/edit_hub_name_test.js b/components/edit_hub_name/edit_hub_name_test.js new file mode 100644 index 0000000..afe1d40 --- /dev/null +++ b/components/edit_hub_name/edit_hub_name_test.js @@ -0,0 +1,78 @@ +import {EditHubNameVM} from "./edit_hub_name"; +import QUnit from "steal-qunit"; +import F from "funcunit"; +import $ from "jquery"; + +F.attach(QUnit); +var template = can.stache(""); + +var Hub = can.Map.extend({ + save : function(){ + QUnit.ok(true, 'Save Called'); + } +}); + +var renderTemplate = function(data){ + $('#qunit-fixture').html(template(data)); +}; + +var renderTemplateAndCheckIfHubNameIsShown = function(){ + renderTemplate({ + hub : new Hub({name: 'Hub Name'}) + }); + F('bh-edit-hub-name h2').text('Hub Name', 'Hub Name is shown'); +}; + +var renderTemplateAndEnterEditingState = function(){ + renderTemplateAndCheckIfHubNameIsShown(); + F('bh-edit-hub-name').click(); +}; + +QUnit.module("Edit Hub Name Tests"); + +QUnit.test("Hub Name will be shown by default", function(){ + renderTemplateAndCheckIfHubNameIsShown(); +}); + +QUnit.test("Clicking on a component will toggle editing state", function(){ + renderTemplateAndEnterEditingState(); + F('bh-edit-hub-name input').exists('Input field is shown'); +}); + +QUnit.test("Pressing escape inside the input field will exit the editing state and revert the changes", 3, function(){ + renderTemplateAndEnterEditingState(); + F('bh-edit-hub-name input').click().type('aaa[escape]'); + F('bh-edit-hub-name input').missing('Exiting edit state'); + F('bh-edit-hub-name h2').text('Hub Name', 'Name is reverted'); +}); + +QUnit.skip("Pressing enter inside the input field will save changes and exit the editing state", 4, function(){ + renderTemplateAndEnterEditingState(); + F('bh-edit-hub-name input').click().type('[\b][\b]foo[enter]'); + F('bh-edit-hub-name input').missing('Exited edit state'); + F('bh-edit-hub-name h2').text('foo', 'Hub name is updated'); +}); + +QUnit.skip('Bluring the input field will save changes and exit the editing state', 4, function(){ + renderTemplateAndEnterEditingState(); + F('bh-edit-hub-name input').click().type('[\b][\b]foo'); + F('bh-edit-hub-name input').type('[\t][\t]'); + F('body').click(); + F('bh-edit-hub-name input').missing('Exited edit state'); + F('bh-edit-hub-name h2').text('foo', 'Hub name is updated'); +}); + +QUnit.test('Committing the same name will not trigger save', 0, function(){ + var editVM = new EditHubNameVM({hub: new Hub({name: 'Hub Name'})}); + editVM.commitNewHubName('Hub Name'); +}); + +QUnit.test('Toggling edit state works', function(){ + var editVM = new EditHubNameVM({hub: new Hub({name: 'Hub Name'})}); + editVM.toggleHubEditing(); + ok(editVM.attr('isEditing'), 'Editing State'); + editVM.toggleHubEditing(); + ok(!editVM.attr('isEditing'), 'Exited editing state'); + editVM.toggleHubEditing(false); + ok(!editVM.attr('isEditing'), 'Did not enter editing state'); +}); diff --git a/components/embed_publish/embed_publish.js b/components/embed_publish/embed_publish.js new file mode 100644 index 0000000..d196e2f --- /dev/null +++ b/components/embed_publish/embed_publish.js @@ -0,0 +1,152 @@ +/* globals Stripe:true */ +/* globals confirm:true */ +import can from "can/"; +import initView from "./embed_publish.stache!"; + +import Preset from "models/preset"; +import $ from "jquery"; +import _some from "lodash-amd/modern/collection/some"; + +import "./embed_publish.less!"; +import "components/integration/"; +import "jquery.payment/lib/jquery.payment"; +import "can/map/define/"; + +var CC = can.Map.extend({ + parsedExpiration(){ + return $.payment.cardExpiryVal(this.expiration || ""); + }, + month(){ + return this.parsedExpiration().month; + }, + year(){ + return this.parsedExpiration().year; + }, + numberNumberWithoutSpaces(){ + return (this.number || "").replace(/[^0-9]/g, ""); + } +}); + +var EmbedPublishVM = can.Map.extend({ + isSaving: false, + init(){ + this.attr({ + cc : new CC(), + errors : null + }); + }, + showCCForm(){ + return !this.attr('state.currentSubscription').hasCC() || this.attr('changeCC'); + }, + validate(){ + var cc = this.attr('cc'); + var expiration = $.payment.cardExpiryVal(cc.expiration || ""); + var errors = {}; + var cardType = $.payment.cardType(cc.number || ""); + + errors.number = !$.payment.validateCardNumber(cc.number || ""); + errors.expiration = !$.payment.validateCardExpiry(expiration.month, expiration.year); + errors.cvc = !$.payment.validateCardCVC(cc.cvc || "", cardType); + + this.attr('errors', errors); + return !_some(errors, function(val){ + return val; + }); + }, + createSubscriptionAndPublishHub(){ + var self = this; + var cc; + if(this.validate()){ + this.attr('isSaving', true); + cc = this.attr('cc'); + Stripe.card.createToken({ + number: cc.numberNumberWithoutSpaces(), + cvc: cc.cvc, + exp_month: cc.month(), + exp_year: cc.year() + }, function(res, obj){ + + $.post('/subscriptions/update', {stripe_token: obj.id}).then(function(){ + self.attr('state.hub').publish().then(function(){ + self.attr('isSaving', false); + self.attr('state.currentSubscription').reload(); + }); + }); + }); + } + }, + removeCCUpdatedNotice : function(){ + this.attr('showCCUpdatedNotice', false); + }, + updateCC : function(){ + var self = this; + var cc; + if(this.validate()){ + this.attr('isUpdatingCC', true); + cc = this.attr('cc'); + Stripe.card.createToken({ + number: cc.numberNumberWithoutSpaces(), + cvc: cc.cvc, + exp_month: cc.month(), + exp_year: cc.year() + }, function(res, obj){ + $.post('/subscriptions/update', {stripe_token: obj.id}).then(function(){ + self.attr({ + isUpdatingCC: false, + changeCC: false, + showCCUpdatedNotice: true + }); + self.attr('state.currentSubscription').reload(); + }); + }); + } + }, + publishHub : function(){ + var self = this; + this.attr('isSaving', true); + this.attr('state.hub').publish().then(function(){ + self.attr('isSaving', false); + }); + }, + unpublishHub : function(){ + var self = this; + if(confirm("Are you sure you want to unpublish this hub?")){ + + this.attr('isSaving', true); + this.attr('state.hub').unpublish().then(function(){ + self.attr('isSaving', false); + }); + } + }, + embedUrl(){ + var state = this.attr('state'); + var currentBrand = state.attr('currentBrand'); + var hub = state.attr('hub'); + var preset = Preset.PREVIEW; + + return preset.fullUrl(currentBrand.attr('tenant_name'), hub.attr('id')); + }, + toggleChangeCC(){ + var newState = !this.attr('changeCC'); + can.batch.start(); + if(newState){ + this.attr('cc', new CC()); + } + this.attr('changeCC', newState); + can.batch.stop(); + } +}); + +can.Component.extend({ + tag : "bh-embed-publish", + template : initView, + scope : EmbedPublishVM, + helpers : { + formatCC(format){ + format = can.isFunction(format) ? format() : format; + return function(el){ + $(el).payment('format' + format); + }; + } + } +}); diff --git a/components/embed_publish/embed_publish.less b/components/embed_publish/embed_publish.less new file mode 100644 index 0000000..ac9327b --- /dev/null +++ b/components/embed_publish/embed_publish.less @@ -0,0 +1,94 @@ +bh-embed-publish { + display: block; + padding: 15px 0; + .alert a { + font-size: 90%; + } + .expiration-cvc-wrap { + .form-group { + width: 50%; + float: left; + &:first-child { + padding-right: 15px; + } + &:last-child { + padding-left: 15px; + } + } + } + .panel-title { + font-weight: bold; + } + .button-wrap { + button { + float: right; + } + } + .cc-input, .cc-info { + background-position: -2px 50%; + background-repeat: no-repeat; + height: 42px; + } + + .cc-info { + border: 1px solid #ddd; + border-radius: 3px; + line-height: 40px; + font-weight: bold; + background-color: #f6f6f6; + padding-left: 10px; + } + + .published-hub-title { + margin: -15px -30px 0; + background: #e4e3e3; + border-bottom: 1px solid #ccc; + padding: 15px 30px; + } + + .maestro, .mastercard, .forbrugsforeningen, .dankort, .visaelectron, .visa, .dinersclub, .discover, .jcb, .amex { + padding-left: 80px; + } + .maestro { + background-image: url(/images/cc/maestro.png); + } + .mastercard { + background-image: url(/images/cc/mastercard.png); + } + .forbrugsforeningen { + background-image: url(/images/cc/forbrugsforeningen.png); + } + .dankort { + background-image: url(/images/cc/dankort.png); + } + .visaelectron { + background-image: url(/images/cc/visaelectron.png); + } + .visa { + background-image: url(/images/cc/visa.png); + } + .amex { + background-image: url(/images/cc/amex.png); + } + .dinersclub { + background-image: url(/images/cc/dinersclub.png); + } + .discover { + background-image: url(/images/cc/discover.png); + } + .jcb { + background-image: url(/images/cc/jcb.png); + } + .change-cc-info { + display: block; + margin-top: 10px; + } + .unpublish-wrap { + margin: -20px -30px; + border-top: 1px solid #ccc; + padding: 20px 30px 0; + } + .panel-change-cc, .alert-cc-updated { + margin-top: 30px; + } +} diff --git a/components/embed_publish/embed_publish.stache b/components/embed_publish/embed_publish.stache new file mode 100644 index 0000000..75d5017 --- /dev/null +++ b/components/embed_publish/embed_publish.stache @@ -0,0 +1,130 @@ +{{#if state.hub.published}} +

This is a published and public hub

+ +
+

Unpublish Hub

+

When you unpublish the hub, the embed code will be deactivated and any embedded BitHub feeds will no longer be visible on your webpage.

+

You will not be charged for unpublished hubs.

+ + + {{#if showCCForm}} +
+
+
Credit Card Info
+
+

Currently we have the following credit card on file:

+
+ {{state.currentSubscription.card.type}} **** **** **** {{state.currentSubscription.card.last4}}, Expiration {{state.currentSubscription.card.exp_month}}/{{state.currentSubscription.card.exp_year}} +
+
+

Please enter your new credit card info.

+
+ + + {{#if errors.number}} + Wrong Credit Card number + {{/if}} +
+
+
+ + + {{#if errors.expiration}} + Wrong expiration date + {{/if}} +
+
+ + + {{#if errors.cvc}} + Wrong CVC number + {{/if}} +
+
+
+ + Cancel +
+
+ {{/if}} + {{#if showCCUpdatedNotice}} +
+ + Your Credit Card information was updated! +
+ {{/if}} +
+ +{{else}} +

This hub is unpublished

+

Unpublished hub can't be embedded in the site.

+

This hub is publicly available at the following link: {{embedUrl}}

+

After the hub is published you will immediately be presented with the embed code that can be placed on your site.

+ +
+ Public hubs are charged $7 per month. Read more about our pricing here » +
+ +
+
+

Credit Card Info

+
+
+ {{#unless showCCForm}} +

The following credit card will be charged:

+
+ {{state.currentSubscription.card.type}} **** **** **** {{state.currentSubscription.card.last4}}, Expiration {{state.currentSubscription.card.exp_month}}/{{state.currentSubscription.card.exp_year}} +
+ Change Credit Card info +{{else}} +

Please enter your credit card info to publish this hub.

+
+ + + {{#if errors.number}} + Wrong Credit Card number + {{/if}} +
+
+
+ + + {{#if errors.expiration}} + Wrong expiration date + {{/if}} +
+
+ + + {{#if errors.cvc}} + Wrong CVC number + {{/if}} +
+
+ {{#if changeCC}} + Cancel + {{/if}} +{{/if}} +
+
+

By clicking "Publish" you authorize us to automatically charge your credit card at the end of each month. You will be charged $7.00 per month for each published feed. If you publish the feed for less than a month, you will only be charged for the time the feed is published. For additional information, please visit Billing located under Support.

+
+ {{#if showCCForm}} + + {{else}} + + {{/if}} +
+ + +{{/if}} + diff --git a/components/helpers.js b/components/helpers.js new file mode 100644 index 0000000..27b5499 --- /dev/null +++ b/components/helpers.js @@ -0,0 +1,39 @@ +steal( +'can/view/stache', +'lodash-amd/modern/collection/reduce.js', +function(stache, _reduce){ + + var getHash = function(optsHash){ + return _reduce(optsHash || {}, function(acc, val, key){ + acc[key] = can.isFunction(val) ? val() : val; + return acc; + }, {}); + }; + + stache.registerHelper('pageUrl', function(page, opts){ + var hash = getHash(opts.hash); + hash.page = can.isFunction(page) ? page() : page; + return can.route.url(hash, false); + }); + + stache.registerHelper('configErrors', function(errors, key, opts){ + var res; + + errors = can.isFunction(errors) ? errors() : errors; + key = can.isFunction(key) ? key() : key; + + if(errors){ + errors = errors.attr(key) || []; + + if(!errors.length) return; + + res = ['
    ']; + for(var i = 0; i < errors.length; i++){ + res.push('
  • ' + errors[i] + '
  • '); + } + res.push('
'); + return res.join(''); + } + }); + +}) diff --git a/components/hub-list/hub-list-tests.js b/components/hub-list/hub-list-tests.js new file mode 100644 index 0000000..9e8223b --- /dev/null +++ b/components/hub-list/hub-list-tests.js @@ -0,0 +1,37 @@ +import "./hub-list"; +import can from "can/"; +import QUnit from "steal-qunit"; +import F from "funcunit"; +import $ from "jquery"; +import fixture from "can/util/fixture/"; + +F.attach(QUnit); +var template = can.stache(""); + +var renderTemplate = function(data){ + $('#qunit-fixture').html(template(data)); +}; + +QUnit.module('Hub List', { + beforeEach : function(){ + fixture('/api/v3/embeds', "./fixtures/embeds.json"); + fixture('/api/v3/services', "./fixtures/services.json"); + fixture.on = true; + fixture.delay = 100; + }, + afterEach : function(){ + fixture('/api/v3/embeds', null); + fixture('/api/v3/services', null); + fixture.on = false; + + } +}); + +QUnit.test('Hub List', 1, function(assert){ + renderTemplate({ + state: new can.Map() + }); + F('bh-hub-list').exists(); + F('bh-hub-list [can-click=toggleExpandedRow]').exists().click(); + F('bh-hub-list .expanded-services').exists('Expand button exists'); +}); diff --git a/components/hub-list/hub-list.html b/components/hub-list/hub-list.html new file mode 100644 index 0000000..8e09d41 --- /dev/null +++ b/components/hub-list/hub-list.html @@ -0,0 +1,23 @@ + + + +
+
+
+
+
+ + + + + \ No newline at end of file diff --git a/components/hub-list/hub-list.js b/components/hub-list/hub-list.js new file mode 100644 index 0000000..c316a76 --- /dev/null +++ b/components/hub-list/hub-list.js @@ -0,0 +1,92 @@ +/* global confirm:true */ + +import can from "can/"; +import initView from "./hub-list.stache!"; +import Models from "models/"; +import _map from "lodash-amd/modern/collection/map"; +import _reduce from "lodash-amd/modern/collection/reduce"; + +import "style/"; +import "./hub-list.less!"; +import "can/map/define/"; +import "components/service-config-formatter/"; + + +can.Component.extend({ + tag : 'bh-hub-list', + template : initView, + scope : { + define : { + expandedRows : { + Value : Array + } + }, + init : function(){ + this.attr('hubs', new Models.Hub.List({})); + }, + createAndEditHub : function(){ + new Models.Hub({ + name: '' + }).save(function(hub){ + can.route.attr({ + hubId : hub.id, + page : 'sidebar', + panel : 'services' + }); + }); + }, + destroyHub : function(hub){ + if(confirm('Are you sure?')){ + hub.destroy(); + } + }, + toggleExpandedRow : function(hub){ + var hubId = hub.attr('id'), + expandedRows = this.attr('expandedRows'), + index = expandedRows.indexOf(hubId); + + if(index === -1){ + expandedRows.push(hubId); + } else { + expandedRows.splice(index, 1); + } + } + }, + helpers : { + isExpandedRow : function(hub, opts){ + var index; + + hub = can.isFunction(hub) ? hub() : hub; + index = this.attr('expandedRows').indexOf(hub.attr('id')); + + return index > -1 ? opts.fn() : opts.inverse(); + }, + formatConnectedServices : function(services){ + var serviceNames; + services = can.isFunction(services) ? services() : services; + + if(!services || services.isPending()){ + return; + } + + serviceNames = can.map(services, function(service){ + return service.printFeed(); + }); + + return _map(_reduce(serviceNames, function(acc, service){ + if(acc[service]){ + acc[service] += 1; + } else { + acc[service] = 1; + } + return acc; + }, {}), function(occurenceCount, service){ + if(occurenceCount > 1){ + return service + ' (' + occurenceCount + ')'; + } + return service; + }).join(', '); + } + } +}); + diff --git a/components/hub-list/hub-list.less b/components/hub-list/hub-list.less new file mode 100644 index 0000000..c3203b5 --- /dev/null +++ b/components/hub-list/hub-list.less @@ -0,0 +1,34 @@ +@import "../../node_modules/bootstrap/less/mixins/clearfix.less"; + +bh-hub-list { + display: block; + .actions { + width: 200px; + } + .btn-add-hub { + float: right; + margin-top: -45px; + } + td.name { + width: 30%; + font-size: 120%; + } + bh-edit-hub-name { + .clearfix; + margin-top: 0px; + margin-bottom: 15px; + width: 66%; + h2, i { + float: left; + margin: 0; + } + i { + margin: 12px 5px 0; + } + b { + display: none; + } + + + } +} diff --git a/components/hub-list/hub-list.stache b/components/hub-list/hub-list.stache new file mode 100644 index 0000000..5582738 --- /dev/null +++ b/components/hub-list/hub-list.stache @@ -0,0 +1,63 @@ + +{{#if hubs.isPending}} +
Loading...
+{{else}} + {{#if hubs.length}} + {{#ifCanAddHub hubs}} + + {{/ifCanAddHub}} + + + + + + + + + + {{#hubs}} + + + + + + {{/hubs}} + +
NameConnected Services
+ {{ name }} + + {{#if services.isPending}} + Loading... + {{else}} + {{#if services.length}} + {{#isExpandedRow this}} +
+ +
    + {{#each services}} +
  • + +
  • + {{/each}} +
+ +
+ {{/else}} + + {{formatConnectedServices services}} + {{/isExpandedRow}} + {{else}} + No connected services. + {{/if}} + {{/if}} +
+
+ Edit + Analytics + +
+
+ {{else}} +
You haven't created any hubs yet. Create your first Hub »
+ {{/if}} +{{/if}} diff --git a/components/integration/integration.js b/components/integration/integration.js new file mode 100644 index 0000000..d0481db --- /dev/null +++ b/components/integration/integration.js @@ -0,0 +1,152 @@ +/* globals confirm:true */ +import can from "can/"; +import initView from "./integration.stache!"; +import Models from "models/"; + +import "./integration.less!"; +import "components/preset-form/"; +import "can/map/define/"; +import "can/construct/proxy/"; + +can.Component.extend({ + tag: 'bh-integration', + template: initView, + scope: { + init : function(){ + this.attr('presets', new Models.Preset.List({embed_id : this.attr('state.hub.id')})); + }, + integrationCodeForPreset : function(preset){ + var currentBrand = this.attr('state.currentBrand'); + var hub = this.attr('state.hub'); + if(currentBrand && hub && preset){ + + return preset.embedCode( + currentBrand.attr('tenant_name'), + hub.attr('id'), + hub.attr('name') + ); + } + }, + defaultPresetUrl : function(){ + return this.urlForPreset(Models.Preset.PREVIEW); + }, + currentPresetUrl : function(){ + return this.urlForPreset(this.currentPreset()); + }, + urlForPreset : function(preset){ + var currentBrand = this.attr('state.currentBrand'); + var hub = this.attr('state.hub'); + + if(!preset){ + return; + } + return preset.fullUrl(currentBrand.attr('tenant_name'), hub.attr('id')); + }, + defaultIntegrationCode : function(){ + return this.integrationCodeForPreset(Models.Preset.PREVIEW); + }, + currentPresetIntegrationCode : function(){ + return this.integrationCodeForPreset(this.currentPreset()); + }, + addPreset : function(){ + can.batch.start(); + this.attr('state.customPreset', new Models.Preset({ + embed_id : this.attr('state.hub.id') + })); + this.attr('isEditing', false); + can.batch.stop(); + }, + customPresetExistsAndIsNew : function(){ + var customPreset = this.currentPreset(); + return customPreset && customPreset.isNew(); + }, + currentPreset : function(){ + return this.attr('state').attr('customPreset'); + }, + toggleCurrentPreset : function(preset){ + var currentPreset = this.currentPreset(); + if(currentPreset === preset){ + this.attr('state.customPreset', null); + } else { + this.attr('state.customPreset', preset); + } + }, + isDefaultPresetOpen : function(){ + return !this.currentPreset(); + }, + clearPreset : function(forceClear){ + var currentPreset = this.currentPreset(); + can.batch.start(); + if(forceClear || currentPreset.isNew()){ + this.attr('state.customPreset', null); + } + this.attr('isEditing', false); + can.batch.stop(); + }, + editPreset : function(preset){ + can.batch.start(); + this.attr('state.customPreset', preset); + this.attr('isEditing', true); + can.batch.stop(); + }, + destroyPreset : function(preset){ + var self = this; + if(confirm('Are you sure?')){ + preset.destroy().then(function(){ + self.clearPreset(true); + }); + } + } + }, + helpers : { + isCurrentPreset : function(preset, opts){ + var currentPreset = this.currentPreset(); + preset = can.isFunction(preset) ? preset() : preset; + + return preset === currentPreset ? opts.fn() : opts.inverse(); + }, + ifCurrentlyEditingPreset : function(preset, opts){ + var currentPreset = this.currentPreset(); + var isEditing = this.attr('isEditing'); + var check; + + preset = can.isFunction(preset) ? preset() : preset; + check = preset === currentPreset && isEditing; + + return check ? opts.fn() : opts.inverse(); + } + }, + events : { + " savePreset" : function(el, ev){ + var self = this; + this.scope.currentPreset().save(function(preset){ + can.batch.start(); + var presets = self.scope.attr('presets'); + var index = presets.indexOf(preset); + if(index === -1){ + presets.unshift(preset); + } + self.scope.attr('isEditing', false); + can.batch.stop(); + }); + }, + 'textarea mousedown' : 'selectCode', + 'textarea focus' : function(el, ev){ + el.select(); + setTimeout(function(){ + el.select(); + }, 1); + }, + selectCode : function(el, ev){ + ev.preventDefault(); + if(el.is(':focus')){ + ev.stopPropagation(); + ev.stopImmediatePropagation(); + } + el.select(); + }, + 'bh-preset-form clearPreset' : function(){ + this.scope.clearPreset(); + } + } +}); diff --git a/components/integration/integration.less b/components/integration/integration.less new file mode 100644 index 0000000..5a58a4d --- /dev/null +++ b/components/integration/integration.less @@ -0,0 +1,74 @@ +bh-integration { + display: block; + .content-section { + padding-top: 10px; + padding-bottom: 25px; + } + .embed-code, .embed-code[readonly] { + height: 100px; + font-family: Monaco, Consolas, monospace; + font-size: 12px; + background: white; + cursor: text; + margin-bottom: 10px; + } + .btn-add-preset { + margin-top: 10px; + float: right; + } + .new-preset-form { + margin: 25px 0; + } + .list-wrapper { + margin: 0 -25px; + .destroy-preset, .edit-preset { + cursor: pointer; + color: #666; + &:hover { + color: #333; + } + } + table.table { + border-top: 2px solid #ccc; + margin-top: 0; + p.instructions { + font-size: 90%; + font-style: oblique; + } + > tbody > tr, > thead > tr { + &.expanded td { + background: #e9e9e9; + } + th.expand { + width: 50px; + } + td.expand { + cursor: pointer; + .fa { + color: #666; + } + &:hover .fa { + color: #000; + } + } + th:first-child, td:first-child { + padding-left: 25px; + } + th:last-child, td:last-child { + padding-right: 25px; + } + th.actions { + width: 70px; + } + td.actions .fa { + display: inline-block; + margin-top: 3px; + } + .preset-embed-code { + border-top: none; + } + } + } + + } +} diff --git a/components/integration/integration.stache b/components/integration/integration.stache new file mode 100644 index 0000000..4c912ca --- /dev/null +++ b/components/integration/integration.stache @@ -0,0 +1,63 @@ +

+ Embed Presets + +

+{{#if customPresetExistsAndIsNew}} + +{{/if}} + +
+ + + + + + + + + + + + + {{#if isDefaultPresetOpen}} + + + + {{/if}} + {{#each presets}} + {{^ifCurrentlyEditingPreset this}} + + + + + {{/ifCurrentlyEditingPreset}} + {{#isCurrentPreset this}} + + + + {{/isCurrentPreset}} + {{/each}} + +
Preset Name
+ + Default Preset +
+ +

Paste this code in the HTML source of your page

+

You can access the embed directly by going to: {{ defaultPresetUrl}}

+
+ + {{ name }} + + + +
+ {{#ifCurrentlyEditingPreset this}} + + {{ else }} + +

Paste this code in the HTML source of your page

+

You can access the embed directly by going to: {{ currentPresetUrl}}

+ {{/ifCurrentlyEditingPreset}} +
+
diff --git a/components/integration/integration_test.js b/components/integration/integration_test.js new file mode 100644 index 0000000..cad7170 --- /dev/null +++ b/components/integration/integration_test.js @@ -0,0 +1,93 @@ +import "./integration"; +import QUnit from "steal-qunit"; +import F from "funcunit"; +import $ from "jquery"; +import fixture from "can/util/fixture/"; + +F.attach(QUnit); +var template = can.stache(""); + +var renderTemplate = function(data){ + $('#qunit-fixture').html(template(data)); +}; + +var presetData = { + "config": { + "theme": "dark", + "live": true + }, + "name": "Dark Preset", + "id": 1 +}; + +var State = can.Map.extend({}); + +window.EMBED_ENDPOINT = 'http://bithub.loc'; + +QUnit.module("Integration test",{ + beforeEach : function(){ + fixture.on = true; + fixture.delay = 1000; + fixture("GET /api/v3/presets", function(){ + return [presetData]; + }); + fixture("DELETE /api/v3/presets/{id}", function(){ + return {}; + }); + fixture("PUT /api/v3/presets/{id}", function(req){ + return req.data; + }); + fixture("POST /api/v3/presets", function(req){ + var data = req.data; + data.id = Date.now(); + return data; + }); + renderTemplate({ + state : new State({ + currentBrand : { + tenant_name: 'foo' + }, + hub : { + id : 1 + } + }) + }); + }, + afterEach : function(){ + fixture.on = false; + fixture.delay = 100; + fixture("GET /api/v3/presets", null); + fixture("DELETE /api/v3/presets/{id}", null); + } +}); + +QUnit.skip("Integration rendering", function(){ + F('bh-integration').exists('Integration is rendered'); + F('bh-integration tbody tr').size(3, 'Default and loaded presets are rendered'); + F('bh-integration tbody tr:nth-child(2) textarea').exists('Default preset is expanded'); +}); + +QUnit.skip("Integration - expanding and editing a preset", function(){ + F('bh-integration [can-click=toggleCurrentPreset]:last').click(); + F('bh-integration tr:last textarea').exists('Loaded preset is expanded'); + F('bh-integration [can-click=editPreset]:last').click(); + F('bh-integration bh-preset-form').exists('Preset form is open'); + F('bh-integration bh-preset-form .clear-preset').click(); + F('bh-integration bh-preset-form').missing('Preset form is removed'); +}); + +QUnit.skip('Deleting a preset', function(){ + F('bh-integration [can-click=destroyPreset]:last').click(); + F.confirm(true); + F('bh-integration tbody tr').size(2, 'Preset is destroyed'); +}); + +QUnit.skip('Preset can be created', function(){ + F('bh-integration [can-click=addPreset]').click(); + F('bh-integration bh-preset-form').exists('New preset form is rendered'); + F('bh-integration bh-preset-form [can-value="preset.name"]').type('Foo'); + F('bh-integration bh-preset-form .save-service').click(); + F('bh-integration bh-preset-form .fa-circle-o-notch').exists('Preset is saving'); + F('bh-integration bh-preset-form').missing('Form is closed'); + F('bh-integration tbody tr').size(4, 'Preset is added to the list'); +}); diff --git a/components/interaction_analytics/interaction_analytics.js b/components/interaction_analytics/interaction_analytics.js new file mode 100644 index 0000000..5430741 --- /dev/null +++ b/components/interaction_analytics/interaction_analytics.js @@ -0,0 +1,79 @@ +import can from "can/"; +import initView from "./interaction_analytics.stache!"; +import InteractionEvent from "models/interaction_event"; +import Chart from "chart.js/Chart"; +import "./interaction_analytics.less!"; + +export var InteractionAnalyticsVM = can.Map.extend({ + init : function(){ + this.loadInteractionsData(); + }, + loadInteractionsData : function(){ + var self = this; + InteractionEvent.findAll({event_type: 'share', zoom: 'rough', primary_source_id: this.attr('state.hubId')}).then(function(data){ + self.attr('totalShareInteractions', data); + }); + InteractionEvent.findAll({event_type: 'share', primary_source_id: this.attr('state.hubId')}).then(function(data){ + self.attr('perNetworkShareInteractions', data); + }); + InteractionEvent.findAll({event_type: 'link', primary_source_id: this.attr('state.hubId')}).then(function(data){ + self.attr('linkInteractions', data); + }); + InteractionEvent.findAll({event_type: 'scroll', primary_source_id: this.attr('state.hubId')}).then(function(data){ + self.attr('scrollInteractions', data); + }); + }, + hasAnyInteractionAnalytics : function(){ + var totalShareInteractions = this.attr('totalShareInteractions'); + var perNetworkShareInteractions = this.attr('perNetworkShareInteractions'); + var linkInteractions = this.attr('linkInteractions'); + var scrollInteractions = this.attr('scrollInteractions'); + + if(totalShareInteractions && totalShareInteractions.length){ + return true; + } + + if(perNetworkShareInteractions && perNetworkShareInteractions.length){ + return true; + } + + if(linkInteractions && linkInteractions.length){ + return true; + } + + if(scrollInteractions && scrollInteractions.length){ + return true; + } + + return false; + } +}); + +can.Component.extend({ + tag : 'bh-interaction-analytics', + template: initView, + scope: InteractionAnalyticsVM, + helpers : { + renderGraph : function(type){ + var self = this; + var fnName; + type = can.isFunction(type) ? type() : type; + fnName = type + 'GraphData'; + return function(el){ + setTimeout(function(){ + var ctx = el.getContext('2d'); + var data = self.attr(type)[fnName](); + if (!data.labels.length) { + return; + } + new Chart(ctx).Line(data, { + bezierCurveTension : 0.1, + pointDotRadius: 2, + datasetStrokeWidth: 2, + multiTooltipTemplate: "<%=datasetLabel%> - <%= value %>" + }); + }, 4); + }; + } + } +}); diff --git a/components/interaction_analytics/interaction_analytics.less b/components/interaction_analytics/interaction_analytics.less new file mode 100644 index 0000000..c479414 --- /dev/null +++ b/components/interaction_analytics/interaction_analytics.less @@ -0,0 +1,7 @@ +bh-interaction-analytics { + display: block; + margin-bottom: 30px; + canvas { + display: block; + } +} diff --git a/components/interaction_analytics/interaction_analytics.stache b/components/interaction_analytics/interaction_analytics.stache new file mode 100644 index 0000000..5cb849c --- /dev/null +++ b/components/interaction_analytics/interaction_analytics.stache @@ -0,0 +1,23 @@ +{{#if totalShareInteractions.length}} +

Total amount of shares

+ +{{/if}} + +{{#if perNetworkShareInteractions.length}} +

Share amount per network

+ +{{/if}} + +{{#if linkInteractions.length}} +

Link clicks

+ +{{/if}} + +{{#if scrollInteractions.length}} +

Scrolls

+ +{{/if}} + +{{#unless hasAnyInteractionAnalytics}} +
We don't have enough data to plot the interactions graph.
+{{/unless}} diff --git a/components/moderation-rules/moderation-rules-test.js b/components/moderation-rules/moderation-rules-test.js new file mode 100644 index 0000000..612cfed --- /dev/null +++ b/components/moderation-rules/moderation-rules-test.js @@ -0,0 +1,125 @@ +import "./moderation-rules"; +import QUnit from "steal-qunit"; +import F from "funcunit"; +import $ from "jquery"; +import Models from "models/"; + +F.attach(QUnit); +var template = can.stache(""); + +var filterData = { + "natlang_queries": [ + { + "is_negated": false, + "val": "foober", + "op": "contains_all", + "attr_name": "content", + "id": 10001 + } + ], + "embed_id": 10001, + "action": "block", + "id": 10001 +}; + +var Hub = can.Map.extend({}); + +var renderTemplate = function(data){ + $('#qunit-fixture').html(template(data)); +}; + +var renderTemplateAndCheckForFilters = function(){ + var filters = new Models.Filter.List([ + new Models.Filter(filterData) + ]); + var hub = new Hub({id : 10001}); + + renderTemplate({ + filters: filters, + hub: hub + }); + + F('bh-moderation-rules').exists('Moderation rules are rendered'); + F('bh-moderation-rules .filter-wrap').size(1, 'Filter is rendered'); +}; + + +QUnit.module('Moderation rules test'); + +QUnit.test('Filters are rendered', function(){ + renderTemplateAndCheckForFilters(); +}); + +QUnit.test('Filters can be added', function(){ + renderTemplateAndCheckForFilters(); + F('bh-moderation-rules [can-click=addFilter]').click(); + F('bh-moderation-rules .filter-wrap').size(2, 'Filter is added'); +}); + +QUnit.test('Filters can be removed', function(){ + var filters = new Models.Filter.List([ + new Models.Filter(filterData) + ]); + var hub = new Hub({id : 10001}); + + renderTemplate({ + filters: filters, + hub: hub + }); + + F('bh-moderation-rules [can-click=markToDestroy]').click(); + F('bh-moderation-rules .filter-wrap').size(0, 'Filter is removed'); + F.wait(1, function(){ + ok(filters[0].__shouldDelete, 'Filter is marked for deletion'); + }); +}); + +QUnit.test('Input fields', function(){ + var filters = new Models.Filter.List([ + new Models.Filter(filterData) + ]); + var hub = new Hub({id : 1}); + + renderTemplate({ + filters: filters, + hub: hub + }); + + F('bh-moderation-rules textarea[can-value=val]').exists('Textarea is rendered'); + + F.wait(1, function(){ + filters.attr('0.natlang_queries.0.op', 'is'); + F('bh-moderation-rules input[can-value=val]').exists('Input field is rendered'); + + }); + + F.wait(1, function(){ + filters.attr('0.natlang_queries.0.op', 'contains_phrase'); + F('bh-moderation-rules input[can-value=val]').exists('Input field is rendered'); + }); + + F.wait(1, function(){ + filters.attr('0.natlang_queries.0.attr_name', 'feed_name'); + F('bh-moderation-rules select[can-value=val]').exists('Select field is rendered'); + }); + +}); + +QUnit.skip('Available Verbs', function(){ + var filters = new Models.Filter.List([ + new Models.Filter(filterData) + ]); + var hub = new Hub({id : 10001}); + + renderTemplate({ + filters: filters, + hub: hub + }); + + F('bh-moderation-rules select[can-value=operation] option').size(9, 'All verbs are available'); + + F.wait(1, function(){ + filters.attr('0.natlang_queries.0.attr_name', 'feed_name'); + F('bh-moderation-rules select[can-value=operation] option').size(2, 'For feeds, only 2 verbs are available'); + }); +}); diff --git a/components/moderation-rules/moderation-rules.js b/components/moderation-rules/moderation-rules.js new file mode 100644 index 0000000..d724227 --- /dev/null +++ b/components/moderation-rules/moderation-rules.js @@ -0,0 +1,100 @@ +import can from "can/"; +import initView from "./moderation-rules.stache!"; +import Models from "models/"; +import "./moderation-rules.less!"; + +var TITLES = { + approve : "Automatically approve items matching the following rules:", + block : "Automatically block items matching the following rules" +}; + +var VERBS = { + "pos:contains_all" : "Contains all words", + "pos:contains_any" : "Contains any", + "pos:contains_phrase" : "Contains a phrase", + "pos:is" : "Is equal to", + "neg:is" : "Isn't equal to", + "pos:starts_with" : "Starts with", + "neg:starts_with" : "Doesn't start with", + "pos:ends_with" : "Ends with", + "neg:ends_with" : "Doesn't end with" +}; + +var FILTERS = { + content : "Content", + title : "Title", + author : "Author", + feed_name : "Feed" +}; + +var FILTER_VERBS = { + feed_name : ['pos:is', 'neg:is'] +}; + +can.Component.extend({ + tag : 'bh-moderation-rules', + template : initView, + scope: { + addFilter : function(){ + this.attr('filters').addFilter(this.attr('hub.id')); + }, + title : function(){ + return TITLES[this.attr('filters.action')]; + }, + availableFilters : FILTERS, + filtersNotMarkedForDelete : function(){ + var filters = this.attr('filters'); + filters.attr('length'); + return can.grep(filters, function(f){ + return !f.attr('__shouldDelete'); + }); + }, + feeds : Models.Service.feeds + }, + events : { + "[can-click=addFilter],[can-click=markToDestroy] click" : function(el, ev){ + ev.preventDefault(); + } + }, + helpers : { + templateIs : function(template, query, opts){ + var templateShouldBe = 'textarea'; + template = can.isFunction(template) ? template() : template; + query = can.isFunction(query) ? query() : query; + + if(query.attr('op') === 'is' || query.attr('op') === 'contains_phrase'){ + templateShouldBe = 'input'; + } + + if(query.attr('attr_name') === 'feed_name'){ + templateShouldBe = 'feed_select'; + } + + if(template === templateShouldBe){ + return opts.fn(); + } + }, + verbsForQuery : function(query, opts){ + var attr_name = query.attr('attr_name'); + var verbs = VERBS; + var verbsSubset = FILTER_VERBS[attr_name]; + var html = []; + + query = can.isFunction(query) ? query() : query; + + if(verbsSubset){ + verbs = {}; + for(var i = 0; i < verbsSubset.length; i++){ + verbs[verbsSubset[i]] = VERBS[verbsSubset[i]]; + } + } + + for(var k in verbs){ + if(verbs.hasOwnProperty(k)){ + html.push(opts.fn(opts.scope.add({filter: k, name: verbs[k]}))); + } + } + return html; + } + } +}); diff --git a/components/moderation-rules/moderation-rules.less b/components/moderation-rules/moderation-rules.less new file mode 100644 index 0000000..7692965 --- /dev/null +++ b/components/moderation-rules/moderation-rules.less @@ -0,0 +1,50 @@ +bh-moderation-rules { + display: block; + .op-wrap, .attr-wrap { + float: left; + width: 44%; + margin-right: 2%; + } + .val-wrap { + width: 90%; + clear: both; + padding-top: 10px; + } + .remove-filter-wrap { + float: right; + width: 7%; + .btn { + width: 100%; + padding-left: 0; + padding-right: 0; + text-align: center; + } + } + .btn-add-rule { + margin-bottom: 10px; + } + .filter-wrap { + padding: 0 25px 20px; + border-bottom: 1px solid #ddd; + margin: 0 -25px 20px; + &:after { + content: "OR"; + display: block; + width: 20px; + background: #f1efef; + font-weight: bold; + font-style: italic; + margin: 0 auto -30px; + width: 50px; + text-align: center; + color: #666; + } + &:last-child { + border-bottom: none; + padding-bottom: 0; + &:after { + display: none; + } + } + } +} diff --git a/components/moderation-rules/moderation-rules.stache b/components/moderation-rules/moderation-rules.stache new file mode 100644 index 0000000..22b0d80 --- /dev/null +++ b/components/moderation-rules/moderation-rules.stache @@ -0,0 +1,55 @@ +

{{{ title }}}

+ + +
+ +
+ {{#each filtersNotMarkedForDelete}} +
+
+ +
+ {{#each natlang_queries}} +
+ +
+
+ +
+
+ {{#templateIs 'textarea' this}} + +

Separate the words with spaces

+ {{/templateIs}} + + {{#templateIs 'input' this}} + +

Whole phrase will be matched

+ {{/templateIs}} + + {{#templateIs 'feed_select' this}} + + {{/templateIs}} +
+ {{/each}} +
+ + + {{/each}} +
+
+ diff --git a/components/moderation/moderation.js b/components/moderation/moderation.js new file mode 100644 index 0000000..e941afb --- /dev/null +++ b/components/moderation/moderation.js @@ -0,0 +1,83 @@ +import can from "can/"; +import initView from "./moderation.stache!"; +import Models from "models/"; + +import "style/"; +import "./moderation.less!"; +import "can/map/define/"; +import "components/moderation-rules/"; + +var parseTruthy = function(el){ + return !!parseInt(el.val(), 10); +}; + +var ModerationVM = can.Map.extend({ + isSaving : false, + hasErrors: false, + approveSomeAutomatically: false, + blockSomeAutomatically: false, + init : function(){ + var self = this; + var id = this.attr('state.hub.id'); + Models.Filter.findAll({embed_id: id}, function(filters){ + var blocking = filters.blocking(); + var approving = filters.approving(); + var approveSomeAutomatically = approving.attr('length') > 0; + var blockSomeAutomatically = blocking.attr('length') > 0; + self.attr({ + blockingFilters: blocking, + approvingFilters: approving, + approveSomeAutomatically: approveSomeAutomatically, + blockSomeAutomatically: blockSomeAutomatically + }); + }); + }, + saveHub : function(ctx, el, ev){ + var self = this; + this.attr({ + hasErrors: false, + isSaving: true + }); + + $.when( + this.attr('state.hub').save(), + this.attr('blockingFilters').saveOrDestroy(), + this.attr('approvingFilters').saveOrDestroy() + ).then(function(){ + self.attr('isSaving', false); + self.attr('state.hub').moderate().then(function(){ + self.attr('state').resetEmbed(); + }); + }, function(){ + self.attr('hasErrors', true); + }); + }, + + toggleApprovedByDefault : function(ctx, el){ + this.attr('state.hub.approved_by_default', parseTruthy(el)); + }, + toggleSomeApprovedAutomatically : function(ctx, el){ + this.attr('approveSomeAutomatically', parseTruthy(el)); + }, + toggleSomeBlockedAutomatically : function(ctx, el){ + this.attr('blockSomeAutomatically', parseTruthy(el)); + }, + isApproveSomeAutomatically : function(){ + var hasApproveSomeAutomatically = this.attr('approveSomeAutomatically'); + var hasApprovingFilters = this.attr('approvingFilters.length'); + + return hasApproveSomeAutomatically || hasApprovingFilters; + }, + isBlockSomeAutomatically: function(){ + var hasBlockSomeAutomatically = this.attr('blockSomeAutomatically'); + var hasBlockingFilters = this.attr('blockingFilters.length'); + + return hasBlockSomeAutomatically || hasBlockingFilters; + } +}); + +can.Component.extend({ + tag : 'bh-moderation', + template : initView, + scope : ModerationVM +}); diff --git a/components/moderation/moderation.less b/components/moderation/moderation.less new file mode 100644 index 0000000..8d01654 --- /dev/null +++ b/components/moderation/moderation.less @@ -0,0 +1,41 @@ +bh-moderation { + display: block; + padding: 15px 0; + .options-wrapper { + background: #fafafa; + border-radius: 3px; + margin: 15px 0; + padding: 15px; + } + .buttons-wrapper { + margin: 0 -25px; + padding: 15px 25px 0; + border-top: 1px solid #ddd; + } + + bh-moderation-rules { + h4 { + margin-left: -25px; + border-left: 3px solid green; + padding-left: 22px; + } + } + + bh-moderation-rules.approving { + border-bottom: 1px solid #ccc; + margin-bottom: 20px; + h4 b { + color: green; + } + } + + bh-moderation-rules.blocking { + h4 { + border-left-color: red; + b { + color: red; + } + } + } + +} diff --git a/components/moderation/moderation.stache b/components/moderation/moderation.stache new file mode 100644 index 0000000..a85cccb --- /dev/null +++ b/components/moderation/moderation.stache @@ -0,0 +1,38 @@ +

Do you want all items approved and public by default?

+
+
+
+ +
+
+ +
+
+ {{#unless state.hub.approved_by_default}} + {{#if approvingFilters.length}} + + {{/if}} + {{/unless}} + {{#if blockingFilters.length}} + + {{/if}} + {{#isSaving}} +
+ Saving… +
+ {{/isSaving}} + {{#hasErrors}} +
+ There was a problem with the moderation update! +
+ {{/hasErrors}} +
+ +
+ diff --git a/components/moderation/moderation_test.js b/components/moderation/moderation_test.js new file mode 100644 index 0000000..ac781b5 --- /dev/null +++ b/components/moderation/moderation_test.js @@ -0,0 +1,206 @@ +import "./moderation"; +import QUnit from "steal-qunit"; +import F from "funcunit"; +import $ from "jquery"; +import fixture from "can/util/fixture/"; + +F.attach(QUnit); +var template = can.stache(""); + +var Hub = can.Map.extend({ + save : function(){ + QUnit.ok(true, 'Save Called'); + } +}); + +var renderTemplate = function(data){ + $('#qunit-fixture').html(template(data)); +}; + + +var State = can.Map.extend({ + resetEmbed : function(){ + ok(true, "Reset Embed Called"); + } +}); + +var Hub = can.Map.extend({ + moderate : function(){ + ok(true, "Moderate called"); + return can.Deferred().resolve({id: this.attr('id')}).promise(); + }, + save : function(){ + ok(true, "Save called"); + return can.Deferred().resolve({id: this.attr('id')}).promise(); + } +}); + +QUnit.module("Moderation Tests", { + beforeEach : function(){ + var fixtureData = [ + { + "natlang_queries": [ + { + "is_negated": false, + "val": "foober", + "op": "contains_all", + "attr_name": "content", + "id": 1 + } + ], + "embed_id": "blocking-and-approving", + "action": "block", + "id": 1 + }, + { + "natlang_queries": [ + { + "is_negated": false, + "val": "testing", + "op": "contains_all", + "attr_name": "content", + "id": 2 + } + ], + "embed_id": "blocking-and-approving", + "action": "approve", + "id": 2 + }, + { + "natlang_queries": [ + { + "is_negated": false, + "val": "testing", + "op": "contains_all", + "attr_name": "content", + "id": 3 + } + ], + "embed_id": "approving", + "action": "approve", + "id": 3 + }, + { + "natlang_queries": [ + { + "is_negated": false, + "val": "foober", + "op": "contains_all", + "attr_name": "content", + "id": 4 + } + ], + "embed_id": "blocking", + "action": "block", + "id": 4 + } + ]; + + var STORE = fixture.store(fixtureData); + fixture({ + "/api/v3/filters": STORE.findAll, + "PUT /api/v3/filters/{id}" : STORE.update, + "DELETE /api/v3/filters/{id}" : STORE.destroy + }); + fixture.on = true; + }, + afterEach : function(){ + fixture({ + "/api/v3/filters" : null, + "PUT /api/v3/filters/{id}" : null, + "DELETE /api/v3/filters/{id}" : null + }); + fixture.on = false; + } +}); + +QUnit.test("Moderation with blocking and approving", 7, function(){ + renderTemplate({ + state: new State({ + hub: new Hub({ + id: 'blocking-and-approving', + approved_by_default: false + }) + }) + }); + + F('bh-moderation').exists('Moderation is rendered'); + F('input[can-change=toggleApprovedByDefault][value=0]:checked') + .exists('Hub items are not approved by default'); + F('bh-moderation bh-moderation-rules.approving').exists('Approving filters are rendered'); + F('bh-moderation bh-moderation-rules.blocking').exists('Blocking filters are rendered'); + F('bh-moderation button.btn-save-moderation').click(); +}); + +QUnit.test("Moderation with only blocking filters present", function(){ + renderTemplate({ + state: new State({ + hub: new Hub({ + id: 'blocking', + approved_by_default: false + }) + }) + }); + F('bh-moderation').exists('Moderation is rendered'); + F('bh-moderation bh-moderation-rules.approving').missing('Approving filters are missing'); + F('bh-moderation bh-moderation-rules.blocking').exists('Blocking filters exist'); +}); + +QUnit.test("Moderation with only approving filters present", function(){ + renderTemplate({ + state: new State({ + hub: new Hub({ + id: 'approving', + approved_by_default: false + }) + }) + }); + F('bh-moderation').exists('Moderation is rendered'); + F('bh-moderation bh-moderation-rules.blocking').missing('Blocking filters are missing'); + F('bh-moderation bh-moderation-rules.approving').exists('Approving filters exist'); +}); + +QUnit.test("Both moderation and approving filters exist, but only blocking should be shown because hub is approving by default", function(){ + renderTemplate({ + state: new State({ + hub: new Hub({ + id: 'blocking-and-approving', + approved_by_default: true + }) + }) + }); + F('bh-moderation').exists('Moderation is rendered'); + F('bh-moderation bh-moderation-rules.approving').missing('Approving filters are missing'); + F('bh-moderation bh-moderation-rules.blocking').exists('Blocking filters exist'); +}); + +QUnit.test("Add filter", function(){ + renderTemplate({ + state: new State({ + hub: new Hub({ + id: 'blocking-and-approving', + approved_by_default: false + }) + }) + }); + + F('bh-moderation').exists('Moderation is rendered'); + F('bh-moderation .filter-wrap').size(2, 'Two moderation filters are rendered'); + F('bh-moderation [can-click=addFilter]:first').click(); + F('bh-moderation .filter-wrap').size(3, 'Three moderation filters are rendered'); +}); + +QUnit.test("Remove filter", function(){ + renderTemplate({ + state: new State({ + hub: new Hub({ + id: 'blocking-and-approving', + approved_by_default: false + }) + }) + }); + F('bh-moderation').exists('Moderation is rendered'); + F('bh-moderation .filter-wrap').size(2, 'Two moderation filters are rendered'); + F('bh-moderation .filter-wrap:first [can-click=markToDestroy]').click(); + F('bh-moderation .filter-wrap').size(1, 'One filter is marked for destroying'); +}); diff --git a/components/oauthorizer/oauthorizer.js b/components/oauthorizer/oauthorizer.js new file mode 100644 index 0000000..26289f3 --- /dev/null +++ b/components/oauthorizer/oauthorizer.js @@ -0,0 +1,205 @@ +import can from "can/"; +import initView from "./oauthorizer.stache!"; +import Models from "models/"; + +import "./oauthorizer.less!"; +import "can/map/define/"; + +var getIdentityProvider = function(feed){ + if(feed === 'youtube'){ + return 'google_oauth2'; + } + return feed; +}; + +var OAuthURL = function(feed){ + return '/auth/' + getIdentityProvider(feed); +}; + +var OAuthConnect = function(feed) { + var windowPropsStr = "width=800,height=600,scrollbars=yes", + title = "OAuth Login", + url = OAuthURL(feed), + oauthWindow = window.open(url, title, windowPropsStr), + def = can.Deferred(), + oauthWindowSweeper = window.setInterval(function() { + if (oauthWindow.closed) { + clearInterval(oauthWindowSweeper); + def.resolve(); + } + }, 100); + return def; +}; + + +var BUTTON_LABELS = { + facebook : ' Log in with Facebook', + twitter : 'Sign in with Twitter', + github : 'Log in in with GitHub', + meetup : 'Log in with Meetup', + foursquare : 'Log in with Foursquare', + instagram : 'Log in with Instagram', + disqus : 'Log in with Disqus' +}; + +var SERVICE_LABELS = { + facebook : 'Facebook', + twitter : 'Twitter', + github : 'GitHub', + meetup : 'Meetup', + foursquare : 'Foursquare', + instagram : 'Instagram', + disqus : 'Disqus', +}; + +var compareIdentities = function(a, b){ + if(a.created_at_timestamp > b.created_at_timestamp){ + return -1; + } + if(a.created_at_timestamp < b.created_at_timestamp){ + return 1; + } + return 0; +}; + +can.Component.extend({ + tag : 'bh-oauthorizer', + template : initView, + scope : { + define : { + accountType : { + set : function(val){ + if(val === 'new'){ + this.attr('service').attr('brand_identity_id', null); + } else if(this.attr('identities')) { + this.selectFirstIdentity(); + } + return val; + } + } + }, + selectedService : null, + accountType : 'existing', + init : function(){ + var self = this; + Models.Identity.findAll({}).then(function(identities){ + can.batch.start(); + self.attr({ + accountType: 'existing', + identities: identities, + }); + self.selectFirstIdentity(); + can.batch.stop(); + }); + }, + serviceLabel : function(){ + return SERVICE_LABELS[this.attr('feed')]; + }, + useExistingAccount : function(){ + return this.attr('accountType') === 'existing'; + }, + addNewAccount : function(){ + return this.attr('accountType') === 'new'; + }, + toggleAccountType : function(ctx, el){ + this.attr('accountType', el.data('accountType')); + }, + isAuthorized : function(){ + return this.hasIdentityForService(this.attr('feed')); + }, + setServiceBrandIdentityId : function(id){ + this.attr('service').attr('brand_identity_id', parseInt(id, 10)); + }, + selectFirstIdentity : function(){ + var identities = this.identitiesForCurrentService(); + if(identities.length){ + this.setServiceBrandIdentityId(identities[0].id); + } + }, + identitiesForCurrentService : function(){ + var currentService = this.attr('feed'); + return can.grep(this.attr('identities'), function(identity){ + return identity.attr('provider') === getIdentityProvider(currentService); + }); + }, + hasIdentityForService : function(service){ + var identities = this.attr('identities'), + length = identities.attr('length'); + + for(var i = 0; i < length; i++){ + if(identities.attr(i + '.provider') === getIdentityProvider(service)){ + return true; + } + } + return false; + }, + buttonLabel : function(){ + return BUTTON_LABELS[this.attr('feed')] || 'Authorize Service'; + }, + identities: null, + isAuthorizing : false, + isAuthorizingOrHasIdentity : function(){ + var hasIdentity = !!this.attr('service.brand_identity_id'); + return this.attr('isAuthorizing') || hasIdentity; + }, + isPending : function(){ + return this.attr('identities') === null; + }, + oauthorize : function(ctx, el, ev){ + var self = this, + feed = this.attr('feed'); + + ev.preventDefault(); + + if(this.attr('service.brand_identity_id')){ + return; + } + + if(!feed){ + throw "You must initialize bh-oauthorizer component with the `feed` attribute"; + } + + this.attr('isAuthorizing', true); + + OAuthConnect(feed).then(function(){ + Models.Identity.findAll({}).then(function(identities){ + self.attr({ + identities : identities, + isAuthorizing : false, + accountType: 'existing' + }); + }); + }); + } + }, + events : { + "{scope} isAuthorizing" : function(scope, ev, newVal){ + var self = this; + + if(newVal){ + return; + } + + setTimeout(function(){ + var identities = self.scope.identitiesForCurrentService(); + if(identities.length){ + identities.sort(compareIdentities); + self.scope.setServiceBrandIdentityId(identities[0].id); + self.element.find('select.service-brand').val(identities[0].id); + } + }, 10); + } + }, + helpers : { + ifServiceIs : function(service, opts){ + service = can.isFunction(service) ? service() : service; + if(service === this.attr('feed')){ + return opts.fn(); + } + }, + withSelectedService : function(opts){ + var selectedService = this.attr('service').attr('brand_identity_id'); + return selectedService && opts.fn(); + } + } +}); diff --git a/components/oauthorizer/oauthorizer.less b/components/oauthorizer/oauthorizer.less new file mode 100644 index 0000000..3dba572 --- /dev/null +++ b/components/oauthorizer/oauthorizer.less @@ -0,0 +1,26 @@ +bh-oauthorizer { + display: block; + .oauthorizer-loader { + height: 20px; + line-height: 20px; + } + .oauthorize-help { + margin: 15px -15px 0; + padding: 15px 15px 0; + border-top: 1px solid #ccc; + color: #333; + h4 { + margin-top: 0; + } + p { + margin-bottom: 0; + } + } + .account-tabs { + margin: 0 -15px 20px; + padding: 0 15px; + .active a, .active a:active, .active a:focus, .active a:hover { + background: #fafafa; + } + } +} \ No newline at end of file diff --git a/components/oauthorizer/oauthorizer.stache b/components/oauthorizer/oauthorizer.stache new file mode 100644 index 0000000..a3d4308 --- /dev/null +++ b/components/oauthorizer/oauthorizer.stache @@ -0,0 +1,60 @@ +{{#if isPending}} +
+ Loading... +
+{{else}} + + {{#if identitiesForCurrentService.length}} + {{#if service.isNew}} + + + + {{#if useExistingAccount}} +
+ + +
+ {{/if}} + + {{#if addNewAccount}} + + {{/if}} + + {{/if}} + {{#withSelectedService}} + + {{/withSelectedService}} + {{else}} + + {{#ifServiceIs 'facebook'}} +
+

Why do I need to log in?

+

+ We need your login info to be able to allow you to collect data from the Facebook pages you administer. +

+
+ {{/ifServiceIs}} + {{/if}} + +{{/if}} \ No newline at end of file diff --git a/components/organization-settings/organization-settings.js b/components/organization-settings/organization-settings.js new file mode 100644 index 0000000..1e1656a --- /dev/null +++ b/components/organization-settings/organization-settings.js @@ -0,0 +1,32 @@ +import can from "can/"; +import initView from "./organization-settings.stache!"; + +import "./organization-settings.less!"; + +function validateEmail(email) { + return email.indexOf('@') > -1; +} + +export default can.Component.extend({ + template: initView, + tag: 'bh-organization-settings', + scope : { + inviteUserEmail : "", + isInviteUserEmailValid : function(){ + return validateEmail(this.attr('inviteUserEmail')); + }, + setInviteUserEmail : function(ctx, el, ev){ + this.attr('inviteUserEmail', el.val()); + }, + inviteUser: function(){ + var organization = this.attr('state').attr('currentOrganization'); + var self = this; + organization.invite(this.attr('inviteUserEmail')).then(function(res){ + organization.addInvitation(res); + self.attr('inviteUserEmail', ""); + }, function(){ + alert("We weren't able to invite the user."); + }); + } + } +}); diff --git a/components/organization-settings/organization-settings.less b/components/organization-settings/organization-settings.less new file mode 100644 index 0000000..7a282d3 --- /dev/null +++ b/components/organization-settings/organization-settings.less @@ -0,0 +1,5 @@ +bh-organization-settings { + .actions { + width: 120px; + } +} diff --git a/components/organization-settings/organization-settings.stache b/components/organization-settings/organization-settings.stache new file mode 100644 index 0000000..cca4a22 --- /dev/null +++ b/components/organization-settings/organization-settings.stache @@ -0,0 +1,55 @@ +

{{state.currentOrganization.name}} Accounts

+
+

Users

+ + + + + + + + + {{#each state.currentOrganization.accounts}} + + + + + {{/each}} + +
Email
{{email}} + {{^eq id state.currentAccount.id}} + + {{/eq}} +
+
+{{#if state.currentOrganization.invitations.length}} +

Invitations

+ + + + + + + + {{#each state.currentOrganization.invitations}} + + + + {{/each}} + +
Email
{{email}}
+
+{{/if}} + +

Invite User

+
+
+
+ +
+ +
+
+
+
+ diff --git a/components/payments/payments.html b/components/payments/payments.html new file mode 100644 index 0000000..e69de29 diff --git a/components/payments/payments.js b/components/payments/payments.js new file mode 100644 index 0000000..2978ac7 --- /dev/null +++ b/components/payments/payments.js @@ -0,0 +1,42 @@ +import can from "can/"; +import initView from "./payments.stache!"; + +import "style/"; +import "./payments.less!"; +import "can/map/define/"; + + +can.Component.extend({ + tag : 'bh-payments', + template : initView, + scope : { + init : function(){ + + }, + billingInfoUrl : "/admin/subscriptions/edit/cc", + accountPlanUrl : "/admin/subscriptions/edit/plan", + planPrice : function(){ + var price = this.attr('state.currentSubscription.plan.amount'); + if(!price){ + return; + } + price = price + ""; + return "$" + price.slice(0, -2) + "." + price.slice(-2); + }, + openBillingInfo : function(){ + this.attr('currentIframe', this.attr('billingInfoUrl')); + }, + openAccountPlan : function(){ + this.attr('currentIframe', this.attr('accountPlanUrl')); + }, + closeIframe : function(){ + this.attr('currentIframe', null); + } + }, + events : { + ".overlay click" : function(el, ev){ + this.scope.closeIframe(); + } + } +}); + diff --git a/components/payments/payments.less b/components/payments/payments.less new file mode 100644 index 0000000..641e614 --- /dev/null +++ b/components/payments/payments.less @@ -0,0 +1,38 @@ +bh-payments { + display: block; + .overlay { + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: rgba(0,0,0,0.5); + .iframe-wrap { + width: 400px; + margin: 100px auto; + position: relative; + iframe { + width: 600px; + height: 400px; + border: none; + background: transparent; + } + } + } + i.fa-times-circle { + position: absolute; + background: white; + border: 2px solid white; + display: block; + font-size: 20px; + left: 585px; + top: -5px; + border-radius: 100%; + width: 22px; + height: 22px; + text-align: center; + line-height: 0.9; + cursor: pointer; + + } +} diff --git a/components/payments/payments.stache b/components/payments/payments.stache new file mode 100644 index 0000000..146cac3 --- /dev/null +++ b/components/payments/payments.stache @@ -0,0 +1,2 @@ +

Payments

+
Currently there are no invoices in the system.
diff --git a/components/preset-form/preset-form.js b/components/preset-form/preset-form.js new file mode 100644 index 0000000..590093d --- /dev/null +++ b/components/preset-form/preset-form.js @@ -0,0 +1,32 @@ +import can from "can/"; +import initView from "./preset-form.stache!"; +import "./preset-form.less!"; + +can.Component.extend({ + tag: 'bh-preset-form', + template: initView, + scope: { + isSaving: false, + init : function(){ + this.attr('preset').backup(); + this.attr('preset.config').backup(); + }, + savePreset : function(ctx, el, ev){ + ev.preventDefault(); + + if(this.attr('isSaving')){ + return; + } + + this.attr('isSaving', true); + el.closest('bh-integration').trigger('savePreset'); + } + }, + events : { + '.clear-preset click' : function(){ + this.scope.attr('preset').restore(); + this.scope.attr('preset.config').restore(); + this.element.trigger('clearPreset'); + } + } +}); diff --git a/components/preset-form/preset-form.less b/components/preset-form/preset-form.less new file mode 100644 index 0000000..537ca1f --- /dev/null +++ b/components/preset-form/preset-form.less @@ -0,0 +1,3 @@ +bh-preset-form { + display: block; +} \ No newline at end of file diff --git a/components/preset-form/preset-form.stache b/components/preset-form/preset-form.stache new file mode 100644 index 0000000..85b90b0 --- /dev/null +++ b/components/preset-form/preset-form.stache @@ -0,0 +1,46 @@ +
+

+ {{#if preset.isNew}}Add{{else}}Edit{{/if}} Preset + +

+ {{#preset}} + +
+
+ + +
+
+ +
+ Theme +
+ +
+
+ +
+
+ +
+
+ + Cancel +
+
+ + {{/preset}} +
diff --git a/components/service-config-formatter/service-config-formatter.js b/components/service-config-formatter/service-config-formatter.js new file mode 100644 index 0000000..ceb8ebc --- /dev/null +++ b/components/service-config-formatter/service-config-formatter.js @@ -0,0 +1,43 @@ +import can from "can/"; +import initView from "./service-config-formatter.stache!"; +import "./service-config-formatter.less!"; + +can.Component.extend({ + template : initView, + tag: 'bh-service-config-formatter', + scope : { + lowercasedFeedName : function(){ + return this.attr('service.feed_name').toLowerCase(); + }, + lowercasedTypeName : function(){ + return this.attr('service.type_name').toLowerCase(); + } + }, + helpers : { + isFeedAndType : function(feed, type, opts){ + feed = (can.isFunction(feed) ? feed() : feed).toLowerCase(); + type = (can.isFunction(type) ? type() : type).toLowerCase(); + if(feed === this.lowercasedFeedName() && type === this.lowercasedTypeName()){ + return opts.fn(); + } + }, + cutoff : function(){ + var str, opts; + if(arguments.length === 1){ + opts = arguments[0]; + str = opts.fn(); + } else { + str = arguments[0]; + opts = arguments[1]; + } + + str = (can.isFunction(str) ? str() : str) || ""; + + if(str.length > 50){ + str = str.substr(0, 50) + '…'; + } + + return str; + } + } +}); diff --git a/components/service-config-formatter/service-config-formatter.less b/components/service-config-formatter/service-config-formatter.less new file mode 100644 index 0000000..7c739b3 --- /dev/null +++ b/components/service-config-formatter/service-config-formatter.less @@ -0,0 +1,3 @@ +bh-service-config-formatter { + display: block; +} \ No newline at end of file diff --git a/components/service-config-formatter/service-config-formatter.stache b/components/service-config-formatter/service-config-formatter.stache new file mode 100644 index 0000000..67ea652 --- /dev/null +++ b/components/service-config-formatter/service-config-formatter.stache @@ -0,0 +1,87 @@ +{{#isFeedAndType 'disqus' 'forum'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'facebook' 'page'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'facebook' 'public_page'}} + Facebook Page {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'foursquare' 'venue'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'github' 'org'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'github' 'repo'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'instagram' 'tag'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'instagram' 'user'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'meetup' 'group'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'rss' 'site'}} + {{service.printFeed}} {{service.printType}} {{{cutoff service.config.url}}} +{{/isFeedAndType}} + +{{#isFeedAndType 'stackexchange' 'tags'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'tumblr' 'blog'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'tumblr' 'tag'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'twitter' 'followers'}} + {{service.printFeed}} {{service.printType}} for {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'twitter' 'hashtag'}} + {{service.printFeed}} {{service.printType}} for {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'twitter' 'user_timeline'}} + {{service.printFeed}} {{service.printType}} for {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'twitter' 'user_retweets'}} + {{service.printFeed}} {{service.printType}} for {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'twitter' 'favorites'}} + {{service.printFeed}} {{service.printType}} for {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'twitter' 'term'}} + {{service.printFeed}} {{service.printType}} for {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'youtube' 'channel'}} + {{service.printFeed}} {{service.printType}} for {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'youtube' 'playlist'}} + {{service.printFeed}} {{service.printType}} for {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'youtube' 'user'}} + {{service.printFeed}} {{service.printType}} for {{service.config.display_name}} +{{/isFeedAndType}} diff --git a/components/service-form/service-form.js b/components/service-form/service-form.js new file mode 100644 index 0000000..2a14261 --- /dev/null +++ b/components/service-form/service-form.js @@ -0,0 +1,196 @@ +import can from 'can/'; +import initView from './service-form.stache!'; +import Models from 'models/'; + +import './service-form.less!'; +import 'can/map/define/'; + +import 'components/service-forms/disqus-forum/'; +import 'components/service-forms/facebook-page/'; +import 'components/service-forms/facebook-public-page/'; +import 'components/service-forms/foursquare-venue/'; +import 'components/service-forms/github-org/'; +import 'components/service-forms/github-repo/'; +import 'components/service-forms/instagram-tag/'; +import 'components/service-forms/instagram-user/'; +import 'components/service-forms/meetup-group/'; +import 'components/service-forms/rss-site/'; +import 'components/service-forms/stackexchange-tags/'; +import 'components/service-forms/tumblr-blog/'; +import 'components/service-forms/tumblr-tag/'; +import 'components/service-forms/twitter-followers/'; +import 'components/service-forms/twitter-hashtag/'; +import 'components/service-forms/twitter-term/'; +import 'components/service-forms/twitter-user-timeline/'; +import 'components/service-forms/twitter-favorites/'; +import 'components/service-forms/twitter-user-retweets/'; +import 'components/service-forms/youtube-channel/'; +import 'components/service-forms/youtube-playlist/'; +import 'components/service-forms/youtube-user/'; +import 'components/oauthorizer/'; + +import 'components/helpers'; + +var FEED_INFOS = { + foursquare: 'You must be a venue manager to be able to add a venue.' +}; + +var makeTemplate = function(feed, type){ + var componentName = ['bh', feed, type.replace(/_/g, '-'), 'service'].join('-'), + template = '<' + componentName + ' map="{service}" errors="{errors.config}">{{{saveButtons}}}', + needsOAuth = Models.Service.needsOAuth[feed]; + + needsOAuth = needsOAuth && can.inArray(type, needsOAuth.types) > -1; + + + if(needsOAuth){ + template = [ + '', + template, + '' + ].join(''); + } + + + return can.stache(template); +}; + +can.Component.extend({ + tag : 'bh-service-form', + template: initView, + scope : { + isHidden: false, + missingConfig : false, + errors: null, + typeErros: null, + saveDisabled : false, + define : { + service : { + set : function(val){ + this.clearErrors(); + return val; + } + } + }, + saveService : function(formData, el, ev){ + ev.preventDefault(); + + var self = this; + var service = this.attr('service'); + var services = this.attr('services'); + this.compute('service'); + + service.attr('embed_id', this.state.attr('hubId')); + if(service.isNew()){ + services.unshift( service ); + } + + service.save( function( newService ) { + self.clearService(); + }, function( error ) { + var index = services.indexOf(service); + var attrs = { + isHidden: false + }; + var errorsResponse; + var errors, typeErrors; + + services.splice(index, 1); + + if(error.status === 400){ + attrs.missingConfig = true; + } else if(error.status = 406){ + try { + errorsResponse = JSON.parse(error.responseText).errors; + errors = errorsResponse.config_attrs; + typeErrors = errorsResponse.type_name; + } catch(e){ + errors = {}; + } + attrs.errors = errors; + } + + if(typeErrors){ + self.attr('typeErrors', typeErrors); + } + + Models.Service.errored(service); + + self.attr(attrs); + }); + + this.attr({ + isHidden: service.isNew(), + missingConfig: false, + errors: null + }); + }, + feedInfo : function(){ + return FEED_INFOS[this.attr('service.feed_name')]; + }, + clearService : function(){ + can.batch.start(); + this.attr({ + service: null, + saveDisabled: false + }); + this.clearErrors(); + can.batch.stop(); + }, + clearErrors : function(){ + this.attr({ + errors: null, + typeErrors: null, + missingConfig: false + }); + }, + currentServiceFeedName : function(){ + var service = this.attr('service'); + if(!service) { + return; + } + var feed = service.attr('feed_name'); + return Models.Service.feeds[feed]; + } + }, + events : { + "service:saveDisabled" : function(){ + var self = this; + setTimeout(function(){ + if(self.element){ + self.element.find('button.save-service').prop('disabled', true); + } + }, 1); + + }, + "service:saveEnabled" : function(){ + var self = this; + setTimeout(function(){ + if(self.element){ + self.element.find('button.save-service').prop('disabled', false); + } + }, 1); + } + }, + helpers : { + renderForm : function(opts){ + var service = this.attr('service'), feed, type; + + if(!service){ + return; + } + + feed = service.attr('feed_name'); + type = service.attr('type_name'); + + + if(type && feed){ + return makeTemplate(feed, type)(opts.scope, { + saveButtons : function(){ + return opts.fn(); + } + }); + } + } + } +}); diff --git a/components/service-form/service-form.less b/components/service-form/service-form.less new file mode 100644 index 0000000..dcac5c3 --- /dev/null +++ b/components/service-form/service-form.less @@ -0,0 +1,24 @@ +bh-service-form { + display: block; + + bh-suggestions { + .panel { + margin-left: -15px; + margin-right: -15px; + margin-bottom: 0; + border-radius: 0; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-left: none; + border-right: none; + } + } + + .form-instructions { + font-style: oblique; + margin-top: 5px; + } + .input-group { + width: 100%; + } +} \ No newline at end of file diff --git a/components/service-form/service-form.stache b/components/service-form/service-form.stache new file mode 100644 index 0000000..bf6548b --- /dev/null +++ b/components/service-form/service-form.stache @@ -0,0 +1,66 @@ +{{#unless isHidden}} +
+

+ {{#if service.isNew}}Add{{else}}Edit{{/if}} {{currentServiceFeedName}} + +

+ {{#service}} + + {{#if error}} +
+ {{ formattedErrorClass }} + {{ formattedError }} +
+ {{/if}} + + {{#if typeErrors.length}} +
+ You have {{ typeErrors.0 }} +
+ {{/if}} + +
+ + {{#if hasMultipleTypes}} + +
+ +
+ {{/if}} + + {{#if missingConfig}} +
Config can't be empty
+ {{/if}} + + {{#if errors}} +
Service config has some errors
+ {{/if}} + + {{#if feedInfo }} +
{{ feedInfo }}
+ {{/if}} + + + {{#renderForm}} +
+ +
+ +
+ + Cancel +
+ {{/renderForm}} + +
+ + {{/service}} +
+{{/unless}} diff --git a/components/service-forms/disqus-forum/disqus-forum.js b/components/service-forms/disqus-forum/disqus-forum.js new file mode 100644 index 0000000..4464016 --- /dev/null +++ b/components/service-forms/disqus-forum/disqus-forum.js @@ -0,0 +1,10 @@ +import can from "can/"; +import initView from "./disqus-forum.stache!"; + +import "./disqus-forum.less!"; +import "components/suggestions/"; + +can.Component.extend({ + tag : 'bh-disqus-forum-service', + template : initView +}); diff --git a/components/service-forms/disqus-forum/disqus-forum.less b/components/service-forms/disqus-forum/disqus-forum.less new file mode 100644 index 0000000..d323ebc --- /dev/null +++ b/components/service-forms/disqus-forum/disqus-forum.less @@ -0,0 +1,3 @@ +bh-disqus-forum-service { + display: block; +} diff --git a/components/service-forms/disqus-forum/disqus-forum.stache b/components/service-forms/disqus-forum/disqus-forum.stache new file mode 100644 index 0000000..2b6cc3a --- /dev/null +++ b/components/service-forms/disqus-forum/disqus-forum.stache @@ -0,0 +1,4 @@ +
+ + {{{configErrors errors 'url'}}} +
diff --git a/components/service-forms/facebook-page/facebook-page.js b/components/service-forms/facebook-page/facebook-page.js new file mode 100644 index 0000000..9f628df --- /dev/null +++ b/components/service-forms/facebook-page/facebook-page.js @@ -0,0 +1,10 @@ +import can from "can/"; + +import initView from './facebook-page.stache!'; +import './facebook-page.less!'; +import 'components/suggestions/'; + +can.Component.extend({ + tag : 'bh-facebook-page-service', + template : initView +}); diff --git a/components/service-forms/facebook-page/facebook-page.less b/components/service-forms/facebook-page/facebook-page.less new file mode 100644 index 0000000..b463e18 --- /dev/null +++ b/components/service-forms/facebook-page/facebook-page.less @@ -0,0 +1,3 @@ +bh-facebook-page-service { + display: block; +} diff --git a/components/service-forms/facebook-page/facebook-page.stache b/components/service-forms/facebook-page/facebook-page.stache new file mode 100644 index 0000000..c1f17ee --- /dev/null +++ b/components/service-forms/facebook-page/facebook-page.stache @@ -0,0 +1,4 @@ +
+ + {{{configErrors errors 'id'}}} +
\ No newline at end of file diff --git a/components/service-forms/facebook-public-page/facebook-public-page.js b/components/service-forms/facebook-public-page/facebook-public-page.js new file mode 100644 index 0000000..6d996f4 --- /dev/null +++ b/components/service-forms/facebook-public-page/facebook-public-page.js @@ -0,0 +1,18 @@ +import can from "can/"; +import initView from './facebook-public-page.stache!'; +import './facebook-public-page.less!'; +import 'components/suggestions/'; + + +can.Component.extend({ + tag : 'bh-facebook-public-page-service', + template : initView, + scope : { + loading: "", + loadedPage: null, + error: "", + init : function(){ + + } + } +}); diff --git a/components/service-forms/facebook-public-page/facebook-public-page.less b/components/service-forms/facebook-public-page/facebook-public-page.less new file mode 100644 index 0000000..3d9fa56 --- /dev/null +++ b/components/service-forms/facebook-public-page/facebook-public-page.less @@ -0,0 +1,8 @@ +bh-facebook-public-page-service { + display: block; + .result { + .alert { + margin-bottom: 0; + } + } +} diff --git a/components/service-forms/facebook-public-page/facebook-public-page.stache b/components/service-forms/facebook-public-page/facebook-public-page.stache new file mode 100644 index 0000000..a37269b --- /dev/null +++ b/components/service-forms/facebook-public-page/facebook-public-page.stache @@ -0,0 +1,7 @@ +
+ +
+ +
+ {{{configErrors errors 'id'}}} +
diff --git a/components/service-forms/foursquare-venue/foursquare-venue.js b/components/service-forms/foursquare-venue/foursquare-venue.js new file mode 100644 index 0000000..8078cb8 --- /dev/null +++ b/components/service-forms/foursquare-venue/foursquare-venue.js @@ -0,0 +1,8 @@ +import can from "can/"; +import initView from './foursquare-venue.stache!'; +import './foursquare-venue.less!'; + +can.Component.extend({ + tag : 'bh-foursquare-venue-service', + template : initView +}); diff --git a/components/service-forms/foursquare-venue/foursquare-venue.less b/components/service-forms/foursquare-venue/foursquare-venue.less new file mode 100644 index 0000000..679d0de --- /dev/null +++ b/components/service-forms/foursquare-venue/foursquare-venue.less @@ -0,0 +1,3 @@ +bh-foursquare-venue-service { + display: block; +} diff --git a/components/service-forms/foursquare-venue/foursquare-venue.stache b/components/service-forms/foursquare-venue/foursquare-venue.stache new file mode 100644 index 0000000..2aaaff2 --- /dev/null +++ b/components/service-forms/foursquare-venue/foursquare-venue.stache @@ -0,0 +1,5 @@ +
To add a Forsquare Venue you must be the manager.
+
+ + {{{configErrors errors 'id'}}} +
diff --git a/components/service-forms/github-org/github-org.js b/components/service-forms/github-org/github-org.js new file mode 100644 index 0000000..d1fc888 --- /dev/null +++ b/components/service-forms/github-org/github-org.js @@ -0,0 +1,8 @@ +import can from "can/"; +import initView from './github-org.stache!'; +import './github-org.less!'; + +can.Component.extend({ + tag : 'bh-github-org-service', + template : initView +}); diff --git a/components/service-forms/github-org/github-org.less b/components/service-forms/github-org/github-org.less new file mode 100644 index 0000000..527cfca --- /dev/null +++ b/components/service-forms/github-org/github-org.less @@ -0,0 +1,3 @@ +bh-github-org-service { + display: block; +} diff --git a/components/service-forms/github-org/github-org.stache b/components/service-forms/github-org/github-org.stache new file mode 100644 index 0000000..a25117f --- /dev/null +++ b/components/service-forms/github-org/github-org.stache @@ -0,0 +1,4 @@ +
+ + {{{configErrors errors 'name'}}} +
\ No newline at end of file diff --git a/components/service-forms/github-repo/github-repo.js b/components/service-forms/github-repo/github-repo.js new file mode 100644 index 0000000..79cd1b9 --- /dev/null +++ b/components/service-forms/github-repo/github-repo.js @@ -0,0 +1,8 @@ +import can from "can/"; +import initView from './github-repo.stache!'; +import './github-repo.less!'; + +can.Component.extend({ + tag : 'bh-github-repo-service', + template : initView +}); diff --git a/components/service-forms/github-repo/github-repo.less b/components/service-forms/github-repo/github-repo.less new file mode 100644 index 0000000..93e9aa6 --- /dev/null +++ b/components/service-forms/github-repo/github-repo.less @@ -0,0 +1,3 @@ +bh-github-repo-service { + display: block; +} diff --git a/components/service-forms/github-repo/github-repo.stache b/components/service-forms/github-repo/github-repo.stache new file mode 100644 index 0000000..946c274 --- /dev/null +++ b/components/service-forms/github-repo/github-repo.stache @@ -0,0 +1,16 @@ +
+ + {{{configErrors errors 'name'}}} +
+
+
+ +
+
+ +
+
diff --git a/components/service-forms/instagram-tag/instagram-tag.js b/components/service-forms/instagram-tag/instagram-tag.js new file mode 100644 index 0000000..d3dd003 --- /dev/null +++ b/components/service-forms/instagram-tag/instagram-tag.js @@ -0,0 +1,8 @@ +import can from "can/"; +import initView from './instagram-tag.stache!'; +import './instagram-tag.less!'; + +can.Component.extend({ + tag : 'bh-instagram-tag-service', + template : initView +}); diff --git a/components/service-forms/instagram-tag/instagram-tag.less b/components/service-forms/instagram-tag/instagram-tag.less new file mode 100644 index 0000000..3492fd3 --- /dev/null +++ b/components/service-forms/instagram-tag/instagram-tag.less @@ -0,0 +1,3 @@ +instagram-tag { + display: block; +} diff --git a/components/service-forms/instagram-tag/instagram-tag.stache b/components/service-forms/instagram-tag/instagram-tag.stache new file mode 100644 index 0000000..1074af9 --- /dev/null +++ b/components/service-forms/instagram-tag/instagram-tag.stache @@ -0,0 +1,5 @@ +
+ + + {{{configErrors errors 'tag'}}} +
\ No newline at end of file diff --git a/components/service-forms/instagram-user/instagram-user.js b/components/service-forms/instagram-user/instagram-user.js new file mode 100644 index 0000000..e2affb4 --- /dev/null +++ b/components/service-forms/instagram-user/instagram-user.js @@ -0,0 +1,67 @@ +import can from "can/"; +import initView from './instagram-user.stache!'; +import './instagram-user.less!'; +import 'selectize'; + +can.Component.extend({ + tag : 'bh-instagram-user-service', + template : initView, + scope : { + isLoading : false, + init : function(){ + this.attr('currentSuggestions', []); + }, + setDisplayName : function(id){ + var currentSuggestions = this.attr('currentSuggestions'); + var length = currentSuggestions.length; + + if(id){ + for(var i = 0; i < length; i++){ + if(id === currentSuggestions[i].id){ + this.attr('map.config.display_name', currentSuggestions[i].username); + } + } + } else { + this.attr('map.config.display_name', ''); + } + } + }, + helpers : { + instagramSuggest : function(){ + var self = this; + return function(el){ + $(el).selectize({ + valueField: 'id', + labelField: 'username', + searchField: 'username', + create: false, + allowEmptyOption : true, + load: function(query, callback){ + if(!query.length){ + return callback(); + } + self.attr('isLoading', true); + $.ajax({ + url: '/api/v3/services/suggestions/instagram', + data: { + username: query + }, + error : function(){ + self.attr('isLoading', false); + callback(); + }, + success : function(res){ + self.attr('currentSuggestions').replace(res); + self.attr('isLoading', false); + callback(res); + } + }); + }, + onChange : function(id){ + self.setDisplayName(id); + } + }); + }; + } + } +}); diff --git a/components/service-forms/instagram-user/instagram-user.less b/components/service-forms/instagram-user/instagram-user.less new file mode 100644 index 0000000..930a76e --- /dev/null +++ b/components/service-forms/instagram-user/instagram-user.less @@ -0,0 +1,37 @@ +bh-instagram-user-service { + display: block; + .selectize-control.single .selectize-input:after { + right: 9px; + } + .suggest-wrapper { + position: relative; + background: #ccc; + height: 34px; + border-radius: 3px; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + .selectize-input { + -webkit-border-top-left-radius: 3px; + -webkit-border-bottom-left-radius: 3px; + -moz-border-radius-topleft: 3px; + -moz-border-radius-bottomleft: 3px; + border-top-left-radius: 3px; + border-bottom-left-radius: 3px; + } + .selectize-control { + margin-left: 34px; + } + .fa { + display: block; + position: absolute; + top: 0; + left: 0; + font-size: 120%; + margin: 8px 0 0 11px; + color: #666; + } + .fa-circle-o-notch { + margin-left: 9px; + } + } +} diff --git a/components/service-forms/instagram-user/instagram-user.stache b/components/service-forms/instagram-user/instagram-user.stache new file mode 100644 index 0000000..1e0b0ec --- /dev/null +++ b/components/service-forms/instagram-user/instagram-user.stache @@ -0,0 +1,10 @@ +
+ +
+ + +
+ + {{{configErrors errors 'id'}}} +
\ No newline at end of file diff --git a/components/service-forms/meetup-group/meetup-group.js b/components/service-forms/meetup-group/meetup-group.js new file mode 100644 index 0000000..c8c46cd --- /dev/null +++ b/components/service-forms/meetup-group/meetup-group.js @@ -0,0 +1,9 @@ +import can from "can/"; +import initView from './meetup-group.stache!'; +import './meetup-group.less!'; +import "components/suggestions/"; + +can.Component.extend({ + tag : 'bh-meetup-group-service', + template : initView +}); diff --git a/components/service-forms/meetup-group/meetup-group.less b/components/service-forms/meetup-group/meetup-group.less new file mode 100644 index 0000000..8d593da --- /dev/null +++ b/components/service-forms/meetup-group/meetup-group.less @@ -0,0 +1,3 @@ +bh-meetup-group-service { + display: block; +} diff --git a/components/service-forms/meetup-group/meetup-group.stache b/components/service-forms/meetup-group/meetup-group.stache new file mode 100644 index 0000000..6905170 --- /dev/null +++ b/components/service-forms/meetup-group/meetup-group.stache @@ -0,0 +1,4 @@ +
+ + {{{configErrors errors 'id'}}} +
\ No newline at end of file diff --git a/components/service-forms/rss-site/rss-site.js b/components/service-forms/rss-site/rss-site.js new file mode 100644 index 0000000..acf39e8 --- /dev/null +++ b/components/service-forms/rss-site/rss-site.js @@ -0,0 +1,8 @@ +import can from "can/"; +import initView from './rss-site.stache!'; +import './rss-site.less!'; + +can.Component.extend({ + tag : 'bh-rss-site-service', + template : initView +}); diff --git a/components/service-forms/rss-site/rss-site.less b/components/service-forms/rss-site/rss-site.less new file mode 100644 index 0000000..404c9a2 --- /dev/null +++ b/components/service-forms/rss-site/rss-site.less @@ -0,0 +1,3 @@ +bh-rss-site-service { + display: block; +} diff --git a/components/service-forms/rss-site/rss-site.stache b/components/service-forms/rss-site/rss-site.stache new file mode 100644 index 0000000..875ff41 --- /dev/null +++ b/components/service-forms/rss-site/rss-site.stache @@ -0,0 +1,5 @@ +
+ + + {{{configErrors errors 'url'}}} +
\ No newline at end of file diff --git a/components/service-forms/stackexchange-tags/stackexchange-tags.js b/components/service-forms/stackexchange-tags/stackexchange-tags.js new file mode 100644 index 0000000..224b4f9 --- /dev/null +++ b/components/service-forms/stackexchange-tags/stackexchange-tags.js @@ -0,0 +1,9 @@ +import can from "can/"; +import initView from './stackexchange-tags.stache!'; +import './stackexchange-tags.less!'; +import 'components/tag-list/'; + +can.Component.extend({ + tag : 'bh-stackexchange-tags-service', + template : initView, +}); diff --git a/components/service-forms/stackexchange-tags/stackexchange-tags.less b/components/service-forms/stackexchange-tags/stackexchange-tags.less new file mode 100644 index 0000000..7ca4b4a --- /dev/null +++ b/components/service-forms/stackexchange-tags/stackexchange-tags.less @@ -0,0 +1,3 @@ +bh-stackexchange-tags-service { + display: block; +} diff --git a/components/service-forms/stackexchange-tags/stackexchange-tags.stache b/components/service-forms/stackexchange-tags/stackexchange-tags.stache new file mode 100644 index 0000000..9b7c4e4 --- /dev/null +++ b/components/service-forms/stackexchange-tags/stackexchange-tags.stache @@ -0,0 +1,5 @@ +
+ + + {{{configErrors errors 'tags'}}} +
\ No newline at end of file diff --git a/components/service-forms/tumblr-blog/tumblr-blog.js b/components/service-forms/tumblr-blog/tumblr-blog.js new file mode 100644 index 0000000..3fa4488 --- /dev/null +++ b/components/service-forms/tumblr-blog/tumblr-blog.js @@ -0,0 +1,8 @@ +import can from "can/"; +import initView from './tumblr-blog.stache!'; +import './tumblr-blog.less!'; + +can.Component.extend({ + tag : 'bh-tumblr-blog-service', + template : initView +}); diff --git a/components/service-forms/tumblr-blog/tumblr-blog.less b/components/service-forms/tumblr-blog/tumblr-blog.less new file mode 100644 index 0000000..a02a7c4 --- /dev/null +++ b/components/service-forms/tumblr-blog/tumblr-blog.less @@ -0,0 +1,3 @@ +bh-tumblr-blog-service { + display: block; +} diff --git a/components/service-forms/tumblr-blog/tumblr-blog.stache b/components/service-forms/tumblr-blog/tumblr-blog.stache new file mode 100644 index 0000000..5c068b5 --- /dev/null +++ b/components/service-forms/tumblr-blog/tumblr-blog.stache @@ -0,0 +1,10 @@ +
+ +
+ + + + + {{{configErrors errors 'hostname'}}} +
+
\ No newline at end of file diff --git a/components/service-forms/tumblr-tag/tumblr-tag.js b/components/service-forms/tumblr-tag/tumblr-tag.js new file mode 100644 index 0000000..a98d9fc --- /dev/null +++ b/components/service-forms/tumblr-tag/tumblr-tag.js @@ -0,0 +1,8 @@ +import can from "can/"; +import initView from './tumblr-tag.stache!'; +import './tumblr-tag.less!'; + +can.Component.extend({ + tag : 'bh-tumblr-tag-service', + template : initView +}); diff --git a/components/service-forms/tumblr-tag/tumblr-tag.less b/components/service-forms/tumblr-tag/tumblr-tag.less new file mode 100644 index 0000000..ad9a85c --- /dev/null +++ b/components/service-forms/tumblr-tag/tumblr-tag.less @@ -0,0 +1,3 @@ +bh-tumblr-tags-service { + display: block; +} diff --git a/components/service-forms/tumblr-tag/tumblr-tag.stache b/components/service-forms/tumblr-tag/tumblr-tag.stache new file mode 100644 index 0000000..1074af9 --- /dev/null +++ b/components/service-forms/tumblr-tag/tumblr-tag.stache @@ -0,0 +1,5 @@ +
+ + + {{{configErrors errors 'tag'}}} +
\ No newline at end of file diff --git a/components/service-forms/twitter-favorites/twitter-favorites.js b/components/service-forms/twitter-favorites/twitter-favorites.js new file mode 100644 index 0000000..794be3a --- /dev/null +++ b/components/service-forms/twitter-favorites/twitter-favorites.js @@ -0,0 +1,8 @@ +import can from "can/"; +import initView from './twitter-favorites.stache!'; +import './twitter-favorites.less!'; + +can.Component.extend({ + tag : 'bh-twitter-favorites-service', + template : initView +}); diff --git a/components/service-forms/twitter-favorites/twitter-favorites.less b/components/service-forms/twitter-favorites/twitter-favorites.less new file mode 100644 index 0000000..44cdb02 --- /dev/null +++ b/components/service-forms/twitter-favorites/twitter-favorites.less @@ -0,0 +1,3 @@ +bh-twitter-favorites-service { + display: block; +} diff --git a/components/service-forms/twitter-favorites/twitter-favorites.stache b/components/service-forms/twitter-favorites/twitter-favorites.stache new file mode 100644 index 0000000..f1aab0d --- /dev/null +++ b/components/service-forms/twitter-favorites/twitter-favorites.stache @@ -0,0 +1,9 @@ +
+ +
+ @ + + {{{configErrors errors 'handle'}}} +
+

Enter any Twitter user handle

+
\ No newline at end of file diff --git a/components/service-forms/twitter-followers/twitter-followers.js b/components/service-forms/twitter-followers/twitter-followers.js new file mode 100644 index 0000000..f8fb3cf --- /dev/null +++ b/components/service-forms/twitter-followers/twitter-followers.js @@ -0,0 +1,8 @@ +import can from "can/"; +import initView from './twitter-followers.stache!'; +import './twitter-followers.less!'; + +can.Component.extend({ + tag : 'bh-twitter-followers-service', + template : initView +}); diff --git a/components/service-forms/twitter-followers/twitter-followers.less b/components/service-forms/twitter-followers/twitter-followers.less new file mode 100644 index 0000000..ac3fc27 --- /dev/null +++ b/components/service-forms/twitter-followers/twitter-followers.less @@ -0,0 +1,3 @@ +bh-twitter-followers-service { + display: block; +} diff --git a/components/service-forms/twitter-followers/twitter-followers.stache b/components/service-forms/twitter-followers/twitter-followers.stache new file mode 100644 index 0000000..72fffc2 --- /dev/null +++ b/components/service-forms/twitter-followers/twitter-followers.stache @@ -0,0 +1,8 @@ +
+ +
+ @ + + {{{configErrors errors 'handle'}}} +
+
\ No newline at end of file diff --git a/components/service-forms/twitter-hashtag/twitter-hashtag.js b/components/service-forms/twitter-hashtag/twitter-hashtag.js new file mode 100644 index 0000000..2fb35b8 --- /dev/null +++ b/components/service-forms/twitter-hashtag/twitter-hashtag.js @@ -0,0 +1,8 @@ +import can from "can/"; +import initView from './twitter-hashtag.stache!'; +import './twitter-hashtag.less!'; + +can.Component.extend({ + tag : 'bh-twitter-hashtag-service', + template : initView +}); diff --git a/components/service-forms/twitter-hashtag/twitter-hashtag.less b/components/service-forms/twitter-hashtag/twitter-hashtag.less new file mode 100644 index 0000000..d07394d --- /dev/null +++ b/components/service-forms/twitter-hashtag/twitter-hashtag.less @@ -0,0 +1,3 @@ +bh-twitter-hashtag-service { + display: block; +} diff --git a/components/service-forms/twitter-hashtag/twitter-hashtag.stache b/components/service-forms/twitter-hashtag/twitter-hashtag.stache new file mode 100644 index 0000000..43af3c6 --- /dev/null +++ b/components/service-forms/twitter-hashtag/twitter-hashtag.stache @@ -0,0 +1,8 @@ +
+ +
+ # + + {{{configErrors errors 'hashtag'}}} +
+
\ No newline at end of file diff --git a/components/service-forms/twitter-term/twitter-term.js b/components/service-forms/twitter-term/twitter-term.js new file mode 100644 index 0000000..7a20873 --- /dev/null +++ b/components/service-forms/twitter-term/twitter-term.js @@ -0,0 +1,8 @@ +import can from "can/"; +import initView from './twitter-term.stache!'; +import './twitter-term.less!'; + +can.Component.extend({ + tag : 'bh-twitter-term-service', + template : initView +}); diff --git a/components/service-forms/twitter-term/twitter-term.less b/components/service-forms/twitter-term/twitter-term.less new file mode 100644 index 0000000..e2f75da --- /dev/null +++ b/components/service-forms/twitter-term/twitter-term.less @@ -0,0 +1,3 @@ +bh-twitter-term-service { + display: block; +} diff --git a/components/service-forms/twitter-term/twitter-term.stache b/components/service-forms/twitter-term/twitter-term.stache new file mode 100644 index 0000000..97829d3 --- /dev/null +++ b/components/service-forms/twitter-term/twitter-term.stache @@ -0,0 +1,5 @@ +
+ + + {{{configErrors errors 'term'}}} +
\ No newline at end of file diff --git a/components/service-forms/twitter-user-retweets/twitter-user-retweets.js b/components/service-forms/twitter-user-retweets/twitter-user-retweets.js new file mode 100644 index 0000000..e1a1210 --- /dev/null +++ b/components/service-forms/twitter-user-retweets/twitter-user-retweets.js @@ -0,0 +1,8 @@ +import can from "can/"; +import initView from './twitter-user-retweets.stache!'; +import './twitter-user-retweets.less!'; + +can.Component.extend({ + tag : 'bh-twitter-user-retweets-service', + template : initView +}); diff --git a/components/service-forms/twitter-user-retweets/twitter-user-retweets.less b/components/service-forms/twitter-user-retweets/twitter-user-retweets.less new file mode 100644 index 0000000..b796b26 --- /dev/null +++ b/components/service-forms/twitter-user-retweets/twitter-user-retweets.less @@ -0,0 +1,3 @@ +bh-twitter-user-retweets-service { + display: block; +} diff --git a/components/service-forms/twitter-user-retweets/twitter-user-retweets.stache b/components/service-forms/twitter-user-retweets/twitter-user-retweets.stache new file mode 100644 index 0000000..f1aab0d --- /dev/null +++ b/components/service-forms/twitter-user-retweets/twitter-user-retweets.stache @@ -0,0 +1,9 @@ +
+ +
+ @ + + {{{configErrors errors 'handle'}}} +
+

Enter any Twitter user handle

+
\ No newline at end of file diff --git a/components/service-forms/twitter-user-timeline/twitter-user-timeline.js b/components/service-forms/twitter-user-timeline/twitter-user-timeline.js new file mode 100644 index 0000000..cabe564 --- /dev/null +++ b/components/service-forms/twitter-user-timeline/twitter-user-timeline.js @@ -0,0 +1,8 @@ +import can from "can/"; +import initView from './twitter-user-timeline.stache!'; +import './twitter-user-timeline.less!'; + +can.Component.extend({ + tag : 'bh-twitter-user-timeline-service', + template : initView +}); diff --git a/components/service-forms/twitter-user-timeline/twitter-user-timeline.less b/components/service-forms/twitter-user-timeline/twitter-user-timeline.less new file mode 100644 index 0000000..3be894f --- /dev/null +++ b/components/service-forms/twitter-user-timeline/twitter-user-timeline.less @@ -0,0 +1,3 @@ +bh-twitter-user-timeline-service { + display: block; +} diff --git a/components/service-forms/twitter-user-timeline/twitter-user-timeline.stache b/components/service-forms/twitter-user-timeline/twitter-user-timeline.stache new file mode 100644 index 0000000..f1aab0d --- /dev/null +++ b/components/service-forms/twitter-user-timeline/twitter-user-timeline.stache @@ -0,0 +1,9 @@ +
+ +
+ @ + + {{{configErrors errors 'handle'}}} +
+

Enter any Twitter user handle

+
\ No newline at end of file diff --git a/components/service-forms/youtube-channel/youtube-channel.js b/components/service-forms/youtube-channel/youtube-channel.js new file mode 100644 index 0000000..bf487cf --- /dev/null +++ b/components/service-forms/youtube-channel/youtube-channel.js @@ -0,0 +1,8 @@ +import can from "can/"; +import initView from './youtube-channel.stache!'; +import './youtube-channel.less!'; + +can.Component.extend({ + tag : 'bh-youtube-channel-service', + template : initView +}); diff --git a/components/service-forms/youtube-channel/youtube-channel.less b/components/service-forms/youtube-channel/youtube-channel.less new file mode 100644 index 0000000..07aed3d --- /dev/null +++ b/components/service-forms/youtube-channel/youtube-channel.less @@ -0,0 +1,3 @@ +bh-youtube-channel { + display: block; +} diff --git a/components/service-forms/youtube-channel/youtube-channel.stache b/components/service-forms/youtube-channel/youtube-channel.stache new file mode 100644 index 0000000..060d72d --- /dev/null +++ b/components/service-forms/youtube-channel/youtube-channel.stache @@ -0,0 +1,4 @@ +
+ + {{{configErrors errors 'name'}}} +
diff --git a/components/service-forms/youtube-playlist/youtube-playlist.js b/components/service-forms/youtube-playlist/youtube-playlist.js new file mode 100644 index 0000000..d309ede --- /dev/null +++ b/components/service-forms/youtube-playlist/youtube-playlist.js @@ -0,0 +1,8 @@ +import can from "can/"; +import initView from './youtube-playlist.stache!'; +import './youtube-playlist.less!'; + +can.Component.extend({ + tag : 'bh-youtube-playlist-service', + template : initView +}); diff --git a/components/service-forms/youtube-playlist/youtube-playlist.less b/components/service-forms/youtube-playlist/youtube-playlist.less new file mode 100644 index 0000000..874a1e8 --- /dev/null +++ b/components/service-forms/youtube-playlist/youtube-playlist.less @@ -0,0 +1,3 @@ +bh-youtube-playlist { + display: block; +} diff --git a/components/service-forms/youtube-playlist/youtube-playlist.stache b/components/service-forms/youtube-playlist/youtube-playlist.stache new file mode 100644 index 0000000..3d95b81 --- /dev/null +++ b/components/service-forms/youtube-playlist/youtube-playlist.stache @@ -0,0 +1,4 @@ +
+ + {{{configErrors errors 'name'}}} +
diff --git a/components/service-forms/youtube-user/youtube-user.js b/components/service-forms/youtube-user/youtube-user.js new file mode 100644 index 0000000..3272f52 --- /dev/null +++ b/components/service-forms/youtube-user/youtube-user.js @@ -0,0 +1,8 @@ +import can from "can/"; +import initView from './youtube-user.stache!'; +import './youtube-user.less!'; + +can.Component.extend({ + tag : 'bh-youtube-user-service', + template : initView +}); diff --git a/components/service-forms/youtube-user/youtube-user.less b/components/service-forms/youtube-user/youtube-user.less new file mode 100644 index 0000000..ddabf7f --- /dev/null +++ b/components/service-forms/youtube-user/youtube-user.less @@ -0,0 +1,3 @@ +bh-youtube-user { + display: block; +} diff --git a/components/service-forms/youtube-user/youtube-user.stache b/components/service-forms/youtube-user/youtube-user.stache new file mode 100644 index 0000000..50a1849 --- /dev/null +++ b/components/service-forms/youtube-user/youtube-user.stache @@ -0,0 +1,3 @@ +
+ +
diff --git a/components/services-list/services-list-test.js b/components/services-list/services-list-test.js new file mode 100644 index 0000000..2254a46 --- /dev/null +++ b/components/services-list/services-list-test.js @@ -0,0 +1,132 @@ +import "./services-list"; +import QUnit from "steal-qunit"; +import F from "funcunit"; +import $ from "jquery"; +import Models from "models/"; + +F.attach(QUnit); +var template = can.stache(""); + +var renderTemplate = function(data){ + $('#qunit-fixture').html(template(data)); +}; + +var services = [ + new Models.Service({ + "error": null, + "config": { + "display_name": "bitovi", + "term": "bitovi" + }, + "entity_count": 98, + "brand_identity_id": 1, + "type_name": "term", + "feed_name": "twitter", + "id": 4 + }) +]; + +QUnit.module('Services List Test'); + +QUnit.skip('Services List is correctly rendered', function(){ + renderTemplate({ + services : new can.List(services), + currentService : new can.compute(), + state : new can.Map({ + hubId: 1, + loadingServices: [] + }) + }); + + F('bh-services-list').exists('Services list is rendered'); + F('bh-services-list tbody tr').size(1, 'Services table is rendered'); +}); + +QUnit.skip('Services can be edited', function(){ + renderTemplate({ + services : new can.List(services), + currentService : new can.compute(), + state : new can.Map({ + hubId: 1, + loadingServices: [] + }) + }); + + F('bh-services-list').exists('Services list is rendered'); + F('bh-services-list [can-click=editService]').click(); + F('bh-services-list bh-service-form').exists('Form is rendered'); +}); + +QUnit.test('Services can be destroyed', function(){ + renderTemplate({ + services : new can.List(services), + currentService : new can.compute(), + state : new can.Map({ + hubId: 1, + loadingServices: [] + }) + }); + + F('bh-services-list').exists('Services list is rendered'); + F('bh-services-list [can-click=destroyService]').exists('Destroy confirmation dialog is rendered'); +}); + +QUnit.test('Services can be in loading state', function(){ + var servicesList = new can.List(services); + renderTemplate({ + services : servicesList, + currentService : new can.compute(), + state : new can.Map({ + hubId: 1, + loadingServices: [servicesList[0]] + }) + }); + + F('bh-services-list').exists('Services list is rendered'); + F('bh-services-list tr.loader').exists('Service is in loading state'); + F('bh-services-list tr.loading-service').exists('Service is marked as loading'); +}); + +QUnit.skip('Services can have no results', function(){ + var servicesList = new can.List(services); + + renderTemplate({ + services : servicesList, + currentService : new can.compute(), + state : new can.Map({ + hubId: 1, + loadingServices: [] + }) + }); + + servicesList[0].attr('noResults', true); + + F('bh-services-list').exists('Services list is rendered'); + F('bh-services-list .no-data-alert').exists('Service has no data alert is shown'); + F('bh-services-list [can-click=hideNoResults]').click(); + F('bh-services-list .no-data-alert').missing('Service has no data alert can be hidden'); +}); + +QUnit.skip('Services can have be in error state', function(){ + var servicesList = new can.List(services); + + renderTemplate({ + services : servicesList, + currentService : new can.compute(), + state : new can.Map({ + hubId: 1, + loadingServices: [] + }) + }); + + servicesList[0].attr('error', { + klass: 'foo', + message: 'bar' + }); + + F('bh-services-list').exists('Services list is rendered'); + F('bh-services-list tr.errored-service').exists('Service is marked as in error state'); + F('bh-services-list .alert-config-error').missing('Errors are not displayed by default'); + F('bh-services-list [can-click=toggleErrorShowing]').click(); + F('bh-services-list .alert-config-error').exists('Errors are displayed'); +}); diff --git a/components/services-list/services-list.js b/components/services-list/services-list.js new file mode 100644 index 0000000..11a8ab2 --- /dev/null +++ b/components/services-list/services-list.js @@ -0,0 +1,78 @@ +import can from "can/"; +import initView from "./services-list.stache!"; +import "./services-list.less!"; +import "can/map/define/"; +import "components/delete_service_dialog/"; +import "components/service-config-formatter/"; + +can.Component.extend({ + tag : 'bh-services-list', + template : initView, + scope: { + deletingService: null, + init : function(){ + this.attr({ + shownErrors: [], + hiddenNoResults: [] + }); + }, + hideNoResults : function(service){ + this.attr('hiddenNoResults').push(service); + }, + destroyService: function( service, el, ev) { + this.attr('deletingService', service); + }, + editService:function(service){ + this.attr('currentService', service); + }, + toggleErrorShowing : function(service){ + var shownErrors = this.attr('shownErrors'), + index = shownErrors.indexOf(service); + if(index > -1){ + shownErrors.splice(index, 1); + } else { + shownErrors.push(service); + } + } + }, + helpers : { + isCurrentService : function(service, opts){ + var check; + + service = can.isFunction(service) ? service() : service; + + check = service === this.attr('currentService'); + check = check && !service.isNew(); + + return check ? opts.fn(opts.scope.add(service)) : opts.inverse(opts.scope.add(service)); + }, + isServiceCurrentlyLoading : function(service, opts){ + var currentlyLoading = this.attr('state.loadingServices'); + + service = can.isFunction(service) ? service() : service; + + if(service.isLoading() || (currentlyLoading.indexOf(service) !== -1 && !service.attr('error') && !service.attr('noResults'))){ + return opts.fn(); + } + }, + serviceHasNoResults : function(service, opts){ + service = can.isFunction(service) ? service() : service; + this.attr('hiddenNoResults').attr('length'); + if(service.attr('noResults') && this.attr('hiddenNoResults').indexOf(service) === -1){ + return opts.fn(); + } + }, + showErrorsForService : function(service, opts){ + service = can.isFunction(service) ? service() : service; + this.attr('shownErrors').attr('length'); + if(service.attr('error') && this.attr('shownErrors').indexOf(service) !== -1){ + return opts.fn(); + } + } + }, + events : { + '{currentService} created' : function(){ + this.scope.attr('currentService', null); + } + } +}); diff --git a/components/services-list/services-list.less b/components/services-list/services-list.less new file mode 100644 index 0000000..c5a8ba7 --- /dev/null +++ b/components/services-list/services-list.less @@ -0,0 +1,83 @@ +bh-services-list { + display: block; + margin: 0 -25px; + border-bottom: 1px solid #ddd; + .destroy-service, .edit-service { + cursor: pointer; + color: #666; + &:hover { + color: #333; + } + } + + table.services-table { + margin-bottom: 0; + > tbody > tr, > thead > tr { + &.service-row td, &.loader td { + border-top-color: #ddd; + } + &.loader td { + background: #97ECFF; + } + &.loading-service td { + border-top: none; + background: #97ECFF; + } + &.errored-service td { + border-top-color: #FFB8B8; + } + th { + border-bottom-color: #ddd; + } + th:first-child, td:first-child { + padding-left: 25px; + } + th:last-child, td:last-child { + padding-right: 25px; + } + th.actions { + width: 70px; + } + td.actions .fa { + display: inline-block; + margin-top: 3px; + + } + th { + color: #f30; + font-size: 16px; + } + .progress { + height: 5px; + margin: 5px 0 0; + } + } + .no-data-alert { + margin: 10px 25px; + } + .alert-config-error { + margin-bottom: 0; + background: white; + } + } + ul.config { + font-size: 12px; + margin: 0; + padding: 0 0 0 16px; + } + .toggle-errors { + cursor: pointer; + float: left; + margin: 3px 5px 0 0; + } + bh-service-config-formatter { + float: left; + } + .table > tbody > tr.current-editing-service > td { + padding-bottom: 0; + padding-top: 25px; + } + .pending-wrap { + padding: 25px; + } +} \ No newline at end of file diff --git a/components/services-list/services-list.stache b/components/services-list/services-list.stache new file mode 100644 index 0000000..be11c05 --- /dev/null +++ b/components/services-list/services-list.stache @@ -0,0 +1,58 @@ +{{#if deletingService}} + +{{/if}} +
+ + + {{#each services}} + {{#isCurrentService this}} + + + + {{else}} + {{#isServiceCurrentlyLoading this}} + + + + {{/isServiceCurrentlyLoading}} + + + + + {{#serviceHasNoResults this}} + + {{/serviceHasNoResults}} + {{#showErrorsForService this}} + + + + {{/showErrorsForService}} + {{/isCurrentService}} + {{/each}} + +
+ +
+
+
+
+
+ {{#if error}} + + {{/if}} + + + + +
+
+ + We couldn't find any data for this service. +
+
+
+ {{ formattedErrorClass }} + {{ formattedError }} +
+
+
diff --git a/components/services/services.js b/components/services/services.js new file mode 100644 index 0000000..f1320be --- /dev/null +++ b/components/services/services.js @@ -0,0 +1,67 @@ +import can from "can/"; +import Models from "models/"; +import initView from "./services.stache!"; + +import "./services.less!"; +import "components/service-form/"; +import "components/services-list/"; + +can.Component.extend({ + tag : 'bh-services', + template : initView, + scope : { + currentService : null, + define : { + services : { + get : function() { + return new Models.Service.List({ + embed_id: this.attr('state.hubId') + }); + } + } + }, + feeds : Models.Service.feeds, + toggleNewService : function(ctx, el){ + var feed = el.data('feed'); + var currentService = this.attr('currentService'); + var check = currentService && currentService.isNew() && currentService.attr('feed_name') === feed; + + if(check){ + this.attr('currentService', null); + return; + } + + this.attr('currentService', Models.Service.createEmptyService(feed)); + } + }, + events : { + init : function(){ + this.preloadIcons(); + }, + preloadIcons : function(){ + var feeds = this.scope.feeds.attr(); + var img; + for(var k in feeds){ + img = new Image(); + img.src = "/images/social-empty/" + k + '.png'; + } + } + }, + helpers : { + currentServiceIsNewAndHasFeedName : function(feedName, opts){ + var currentService = this.attr('currentService'); + + feedName = can.isFunction(feedName) ? feedName() : feedName; + + if(!currentService){ + return opts.inverse(this); + } + + if(currentService.isNew() && + currentService.attr('feed_name') === feedName){ + return opts.fn(this); + } + return opts.inverse(this); + } + } +}); diff --git a/components/services/services.less b/components/services/services.less new file mode 100644 index 0000000..d930e6d --- /dev/null +++ b/components/services/services.less @@ -0,0 +1,42 @@ +bh-services { + display: block; + .service-slider-outer-wrap { + position: relative; + margin-bottom: 20px; + } + .service-slider-wrap { + padding: 25px 0; + .new-service-picker { + margin-bottom: 0; + li { + float: left; + width: 14.285%; + height: 77px; + border: 1px solid #dad9d9; + text-align: center; + font-size: 9px; + margin-right: -1px; + margin-top: -1px; + cursor: pointer; + img { + width: 48px; + height: 48px; + display: block; + margin: 5px auto; + } + &.active { + background: white; + color: #249cb8; + } + } + } + } + .alert-error-list { + padding: 5px; + margin-top: 5px; + font-size: 85%; + } + bh-service-form { + margin-bottom: 25px; + } +} \ No newline at end of file diff --git a/components/services/services.stache b/components/services/services.stache new file mode 100644 index 0000000..716e5b9 --- /dev/null +++ b/components/services/services.stache @@ -0,0 +1,31 @@ +

Connect a service

+ +
+
    + {{#each feeds}} +
  • + {{#currentServiceIsNewAndHasFeedName @key}} + + {{else}} + + {{/currentServiceIsNewAndHasFeedName}} + {{ . }} +
  • + {{/each}} +
+
+ +{{#if currentService.isNew}} + +{{/if}} + +{{#if state.services.isPending}} +
+ Loading ... +
+{{else}} + {{#if state.services.length}} +

Connected services

+ + {{/if}} +{{/if}} diff --git a/components/services/services_test.js b/components/services/services_test.js new file mode 100644 index 0000000..17df8d9 --- /dev/null +++ b/components/services/services_test.js @@ -0,0 +1,96 @@ +import "./services"; +import QUnit from "steal-qunit"; +import F from "funcunit"; +import $ from "jquery"; +import fixture from "can/util/fixture/"; +import Models from "models/"; + +import "can/map/define/"; + +F.attach(QUnit); +var template = can.stache(""); + +var renderTemplate = function(data){ + $('#qunit-fixture').html(template(data)); +}; + +can.stache.registerHelper( + 'ifCanAddService', + function(services, feed, type, opts){ + return opts.fn(); + } +); + +var StateMap = can.Map.extend({ + define : { + services : { + get : function() { + var res = new Models.Service.List({ + embed_id: this.attr('hubId') + }); + console.log(res); + return res; + } + } + } +}); + +QUnit.module('Services Test', { + beforeEach : function(){ + var fixtureData = [ + { + "error": null, + "config": { + "display_name": "bitovi", + "term": "bitovi" + }, + "entity_count": 98, + "brand_identity_id": 1, + "type_name": "term", + "feed_name": "twitter", + "id": 4 + } + ]; + fixture('GET /api/v3/services', function(){ + return fixtureData; + }); + fixture.delay = 1000; + fixture.on = true; + }, + afterEach : function(){ + fixture('GET /api/v3/services', null); + fixture.on = false; + fixture.delay = 100; + } +}); + +QUnit.skip('Services are correctly rendered', function(){ + renderTemplate({ + state : new StateMap({ + hubId: 1, + loadingServices: [] + }) + }); + + F('bh-services').exists('Services are rendered'); + F('bh-services .pending-wrap').exists('Loader is rendered'); + F('bh-services bh-services-list').exists('Services list is rendered'); + F('bh-services .service-slider-wrap li').exists('Feed buttons are loaded'); +}); + +QUnit.skip('Clicking on a feed button will toggle the service form', function(){ + renderTemplate({ + state : new can.Map({ + hubId: 1, + loadingServices: [] + }) + }); + + F('bh-services li[can-click=toggleNewService]:first').click(); + F('bh-services bh-service-form').exists('Service form is rendered'); + F.wait(1, function(){ + ok(F('bh-services li[can-click=toggleNewService]:first').is('.active'), 'First service button is activated'); + }); + F('bh-services li[can-click=toggleNewService].active').click(); + F('bh-services li[can-click=toggleNewService].active').missing('First service button is deactivated'); +}); diff --git a/components/sidebar/sidebar.js b/components/sidebar/sidebar.js new file mode 100644 index 0000000..e49fe07 --- /dev/null +++ b/components/sidebar/sidebar.js @@ -0,0 +1,46 @@ +import can from "can/"; +import initView from "./sidebar.stache!"; + +import './sidebar.less!'; +import 'components/services/'; +import 'components/moderation/'; +import 'components/embed_publish/'; +import 'components/edit_hub_name/'; +import 'can/route/'; +import 'components/helpers'; + +can.Component.extend({ + tag : 'bh-sidebar', + template : initView, + scope : { + init : function(){ + console.log(this.attr()) +}, + menuOpen : true, + toggleSidebarPosition : function(ctx, el, ev){ + this.attr('state.sidebarIsExpanded', !this.attr('state.sidebarIsExpanded')); + }, + toggleSidebar : function(val){ + this.attr('menuOpen', val); + } + }, + events : { + init : function(){ + this.element.on('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', this.proxy('toggleMenu')); + }, + toggleMenu : function(){ + this.scope.toggleSidebar(this.scope.attr('state.sidebarIsExpanded')); + }, + '{state} sidebarIsExpanded' : function(state, ev, newVal){ + if(newVal){ + this.scope.toggleSidebar(true); + } + } + }, + helpers : { + linkToPanel : function(panel){ + panel = can.isFunction(panel) ? panel() : panel; + return can.route.url({panel: panel}, true); + } + } +}); diff --git a/components/sidebar/sidebar.less b/components/sidebar/sidebar.less new file mode 100644 index 0000000..e420861 --- /dev/null +++ b/components/sidebar/sidebar.less @@ -0,0 +1,128 @@ +bh-sidebar { + display: block; + background: #f1efef; + box-shadow: 0 0 30px rgba(0,0,0,0.2); + position: relative; + .header { + height: 50px; + line-height: 20px; + padding: 15px; + border-bottom: 1px solid #cecdcd; + margin-bottom: 15px; + .close-sidebar { + float: right; + cursor: pointer; + } + .back-to-admin { + float: left; + } + .close-sidebar, .back-to-admin { + height: 20px; + line-height: 20px; + margin-top: -20px; + } + h1 { + text-align: center; + margin: 0; + height: 20px; + line-height: 20px; + font-size: 20px; + } + } + .hub-name-wrap { + margin: 0 15px 15px; + height: 36px; + line-height: 36px; + position: relative; + h2 { + display: inline-block; + margin: 0; + font-size: 20px; + line-height: 36px; + height: 36px; + + } + b { + color: #727272; + float: left; + margin: 0px 10px 0 0; + } + } + .hub-name { + display: inline-block; + width: 429px; + } + .hub-name-is-editting { + border-bottom-color: transparent; + padding-right: 0; + } + .service-tabs { + border-bottom: 2px solid #f30; + } + .panel-link { + border: 1px solid #cecdcd; + border-bottom: none; + border-right: none; + background: #e4e3e3; + height: 37px; + float: left; + width: 33.3333%; + float: left; + line-height: 37px; + padding: 0 15px; + color: #727272; + text-transform: uppercase; + font-size: 12px; + text-align: center; + &:last-child { + border-right: none; + } + &.active { + border-color: #f30; + background: #f30; + color: white; + text-decoration: none; + } + } + .panel-container { + padding: 0 25px 25px; + overflow-y: auto; + top: 155px; + left: 0; + right: 0; + bottom: 0; + position: absolute; + } + .edit-hub-name { + position: absolute; + top: 10px; + right: 0; + cursor: pointer; + } + h2.subtitle-separator { + background: #e4e3e3; + margin: 0 -25px 0; + padding: 0 25px; + font-size: 12px; + font-weight: bold; + line-height: 40px; + text-transform: uppercase; + &:first-child { + border-top: none; + } + } + .menu-wrap { + position: absolute; + right: 0; + top: 0; + height: 50px; + width: 50px; + border-bottom: 1px solid #cecdcd; + line-height: 50px; + text-align: center; + cursor: pointer; + &:hover { + background: #ccc; + } + } +} \ No newline at end of file diff --git a/components/sidebar/sidebar.stache b/components/sidebar/sidebar.stache new file mode 100644 index 0000000..ef5766f --- /dev/null +++ b/components/sidebar/sidebar.stache @@ -0,0 +1,49 @@ +{{#if menuOpen}} + + {{#state.hub}} +
+

Hub Settings

+ + + Admin + + +
+ + + + {{#eq state.panel 'services'}} +
+ +
+ {{/eq}} + + + {{#eq state.panel 'moderation'}} +
+ +
+ {{/eq}} + + + {{#eq state.panel 'integration'}} +
+ +
+ {{/eq}} + {{/hub}} +{{else}} + +{{/if}} diff --git a/components/sidebar/sidebar_tests.js b/components/sidebar/sidebar_tests.js new file mode 100644 index 0000000..6d89a8f --- /dev/null +++ b/components/sidebar/sidebar_tests.js @@ -0,0 +1,74 @@ +import "./sidebar"; +import QUnit from "steal-qunit"; +import F from "funcunit"; +import $ from "jquery"; +import Models from "models/"; +import fixture from "can/util/fixture/"; + +F.attach(QUnit); +var template = can.stache(""); + +var renderTemplate = function(data){ + $('#qunit-fixture').html(template(data)); +}; + +var State = can.Map.extend({ + sidebarIsExpanded: true +}); + +QUnit.module('Sidebar tests', { + beforeEach : function(){ + fixture.on = true; + fixture.delay = 100; + fixture('/api/v3/filters', function(){ + return []; + }); + }, + afterEach : function(){ + fixture.on = false; + fixture('/api/v3/filters', null); + } +}); + +QUnit.test("Sidebar tabs", function(){ + var state = new State({ + panel: 'services', + loadingServices: [], + currentBrand: new Models.Brand(), + hub : new Models.Hub() + }); + + renderTemplate({ + state: state + }); + + F('bh-sidebar').exists('Sidebar is loaded'); + F('bh-sidebar .service-tabs a').size(3, 'Links are rendered'); + F('bh-sidebar .service-tabs a.active').exists('Active link is set'); + F('bh-sidebar .service-tabs a.active').text(/Services/, 'Services tab is active'); + F('bh-sidebar bh-services').exists('Services panel is loaded'); + F.wait(1, function(){ + state.attr('panel', 'moderation'); + F('bh-sidebar .service-tabs a.active').text(/Moderation/, 'Active tab is switched to moderation'); + F('bh-sidebar bh-moderation').exists('Moderation panel is rendered'); + }); +}); + +QUnit.test('Expanding/collapsing sidebar', function(){ + var state = new State({ + panel: 'services', + loadingServices: [], + currentBrand: new Models.Brand(), + hub : new Models.Hub() + }); + + renderTemplate({ + state: state + }); + + F('bh-sidebar .header').exists('Sidebar is rendered'); + F('bh-sidebar [can-click=toggleSidebarPosition]').click(); + F.wait(1, function(){ + ok(!state.attr('sidebarIsExpanded'), 'Sidebar collapsed/expanded state is reflected on the state object'); + }); +}); diff --git a/components/suggestions/suggestions.js b/components/suggestions/suggestions.js new file mode 100644 index 0000000..f9827f7 --- /dev/null +++ b/components/suggestions/suggestions.js @@ -0,0 +1,61 @@ +import initView from './suggestions.stache!'; +import Models from 'models/'; +import './suggestions.less!'; + +export var SuggestionsVM = can.Map.extend({ + enterYourOwnLabel : 'Enter your own', + pickSuggestionLabel : 'Pick a suggestion', + allowExtra : false, + isLoading : true, + init : function(){ + var self = this; + this.attr('isLoading', true); + Models.Suggestion.findAll({ + service: this.attr('service'), + brandIdentityId: this.attr('brandIdentityId') + }).then(function(data){ + self.attr({ + suggestions: data, + isLoading : false + }); + }); + }, + toggleSuggestion : function(suggestion){ + var currentSuggestion = this.attr('val'); + var newSuggestion = suggestion.attr('id'); + + if(currentSuggestion === newSuggestion){ + this.attr('val', null); + } else { + this.attr('val', suggestion.attr('id')); + } + + }, + hasExtra : function(){ + var suggestions = this.attr('suggestions'); + var length = suggestions.attr('length'); + var val = this.attr('val'); + + for(var i = 0; i < length; i++){ + if(suggestions[i].id === val){ + return false; + } + } + return !!this.attr('allowExtra'); + } +}); + +can.Component.extend({ + tag : 'bh-suggestions', + template : initView, + scope : SuggestionsVM, + helpers : { + isSelected : function(suggestion, opts){ + suggestion = can.isFunction(suggestion) ? suggestion() : suggestion; + if(suggestion.attr('id') === this.attr('val')){ + return opts.fn(); + } + return opts.inverse(); + } + } +}); diff --git a/components/suggestions/suggestions.less b/components/suggestions/suggestions.less new file mode 100644 index 0000000..d3cc854 --- /dev/null +++ b/components/suggestions/suggestions.less @@ -0,0 +1,26 @@ +bh-suggestions { + display: block; + tr { + cursor: pointer; + td:first-child { + padding-left: 15px; + } + &:first-child td { + border-top: none; + } + } + .scroll { + max-height: 215px; + overflow-y: auto; + .table { + margin-bottom: 0; + } + } + .panel { + margin-top: 10px; + } + label.enter-your-own { + display: block; + margin-top: 15px; + } +} \ No newline at end of file diff --git a/components/suggestions/suggestions.stache b/components/suggestions/suggestions.stache new file mode 100644 index 0000000..05a1e84 --- /dev/null +++ b/components/suggestions/suggestions.stache @@ -0,0 +1,35 @@ +{{#if isLoading}} +
+ Loading... +
+{{else}} + {{#if suggestions.length}} +
+
+ {{ pickSuggestionLabel }} +
+
+ + + {{#each suggestions}} + + + + {{/each}} + +
+ + {{ name }} +
+
+
+ {{else}} +
+ We couldn't load any suggestions for this feed. +
+ {{/if}} + {{#if hasExtra}} + + + {{/if}} +{{/if}} diff --git a/components/suggestions/suggestions_test.js b/components/suggestions/suggestions_test.js new file mode 100644 index 0000000..9d32cb3 --- /dev/null +++ b/components/suggestions/suggestions_test.js @@ -0,0 +1,130 @@ +import "./suggestions"; +import QUnit from "steal-qunit"; +import F from "funcunit"; +import $ from "jquery"; + +F.attach(QUnit); +import fixture from "can/util/fixture/"; + +var template = can.stache(""); + +var renderTemplate = function(data){ + $('#qunit-fixture').html(template(data)); +}; + + +var fixtureUrl = '/api/v3/services/suggestions/repo?brand_identity_id={brandIdentityId}'; + +QUnit.module('Suggestions Tests', { + beforeEach : function(){ + fixture(fixtureUrl, function(req){ + if(req.data.brandIdentityId !== '1'){ + return []; + } + return [ + { + "name": "aljosa/muchi.me", + "id": "aljosa/muchi.me" + }, + { + "name": "retro/apitizer", + "id": "retro/apitizer" + } + ]; + }); + fixture.delay = 100; + fixture.on = true; + }, + afterEach : function(){ + fixture.on = false; + fixture.delay = 0; + fixture(fixtureUrl, null); + } +}); + +QUnit.test("Suggestions are listed", function(){ + renderTemplate({ + brandIdentityId: 1, + service: 'repo' + }); + + F('bh-suggestions .loader').exists('Loader is displayed'); + F('bh-suggestions .panel').exists('Suggestions are loaded'); + F('bh-suggestions td').text(/aljosa\/muchi\.me/, 'First suggestion is rendered'); + F('bh-suggestions td').text(/retro\/apitizer/, 'Secong suggestion is rendered'); + +}); + +QUnit.test("When there are no suggestions, info is shown", function(){ + renderTemplate({ + brandIdentityId: 2, + service: 'repo' + }); + + F('bh-suggestions .panel').missing('Suggestions are not loaded'); + F('bh-suggestions .alert-info').exists('Info panel is shown instead of suggestions'); +}); + +QUnit.test("Allow extra", function(){ + renderTemplate({ + brandIdentityId: 1, + service: 'repo', + allowExtra: true + }); + + F('bh-suggestions [can-value=val]').exists('Input field for extra is shown'); + F('bh-suggestions [can-value=val]').type('foo/bar[\t]'); + F.wait(1, function() { + QUnit.equal(can.viewModel($('bh-suggestions')).attr('val'), 'foo/bar', 'Val is set to extra value'); + }); +}); + +QUnit.test("Selecting suggestion", function(){ + renderTemplate({ + brandIdentityId: 1, + service: 'repo' + }); + + F('bh-suggestions .panel').exists('Suggestions are loaded'); + F('tr:first').click(); + F('tr.info td').text(/aljosa\/muchi\.me/, 'Suggestion is selected'); + F.wait(1, function(){ + QUnit.equal(can.viewModel($('bh-suggestions')).attr('val'), 'aljosa/muchi.me', 'Suggestion is set on scope'); + }); +}); + +QUnit.test("Selecting suggestion is possible through the attribute", function(){ + renderTemplate({ + brandIdentityId: 1, + service: 'repo', + val: 'aljosa/muchi.me' + }); + F('tr.info td').text(/aljosa\/muchi\.me/, 'Suggestion is selected'); +}); + +QUnit.test("Clicking on a selected suggestion will hide it", function(){ + renderTemplate({ + brandIdentityId: 1, + service: 'repo', + val: 'aljosa/muchi.me' + }); + + F('tr.info').click(); + F('tr.info').missing('Suggestion is deselected'); +}); + +QUnit.test("Selecting a suggestion from the list will hide the extra input", function(){ + renderTemplate({ + brandIdentityId: 1, + service: 'repo', + allowExtra: true + }); + + F('[can-value=val]').exists('Extra input is shown'); + F('tr:first').click(); + F('tr.info').exists('Suggestion is selected'); + F('[can-value=val]').missing('Extra input is hidden'); + F('tr.info').click(); + F('tr.info').missing('Suggestion is deselected'); + F('[can-value=val]').exists('Extra input is shown'); +}); diff --git a/components/tag-list/tag-list-tests.js b/components/tag-list/tag-list-tests.js new file mode 100644 index 0000000..c34d498 --- /dev/null +++ b/components/tag-list/tag-list-tests.js @@ -0,0 +1,67 @@ +import {TagListVM} from "./tag-list"; +import QUnit from "steal-qunit"; +import F from "funcunit"; +import $ from "jquery"; + +F.attach(QUnit); +var template = can.stache(""); + +var renderTemplate = function(data){ + $('#qunit-fixture').html(template(data)); +}; + +var getTags = function(vm){ + return vm.attr('tags').attr(); +}; + +QUnit.module("Tag List Tests"); + +QUnit.test('Adding tags', function(){ + var tags = new can.List(); + + renderTemplate({tags: tags}); + + F('bh-tag-list').exists(); + F('bh-tag-list').click(); + F('bh-tag-list input').type('FOO '); + F.wait(1, function(){ + QUnit.assert.deepEqual(tags.attr(), ['FOO']); + }); +}); + +QUnit.test('Removing tags', function(){ + var tags = new can.List(['tag1', 'tag2']); + + renderTemplate({tags: tags}); + + F('bh-tag-list input').type('\b'); + + F.wait(1, function(){ + QUnit.assert.deepEqual(tags.attr(), ['tag1']); + }); +}); + +QUnit.test('addTag function', function(){ + var vm = new TagListVM(); + QUnit.assert.deepEqual(getTags(vm), [], 'VM is initalized with empty tag list'); + vm.addTag('foo'); + QUnit.assert.deepEqual(getTags(vm), ['foo'], 'Tag is added'); + vm.addTag('foo'); + QUnit.assert.deepEqual(getTags(vm), ['foo'], 'Duplicate tag entry is prevented'); + vm.addTag(' bar#$'); + QUnit.assert.deepEqual(getTags(vm), ['foo', 'bar'], 'Tags are cleaned before they are added to the list'); + vm.addTag(' bar$$$'); + QUnit.assert.deepEqual(getTags(vm), ['foo', 'bar'], 'Tags are cleaned before checking for duplicates'); +}); + +QUnit.test('removeTag function', function(){ + var vm = new TagListVM({ + tags : ['foo', 'bar', 'baz'] + }); + vm.removeTag(); + QUnit.assert.deepEqual(getTags(vm), ['foo', 'bar'], 'When called without argument removeTag removes last tag from the list'); + vm.removeTag('foo'); + QUnit.assert.deepEqual(getTags(vm), ['bar'], 'When called with argument, removeTag will find the tag in the list and remove it'); + vm.removeTag('foobarbaz'); + QUnit.assert.deepEqual(getTags(vm), ['bar'], 'When called with the non existing tag removeTag function will do nothing'); +}); diff --git a/components/tag-list/tag-list.js b/components/tag-list/tag-list.js new file mode 100644 index 0000000..ebd5df7 --- /dev/null +++ b/components/tag-list/tag-list.js @@ -0,0 +1,77 @@ +import can from "can/"; +import initView from "./tag-list.stache!"; +import "./tag-list.less!"; + +var KEYMAP = { + COMMA : 188, + SPACE : 32, + BACKSPACE : 8, + ENTER : 13 +}; + +export var TagListVM = can.Map.extend({ + init : function(){ + if(!this.attr('tags')){ + this.attr('tags', []); + } + }, + removeTag : function(tag){ + var tags = this.attr('tags'); + var index = tag ? tags.indexOf(tag) : tags.attr('length') - 1; + if(index >= 0){ + tags.splice(index, 1); + } + }, + addTag : function(tag){ + var tags, canAddTag; + + tag = tag.replace(/[^a-zA-Z0-9-_]/g ,""); + tags = this.attr('tags'); + canAddTag = tags.indexOf(tag) === -1; + + if(canAddTag){ + tags.push(tag); + } + } +}); + +can.Component.extend({ + tag : 'bh-tag-list', + template : initView, + scope : TagListVM, + events: { + 'input keydown' : function(el, ev){ + var val = can.trim(el.val()); + if((ev.which === KEYMAP.COMMA || + ev.which === KEYMAP.SPACE || + ev.which === KEYMAP.ENTER) && val !== ''){ + this.scope.addTag(val); + el.val(''); + if(ev.which !== KEYMAP.ENTER){ + ev.preventDefault(); + } + } else if(ev.which === KEYMAP.BACKSPACE && this.__lastSelectionStart === 0){ + this.scope.removeTag(); + } + this.__lastSelectionStart = el[0].selectionStart; + }, + 'input click': function(el){ + this.__lastSelectionStart = el[0].selectionStart; + }, + 'input focus': function(el){ + this.__lastSelectionStart = el[0].selectionStart; + }, + 'input blur' : function(el, ev){ + var val = can.trim(el.val() || ""); + if(val !== ""){ + this.scope.addTag(val); + el.val(""); + } + }, + click : function(el, ev){ + if(ev.target === this.element[0] || $(ev.target).is('.tag-list-wrap')){ + this.element.find('input').focus(); + } + } + } +}); diff --git a/components/tag-list/tag-list.less b/components/tag-list/tag-list.less new file mode 100644 index 0000000..bd4b854 --- /dev/null +++ b/components/tag-list/tag-list.less @@ -0,0 +1,25 @@ +@import "../../node_modules/bootstrap/less/mixins.less"; + +bh-tag-list { + input { + border: none; + outline: none; + box-shadow: none; + float: left; + margin-bottom: 4px; + } + .tag-list-wrap { + padding: 5px 0 0 5px; + height: auto; + } + .label { + float: left; + font-size: 95%; + font-weight: 300; + margin: 0 5px 5px 0; + .remove-tag { + cursor: pointer; + margin-right: 0; + } + } +} diff --git a/components/tag-list/tag-list.stache b/components/tag-list/tag-list.stache new file mode 100644 index 0000000..3ce5ffe --- /dev/null +++ b/components/tag-list/tag-list.stache @@ -0,0 +1,9 @@ +
+ {{#each tags}} + + {{ . }} + + + {{/each}} + +
\ No newline at end of file diff --git a/components/user-settings/user-settings.js b/components/user-settings/user-settings.js new file mode 100644 index 0000000..f2f4fb8 --- /dev/null +++ b/components/user-settings/user-settings.js @@ -0,0 +1,32 @@ +import can from "can/"; +import initView from "./user-settings.stache!"; + +import "./user-settings.less!"; + + + +export default can.Component.extend({ + template: initView, + tag: 'bh-user-settings', + scope : { + updateAccount : function(ctx, el, ev){ + var account = this.attr('state').attr('currentAccount'); + var self = this; + + this.removeAttr('notice'); + this.removeAttr('errors'); + + account.save(function(){ + can.batch.start(); + self.attr('notice', 'Your credentials were saved'); + account.removeAttr('current_password'); + account.removeAttr('password'); + account.removeAttr('password_confirmation'); + can.batch.stop(); + }, function(res){ + self.attr('errors', res.responseJSON.errors); + }); + ev.preventDefault(); + } + } +}); diff --git a/components/user-settings/user-settings.less b/components/user-settings/user-settings.less new file mode 100644 index 0000000..e69de29 diff --git a/components/user-settings/user-settings.stache b/components/user-settings/user-settings.stache new file mode 100644 index 0000000..db048a7 --- /dev/null +++ b/components/user-settings/user-settings.stache @@ -0,0 +1,64 @@ +

{{state.currentAccount.email}} Settings

+
+{{#state.currentAccount}} +{{#if notice}} +
{{notice}}
+{{/if}} +
+
+ + + {{#if errors.name}} +
+
    + {{#each errors.name}} +
  • {{.}}
  • + {{/each}} +
+
+ {{/if}} +
+
+ + + {{#if errors.current_password}} +
+
    + {{#each errors.current_password}} +
  • {{.}}
  • + {{/each}} +
+
+ {{/if}} +
+
+ + + {{#if errors.password}} +
+
    + {{#each errors.password}} +
  • {{.}}
  • + {{/each}} +
+
+ {{/if}} +
+
+ + + {{#if errors.password_confirmation}} +
+
    + {{#each errors.password_confirmation}} +
  • {{.}}
  • + {{/each}} +
+
+ {{/if}} +
+
+ +
+
+{{/state.currentAccount}} diff --git a/connect-liveservice.js b/connect-liveservice.js new file mode 100644 index 0000000..7bfb3fb --- /dev/null +++ b/connect-liveservice.js @@ -0,0 +1,42 @@ +/* globals io:true */ + +import $ from 'jquery'; + +var currentSocket; + +$(window).on('beforeunload', function(){ + if(currentSocket && currentSocket.close){ + currentSocket.close(); + } +}); + +var url = '/?embed_id={embedId}'; +var publicUrl = '/?embed_id={embedId}&tenant_name={tenantName}'; + +export default function(hubId, tenantName){ + + if(currentSocket && currentSocket.close){ + currentSocket.close(); + } + + if(typeof io !== 'undefined'){ + currentSocket = io(can.sub((tenantName ? publicUrl : url), { + embedId : hubId, + tenantName : tenantName + }), { multiplex: false }); + + currentSocket.on('connect', function() { + console.log('CONNECTED!', currentSocket.id); + }); + + currentSocket.on('connect_error', function( err ) { + console.log('CONNECTION ERROR!', err.description, err.message, err.type); + }); + + currentSocket.on('disconnect', function( msg ) { + console.log('DISCONNECTION!', msg); + }); + + return currentSocket; + } +} diff --git a/deploy-key.pem.enc b/deploy-key.pem.enc new file mode 100644 index 0000000..8dc1898 Binary files /dev/null and b/deploy-key.pem.enc differ diff --git a/embed.stache b/embed.stache new file mode 100644 index 0000000..1b6595e --- /dev/null +++ b/embed.stache @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/favicon.ico b/favicon.ico new file mode 100644 index 0000000..e69de29 diff --git a/fixtures/bits.json b/fixtures/bits.json new file mode 100644 index 0000000..46feaf3 --- /dev/null +++ b/fixtures/bits.json @@ -0,0 +1,422 @@ +{ + "data": [ + { + "id": 1, + "title": "WebCamp 2014", + "body": "Whew, WebCamp 2014 is finally behind us. After working on this year's edition for more than six months, I feel really relieved that everything went smoothly.\n\n ", + "feed_name": "rss", + "type_name": "post", + "url": "http://retroaktive.me/blog/webcamp-2014/", + "created_at": "2014-12-19T16:30:55.736Z", + "updated_at": "2014-12-19T16:30:55.736Z", + "thread_updated_ts": 1412633882, + "thread_updated_at": "2014-10-06T22:18:02.000Z", + "author": { + "id": null, + "avatar_url": null + }, + "service_ids": [ + 1 + ] + }, + { + "id": 2, + "title": "FuncUnit and Cucumber - a perfect combo for frontend testing", + "body": "This weekend I spent some time playing with FuncUnit and Cucumber. In this article I'll explain why I like this combination, and how it enables you to super charge your frontend tests.", + "feed_name": "rss", + "type_name": "post", + "url": "http://retroaktive.me/blog/funcunit-and-cucumber-a-perfect-combo-for-frontend-testing/", + "created_at": "2014-12-19T16:30:56.397Z", + "updated_at": "2014-12-19T16:30:56.397Z", + "thread_updated_ts": 1406022105, + "thread_updated_at": "2014-07-22T09:41:45.000Z", + "author": { + "id": null, + "avatar_url": null + }, + "service_ids": [ + 1 + ] + }, + { + "id": 3, + "title": "CanJS Hangouts - can-form", + "body": "Today I had an opportunity to present the can-form plugin on the CanJS weekly community hangouts. It's a plugin I plan to release somewhere next week, so the blog post about it will be published then. In the mean time check the presentation and the hangouts in the rest of the article.", + "feed_name": "rss", + "type_name": "post", + "url": "http://retroaktive.me/blog/canjs-hangouts-can-form/", + "created_at": "2014-12-19T16:30:56.733Z", + "updated_at": "2014-12-19T16:30:56.733Z", + "thread_updated_ts": 1405112126, + "thread_updated_at": "2014-07-11T20:55:26.000Z", + "author": { + "id": null, + "avatar_url": null + }, + "service_ids": [ + 1 + ] + }, + { + "id": 14, + "title": "

Napokon bina samo moja!!!

", + "body": null, + "feed_name": "tumblr", + "type_name": "photo", + "url": "http://wannabeibb.tumblr.com/post/91467710949/napokon-bina-samo-moja", + "created_at": "2014-12-19T16:33:50.677Z", + "updated_at": "2014-12-19T16:33:50.677Z", + "thread_updated_ts": 1405099585, + "thread_updated_at": "2014-07-11T17:26:25.000Z", + "author": { + "id": "wannabeibb", + "avatar_url": null + }, + "service_ids": [ + 3 + ] + }, + { + "id": 4, + "title": "Manually parse HStore data in Rails 4", + "body": "Today I needed to manually parse a string returned from the HStore with Rails 4. The fix is not as intuitive as I'd like it, so here's a note to myself and for anyone else who has a similar problem.", + "feed_name": "rss", + "type_name": "post", + "url": "http://retroaktive.me/blog/manually-parse-hstore-data-in-rails-4/", + "created_at": "2014-12-19T16:30:57.085Z", + "updated_at": "2014-12-19T16:30:57.085Z", + "thread_updated_ts": 1404419847, + "thread_updated_at": "2014-07-03T20:37:27.000Z", + "author": { + "id": null, + "avatar_url": null + }, + "service_ids": [ + 1 + ] + }, + { + "id": 5, + "title": "Setting up a CanJS project with the generator-canjs and Yeoman", + "body": "In this blog post I'll show you how to setup a CanJS project with the help of the generator-canjs and Yeoman. I'll also show you some tricks I'm using to get everything working smoothly both in the development and production modes. We'll be setting up the project to use the Bootstrap and FontAwesome for the styles and icons.", + "feed_name": "rss", + "type_name": "post", + "url": "http://retroaktive.me/blog/setting-up-a-canjs-project-with-the-generator-canjs-and-yeoman/", + "created_at": "2014-12-19T16:30:57.462Z", + "updated_at": "2014-12-19T16:30:57.462Z", + "thread_updated_ts": 1404167108, + "thread_updated_at": "2014-06-30T22:25:08.000Z", + "author": { + "id": null, + "avatar_url": null + }, + "service_ids": [ + 1 + ] + }, + { + "id": 15, + "title": "

Postalo mi dosadno ovo! Fali mi netokracija i ekipa! Mislim da cu se vratiti doma.. A i tamo mi je moj kilt, ovo je predugačko!

", + "body": null, + "feed_name": "tumblr", + "type_name": "photo", + "url": "http://wannabeibb.tumblr.com/post/90145308149/postalo-mi-dosadno-ovo-fali-mi-netokracija-i", + "created_at": "2014-12-19T16:33:51.035Z", + "updated_at": "2014-12-19T16:33:51.035Z", + "thread_updated_ts": 1403950129, + "thread_updated_at": "2014-06-28T10:08:49.000Z", + "author": { + "id": "wannabeibb", + "avatar_url": null + }, + "service_ids": [ + 3 + ] + }, + { + "id": 16, + "title": "

Zakon su rođendani s ovakvim čestitarima!

", + "body": null, + "feed_name": "tumblr", + "type_name": "photo", + "url": "http://wannabeibb.tumblr.com/post/89247883914/zakon-su-ro-endani-s-ovakvim-cestitarima", + "created_at": "2014-12-19T16:33:51.376Z", + "updated_at": "2014-12-19T16:33:51.376Z", + "thread_updated_ts": 1403171666, + "thread_updated_at": "2014-06-19T09:54:26.000Z", + "author": { + "id": "wannabeibb", + "avatar_url": null + }, + "service_ids": [ + 3 + ] + }, + { + "id": 17, + "title": "

Srijeda! Jebo posao, idealan dan za filmove!

", + "body": null, + "feed_name": "tumblr", + "type_name": "photo", + "url": "http://wannabeibb.tumblr.com/post/89144379124/srijeda-jebo-posao-idealan-dan-za-filmove", + "created_at": "2014-12-19T16:33:51.715Z", + "updated_at": "2014-12-19T16:33:51.715Z", + "thread_updated_ts": 1403081998, + "thread_updated_at": "2014-06-18T08:59:58.000Z", + "author": { + "id": "wannabeibb", + "avatar_url": null + }, + "service_ids": [ + 3 + ] + }, + { + "id": 6, + "title": "Celery - Best Practices", + "body": "

If you've worked with Django at some point you probably had the need for some background\nprocessing of long running tasks. Chances are you've used some sort of task queue, and Celery is currently\nthe most popular project for this sort of thing in the Python (and Django) world (but there are others).

\n

While working on some projects that used Celery for a task queue I've gathered a number of best practices and decided to document them.\nNevertheless, this is more a rant about what I think should be the proper way to do things, and about some underused features that the celery\necosystem offers.\n

Read more… (5 min remaining to read)

", + "feed_name": "rss", + "type_name": "post", + "url": "http://denibertovic.com/posts/celery-best-practices/", + "created_at": "2014-12-19T16:33:30.976Z", + "updated_at": "2014-12-19T16:33:30.976Z", + "thread_updated_ts": 1403045392, + "thread_updated_at": "2014-06-17T22:49:52.000Z", + "author": { + "id": null, + "avatar_url": null + }, + "service_ids": [ + 2 + ] + }, + { + "id": 18, + "title": "

Zoovi, samo zoovi, svi će sokolovi, za te život daati!! Hrvatska!! Hrvatska!! Hrvatska!!

", + "body": null, + "feed_name": "tumblr", + "type_name": "photo", + "url": "http://wannabeibb.tumblr.com/post/89047956734/zoovi-samo-zoovi-svi-ce-sokolovi-za-te-zivot", + "created_at": "2014-12-19T16:33:52.069Z", + "updated_at": "2014-12-19T16:33:52.069Z", + "thread_updated_ts": 1403001548, + "thread_updated_at": "2014-06-17T10:39:08.000Z", + "author": { + "id": "wannabeibb", + "avatar_url": null + }, + "service_ids": [ + 3 + ] + }, + { + "id": 19, + "title": "

Jebo #volimeso ovo je život!

", + "body": null, + "feed_name": "tumblr", + "type_name": "photo", + "url": "http://wannabeibb.tumblr.com/post/88958777214/jebo-volimeso-ovo-je-zivot", + "created_at": "2014-12-19T16:33:52.384Z", + "updated_at": "2014-12-19T16:33:52.384Z", + "thread_updated_ts": 1402928773, + "thread_updated_at": "2014-06-16T14:26:13.000Z", + "author": { + "id": "wannabeibb", + "avatar_url": null + }, + "service_ids": [ + 3 + ] + }, + { + "id": 20, + "title": "

Saturday night fever!! Hijaaaoo!

", + "body": null, + "feed_name": "tumblr", + "type_name": "photo", + "url": "http://wannabeibb.tumblr.com/post/88785205069/saturday-night-fever-hijaaaoo", + "created_at": "2014-12-19T16:33:52.714Z", + "updated_at": "2014-12-19T16:33:52.714Z", + "thread_updated_ts": 1402774384, + "thread_updated_at": "2014-06-14T19:33:04.000Z", + "author": { + "id": "wannabeibb", + "avatar_url": null + }, + "service_ids": [ + 3 + ] + }, + { + "id": 21, + "title": "

Odlično buđenje!

", + "body": null, + "feed_name": "tumblr", + "type_name": "photo", + "url": "http://wannabeibb.tumblr.com/post/88747327469/odlicno-bu-enje", + "created_at": "2014-12-19T16:33:53.067Z", + "updated_at": "2014-12-19T16:33:53.067Z", + "thread_updated_ts": 1402736639, + "thread_updated_at": "2014-06-14T09:03:59.000Z", + "author": { + "id": "wannabeibb", + "avatar_url": null + }, + "service_ids": [ + 3 + ] + }, + { + "id": 22, + "title": "

Dosta mi je bilo nerdovskog života, marketinških partija i netokracijinog ureda! Odlučio sam otkriti svijet! #RunForrestRun

", + "body": null, + "feed_name": "tumblr", + "type_name": "photo", + "url": "http://wannabeibb.tumblr.com/post/88697022289/dosta-mi-je-bilo-nerdovskog-zivota-marketinskih", + "created_at": "2014-12-19T16:33:53.411Z", + "updated_at": "2014-12-19T16:33:53.411Z", + "thread_updated_ts": 1402692900, + "thread_updated_at": "2014-06-13T20:55:00.000Z", + "author": { + "id": "wannabeibb", + "avatar_url": null + }, + "service_ids": [ + 3 + ] + }, + { + "id": 7, + "title": "Setting up Systemd on Debian in 10 minutes", + "body": "

Recently I've been reading more and more about Systemd. Now, most distros have already moved to\nSystemd but I'm using Debian and was stuck with init which was the default. Given the recent\ndiscussion on the Debian mailing lists about migrating to systemd as the new default, I was even more\ninclined to make the switch now and get used to it before it's forced upon us.

\n

Actually I was really looking forward to it, but as Linux goes I was expecting it to be a pain, so I\nwas pleasantly surprised that it only took me 10 minutes and wasn't a hassle at all.

\n

I've decided to document the steps I've taken in case that someone finds it useful.\n

Read more… (1 min remaining to read)

", + "feed_name": "rss", + "type_name": "post", + "url": "http://denibertovic.com/posts/setting-up-systemd-on-debian-in-10-minutes/", + "created_at": "2014-12-19T16:33:31.314Z", + "updated_at": "2014-12-19T16:33:31.314Z", + "thread_updated_ts": 1396799466, + "thread_updated_at": "2014-04-06T15:51:06.000Z", + "author": { + "id": null, + "avatar_url": null + }, + "service_ids": [ + 2 + ] + }, + { + "id": 8, + "title": "Docker and Logstash: Smarter Log Management For Your Containers", + "body": "

Docker currently supports getting logs from a container that logs to stdout/stderr.\nEverything that the process running in the container writes to stdout or stderr docker will\nconvert to json and store in a file on the host machine's disk which you can then\nretrieve with the docker logs command.

\n

This is handy but it has its drawbacks because you don't get any log rotation and the file\nsize of the collected logs can become an issue as it eats up your host's disk space. Not to mention\nthe fact that every time you run docker logs container_id you get all the logs of that processes from\nthe beginning.

\n

While there are some interesting things being discussed on the docker-dev mailing list,\nI wanted to see if I could get docker to play along with proven logging systems out there with the\nfunctionality I have now.\n

Read more… (4 min remaining to read)

", + "feed_name": "rss", + "type_name": "post", + "url": "http://denibertovic.com/posts/docker-and-logstash-smarter-log-management-for-your-containers/", + "created_at": "2014-12-19T16:33:31.632Z", + "updated_at": "2014-12-19T16:33:31.632Z", + "thread_updated_ts": 1391463526, + "thread_updated_at": "2014-02-03T21:38:46.000Z", + "author": { + "id": null, + "avatar_url": null + }, + "service_ids": [ + 2 + ] + }, + { + "id": 9, + "title": "Classes for all the things?", + "body": "

Recently I've been thinking a lot about how to simplify my code. Now, the key thing to note\nhere is that simple != familiar.

\n

Classes for example are familiar to most people. But code consisting exclusively of classes\nand OOP concepts isn't necessarily simple all of the time. The question arises: Is there something\nsimpler?

\n

Well, the first thing that comes to mind, of course, good old functions.\nFunctions are universal, everybody understand them, even new programmers that don't yet get all\nthe fancy concepts about OOP get plain old functions.

\n

Keep in mind, I'm not saying that classes don't have their place in our code, but rather that maybe we don't\nneed them quite as often as we might think.\n

Read more… (4 min remaining to read)

", + "feed_name": "rss", + "type_name": "post", + "url": "http://denibertovic.com/posts/classes-for-all-the-things/", + "created_at": "2014-12-19T16:33:31.941Z", + "updated_at": "2014-12-19T16:33:31.941Z", + "thread_updated_ts": 1390062054, + "thread_updated_at": "2014-01-18T16:20:54.000Z", + "author": { + "id": null, + "avatar_url": null + }, + "service_ids": [ + 2 + ] + }, + { + "id": 10, + "title": "The switch to Nikola", + "body": "

I switched Blog engines because I wasn't very happy with the one I was using (Syte)\nand I wanted something more simple. Something that wold let me focus on writing and not maintaining\ncode. Don't get me wrong, Syte is an awesome project, it just seems like way too much.\nAnd the deal breaker for me was the fact that it used Tumblr for hosting blog posts and Tumblr\nhas one of the worst online editors ever. It's just not made for writing.\n

Read more… (1 min remaining to read)

", + "feed_name": "rss", + "type_name": "post", + "url": "http://denibertovic.com/posts/the-switch-to-nikola/", + "created_at": "2014-12-19T16:33:32.303Z", + "updated_at": "2014-12-19T16:33:32.303Z", + "thread_updated_ts": 1378325005, + "thread_updated_at": "2013-09-04T20:03:25.000Z", + "author": { + "id": null, + "avatar_url": null + }, + "service_ids": [ + 2 + ] + }, + { + "id": 11, + "title": "One-liner Instant Postgres for your development environment", + "body": "

When working on web applications it's very important to have a setup as similar to the production\nenvironment as possible.

\n

The major component here is using the same database locally, for development, as you use in\nproduction. I myself work mostly with Django and, as most of you Django devs know, it's very\neasy to get started using a Sqlite database.\n

Read more… (5 min remaining to read)

", + "feed_name": "rss", + "type_name": "post", + "url": "http://denibertovic.com/posts/57513642221/", + "created_at": "2014-12-19T16:33:32.677Z", + "updated_at": "2014-12-19T16:33:32.677Z", + "thread_updated_ts": 1375771293, + "thread_updated_at": "2013-08-06T06:41:33.000Z", + "author": { + "id": null, + "avatar_url": null + }, + "service_ids": [ + 2 + ] + }, + { + "id": 12, + "title": "Pixbin.us just got an API", + "body": "

Took us awhile but Pixbin just got an API. Well…the beginning of one at least. You heard it here first folks. :)\nYou can now upload images from your code.\n

Read more… (1 min remaining to read)

", + "feed_name": "rss", + "type_name": "post", + "url": "http://denibertovic.com/posts/32625923174/", + "created_at": "2014-12-19T16:33:33.007Z", + "updated_at": "2014-12-19T16:33:33.007Z", + "thread_updated_ts": 1349078661, + "thread_updated_at": "2012-10-01T08:04:21.000Z", + "author": { + "id": null, + "avatar_url": null + }, + "service_ids": [ + 2 + ] + }, + { + "id": 13, + "title": "Finally", + "body": "

I’ve been struggling for a while now with the idea of writing a blog.\nThe problem was that I never got around to actually making the site and months passed by.\n

Read more… (1 min remaining to read)

", + "feed_name": "rss", + "type_name": "post", + "url": "http://denibertovic.com/posts/30680397805/", + "created_at": "2014-12-19T16:33:33.321Z", + "updated_at": "2014-12-19T16:33:33.321Z", + "thread_updated_ts": 1346486828, + "thread_updated_at": "2012-09-01T08:07:08.000Z", + "author": { + "id": null, + "avatar_url": null + }, + "service_ids": [ + 2 + ] + } + ] +} \ No newline at end of file diff --git a/fixtures/embeds.json b/fixtures/embeds.json new file mode 100644 index 0000000..ba16a75 --- /dev/null +++ b/fixtures/embeds.json @@ -0,0 +1,6 @@ +[{ + "id": 1, + "name": "foo", + "colorscheme": null, + "layout": null +}] \ No newline at end of file diff --git a/fixtures/fixtures.js b/fixtures/fixtures.js new file mode 100644 index 0000000..de7735c --- /dev/null +++ b/fixtures/fixtures.js @@ -0,0 +1,12 @@ +steal( +'can/util/fixture', +function(fixture){ + + can.fixture('/api/v3/embeds/{hubId}/entities', "./fixtures/bits.json"); + can.fixture('/api/v3/embeds', "./fixtures/embeds.json"); + can.fixture('/api/v3/identities', "./fixtures/identities.json"); + can.fixture('/api/v3/services', "./fixtures/services.json"); + + can.fixture.on = true; + can.fixture.delay = 0; +}); diff --git a/fixtures/identities.json b/fixtures/identities.json new file mode 100644 index 0000000..483a5a0 --- /dev/null +++ b/fixtures/identities.json @@ -0,0 +1,22 @@ +{ + "data": [ + { + "id": 3, + "provider": "meetup", + "uid": "13295091", + "brand_id": 1 + }, + { + "id": 2, + "provider": "twitter", + "uid": "14880314", + "brand_id": 1 + }, + { + "id": 1, + "provider": "disqus", + "uid": "86150", + "brand_id": 1 + } + ] +} \ No newline at end of file diff --git a/fixtures/services.json b/fixtures/services.json new file mode 100644 index 0000000..fb5b0e4 --- /dev/null +++ b/fixtures/services.json @@ -0,0 +1,28 @@ +[ + { + "id": 1, + "feed_name": "rss", + "type_name": "site", + "config": { + "url": "http://retroaktive.me/rss", + "tag_with": "retroaktive" + } + }, + { + "id": 2, + "feed_name": "rss", + "type_name": "site", + "config": { + "url": "https://denibertovic.com/rss.xml", + "tag_with": "deni" + } + }, + { + "id": 3, + "feed_name": "tumblr", + "type_name": "blog", + "config": { + "hostname": "wannabeibb.tumblr.com" + } + } +] \ No newline at end of file diff --git a/homepage_embed/bit/bit.js b/homepage_embed/bit/bit.js new file mode 100755 index 0000000..797c229 --- /dev/null +++ b/homepage_embed/bit/bit.js @@ -0,0 +1,212 @@ +import can from "can/"; +import initView from "./bit.stache!"; +import _map from "lodash/collection/map"; + +import "./image-gallery/image-gallery"; +import "./body-wrap/body-wrap"; +import "./share-bit/share-bit"; + +import "./bit.less!"; +import "can/construct/super/super"; + +// Image loading statuses +var IMAGE_STATUSES = { + LOADING : 'LOADING', + LOADED : 'LOADED', + ERROR : 'ERROR' +}; + +// check image's status. It's either still loading, loaded or errored +var imageStatus = function(img){ + if(!img.complete){ + return IMAGE_STATUSES.LOADING; + } + if(img.naturalWidth === 0){ + return IMAGE_STATUSES.ERROR; + } + return IMAGE_STATUSES.LOADED; +}; + +export var BitVM = can.Map.extend({ + actionFail: null, + sharePanelOpen: false, + toggleApproveBit : function(){ + if(this.attr('bit.is_approved')){ + this.disapproveBit(); + } else { + this.approveBit(); + } + }, + togglePinBit : function(){ + if(this.attr('bit.is_pinned')){ + this.unpinBit(); + } else { + this.pinBit(); + } + }, + actionFailTitle : function(){ + var actionFail = this.attr('actionFail'); + return actionFail === 'disapprove' ? 'block' : actionFail; + }, + removeFailNotice : function(){ + this.attr('actionFail', null); + }, + showAdminPanel : function(){ + return !!this.attr('state').isAdmin() && !(this.attr('actionFail')); + }, + sharePanelToggle : function(){ + this.attr('sharePanelOpen', !this.attr('sharePanelOpen')); + }, + shouldRender : function(){ + var bit = this.attr('bit'); + return bit && !bit.attr('@pendingRender'); + }, + blockedClass : function(){ + if(!!this.attr('state').isAdmin() && !this.attr('bit').attr('is_approved')){ + return 'blocked'; + } + return ""; + }, + pinnedClass : function(){ + if(!!this.attr('state').isAdmin() && this.attr('bit').attr('is_pinned')){ + return 'pinned'; + } + return ""; + } +}); + +var BIT_ACTIONS = ['pin', 'unpin', 'approve', 'disapprove']; + +for(var i = 0; i < BIT_ACTIONS.length; i++){ + BitVM.prototype[BIT_ACTIONS[i] + 'Bit'] = (function(action){ + return function(){ + var self = this; + var def = this.attr('bit')[action](this.attr('state.hubId')); + def.fail(function(){ + self.attr('actionFail', action); + }); + }; + })(BIT_ACTIONS[i]); +} + +can.Component.extend({ + tag: 'bh-bit', + template : initView, + scope : BitVM, + helpers : { + formattedTitle : function(title){ + title = can.isFunction(title) ? title() : title; + if(title && title !== 'undefined'){ + return title; + } + return ""; + } + }, + events : { + inserted : function(){ + var bit = this.scope.attr('bit'); + + if(!bit.attr('@pendingRender')){ + this.__initTimeout = setTimeout(this.proxy('initImages')); + } + + // We need to wait until the bit was loaded to calculate it's height + // When the bit is loaded the `animate-height` class is removed from the bit + // which will cause the height transition. After the transition is done + // we remove the explicit height so bit can be resized based on user's actions. + // If bit was already on the page we don't have to wait for all images to load + // before removing the height. + if(!bit.attr('@resolvedHeight')){ + this.element.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', this.proxy('removeExplicitHeight')); + + } else { + this.removeExplicitHeight(); + } + }, + '{bit} @pendingRender' : function(bit, ev, newVal){ + if(newVal === false){ + setTimeout(() => { + if(this.element){ + this.__initTimeout = setTimeout(this.proxy('initImages')); + this.bitLoadedAndRendered(); + } + }, 1); + } + }, + initImages : function(){ + this.imgs = this.element.find('img').toArray(); + this.imagesToLoadCount = this.imgs.length; + + if(this.imgs.length){ + this.__imgSweeperTimeout = setTimeout(this.proxy('imgSweeper'), 500); + } else { + this.doneLoading(); + } + }, + 'a click' : function(el, ev){ + ev.preventDefault(); + window.open(el.attr('href')); + this.element.trigger('interaction:link', [this.scope.attr('state.hubId'), this.scope.attr('bit.id')]); + }, + // Go through all images and make sure all are loaded or errored + // Before calling the `doneLoading` function which will remove the loading class + imgSweeper : function(){ + var statuses = _map(this.imgs, imageStatus); + var errored; + + // If any of the images is still loading, check again in 500ms + if(can.inArray(IMAGE_STATUSES.LOADING, statuses) > -1){ + this.__imgSweeperTimeout = setTimeout(this.proxy('imgSweeper'), 500); + } else { + this.doneLoading(); + } + + for(var i = 0; i < statuses.length; i++){ + if(statuses[i] === IMAGE_STATUSES.ERROR){ + errored = this.imgs.splice(i, 1)[0]; + if(errored){ + $(errored).remove(); + } + } + } + }, + // All images in bit are loaded and we can calculate it's height. We set the explicit height + // to make sure that that the transition animation runs. + doneLoading : function(){ + var bit = this.scope.attr('bit'); + if(!bit.attr('@resolvedHeight')){ + this.element.find('.bit-wrap').height(this.element.find('.bit').height()); + } + bit.attr('@isLoaded', true); + this.bitLoadedAndRendered(); + }, + // When we're done with the height transition remove the explicit height + // and mark the bit's height as resolved + removeExplicitHeight : function(){ + var self = this; + this.__removeExplicitHeightTimeout = setTimeout(function(){ + self.scope.attr('bit').attr('@resolvedHeight', true); + if(self.element){ + self.element.find('.bit-wrap').css('height', 'auto'); + self.bitLoadedAndRendered(); + } + }, 1); + }, + bitLoadedAndRendered : function(){ + var bit = this.scope.attr('bit'); + var check = bit.attr('@resolvedHeight') && bit.attr('@isLoaded') && !bit.attr('@pendingRender'); + + if(check){ + this.element.trigger('bit:loaded'); + } + + }, + // Clean up the timeouts + destroy : function(){ + clearTimeout(this.__imgSweeperTimeout); + clearTimeout(this.__initTimeout); + clearTimeout(this.__removeExplicitHeightTimeout); + return this._super.apply(this, arguments); + } + } +}); diff --git a/homepage_embed/bit/bit.less b/homepage_embed/bit/bit.less new file mode 100755 index 0000000..ff4d5cf --- /dev/null +++ b/homepage_embed/bit/bit.less @@ -0,0 +1,391 @@ +@import "../node_modules/bootstrap/less/mixins.less"; +@import "../node_modules/bootstrap/less/variables.less"; + +.border-radius (@radius: @baseBorderRadius) { + border-radius: @radius; + -moz-border-radius: @radius; + -webkit-border-radius: @radius; +} + +@gray-darker: lighten(#000, 13.5%); // #222 +@gray-dark: lighten(#000, 20%); // #333 +@gray: lighten(#000, 33.5%); // #555 +@gray-light: lighten(#000, 80.7%); // #777 +@gray-lighter: lighten(#000, 93.5%); // #eee + +@brand-primary: #428bca; +@brand-success: #5cb85c; +@brand-info: #5bc0de; +@brand-warning: #f0ad4e; +@brand-danger: #d9534f; + +// custom brand colors +@white: #fff; + +bh-bit { + display: block; + .bit-wrap { + .border-radius(5px); + position: relative; + background-color: @white; + border: 1px solid @gray-light; + overflow: hidden; + margin: 20px 10px 0; + opacity: 1; + -webkit-transition: opacity 0.2s ease-in-out; + -moz-transition: opacity 0.2s ease-in-out; + transition: opacity 0.2s ease-in-out; + + &.animate-height { + -webkit-transition: height 0.5s ease-in, opacity 0.2s ease-in-out; + -moz-transition: height 0.5s ease-in, opacity 0.2s ease-in-out; + transition: height 0.5s ease-in, opacity 0.2s ease-in-out; + } + + &.blocked { + border: 2px solid red; + background: #FFDDDD; + bh-body-wrap .expand-collapse { + box-shadow: 0 0 20px 10px #FFDDDD; + } + } + + &.pinned { + border: 2px solid gold; + } + + &:hover { + .admin-panel { + display: block; + } + } + + &.loading { + height: 100px; + background: url(../images/card-loader.gif); + background-repeat: no-repeat; + background-position: 50% 50%; + .bit { + opacity: 0; + } + } + + &.loading, &.animate-height { + &:hover { + .admin-panel { + display: none; + } + } + } + + &:hover { + .box-shadow(0 0 20px rgba(0,0,0,.15)); + } + + .current-image-wrap img { + .border-top-radius(4px); + } + + // Default "Clear" Theme + .bit { + -webkit-transition: opacity 0.5s ease-in-out; + -moz-transition: opacity 0.5s ease-in-out; + transition: opacity 0.5s ease-in-out; + .clearfix; + + // header + .bit-header, + .bit-footer { + padding: 10px 0; + .clearfix; + } + .bit-footer { + border-top: 1px solid lighten(@gray-light, 5%); + padding: 10px; + figcaption { + float: left; + max-width: 85%; + .bit-authorName a { + width: 100%; + display:block; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } + } + + } + .bit-avatar { + float: left; + margin-right: 10px; + .bit-avatar--img { + width: 35px; + height: 35px; + border-radius: 50%; + } + } + .bh-icon { + font-size: 1.5em; + float: right; + margin-top: 6px; + &:hover { + text-decoration: none; + } + } + .bh-icon-twitter { + color: #55acee; + } + .bh-icon-youtube { + color: #cc181e; + } + .bh-icon-facebook { + color: #3b5998; + } + .bh-icon-instagram { + color: #3f729b; + } + .bh-icon-flickr { + color: #FF0084; + } + .bh-icon-googleplus { + color: #d73d32; + } + .bh-icon-tumblr { + color: #2d4661; + } + .share-fb { + width: 70px; + } + .share-tw { + width: 76px; + margin-right:20px; + } + // Content + .bit-content--media { + max-height: 350px; + overflow-y: auto; + overflow-x: hidden; + } + .bit-content--caption { + padding-bottom: 15px; + iframe { + display: block; + } + p .img-wrap { + margin: 0 -15px 15px; + img { + width: 100%; + } + } + } + .img-responsive { + margin:0 auto; + } + } + + + .bit-content { + overflow: hidden; + bh-body-wrap h4 { + padding-left: 15px; + padding-right: 15px; + p { + padding-left: 0; + padding-right: 0; + } + } + p { + padding: 0 15px; + &:last-child { + margin-bottom: 0; + } + } + .body-inner-wrap { + padding: 0 15px 15px; + pre { + margin-left: -15px; + margin-right: -15px; + } + p { + padding: 0; + } + .iframe-wrap { + margin: 0 -15px; + } + p .img-wrap { + margin: 0 -15px; + } + } + pre { + border-radius: 0; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-left: none; + border-right: none; + padding: 10px 15px; + } + } + + .bit-created-at { + font-size: 70%; + position: relative; + top: -3px; + } + .image-wrap { + margin: 0 -15px 10px; + position: relative; + img { + width: 100%; + } + } + .admin-panel { + background: rgba(0, 0, 0, 0.85); + position: absolute; + z-index: 10000; + color: #bbb; + height: 30px; + width: 200px; + top: 0; + left: 50%; + margin-left: -100px; + border--webkit-border-bottom-right-radius: 3px; + -webkit-border-bottom-left-radius: 3px; + -moz-border-radius-bottomright: 3px; + -moz-border-radius-bottomleft: 3px; + border-bottom-right-radius: 3px; + border-bottom-left-radius: 3px; + display: none; + .disapprove-approve, .pin { + top: 0; + width: 50%; + height: 100%; + position: absolute; + cursor: pointer; + img { + height: 24px; + opacity: 0.7; + display: inline-block; + } + .action-is { + cursor: pointer; + text-align: center; + text-transform: uppercase; + font-weight: bold; + font-size: 12px; + line-height: 30px; + } + &:hover { + background: rgba(0,0,0,0.5); + color: white; + img { + opacity: 1; + } + } + } + .disapprove-approve { + left: 0; + -webkit-border-bottom-left-radius: 3px; + -moz-border-radius-bottomleft: 3px; + border-bottom-left-radius: 3px; + } + .pin { + -webkit-border-bottom-right-radius: 3px; + -moz-border-radius-bottomright: 3px; + border-bottom-right-radius: 3px; + right: 0; + } + } + .social-icon { + float: right; + width: 32px; + height: 32px; + img { + width: 100%; + height: 100%; + } + } + bh-body-wrap.tall .body-inner-wrap p:last-child { + margin-bottom: -15px; + } + .action-fail-alert { + background: rgba(255,0,0,0.85); + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + color: white; + display: inline-block; + div { + height: 40px; + position: absolute; + top: 50%; + left: 0; + right: 0; + margin-top: -20px; + text-align: center; + padding: 0 20px; + } + i { + position: absolute; + top: 20px; + right: 20px; + cursor: pointer; + color: #E29A9A; + &:hover { + color: white; + } + } + } + .share-panel-toggle { + float: right; + font-size: 24px; + margin: 5px; + color: #9a9a9a; + cursor: pointer; + &:hover, &.open { + color: @brand-primary; + } + } + .youtube-embed-container { + position: relative; + padding-bottom: 56.25%; + height: 0; + overflow: hidden; + max-width: 100%; + iframe, object, embed { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + } + } + } + bh-share-bit { + position: relative; + z-index: 100000; + } +} +.dark-theme { + bh-bit { + .bit-wrap { + color: #eee; + background: #1f1f1f; + border-color: #444; + .bit-footer { + border-top-color: #444; + } + &.loading { + background: url(../images/card-loader-dark.gif); + background-repeat: no-repeat; + background-position: 50% 50%; + } + } + + } + bh-share-bit { + background: #444; + border-color: #444; + } +} diff --git a/homepage_embed/bit/bit.stache b/homepage_embed/bit/bit.stache new file mode 100755 index 0000000..cee3877 --- /dev/null +++ b/homepage_embed/bit/bit.stache @@ -0,0 +1,85 @@ +{{#if shouldRender}} + {{#bit}} +
+ {{#if showAdminPanel}} +
+
+
+ + {{#is_approved}} + Block + {{else}} + Approve + {{/is_approved}} +
+
+ +
+
+ + {{#is_pinned}} + Unpin + {{else}} + Pin + {{/is_pinned}} +
+
+
+ {{/if}} + +
+
+ + {{#if images.length}} + + {{/if}} + + {{#if isYoutube}} +
+ '); + CURRENT_IFRAME = iframe[0]; + } + + return CURRENT_IFRAME; + } + } + }, + iframeSrc : { + get : function(){ + var currentBrand = this.attr('currentBrand'); + var hubId = this.attr('hubId'); + + if(hubId && currentBrand){ + return this.attr('preset').url(currentBrand.attr('tenant_name'), hubId); + } + }, + serialize: false + }, + adminPreset : { + value : Models.Preset.ADMIN, + serialize: false + }, + defaultPreviewPreset : { + value : Models.Preset.PREVIEW, + serialize: false + }, + preset : { + get : function(){ + var embedType = this.embedType(); + var customPreset; + + if(embedType === 'admin'){ + return this.attr('adminPreset'); + } else { + customPreset = this.attr('customPreset'); + return customPreset || this.attr('defaultPreviewPreset'); + } + }, + set : function(val){ + var embedType = this.embedType(); + var adminPreset = this.attr('adminPreset'); + + if(embedType === 'admin'){ + adminPreset.attr('config').attr(val.attr ? val.attr() : val); + return val; + } + }, + serialize : function(){ + var embedType = this.embedType(); + var adminPreset = this.attr('adminPreset'); + var adminParams; + if(adminPreset){ + adminPreset.attr(); + } + + + if(embedType === 'admin'){ + adminParams = { + order: adminPreset.attr('config.order'), + decision: adminPreset.attr('config.decision') + }; + + if(adminPreset.attr('config.service_id')){ + adminParams.service_id = adminPreset.attr('config.service_id'); + } + + return adminParams; + } + } + }, + customPreset: { + serialize: false + }, + hub : { + serialize : false, + get : function(lastSetValue, setAttrValue){ + Models.Hub.findOne({id: this.attr('hubId')}) + .then(function(hub){ + setAttrValue(hub); + }); + } + }, + services : { + get : function() { + return new Models.Service.List({ + embed_id: this.attr('hubId') + }); + } + }, + sidebarIsExpanded : { + value : true, + serialize: false + }, + loadingServices : { + value : [], + serialize: false + }, + bits : { + Value : Models.Bit.List, + serialize: false + }, + scrollTop : { + value : 0, + serialize: false + }, + scrollHeight: { + value : 0, + serialize: false + }, + currentBrand : { + serialize: false + } + }, + init : function(){ + var self = this; + this.communicator = Communicator.bind(this.compute('iframe'), { + loadedBits : function(payload){ + self.bitsWereLoaded(payload); + } + }); + }, + updateIframeAttrs : function(){ + var preset = this.attr('preset'); + var currentBrand = this.attr('currentBrand'); + var hubId = this.attr('hubId'); + var newAttrs; + + if(preset && currentBrand && hubId){ + newAttrs = preset.embedAttrs(currentBrand.attr('tenant_name'), hubId); + this.communicator.send('updateAttrs', newAttrs); + } + }, + resetEmbed : function(){ + this.communicator.send('reset'); + }, + bitsWereLoaded : function(serviceIds){ + var loadingServices = this.attr('loadingServices'); + var loadingServicesByIds = _reduce(loadingServices, function(acc, service){ + acc[service.attr('id') + ""] = service; + return acc; + }, {}); + var index; + + for(var i = 0; i < serviceIds.length; i++){ + if(loadingServicesByIds[serviceIds[i]]){ + index = loadingServices.indexOf(loadingServicesByIds[serviceIds[i]]); + loadingServices.splice(index, 1); + } + } + }, + isAdminEmbed : function(){ + var preset = this.attr('preset'); + return preset && preset.attr('config.view') === 'admin'; + }, + theme : function(){ + var preset = this.attr('preset'); + return (preset && preset.attr('config.theme')) || 'light'; + }, + isSidebar : function(){ + return this.attr('page') === 'sidebar' && this.attr('hubId'); + }, + embedType : function(){ + return this.attr('embedType'); + }, + embedTypeTitle : function(){ + var titles = { + admin: 'Administration', + preview: 'Preview' + }; + return titles[this.embedType()]; + }, + isAnalyticsPageActive : function(){ + return this.attr('page') === 'analytics'; + }, + setDecision : function(ctx, el, ev){ + var decision = el.data('decision'); + this.attr('preset.config.decision', decision); + } +}); diff --git a/models/bit.js b/models/bit.js new file mode 100644 index 0000000..abade6a --- /dev/null +++ b/models/bit.js @@ -0,0 +1,91 @@ +import can from "can/"; +import Bit from "bithub-embed/models/bit"; + +import "can/list/promise/"; +import "can/map/define/"; + +var checkIfBitIsBelowCurrentBit = function(bit, currentBit){ + if(!currentBit){ + return false; + } + if(currentBit.is_pinned){ + return true; + } + return bit.thread_updated_ts < currentBit.thread_updated_ts; +}; + +var isFullBit = function(bit){ + return !!bit.created_at; +}; + +var buffer = (function(){ + var _buffer = []; + var _currentSweeper; + + return { + add : function(bit){ + _buffer.push(bit); + if(!_currentSweeper){ + _currentSweeper = setTimeout(function(){ + var localBuffer = _buffer.splice(0).reverse(); + for(var i = 0; i < localBuffer.length; i++){ + can.trigger(Bit, 'lifecycle', [localBuffer[i]]); + } + _currentSweeper = null; + }, 5000); + } + } + }; +})(); + +Bit.messageFromLiveService = function(msg){ + //console.log('MSG FROM LIVE SERVICE', msg); + var parsed = JSON.parse(msg); + parsed._isFromLiveService = true; + + if(this.store[parsed.id]){ + this.store[parsed.id].attr(parsed); + } else if(isFullBit(parsed)){ + buffer.add(this.model(parsed)); + } + if(!parsed.decision === 'deleted'){ + can.trigger(Bit, 'disapproved', [this.store[parsed.id]]); + } +}; + +Bit.List = Bit.List.extend({ + place : function(bit){ + var index = -1; + var currentIndex, currentBit; + + this.attr('length'); + + currentIndex = this.indexOf(bit); + + // if it exists in the list remove it because we are changing the order + if(currentIndex > -1){ + this.splice(currentIndex, 1); + } + + if(bit.attr('is_pinned')){ + do { + index++; + currentBit = this.attr(index); + } while(currentBit && currentBit.attr('is_pinned')); + } else { + do { + index++; + currentBit = this.attr(index); + } while(checkIfBitIsBelowCurrentBit(bit, currentBit)); + } + + this.splice(index, 0, bit); + } +}); + +Bit.prototype.isPublic = function(){ + var d = this.attr('decision') + return d === 'approved' || d === 'starred'; +} + +export default Bit; diff --git a/models/brand.js b/models/brand.js new file mode 100644 index 0000000..fa75590 --- /dev/null +++ b/models/brand.js @@ -0,0 +1,5 @@ +import can from "can/"; + +export default can.Model.extend({ + findOne : '/api/v3/brands/current' +}, {}); diff --git a/models/embed_appstate.js b/models/embed_appstate.js new file mode 100644 index 0000000..077d4d7 --- /dev/null +++ b/models/embed_appstate.js @@ -0,0 +1,128 @@ +import can from "can/"; +import Bit from "models/bit"; +import connectLiveService from "connect-liveservice"; +import "can/map/define/"; + +var addDefaultAttrs = function(params){ + var defaultParams = { + view: 'public', + theme: 'light', + live: false + }; + return can.extend(defaultParams, params); +}; + +var liveService; + +export default can.Map.extend({ + define : { + live : { + set : function(val){ + return (val === true || val === 'true'); + } + }, + hub : { + serialize : false, + }, + bits : { + Value : Bit.List, + serialize: false + }, + currentBrand : { + serialize: false + }, + }, + setAttrs : function(attrs){ + this.attr(addDefaultAttrs(attrs)); + }, + init : function(){ + this.setDefaultParams(); + }, + isLive : function(){ + return this.attr('live'); + }, + isPublic : function(){ + return !this.isAdmin(); + }, + isGroupedByDate : function(){ + return this.attr('order') === 'grouped-by-date'; + }, + showPoweredBy : function(){ + return this.isPublic(); + }, + reset : function(){ + can.batch.start(); + this.setDefaultParams(); + this.bits.splice(0); + can.batch.stop(); + }, + getView : function(){ + if(this.isAdmin()){ + return 'admin'; + } + return 'public'; + }, + connectLiveService : function(){ + + var hubId = this.attr('hubId'); + liveService = connectLiveService(hubId, this.attr('tenant')); + console.log('HUB ID', hubId, liveService, this.attr('tenant')) + + if(liveService){ + console.log('LIVESERVICE ENTITIES', liveService); + + liveService.on('entities', can.proxy(Bit.messageFromLiveService, Bit)); + } + }, + getParams: function(){ + var hubId = this.attr('hubId'); + var params = {}; + var tenant = this.attr('tenant'); + var isPublic = this.isPublic(); + var decision = this.attr('decision'); + var serviceId = this.attr('service_id'); + var imageOnly = this.attr('image_only'); + + imageOnly = imageOnly === true || imageOnly === 'true'; + + params.view = this.getView(); + + if(isPublic){ + params.tenant_name = tenant; + if(decision === 'approved' || decision === 'starred'){ + params.decision = decision; + } + } else { + params.order = this.attr('order') || "created_at:desc"; + if(params.order === 'grouped-by-date'){ + params.order = 'preview'; + } + if(decision){ + params.decision = decision; + } + if(serviceId){ + params.service_id = serviceId; + } + } + + if(imageOnly){ + params.image_only = true; + } + + + params.hubId = hubId; + + console.log(params) + + return params; + }, + setDefaultParams : function(){ + this.attr('params', { + offset: 0, + limit: 50 + }); + }, + isAdmin : function(){ + return this.attr('hub') && this.attr('view') === 'admin'; + } +}); diff --git a/models/filter.js b/models/filter.js new file mode 100644 index 0000000..0da7591 --- /dev/null +++ b/models/filter.js @@ -0,0 +1,91 @@ +import can from "can/"; +import NatlangQuery from "./natlang-query"; +import "can/map/define/"; +import "can/construct/super/"; + +var ModerationRuleset = can.Model.extend({ + resource : "/api/v3/filters", + destroy : function(id, data){ + return $.ajax({ + url : "/api/v3/filters/" + id + "?embed_id=" + data.filter.embed_id, + type : "DELETE" + }); + } +}, { + define : { + natlang_queries: { + Value : NatlangQuery.List, + set : function(val){ + return new NatlangQuery.List(can.map(val, function(v){ + return NatlangQuery.model(v); + })); + } + }, + }, + addQuery : function(){ + this.natlang_queries.push(new NatlangQuery()); + }, + removeQuery : function(filter){ + var natlang = this.attr('natlang_queries'); + var index = natlang.indexOf(filter); + if(index > -1){ + natlang.splice(index, 1); + } + }, + serialize : function(){ + var data = this._super.apply(this, arguments); + return { + filter: data + }; + }, + markToDestroy : function(){ + this.attr('__shouldDelete', true); + }, + saveOrDestroy : function(){ + if(this.attr('__shouldDelete')){ + return this.destroy(); + } + return this.save(); + } +}); + +ModerationRuleset.List = ModerationRuleset.List.extend({ + blocking : function(){ + return this.filtersByAction('block'); + }, + approving : function(){ + return this.filtersByAction('approve'); + }, + filtersByAction : function(action){ + var list = new this.constructor(); + var length = this.attr('length'); + var current; + for(var i = 0; i < length; i++){ + current = this.attr(i); + if(current.attr('action') === action){ + list.push(current); + } + } + list.attr('action', action); + return list; + }, + addFilter : function(embedId){ + var filter = new ModerationRuleset({action: this.attr('action'), embed_id: embedId}); + filter.addQuery(); + this.push(filter); + }, + removeFilter : function(filter){ + var index = this.indexOf(filter); + + if(index > -1){ + this.splice(index, 1); + } + }, + saveOrDestroy : function(){ + return $.when.apply($, can.map(this, function(f){ + f.saveOrDestroy(); + })); + } +}); + +export default ModerationRuleset; diff --git a/models/hub.js b/models/hub.js new file mode 100644 index 0000000..cc6b8f5 --- /dev/null +++ b/models/hub.js @@ -0,0 +1,48 @@ +import can from "can/"; +import ServiceModel from './service'; +import 'can/list/promise/'; +import 'can/construct/super/'; +import 'can/map/backup/'; +import 'can/map/define/'; + +var Bit = can.Model.extend({ + resource : '/api/v3/embeds', +}, { + define : { + services : { + get : function(){ + return new ServiceModel.List({embed_id: this.attr('id')}); + } + } + }, + serialize : function(){ + return { + embed : this._super.apply(this, arguments) + }; + }, + moderate : function(){ + return $.ajax({ + type : 'POST', + url : '/api/v3/embeds/' + this.attr('id') + '/moderate' + }); + }, + publish : function(){ + return $.ajax({ + type: 'PUT', + url: '/api/v3/embeds/' + this.attr('id') + '/publish' + }).then(function(data){ + Bit.model(data); + }); + }, + unpublish : function(){ + return $.ajax({ + type: 'PUT', + url: '/api/v3/embeds/' + this.attr('id') + '/unpublish' + }).then(function(data){ + Bit.model(data); + }); + } + +}); + +export default Bit; diff --git a/models/identity.js b/models/identity.js new file mode 100644 index 0000000..47d6a44 --- /dev/null +++ b/models/identity.js @@ -0,0 +1,20 @@ +import can from "can/"; +import "can/list/promise/"; + +var identities; + +export default can.Model.extend({ + resource : '/api/v3/identities', + getAll : function(){ + return this.reloadAll(); + }, + reloadAll : function(){ + var def = new this.List({}); + + def.then(function(data){ + identities = data; + }); + + return def; + } +}, {}); diff --git a/models/interaction_event.js b/models/interaction_event.js new file mode 100644 index 0000000..0d82cc1 --- /dev/null +++ b/models/interaction_event.js @@ -0,0 +1,127 @@ +import can from "can/"; +import moment from "moment"; +import "can/construct/super/"; + +var wrapCreate = function(data){ + return { + interaction: data + }; +}; + +var InteractionEvent = can.Model.extend({ + create : 'POST /api/v3/interactions', + findAll : 'GET /api/v3/interactions', + + createScrollInteraction : function(tenant_name, hubId){ + return this.create(wrapCreate({ + tenant_name: tenant_name, + primary_source_id: hubId, + primary_source_type: 'Embed', + event_type: 'scroll' + })); + }, + createLinkClickedInteraction : function(tenant_name, hubId, entityId){ + return this.create(wrapCreate({ + tenant_name: tenant_name, + primary_source_id: hubId, + primary_source_type: 'Embed', + secondary_source_id: entityId, + secondary_source_type: 'Entity', + event_type: 'link' + })); + }, + createEntitySharedInteraction : function(tenant_name, hubId, entityId, target){ + return this.create(wrapCreate({ + tenant_name: tenant_name, + primary_source_id: hubId, + primary_source_type: 'Embed', + secondary_source_id: entityId, + secondary_source_type: 'Entity', + event_type: 'share', + event_subtype: target + })); + } +}, {}); + +var fillZeroes = function(data, length){ + while(data.length < length){ + data.unshift(0); + } + return data; +}; + +InteractionEvent.List = InteractionEvent.List.extend({ + totalShareInteractionsGraphData: function(){ + var length = this.attr('length'); + var labels = []; + var data = []; + var i; + for(i = 0; i < length; i++){ + labels.push(moment(this.attr(i + '.created_at')).fromNow()); + data.push(this.attr(i + '.volume')); + } + + return { + datasets: [{ + data: data, + label: "Share count", + strokeColor: '#f30', + fillColor: '#fff' + }], + labels: labels + }; + }, + linkInteractionsGraphData : function(){ + return this.totalShareInteractionsGraphData(); + }, + scrollInteractionsGraphData : function(){ + return this.totalShareInteractionsGraphData(); + }, + perNetworkShareInteractionsGraphData : function(){ + var length = this.attr('length'); + var labels = {}; + var data = {}; + var longestLabels = []; + var datasets = []; + var i, k, current, currentSubtype; + + for(i = 0; i < length; i++){ + current = this.attr(i); + currentSubtype = current.attr('event_subtype'); + if(!data[currentSubtype]){ + data[currentSubtype] = []; + } + if(!labels[currentSubtype]){ + labels[currentSubtype] = []; + } + data[currentSubtype].push(current.attr('volume')); + labels[currentSubtype].push(moment(current.attr('created_at')).fromNow()); + } + + for(k in labels){ + if(labels[k].length > longestLabels.length){ + longestLabels = labels[k]; + } + } + + for(k in data){ + if(data[k].length < longestLabels.length){ + data[k] = fillZeroes(data[k], longestLabels.length); + } + datasets.push({ + label: k, + data: data[k], + strokeColor: '#f30', + fillColor: 'rgba(255,255,255,0)' + }); + } + + return { + labels: longestLabels, + datasets: datasets + }; + + } +}); + +export default InteractionEvent; diff --git a/models/models.js b/models/models.js new file mode 100644 index 0000000..9294c5e --- /dev/null +++ b/models/models.js @@ -0,0 +1,27 @@ +import Hub from './hub'; +import Service from './service'; +import Bit from './bit'; +import Identity from './identity'; +import Suggestion from './suggestion'; +import Brand from './brand'; +import Preset from './preset'; +import Analytics from './analytics'; +import Subscription from './subscription'; +import Filter from './filter'; +import Account from './account'; +import Organization from "./organization"; + +export default { + Hub : Hub, + Service : Service, + Bit : Bit, + Identity : Identity, + Suggestion : Suggestion, + Brand : Brand, + Preset: Preset, + Analytics : Analytics, + Subscription : Subscription, + Filter : Filter, + Account : Account, + Organization: Organization +}; diff --git a/models/natlang-query.js b/models/natlang-query.js new file mode 100644 index 0000000..3effca9 --- /dev/null +++ b/models/natlang-query.js @@ -0,0 +1,36 @@ +import can from "can/"; +import "can/map/define/"; + +export default can.Model.extend({}, { + define : { + operation : { + set : function(val){ + var typeAndOp = val.split(":"); + var type = typeAndOp.shift(); + var op = typeAndOp.shift(); + + this.attr({ + is_negated: (type !== 'pos'), + op : op + }); + }, + get : function(){ + var type = this.attr('is_negated') ? 'neg' : 'pos'; + var op = this.attr('op'); + return [type, op].join(':'); + } + }, + attr_name : { + value : 'content' + }, + op : { + value : 'contains_all', + set : function(val){ + return val; + } + }, + is_negated : { + value : false + } + } +}); diff --git a/models/organization.js b/models/organization.js new file mode 100644 index 0000000..6a758b5 --- /dev/null +++ b/models/organization.js @@ -0,0 +1,35 @@ +import can from "can/"; + +export default can.Model.extend({ + findOne : '/api/v3/current/organization', + update: 'PUT /api/v3/current/organization', + current : function(){ + return this.findOne({}); + }, + choose : function(id){ + return $.ajax({ + url: '/api/v3/current/organization/choose?id=' + id, + type: 'PUT' + }); + } +}, { + invite : function(email){ + var def = can.Deferred(); + $.post('/api/v3/current/organization/accounts', {account: {email: email}}).then(function(res){ + def.resolve(res.account); + }, function(){ + $.post('/accounts/invitation', {account: {email: email}}).then(function(res){ + def.resolve(res); + }, function(){ + def.reject(); + }); + }); + return def; + }, + addInvitation: function(invitation){ + if(!this.attr('invitations')){ + this.attr('invitations', []); + } + this.attr('invitations').push(invitation); + } +}); diff --git a/models/preset.js b/models/preset.js new file mode 100644 index 0000000..37476ae --- /dev/null +++ b/models/preset.js @@ -0,0 +1,83 @@ +/* globals EMBED_ENDPOINT:true */ + +import can from "can/"; + +import 'can/construct/super/'; +import 'can/map/define/'; +import 'can/list/promise/'; +import 'can/map/backup/'; + +var EMBED_TEMPLATE = '{hubName} Embed'; + +var Preset = can.Model.extend({ + resource: '/api/v3/presets', +}, { + define : { + config : { + value : function(){ + return { + theme: 'light', + view: 'public' + }; + } + } + }, + embedAttrs : function(tenantName, hubId){ + return can.extend({ + hubId: hubId, + tenant: tenantName + }, this.serialize().preset.config || {}); + }, + url : function(tenantName, hubId){ + var attrs = this.embedAttrs(tenantName, hubId); + return '/embed?' + can.param(attrs); + }, + fullUrl : function(tenantName, hubId){ + return can.sub("http://{embedEndpoint}{embedUrl}", { + embedEndpoint: EMBED_ENDPOINT, + embedUrl: this.url(tenantName, hubId) + }); + }, + embedCode : function(tenantName, hubId, hubName){ + return can.sub(EMBED_TEMPLATE, { + embedEndpoint : EMBED_ENDPOINT, + embedUrl: this.url(tenantName, hubId), + hubName: hubName + }); + }, + serialize : function(){ + var data = this._super.apply(this, arguments); + if(!data.config){ + data.config = {}; + } + if(!data.config.view){ + data.config.view = 'public'; + } + if(!data.config.live){ + delete data.config.live; + } + + return { + preset: data + }; + } +}); + +Preset.ADMIN = new Preset({ + config: { + live: true, + view: 'admin', + order: 'grouped-by-date', + decision: 'pending' + } +}); + +Preset.PREVIEW = new Preset({ + name : 'Default Preset', + config: { + live: false, + decision: 'approved' + } +}); + +export default Preset; diff --git a/models/service.js b/models/service.js new file mode 100644 index 0000000..6b81065 --- /dev/null +++ b/models/service.js @@ -0,0 +1,350 @@ +import can from "can/"; +import _keys from "lodash-amd/modern/object/keys"; + +import 'can/list/promise/'; +import 'can/map/define/'; +import 'can/construct/super/'; + +var RELOAD_TIMEOUTS = {}; + +var isCelluloidError = function(klass){ + return (/celluloid/).test(klass.toLowerCase()); +}; + +var isConfigError = function(klass){ + return (/configerror/).test(klass.toLowerCase()); +}; + +var getErrorMessage = (function(){ + var MESSAGES = { + autherror: "We are unable to authorize with your service credentials. Are you sure you have rights to access this content?", + remoteerror: "Service is currently unavailable. We will try to load data again later.", + unknownerror: "We are so sorry. Unknown error occured when we tried to load data from this service. We have been notified about this error, and we'll try to fix it as soon as possible.", + ratelimiterror: "Due to number of services authorized with the same account we are unable to load data from this service at the moment. We will try again soon." + }; + return function(error){ + var klass = error.klass.toLowerCase(); + return MESSAGES[klass] || error.message; + }; +})(); + + +var convertHexToRgb = function(hex){ + var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + var r, g, b; + if(result){ + r = parseInt(result[1], 16); + g = parseInt(result[2], 16); + b = parseInt(result[3], 16); + var res = 'rgb(' + r + ',' + g + ',' + b + ')'; + return res; + } + return 'rgb(0,0,0)'; +}; + +var GRAPH_COLORS = { + disqus : convertHexToRgb('#ffe842'), + facebook : convertHexToRgb('#80a2bd'), + foursquare : convertHexToRgb('#655557'), + github : convertHexToRgb('#191749'), + instagram : convertHexToRgb('#450d0b'), + meetup : convertHexToRgb('#062233'), + rss : convertHexToRgb('#183a37'), + stackexchange : convertHexToRgb('#95b26e'), + tumblr : convertHexToRgb('#c44900'), + twitter : convertHexToRgb('#432534'), + youtube : convertHexToRgb('#432834') +}; + + +var TYPES = { + disqus : { + forum : 'Forum' + }, + facebook : { + page : 'Page', + public_page : 'Public Page' + }, + foursquare : { + venue : 'Venue' + }, + github : { + org : 'Organization', + repo : 'Repository' + }, + instagram : { + tag : 'Tag', + // location : 'Location', + // geography : 'Geography', + user : 'User' + }, + meetup : { + group : 'Group' + }, + rss : { + site : 'URL' + }, + stackexchange : { + tags : 'Tags' + }, + tumblr : { + blog : 'Blog', + tag : 'Tag' + }, + twitter : { + followers : 'Followers', + hashtag : 'Hashtag', + term : 'Search', + user_timeline : 'User Timeline', + user_retweets: 'User Retweets', + favorites: 'User Favorites' + }, + youtube : { + channel : "Channel", + playlist: "Playlist"/*, + user : "User"*/ + } +}; + +var FEEDS = { + disqus : 'Disqus', + facebook : 'Facebook', + foursquare : 'Foursquare', + github : 'GitHub', + instagram : 'Instagram', + meetup : 'Meetup', + rss : 'RSS', + stackexchange : 'StackExchange', + tumblr : 'Tumblr', + twitter : 'Twitter', + youtube : 'YouTube' +}; + +var NEEDS_OAUTH = { + github : { + types : ['repo', 'org'] + }, + twitter : { + types : ['followers', 'hashtag', 'user_timeline', 'term', 'favorites', 'user_retweets'] + }, + meetup : { + types : ['group'] + }, + facebook : { + types : ['page'] + }, + foursquare : { + types : ['venue'] + }, + disqus : { + types: ['forum'] + }, + instagram : { + types: ['tag', 'user'] + }, + youtube : { + types: ['channel', 'playlist', 'user'] + } +}; + +var formatKey = function(key){ + if(key === 'url'){ + return 'URL'; + } + return can.capitalize(key.replace(/_/g, ' ')); +}; + +var formatConfig = function(config){ + var res = ['
    ']; + for(var k in config){ + res.push('
  • ' + formatKey(k) + ': '); + if(can.isPlainObject(config[k])){ + res.push(formatConfig(config[k])); + } else { + res.push(config[k]); + } + res.push('
  • '); + } + res.push('
'); + return res.join(''); +}; + +var emptyConfigForService = function(feed){ + var config = {}; + + if(feed === 'github'){ + config.tracking = {}; + } + + if(feed === 'stackexchange'){ + config.tags = []; + } + return config; +}; + +var Service = can.Model.extend({ + resource : '/api/v3/services', + feeds : FEEDS, + needsOAuth : NEEDS_OAUTH, + createEmptyService : function(feed){ + + return new this({ + feed_name : feed, + config: emptyConfigForService(feed) + }); + }, + errored : function(service){ + can.trigger(this, 'errored', [this]); + }, + messageFromLiveService : function( msg ) { + var cb = can.noop, + timeout = 1, + self = this, + timeoutKey; + + if(typeof msg === 'string'){ + msg = JSON.parse(msg); + } + + timeoutKey = msg.service.id; + + if(msg.service.empty_results){ + timeoutKey = msg.service.id + '-noResults'; + cb = function(service){ + if(service.attr('entity_count') === 0){ + service.hasNoResults(); + } + }; + timeout = 2000; + } + + clearTimeout(RELOAD_TIMEOUTS[timeoutKey]); + + RELOAD_TIMEOUTS[timeoutKey] = setTimeout(function(){ + self.findOne({id: msg.service.id}).then(cb); + }, timeout); + } +}, { + define : { + feed_name : { + set : function(val){ + var keys = _keys(TYPES[val]); + + this.attr('type_name', keys.length === 1 ? keys[0] : ""); + this.attr('graphColor', GRAPH_COLORS[val]); + + return val; + } + }, + type_name : { + set : function(val){ + this.attr('config', emptyConfigForService(this.attr('feed_name'))); + return val; + } + }, + error : { + set : function(val){ + var klass = val && val.klass; + if(klass && isCelluloidError(klass)){ + return; + } + return val; + } + }, + approved_by_default : { + set : function(val){ + return !!val; + } + } + }, + serialize : function(){ + var data = this._super.apply(this, arguments); + + if(!(data.feed_name === 'instagram' && data.type_name === 'user') && !(data.feed_name === 'facebook' && data.type_name === 'public_page')){ + if(data.config){ + delete data.config.display_name; + } + } + + return { + service : data + }; + }, + typesForFeed : function(){ + var currentFeed = this.attr('feed_name'), + types = TYPES[currentFeed]; + + return types; + }, + hasMultipleTypes : function(){ + var typesForFeed = this.typesForFeed(); + return _keys(typesForFeed || {}).length > 1; + }, + printFeed : function() { + return FEEDS[ this.attr('feed_name') ]; + }, + printType : function() { + return TYPES[ this.attr('feed_name') ][ this.attr('type_name') ]; + }, + printConfig: function() { + var output = [], + config = this.attr('config'); + + config = config ? config.attr() : config; + + if(!config){ + return; + } + + for( var key in config ) { + output.push(key + ': ' + config[key]); + } + + // remove last ', ' + return output.join('
'); + }, + hasNoResults : function(){ + can.batch.start(); + if(this.attr('_isNewlyCreated')){ + this.attr('noResults', true); + } + this.attr({ + error: null + }); + can.batch.stop(); + }, + clearNoResults : function(){ + this.removeAttr('noResults'); + }, + save : function(){ + this.removeAttr('noResults'); + can.trigger(this.constructor, 'saving', [this]); + return this._super.apply(this, arguments); + }, + formattedConfig : function(){ + return formatConfig(this.attr('config').attr()); + }, + formattedError : function(){ + return getErrorMessage(this.attr('error')); + }, + formattedErrorClass : function(){ + var klass = this.attr('error.klass'); + return !isConfigError(klass) ? '' : 'Configuration Error'; + }, + clearErrors : function(){ + this.removeAttr('error'); + }, + isLoading : function(){ + return this.attr('state') === 'loading'; + } +}); + +Service.on('created', function(ev, service){ + service.attr('_isNewlyCreated', true); +}); + +Service.on('updated', function(ev, service){ + service.attr('_isNewlyCreated', true); +}); + +export default Service; diff --git a/models/subscription.js b/models/subscription.js new file mode 100644 index 0000000..a5394ef --- /dev/null +++ b/models/subscription.js @@ -0,0 +1,36 @@ +import can from "can/"; + +export default can.Model.extend({ + findOne: '/api/v3/subscriptions/current' +}, { + reload : function(){ + this.constructor.findOne({}); + }, + canAddHub : function(hubs){ + return true; + /*var currentLength = hubs.attr('length'); + var limit = this.attr('plan.limits.embeds_per_brand') || Infinity; + return currentLength < limit;*/ + }, + canAddService : function(services, feed, type){ + return true; + /*var currentLength = services.attr('length'); + var limit = this.attr('plan.limits.services_per_embed') || Infinity; + var currentTypeFeed = [feed, type].join('_'); + var limitCurrentTypeFeed = this.attr('plan.limits').attr(currentTypeFeed) || Infinity; + var servicesWithCurrentTypeFeed = services.filter(function(s){ + return s.attr('feed_name') === feed && s.attr('type_name') === type; + }); + + if(currentLength >= limit){ + return false; + } + if(servicesWithCurrentTypeFeed.attr('length') >= limitCurrentTypeFeed){ + return false; + } + return true;*/ + }, + hasCC : function(){ + return !!this.attr('card'); + } +}); diff --git a/models/suggestion.js b/models/suggestion.js new file mode 100644 index 0000000..6c930d6 --- /dev/null +++ b/models/suggestion.js @@ -0,0 +1,4 @@ +import can from "can/"; +export default can.Model.extend({ + findAll : '/api/v3/services/suggestions/{service}?brand_identity_id={brandIdentityId}' +}, {}); diff --git a/new-app/components/admin-embed/admin-embed.js b/new-app/components/admin-embed/admin-embed.js new file mode 100644 index 0000000..46eebc0 --- /dev/null +++ b/new-app/components/admin-embed/admin-embed.js @@ -0,0 +1,48 @@ +import can from "can"; +import initView from "./admin-embed.stache!"; +import "./admin-embed.less!"; + +import Bit from "models/bit"; +import Preset from "models/preset"; +import "can/map/define/"; +import "components/bit/"; +import $ from "jquery"; +import iframe from "iframe-resizer/js/index"; + + +export default can.Component.extend({ + tag : 'bh-admin-embed', + template: initView, + scope : { + define : { + iframe : { + get : function(){ + var src = this.attr('iframeSrc'); + var iframe; + + if(src){ + iframe = $(''); + setTimeout(function(){ + iframe.iFrameResize({heightCalculationMethod: 'lowestElement'}); + }, 1); + return iframe[0]; + } + } + }, + iframeSrc : { + get : function(){ + var currentBrand = this.attr('appState.currentBrand'); + var hubId = this.attr('appState.currentHub.id'); + + if(hubId && currentBrand){ + return Preset.ADMIN.url(currentBrand.attr('tenant_name'), hubId); + } + }, + serialize: false + }, + }, + init : function(){ + var self = this; + } + } +}); diff --git a/new-app/components/admin-embed/admin-embed.less b/new-app/components/admin-embed/admin-embed.less new file mode 100644 index 0000000..6f45e7e --- /dev/null +++ b/new-app/components/admin-embed/admin-embed.less @@ -0,0 +1,8 @@ +bh-admin-embed { + iframe { + width: 100%; + overflow: hidden; + border: none; + min-height: 300px; + } +} diff --git a/new-app/components/admin-embed/admin-embed.stache b/new-app/components/admin-embed/admin-embed.stache new file mode 100644 index 0000000..257b333 --- /dev/null +++ b/new-app/components/admin-embed/admin-embed.stache @@ -0,0 +1,5 @@ +
+ {{{ iframe }}} +
+ + diff --git a/new-app/components/analytics-page/analytics-page.js b/new-app/components/analytics-page/analytics-page.js new file mode 100644 index 0000000..6e8e0c2 --- /dev/null +++ b/new-app/components/analytics-page/analytics-page.js @@ -0,0 +1,10 @@ +import can from "can"; +import initView from "./analytics-page.stache!"; + +import "./analytics-page.less!"; +import "components/empty-slate/"; + +export default can.Component.extend({ + tag: 'bh-analytics-page', + template: initView +}); diff --git a/new-app/components/analytics-page/analytics-page.less b/new-app/components/analytics-page/analytics-page.less new file mode 100644 index 0000000..e69de29 diff --git a/new-app/components/analytics-page/analytics-page.stache b/new-app/components/analytics-page/analytics-page.stache new file mode 100644 index 0000000..a295f7c --- /dev/null +++ b/new-app/components/analytics-page/analytics-page.stache @@ -0,0 +1,2 @@ +

ANALYTICS

+ diff --git a/new-app/components/bit/bit.js b/new-app/components/bit/bit.js new file mode 100644 index 0000000..af2799a --- /dev/null +++ b/new-app/components/bit/bit.js @@ -0,0 +1,222 @@ +import can from "can/"; +import initView from "./bit.stache!"; +import _map from "lodash/collection/map"; +import moment from "moment"; + +import "./image-gallery/image-gallery"; +import "./body-wrap/body-wrap"; +import "./share-bit/share-bit"; + +import "./bit.less!"; +import "can/construct/super/super"; + +// Image loading statuses +var IMAGE_STATUSES = { + LOADING : 'LOADING', + LOADED : 'LOADED', + ERROR : 'ERROR' +}; + +// check image's status. It's either still loading, loaded or errored +var imageStatus = function(img){ + if(!img.complete){ + return IMAGE_STATUSES.LOADING; + } + if(img.naturalWidth === 0){ + return IMAGE_STATUSES.ERROR; + } + return IMAGE_STATUSES.LOADED; +}; + +export var BitVM = can.Map.extend({ + actionFail: null, + sharePanelOpen: false, + toggleApproveBit : function(){ + if(this.attr('bit.is_approved')){ + this.disapproveBit(); + } else { + this.approveBit(); + } + }, + togglePinBit : function(){ + if(this.attr('bit.is_pinned')){ + this.unpinBit(); + } else { + this.pinBit(); + } + }, + actionFailTitle : function(){ + var actionFail = this.attr('actionFail'); + return actionFail === 'disapprove' ? 'block' : actionFail; + }, + removeFailNotice : function(){ + this.attr('actionFail', null); + }, + showAdminPanel : function(){ + return !!this.attr('state').isAdmin() && !(this.attr('actionFail')); + }, + sharePanelToggle : function(){ + this.attr('sharePanelOpen', !this.attr('sharePanelOpen')); + }, + shouldRender : function(){ + var bit = this.attr('bit'); + return bit && !bit.attr('@pendingRender'); + }, + blockedClass : function(){ + if(!!this.attr('state').isAdmin() && !this.attr('bit').attr('is_approved')){ + return 'blocked'; + } + return ""; + }, + pinnedClass : function(){ + if(!!this.attr('state').isAdmin() && this.attr('bit').attr('is_pinned')){ + return 'pinned'; + } + return ""; + } +}); + +var BIT_ACTIONS = ['pin', 'unpin', 'approve', 'disapprove']; + +for(var i = 0; i < BIT_ACTIONS.length; i++){ + BitVM.prototype[BIT_ACTIONS[i] + 'Bit'] = (function(action){ + return function(){ + var self = this; + var def = this.attr('bit')[action](this.attr('state.hubId')); + def.fail(function(){ + self.attr('actionFail', action); + }); + }; + })(BIT_ACTIONS[i]); +} + +can.Component.extend({ + tag: 'bh-bit', + template : initView, + scope : BitVM, + helpers : { + formattedTitle : function(title){ + title = can.isFunction(title) ? title() : title; + if(title && title !== 'undefined'){ + return title; + } + return ""; + }, + formattedQuotedTweetDate : function(date){ + date = can.isFunction(date) ? date() : date; + return moment(date, 'dd MMM DD HH:mm:ss ZZ YYYY').format('LL'); + } + }, + events : { + inserted : function(){ + var bit = this.scope.attr('bit'); + + this.element.data('bitId', bit.attr('id')); + + if(!bit.attr('@pendingRender')){ + this.__initTimeout = setTimeout(this.proxy('initImages')); + } + + // We need to wait until the bit was loaded to calculate it's height + // When the bit is loaded the `animate-height` class is removed from the bit + // which will cause the height transition. After the transition is done + // we remove the explicit height so bit can be resized based on user's actions. + // If bit was already on the page we don't have to wait for all images to load + // before removing the height. + if(!bit.attr('@resolvedHeight')){ + this.element.one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', this.proxy('removeExplicitHeight')); + + } else { + this.removeExplicitHeight(); + } + }, + '{bit} @pendingRender' : function(bit, ev, newVal){ + if(newVal === false){ + setTimeout(() => { + if(this.element){ + this.__initTimeout = setTimeout(this.proxy('initImages')); + this.bitLoadedAndRendered(); + } + }, 1); + } + }, + initImages : function(){ + this.imgs = this.element.find('img').toArray(); + this.imagesToLoadCount = this.imgs.length; + + if(this.imgs.length){ + this.__imgSweeperTimeout = setTimeout(this.proxy('imgSweeper'), 500); + } else { + this.doneLoading(); + } + }, + 'a click' : function(el, ev){ + ev.preventDefault(); + window.open(el.attr('href')); + this.element.trigger('interaction:link', [this.scope.attr('state.hubId'), this.scope.attr('bit.id')]); + }, + // Go through all images and make sure all are loaded or errored + // Before calling the `doneLoading` function which will remove the loading class + imgSweeper : function(){ + var statuses = _map(this.imgs, imageStatus); + var errored; + + // If any of the images is still loading, check again in 500ms + if(can.inArray(IMAGE_STATUSES.LOADING, statuses) > -1){ + this.__imgSweeperTimeout = setTimeout(this.proxy('imgSweeper'), 500); + } else { + this.doneLoading(); + } + + for(var i = 0; i < statuses.length; i++){ + if(statuses[i] === IMAGE_STATUSES.ERROR){ + errored = this.imgs.splice(i, 1)[0]; + if(errored){ + $(errored).remove(); + } + } + } + }, + // All images in bit are loaded and we can calculate it's height. We set the explicit height + // to make sure that that the transition animation runs. + doneLoading : function(){ + var bit = this.scope.attr('bit'); + if(!bit.attr('@resolvedHeight')){ + this.element.find('.bit-wrap').height(this.element.find('.bit').height()); + } + bit.attr('@isLoaded', true); + this.bitLoadedAndRendered(); + }, + // When we're done with the height transition remove the explicit height + // and mark the bit's height as resolved + removeExplicitHeight : function(){ + var self = this; + this.__removeExplicitHeightTimeout = setTimeout(function(){ + self.scope.attr('bit').attr('@resolvedHeight', true); + if(self.element){ + self.element.find('.bit-wrap').css('height', 'auto'); + self.bitLoadedAndRendered(); + } + }, 1); + }, + bitLoadedAndRendered : function(){ + var bit = this.scope.attr('bit'); + var check = bit.attr('@resolvedHeight') && bit.attr('@isLoaded') && !bit.attr('@pendingRender'); + + if(check){ + this.element.trigger('bit:loaded'); + } + + }, + "bit:loaded" : function(){ + this.element.find('.bit-wrap').removeClass('loading'); + }, + // Clean up the timeouts + destroy : function(){ + clearTimeout(this.__imgSweeperTimeout); + clearTimeout(this.__initTimeout); + clearTimeout(this.__removeExplicitHeightTimeout); + return this._super.apply(this, arguments); + } + } +}); diff --git a/new-app/components/bit/bit.less b/new-app/components/bit/bit.less new file mode 100644 index 0000000..0e99b11 --- /dev/null +++ b/new-app/components/bit/bit.less @@ -0,0 +1,400 @@ +@import "../../node_modules/bootstrap/less/mixins.less"; +@import "../../node_modules/bootstrap/less/variables.less"; + +.border-radius (@radius: @baseBorderRadius) { + border-radius: @radius; + -moz-border-radius: @radius; + -webkit-border-radius: @radius; +} + +@gray-darker: lighten(#000, 13.5%); // #222 +@gray-dark: lighten(#000, 20%); // #333 +@gray: lighten(#000, 33.5%); // #555 +@gray-light: lighten(#000, 80.7%); // #777 +@gray-lighter: lighten(#000, 93.5%); // #eee + +@brand-primary: #428bca; +@brand-success: #5cb85c; +@brand-info: #5bc0de; +@brand-warning: #f0ad4e; +@brand-danger: #d9534f; + +// custom brand colors +@white: #fff; + +bh-bit { + display: block; + .bit-wrap { + .border-radius(5px); + position: relative; + background-color: @white; + border: 1px solid @gray-light; + overflow: hidden; + margin: 20px 10px 0; + opacity: 1; + -webkit-transition: opacity 0.2s ease-in-out; + -moz-transition: opacity 0.2s ease-in-out; + transition: opacity 0.2s ease-in-out; + + &.animate-height { + -webkit-transition: height 0.5s ease-in, opacity 0.2s ease-in-out; + -moz-transition: height 0.5s ease-in, opacity 0.2s ease-in-out; + transition: height 0.5s ease-in, opacity 0.2s ease-in-out; + } + + &.blocked { + border: 2px solid red; + background: #FFDDDD; + bh-body-wrap .expand-collapse { + box-shadow: 0 0 20px 10px #FFDDDD; + } + } + + &.pinned { + border: 2px solid gold; + } + + &:hover { + .admin-panel { + display: block; + } + } + + &.loading { + height: 100px; + background: url(../images/card-loader.gif); + background-repeat: no-repeat; + background-position: 50% 50%; + .bit { + opacity: 0; + } + } + + &.loading, &.animate-height { + &:hover { + .admin-panel { + display: none; + } + } + } + + &:hover { + .box-shadow(0 0 20px rgba(0,0,0,.15)); + } + + .current-image-wrap img { + .border-top-radius(4px); + } + + // Default "Clear" Theme + .bit { + -webkit-transition: opacity 0.5s ease-in-out; + -moz-transition: opacity 0.5s ease-in-out; + transition: opacity 0.5s ease-in-out; + .clearfix; + + // header + .bit-header, + .bit-footer { + padding: 10px 0; + .clearfix; + } + .bit-footer { + border-top: 1px solid lighten(@gray-light, 5%); + padding: 10px; + figcaption { + float: left; + max-width: 85%; + .bit-authorName a { + width: 100%; + display:block; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } + } + + } + .bit-avatar { + float: left; + margin-right: 10px; + .bit-avatar--img { + width: 35px; + height: 35px; + border-radius: 50%; + } + } + .bh-icon { + font-size: 1.5em; + float: right; + margin-top: 6px; + &:hover { + text-decoration: none; + } + } + .bh-icon-twitter { + color: #55acee; + } + .bh-icon-youtube { + color: #cc181e; + } + .bh-icon-facebook { + color: #3b5998; + } + .bh-icon-instagram { + color: #3f729b; + } + .bh-icon-flickr { + color: #FF0084; + } + .bh-icon-googleplus { + color: #d73d32; + } + .bh-icon-tumblr { + color: #2d4661; + } + .share-fb { + width: 70px; + } + .share-tw { + width: 76px; + margin-right:20px; + } + // Content + .bit-content--media { + max-height: 350px; + overflow-y: auto; + overflow-x: hidden; + } + .bit-content--caption { + padding-bottom: 15px; + iframe { + display: block; + } + p .img-wrap { + margin: 0 -15px 15px; + img { + width: 100%; + } + } + } + .img-responsive { + margin:0 auto; + } + .quoted-tweet { + margin: 0 15px 15px; + border-left: 3px solid @gray-light; + padding-left: 15px; + .bit-footer { + padding: 10px 0 0; + margin-top: 10px; + } + } + } + + + .bit-content { + overflow: hidden; + bh-body-wrap h4 { + padding-left: 15px; + padding-right: 15px; + p { + padding-left: 0; + padding-right: 0; + } + } + p { + padding: 0 15px; + &:last-child { + margin-bottom: 0; + } + } + .body-inner-wrap { + padding: 0 15px 15px; + pre { + margin-left: -15px; + margin-right: -15px; + } + p { + padding: 0; + } + .iframe-wrap { + margin: 0 -15px; + } + p .img-wrap { + margin: 0 -15px; + } + } + pre { + border-radius: 0; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-left: none; + border-right: none; + padding: 10px 15px; + } + } + + .bit-created-at { + font-size: 70%; + position: relative; + top: -3px; + } + .image-wrap { + margin: 0 -15px 10px; + position: relative; + img { + width: 100%; + } + } + .admin-panel { + background: rgba(0, 0, 0, 0.85); + position: absolute; + z-index: 10000; + color: #bbb; + height: 30px; + width: 200px; + top: 0; + left: 50%; + margin-left: -100px; + border--webkit-border-bottom-right-radius: 3px; + -webkit-border-bottom-left-radius: 3px; + -moz-border-radius-bottomright: 3px; + -moz-border-radius-bottomleft: 3px; + border-bottom-right-radius: 3px; + border-bottom-left-radius: 3px; + display: none; + .disapprove-approve, .pin { + top: 0; + width: 50%; + height: 100%; + position: absolute; + cursor: pointer; + img { + height: 24px; + opacity: 0.7; + display: inline-block; + } + .action-is { + cursor: pointer; + text-align: center; + text-transform: uppercase; + font-weight: bold; + font-size: 12px; + line-height: 30px; + } + &:hover { + background: rgba(0,0,0,0.5); + color: white; + img { + opacity: 1; + } + } + } + .disapprove-approve { + left: 0; + -webkit-border-bottom-left-radius: 3px; + -moz-border-radius-bottomleft: 3px; + border-bottom-left-radius: 3px; + } + .pin { + -webkit-border-bottom-right-radius: 3px; + -moz-border-radius-bottomright: 3px; + border-bottom-right-radius: 3px; + right: 0; + } + } + .social-icon { + float: right; + width: 32px; + height: 32px; + img { + width: 100%; + height: 100%; + } + } + bh-body-wrap.tall .body-inner-wrap p:last-child { + margin-bottom: -15px; + } + .action-fail-alert { + background: rgba(255,0,0,0.85); + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + color: white; + display: inline-block; + div { + height: 40px; + position: absolute; + top: 50%; + left: 0; + right: 0; + margin-top: -20px; + text-align: center; + padding: 0 20px; + } + i { + position: absolute; + top: 20px; + right: 20px; + cursor: pointer; + color: #E29A9A; + &:hover { + color: white; + } + } + } + .share-panel-toggle { + float: right; + font-size: 24px; + margin: 5px; + color: #9a9a9a; + cursor: pointer; + &:hover, &.open { + color: @brand-primary; + } + } + .youtube-embed-container { + position: relative; + padding-bottom: 56.25%; + height: 0; + overflow: hidden; + max-width: 100%; + iframe, object, embed { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + } + } + } + bh-share-bit { + position: relative; + z-index: 100000; + } +} +.dark-theme { + bh-bit { + .bit-wrap { + color: #eee; + background: #1f1f1f; + border-color: #444; + .bit-footer { + border-top-color: #444; + } + &.loading { + background: url(../images/card-loader-dark.gif); + background-repeat: no-repeat; + background-position: 50% 50%; + } + } + + } + bh-share-bit { + background: #444; + border-color: #444; + } +} diff --git a/new-app/components/bit/bit.stache b/new-app/components/bit/bit.stache new file mode 100644 index 0000000..acb46c6 --- /dev/null +++ b/new-app/components/bit/bit.stache @@ -0,0 +1,110 @@ +{{#if shouldRender}} + {{#bit}} +
+ {{#if showAdminPanel}} +
+
+
+ + {{#is_approved}} + Block + {{else}} + Approve + {{/is_approved}} +
+
+ +
+
+ + {{#is_pinned}} + Unpin + {{else}} + Pin + {{/is_pinned}} +
+
+
+ {{/if}} + +
+
+ + {{#if images.length}} + + {{/if}} + + {{#if isYoutube}} +
+ +
+
+
+{{/if}} diff --git a/new-app/components/service-config-formatter/service-config-formatter.js b/new-app/components/service-config-formatter/service-config-formatter.js new file mode 100644 index 0000000..f0d4c17 --- /dev/null +++ b/new-app/components/service-config-formatter/service-config-formatter.js @@ -0,0 +1,43 @@ +import can from "can"; +import initView from "./service-config-formatter.stache!"; +import "./service-config-formatter.less!"; + +can.Component.extend({ + template : initView, + tag: 'bh-service-config-formatter', + scope : { + lowercasedFeedName : function(){ + return this.attr('service.feed_name').toLowerCase(); + }, + lowercasedTypeName : function(){ + return this.attr('service.type_name').toLowerCase(); + } + }, + helpers : { + isFeedAndType : function(feed, type, opts){ + feed = (can.isFunction(feed) ? feed() : feed).toLowerCase(); + type = (can.isFunction(type) ? type() : type).toLowerCase(); + if(feed === this.lowercasedFeedName() && type === this.lowercasedTypeName()){ + return opts.fn(); + } + }, + cutoff : function(){ + var str, opts; + if(arguments.length === 1){ + opts = arguments[0]; + str = opts.fn(); + } else { + str = arguments[0]; + opts = arguments[1]; + } + + str = can.isFunction(str) ? str() : str; + + if(str.length > 50){ + str = str.substr(0, 50) + '…'; + } + + return str; + } + } +}); diff --git a/new-app/components/service-config-formatter/service-config-formatter.less b/new-app/components/service-config-formatter/service-config-formatter.less new file mode 100644 index 0000000..7c739b3 --- /dev/null +++ b/new-app/components/service-config-formatter/service-config-formatter.less @@ -0,0 +1,3 @@ +bh-service-config-formatter { + display: block; +} \ No newline at end of file diff --git a/new-app/components/service-config-formatter/service-config-formatter.stache b/new-app/components/service-config-formatter/service-config-formatter.stache new file mode 100644 index 0000000..67ea652 --- /dev/null +++ b/new-app/components/service-config-formatter/service-config-formatter.stache @@ -0,0 +1,87 @@ +{{#isFeedAndType 'disqus' 'forum'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'facebook' 'page'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'facebook' 'public_page'}} + Facebook Page {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'foursquare' 'venue'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'github' 'org'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'github' 'repo'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'instagram' 'tag'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'instagram' 'user'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'meetup' 'group'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'rss' 'site'}} + {{service.printFeed}} {{service.printType}} {{{cutoff service.config.url}}} +{{/isFeedAndType}} + +{{#isFeedAndType 'stackexchange' 'tags'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'tumblr' 'blog'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'tumblr' 'tag'}} + {{service.printFeed}} {{service.printType}} {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'twitter' 'followers'}} + {{service.printFeed}} {{service.printType}} for {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'twitter' 'hashtag'}} + {{service.printFeed}} {{service.printType}} for {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'twitter' 'user_timeline'}} + {{service.printFeed}} {{service.printType}} for {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'twitter' 'user_retweets'}} + {{service.printFeed}} {{service.printType}} for {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'twitter' 'favorites'}} + {{service.printFeed}} {{service.printType}} for {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'twitter' 'term'}} + {{service.printFeed}} {{service.printType}} for {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'youtube' 'channel'}} + {{service.printFeed}} {{service.printType}} for {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'youtube' 'playlist'}} + {{service.printFeed}} {{service.printType}} for {{service.config.display_name}} +{{/isFeedAndType}} + +{{#isFeedAndType 'youtube' 'user'}} + {{service.printFeed}} {{service.printType}} for {{service.config.display_name}} +{{/isFeedAndType}} diff --git a/new-app/components/service-form/service-form.js b/new-app/components/service-form/service-form.js new file mode 100644 index 0000000..0a6c244 --- /dev/null +++ b/new-app/components/service-form/service-form.js @@ -0,0 +1,196 @@ +import can from 'can/'; +import initView from './service-form.stache!'; +import Models from 'models/'; + +import './service-form.less!'; +import 'can/map/define/'; + +import 'components/service-forms/disqus-forum/'; +import 'components/service-forms/facebook-page/'; +import 'components/service-forms/facebook-public-page/'; +import 'components/service-forms/foursquare-venue/'; +import 'components/service-forms/github-org/'; +import 'components/service-forms/github-repo/'; +import 'components/service-forms/instagram-tag/'; +import 'components/service-forms/instagram-user/'; +import 'components/service-forms/meetup-group/'; +import 'components/service-forms/rss-site/'; +import 'components/service-forms/stackexchange-tags/'; +import 'components/service-forms/tumblr-blog/'; +import 'components/service-forms/tumblr-tag/'; +import 'components/service-forms/twitter-followers/'; +import 'components/service-forms/twitter-hashtag/'; +import 'components/service-forms/twitter-term/'; +import 'components/service-forms/twitter-user-timeline/'; +import 'components/service-forms/twitter-favorites/'; +import 'components/service-forms/twitter-user-retweets/'; +import 'components/service-forms/youtube-channel/'; +import 'components/service-forms/youtube-playlist/'; +import 'components/service-forms/youtube-user/'; +import 'components/oauthorizer/'; + +import 'components/helpers'; + +var FEED_INFOS = { + foursquare: 'You must be a venue manager to be able to add a venue.' +}; + +var makeTemplate = function(feed, type){ + var componentName = ['bh', feed, type.replace(/_/g, '-'), 'service'].join('-'), + template = '<' + componentName + ' map="{service}" errors="{errors.config}">{{{saveButtons}}}', + needsOAuth = Models.Service.needsOAuth[feed]; + + needsOAuth = needsOAuth && can.inArray(type, needsOAuth.types) > -1; + + + if(needsOAuth){ + template = [ + '', + template, + '' + ].join(''); + } + + + return can.stache(template); +}; + +can.Component.extend({ + tag : 'bh-service-form', + template: initView, + scope : { + isHidden: false, + missingConfig : false, + errors: null, + typeErros: null, + saveDisabled : false, + define : { + service : { + set : function(val){ + this.clearErrors(); + return val; + } + } + }, + saveService : function(formData, el, ev){ + ev.preventDefault(); + + var self = this; + var service = this.attr('service'); + var services = this.attr('services'); + this.compute('service'); + + service.attr('embed_id', this.state.attr('hubId')); + if(service.isNew()){ + services.unshift( service ); + } + + service.save( function( newService ) { + self.clearService(); + }, function( error ) { + var index = services.indexOf(service); + var attrs = { + isHidden: false + }; + var errorsResponse; + var errors, typeErrors; + + services.splice(index, 1); + + if(error.status === 400){ + attrs.missingConfig = true; + } else if(error.status = 406){ + try { + errorsResponse = JSON.parse(error.responseText).errors; + errors = errorsResponse.config_attrs; + typeErrors = errorsResponse.type_name; + } catch(e){ + errors = {}; + } + attrs.errors = errors; + } + + if(typeErrors){ + self.attr('typeErrors', typeErrors); + } + + Models.Service.errored(service); + + self.attr(attrs); + }); + + this.attr({ + isHidden: service.isNew(), + missingConfig: false, + errors: null + }); + }, + feedInfo : function(){ + return FEED_INFOS[this.attr('service.feed_name')]; + }, + clearService : function(){ + can.batch.start(); + this.attr({ + saveDisabled: false, + service: null + }); + this.clearErrors(); + can.batch.stop(); + }, + clearErrors : function(){ + this.attr({ + errors: null, + typeErrors: null, + missingConfig: false + }); + }, + currentServiceFeedName : function(){ + var service = this.attr('service'); + if(!service) { + return; + } + var feed = service.attr('feed_name'); + return Models.Service.feeds[feed]; + } + }, + events : { + "service:saveDisabled" : function(){ + var self = this; + setTimeout(function(){ + if(self.element){ + self.element.find('button.save-service').prop('disabled', true); + } + }, 1); + + }, + "service:saveEnabled" : function(){ + var self = this; + setTimeout(function(){ + if(self.element){ + self.element.find('button.save-service').prop('disabled', false); + } + }, 1); + } + }, + helpers : { + renderForm : function(opts){ + var service = this.attr('service'), feed, type; + + if(!service){ + return; + } + + feed = service.attr('feed_name'); + type = service.attr('type_name'); + + + if(type && feed){ + return makeTemplate(feed, type)(opts.scope, { + saveButtons : function(){ + return opts.fn(); + } + }); + } + } + } +}); diff --git a/new-app/components/service-form/service-form.less b/new-app/components/service-form/service-form.less new file mode 100644 index 0000000..dcac5c3 --- /dev/null +++ b/new-app/components/service-form/service-form.less @@ -0,0 +1,24 @@ +bh-service-form { + display: block; + + bh-suggestions { + .panel { + margin-left: -15px; + margin-right: -15px; + margin-bottom: 0; + border-radius: 0; + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-left: none; + border-right: none; + } + } + + .form-instructions { + font-style: oblique; + margin-top: 5px; + } + .input-group { + width: 100%; + } +} \ No newline at end of file diff --git a/new-app/components/service-form/service-form.stache b/new-app/components/service-form/service-form.stache new file mode 100644 index 0000000..bf6548b --- /dev/null +++ b/new-app/components/service-form/service-form.stache @@ -0,0 +1,66 @@ +{{#unless isHidden}} +
+

+ {{#if service.isNew}}Add{{else}}Edit{{/if}} {{currentServiceFeedName}} + +

+ {{#service}} + + {{#if error}} +
+ {{ formattedErrorClass }} + {{ formattedError }} +
+ {{/if}} + + {{#if typeErrors.length}} +
+ You have {{ typeErrors.0 }} +
+ {{/if}} + +
+ + {{#if hasMultipleTypes}} + +
+ +
+ {{/if}} + + {{#if missingConfig}} +
Config can't be empty
+ {{/if}} + + {{#if errors}} +
Service config has some errors
+ {{/if}} + + {{#if feedInfo }} +
{{ feedInfo }}
+ {{/if}} + + + {{#renderForm}} +
+ +
+ +
+ + Cancel +
+ {{/renderForm}} + +
+ + {{/service}} +
+{{/unless}} diff --git a/new-app/components/service-forms/disqus-forum/disqus-forum.js b/new-app/components/service-forms/disqus-forum/disqus-forum.js new file mode 100644 index 0000000..6766f9f --- /dev/null +++ b/new-app/components/service-forms/disqus-forum/disqus-forum.js @@ -0,0 +1,10 @@ +import can from "can"; +import initView from "./disqus-forum.stache!"; + +import "./disqus-forum.less!"; +import "components/suggestions/"; + +can.Component.extend({ + tag : 'bh-disqus-forum-service', + template : initView +}); diff --git a/new-app/components/service-forms/disqus-forum/disqus-forum.less b/new-app/components/service-forms/disqus-forum/disqus-forum.less new file mode 100644 index 0000000..d323ebc --- /dev/null +++ b/new-app/components/service-forms/disqus-forum/disqus-forum.less @@ -0,0 +1,3 @@ +bh-disqus-forum-service { + display: block; +} diff --git a/new-app/components/service-forms/disqus-forum/disqus-forum.stache b/new-app/components/service-forms/disqus-forum/disqus-forum.stache new file mode 100644 index 0000000..2b6cc3a --- /dev/null +++ b/new-app/components/service-forms/disqus-forum/disqus-forum.stache @@ -0,0 +1,4 @@ +
+ + {{{configErrors errors 'url'}}} +
diff --git a/new-app/components/service-forms/facebook-page/facebook-page.js b/new-app/components/service-forms/facebook-page/facebook-page.js new file mode 100644 index 0000000..60f3dcb --- /dev/null +++ b/new-app/components/service-forms/facebook-page/facebook-page.js @@ -0,0 +1,10 @@ +import can from "can"; + +import initView from './facebook-page.stache!'; +import './facebook-page.less!'; +import 'components/suggestions/'; + +can.Component.extend({ + tag : 'bh-facebook-page-service', + template : initView +}); diff --git a/new-app/components/service-forms/facebook-page/facebook-page.less b/new-app/components/service-forms/facebook-page/facebook-page.less new file mode 100644 index 0000000..b463e18 --- /dev/null +++ b/new-app/components/service-forms/facebook-page/facebook-page.less @@ -0,0 +1,3 @@ +bh-facebook-page-service { + display: block; +} diff --git a/new-app/components/service-forms/facebook-page/facebook-page.stache b/new-app/components/service-forms/facebook-page/facebook-page.stache new file mode 100644 index 0000000..c1f17ee --- /dev/null +++ b/new-app/components/service-forms/facebook-page/facebook-page.stache @@ -0,0 +1,4 @@ +
+ + {{{configErrors errors 'id'}}} +
\ No newline at end of file diff --git a/new-app/components/service-forms/facebook-public-page/facebook-public-page.js b/new-app/components/service-forms/facebook-public-page/facebook-public-page.js new file mode 100644 index 0000000..8693004 --- /dev/null +++ b/new-app/components/service-forms/facebook-public-page/facebook-public-page.js @@ -0,0 +1,18 @@ +import can from "can"; +import initView from './facebook-public-page.stache!'; +import './facebook-public-page.less!'; +import 'components/suggestions/'; + + +can.Component.extend({ + tag : 'bh-facebook-public-page-service', + template : initView, + scope : { + loading: "", + loadedPage: null, + error: "", + init : function(){ + + } + } +}); diff --git a/new-app/components/service-forms/facebook-public-page/facebook-public-page.less b/new-app/components/service-forms/facebook-public-page/facebook-public-page.less new file mode 100644 index 0000000..3d9fa56 --- /dev/null +++ b/new-app/components/service-forms/facebook-public-page/facebook-public-page.less @@ -0,0 +1,8 @@ +bh-facebook-public-page-service { + display: block; + .result { + .alert { + margin-bottom: 0; + } + } +} diff --git a/new-app/components/service-forms/facebook-public-page/facebook-public-page.stache b/new-app/components/service-forms/facebook-public-page/facebook-public-page.stache new file mode 100644 index 0000000..a37269b --- /dev/null +++ b/new-app/components/service-forms/facebook-public-page/facebook-public-page.stache @@ -0,0 +1,7 @@ +
+ +
+ +
+ {{{configErrors errors 'id'}}} +
diff --git a/new-app/components/service-forms/foursquare-venue/foursquare-venue.js b/new-app/components/service-forms/foursquare-venue/foursquare-venue.js new file mode 100644 index 0000000..ac03c9c --- /dev/null +++ b/new-app/components/service-forms/foursquare-venue/foursquare-venue.js @@ -0,0 +1,8 @@ +import can from "can"; +import initView from './foursquare-venue.stache!'; +import './foursquare-venue.less!'; + +can.Component.extend({ + tag : 'bh-foursquare-venue-service', + template : initView +}); diff --git a/new-app/components/service-forms/foursquare-venue/foursquare-venue.less b/new-app/components/service-forms/foursquare-venue/foursquare-venue.less new file mode 100644 index 0000000..679d0de --- /dev/null +++ b/new-app/components/service-forms/foursquare-venue/foursquare-venue.less @@ -0,0 +1,3 @@ +bh-foursquare-venue-service { + display: block; +} diff --git a/new-app/components/service-forms/foursquare-venue/foursquare-venue.stache b/new-app/components/service-forms/foursquare-venue/foursquare-venue.stache new file mode 100644 index 0000000..2aaaff2 --- /dev/null +++ b/new-app/components/service-forms/foursquare-venue/foursquare-venue.stache @@ -0,0 +1,5 @@ +
To add a Forsquare Venue you must be the manager.
+
+ + {{{configErrors errors 'id'}}} +
diff --git a/new-app/components/service-forms/github-org/github-org.js b/new-app/components/service-forms/github-org/github-org.js new file mode 100644 index 0000000..b2b249a --- /dev/null +++ b/new-app/components/service-forms/github-org/github-org.js @@ -0,0 +1,8 @@ +import can from "can"; +import initView from './github-org.stache!'; +import './github-org.less!'; + +can.Component.extend({ + tag : 'bh-github-org-service', + template : initView +}); diff --git a/new-app/components/service-forms/github-org/github-org.less b/new-app/components/service-forms/github-org/github-org.less new file mode 100644 index 0000000..527cfca --- /dev/null +++ b/new-app/components/service-forms/github-org/github-org.less @@ -0,0 +1,3 @@ +bh-github-org-service { + display: block; +} diff --git a/new-app/components/service-forms/github-org/github-org.stache b/new-app/components/service-forms/github-org/github-org.stache new file mode 100644 index 0000000..a25117f --- /dev/null +++ b/new-app/components/service-forms/github-org/github-org.stache @@ -0,0 +1,4 @@ +
+ + {{{configErrors errors 'name'}}} +
\ No newline at end of file diff --git a/new-app/components/service-forms/github-repo/github-repo.js b/new-app/components/service-forms/github-repo/github-repo.js new file mode 100644 index 0000000..70898f2 --- /dev/null +++ b/new-app/components/service-forms/github-repo/github-repo.js @@ -0,0 +1,8 @@ +import can from "can"; +import initView from './github-repo.stache!'; +import './github-repo.less!'; + +can.Component.extend({ + tag : 'bh-github-repo-service', + template : initView +}); diff --git a/new-app/components/service-forms/github-repo/github-repo.less b/new-app/components/service-forms/github-repo/github-repo.less new file mode 100644 index 0000000..93e9aa6 --- /dev/null +++ b/new-app/components/service-forms/github-repo/github-repo.less @@ -0,0 +1,3 @@ +bh-github-repo-service { + display: block; +} diff --git a/new-app/components/service-forms/github-repo/github-repo.stache b/new-app/components/service-forms/github-repo/github-repo.stache new file mode 100644 index 0000000..946c274 --- /dev/null +++ b/new-app/components/service-forms/github-repo/github-repo.stache @@ -0,0 +1,16 @@ +
+ + {{{configErrors errors 'name'}}} +
+
+
+ +
+
+ +
+
diff --git a/new-app/components/service-forms/instagram-tag/instagram-tag.js b/new-app/components/service-forms/instagram-tag/instagram-tag.js new file mode 100644 index 0000000..2a50473 --- /dev/null +++ b/new-app/components/service-forms/instagram-tag/instagram-tag.js @@ -0,0 +1,8 @@ +import can from "can"; +import initView from './instagram-tag.stache!'; +import './instagram-tag.less!'; + +can.Component.extend({ + tag : 'bh-instagram-tag-service', + template : initView +}); diff --git a/new-app/components/service-forms/instagram-tag/instagram-tag.less b/new-app/components/service-forms/instagram-tag/instagram-tag.less new file mode 100644 index 0000000..3492fd3 --- /dev/null +++ b/new-app/components/service-forms/instagram-tag/instagram-tag.less @@ -0,0 +1,3 @@ +instagram-tag { + display: block; +} diff --git a/new-app/components/service-forms/instagram-tag/instagram-tag.stache b/new-app/components/service-forms/instagram-tag/instagram-tag.stache new file mode 100644 index 0000000..1074af9 --- /dev/null +++ b/new-app/components/service-forms/instagram-tag/instagram-tag.stache @@ -0,0 +1,5 @@ +
+ + + {{{configErrors errors 'tag'}}} +
\ No newline at end of file diff --git a/new-app/components/service-forms/instagram-user/instagram-user.js b/new-app/components/service-forms/instagram-user/instagram-user.js new file mode 100644 index 0000000..6dbb5e4 --- /dev/null +++ b/new-app/components/service-forms/instagram-user/instagram-user.js @@ -0,0 +1,67 @@ +import can from "can"; +import initView from './instagram-user.stache!'; +import './instagram-user.less!'; +import 'selectize'; + +can.Component.extend({ + tag : 'bh-instagram-user-service', + template : initView, + scope : { + isLoading : false, + init : function(){ + this.attr('currentSuggestions', []); + }, + setDisplayName : function(id){ + var currentSuggestions = this.attr('currentSuggestions'); + var length = currentSuggestions.length; + + if(id){ + for(var i = 0; i < length; i++){ + if(id === currentSuggestions[i].id){ + this.attr('map.config.display_name', currentSuggestions[i].username); + } + } + } else { + this.attr('map.config.display_name', ''); + } + } + }, + helpers : { + instagramSuggest : function(){ + var self = this; + return function(el){ + $(el).selectize({ + valueField: 'id', + labelField: 'username', + searchField: 'username', + create: false, + allowEmptyOption : true, + load: function(query, callback){ + if(!query.length){ + return callback(); + } + self.attr('isLoading', true); + $.ajax({ + url: '/api/v3/services/suggestions/instagram', + data: { + username: query + }, + error : function(){ + self.attr('isLoading', false); + callback(); + }, + success : function(res){ + self.attr('currentSuggestions').replace(res); + self.attr('isLoading', false); + callback(res); + } + }); + }, + onChange : function(id){ + self.setDisplayName(id); + } + }); + }; + } + } +}); diff --git a/new-app/components/service-forms/instagram-user/instagram-user.less b/new-app/components/service-forms/instagram-user/instagram-user.less new file mode 100644 index 0000000..930a76e --- /dev/null +++ b/new-app/components/service-forms/instagram-user/instagram-user.less @@ -0,0 +1,37 @@ +bh-instagram-user-service { + display: block; + .selectize-control.single .selectize-input:after { + right: 9px; + } + .suggest-wrapper { + position: relative; + background: #ccc; + height: 34px; + border-radius: 3px; + -webkit-border-radius: 3px; + -moz-border-radius: 3px; + .selectize-input { + -webkit-border-top-left-radius: 3px; + -webkit-border-bottom-left-radius: 3px; + -moz-border-radius-topleft: 3px; + -moz-border-radius-bottomleft: 3px; + border-top-left-radius: 3px; + border-bottom-left-radius: 3px; + } + .selectize-control { + margin-left: 34px; + } + .fa { + display: block; + position: absolute; + top: 0; + left: 0; + font-size: 120%; + margin: 8px 0 0 11px; + color: #666; + } + .fa-circle-o-notch { + margin-left: 9px; + } + } +} diff --git a/new-app/components/service-forms/instagram-user/instagram-user.stache b/new-app/components/service-forms/instagram-user/instagram-user.stache new file mode 100644 index 0000000..1e0b0ec --- /dev/null +++ b/new-app/components/service-forms/instagram-user/instagram-user.stache @@ -0,0 +1,10 @@ +
+ +
+ + +
+ + {{{configErrors errors 'id'}}} +
\ No newline at end of file diff --git a/new-app/components/service-forms/meetup-group/meetup-group.js b/new-app/components/service-forms/meetup-group/meetup-group.js new file mode 100644 index 0000000..d4c30e3 --- /dev/null +++ b/new-app/components/service-forms/meetup-group/meetup-group.js @@ -0,0 +1,9 @@ +import can from "can"; +import initView from './meetup-group.stache!'; +import './meetup-group.less!'; +import "components/suggestions/"; + +can.Component.extend({ + tag : 'bh-meetup-group-service', + template : initView +}); diff --git a/new-app/components/service-forms/meetup-group/meetup-group.less b/new-app/components/service-forms/meetup-group/meetup-group.less new file mode 100644 index 0000000..8d593da --- /dev/null +++ b/new-app/components/service-forms/meetup-group/meetup-group.less @@ -0,0 +1,3 @@ +bh-meetup-group-service { + display: block; +} diff --git a/new-app/components/service-forms/meetup-group/meetup-group.stache b/new-app/components/service-forms/meetup-group/meetup-group.stache new file mode 100644 index 0000000..6905170 --- /dev/null +++ b/new-app/components/service-forms/meetup-group/meetup-group.stache @@ -0,0 +1,4 @@ +
+ + {{{configErrors errors 'id'}}} +
\ No newline at end of file diff --git a/new-app/components/service-forms/rss-site/rss-site.js b/new-app/components/service-forms/rss-site/rss-site.js new file mode 100644 index 0000000..e4b0c3d --- /dev/null +++ b/new-app/components/service-forms/rss-site/rss-site.js @@ -0,0 +1,8 @@ +import can from "can"; +import initView from './rss-site.stache!'; +import './rss-site.less!'; + +can.Component.extend({ + tag : 'bh-rss-site-service', + template : initView +}); diff --git a/new-app/components/service-forms/rss-site/rss-site.less b/new-app/components/service-forms/rss-site/rss-site.less new file mode 100644 index 0000000..404c9a2 --- /dev/null +++ b/new-app/components/service-forms/rss-site/rss-site.less @@ -0,0 +1,3 @@ +bh-rss-site-service { + display: block; +} diff --git a/new-app/components/service-forms/rss-site/rss-site.stache b/new-app/components/service-forms/rss-site/rss-site.stache new file mode 100644 index 0000000..875ff41 --- /dev/null +++ b/new-app/components/service-forms/rss-site/rss-site.stache @@ -0,0 +1,5 @@ +
+ + + {{{configErrors errors 'url'}}} +
\ No newline at end of file diff --git a/new-app/components/service-forms/stackexchange-tags/stackexchange-tags.js b/new-app/components/service-forms/stackexchange-tags/stackexchange-tags.js new file mode 100644 index 0000000..e158cfb --- /dev/null +++ b/new-app/components/service-forms/stackexchange-tags/stackexchange-tags.js @@ -0,0 +1,9 @@ +import can from "can"; +import initView from './stackexchange-tags.stache!'; +import './stackexchange-tags.less!'; +import'components/tag-list/'; + +can.Component.extend({ + tag : 'bh-stackexchange-tags-service', + template : initView, +}); diff --git a/new-app/components/service-forms/stackexchange-tags/stackexchange-tags.less b/new-app/components/service-forms/stackexchange-tags/stackexchange-tags.less new file mode 100644 index 0000000..7ca4b4a --- /dev/null +++ b/new-app/components/service-forms/stackexchange-tags/stackexchange-tags.less @@ -0,0 +1,3 @@ +bh-stackexchange-tags-service { + display: block; +} diff --git a/new-app/components/service-forms/stackexchange-tags/stackexchange-tags.stache b/new-app/components/service-forms/stackexchange-tags/stackexchange-tags.stache new file mode 100644 index 0000000..9b7c4e4 --- /dev/null +++ b/new-app/components/service-forms/stackexchange-tags/stackexchange-tags.stache @@ -0,0 +1,5 @@ +
+ + + {{{configErrors errors 'tags'}}} +
\ No newline at end of file diff --git a/new-app/components/service-forms/tumblr-blog/tumblr-blog.js b/new-app/components/service-forms/tumblr-blog/tumblr-blog.js new file mode 100644 index 0000000..bad0f07 --- /dev/null +++ b/new-app/components/service-forms/tumblr-blog/tumblr-blog.js @@ -0,0 +1,8 @@ +import can from "can"; +import initView from './tumblr-blog.stache!'; +import './tumblr-blog.less!'; + +can.Component.extend({ + tag : 'bh-tumblr-blog-service', + template : initView +}); diff --git a/new-app/components/service-forms/tumblr-blog/tumblr-blog.less b/new-app/components/service-forms/tumblr-blog/tumblr-blog.less new file mode 100644 index 0000000..a02a7c4 --- /dev/null +++ b/new-app/components/service-forms/tumblr-blog/tumblr-blog.less @@ -0,0 +1,3 @@ +bh-tumblr-blog-service { + display: block; +} diff --git a/new-app/components/service-forms/tumblr-blog/tumblr-blog.stache b/new-app/components/service-forms/tumblr-blog/tumblr-blog.stache new file mode 100644 index 0000000..5c068b5 --- /dev/null +++ b/new-app/components/service-forms/tumblr-blog/tumblr-blog.stache @@ -0,0 +1,10 @@ +
+ +
+ + + + + {{{configErrors errors 'hostname'}}} +
+
\ No newline at end of file diff --git a/new-app/components/service-forms/tumblr-tag/tumblr-tag.js b/new-app/components/service-forms/tumblr-tag/tumblr-tag.js new file mode 100644 index 0000000..46ca23f --- /dev/null +++ b/new-app/components/service-forms/tumblr-tag/tumblr-tag.js @@ -0,0 +1,8 @@ +import can from "can"; +import initView from './tumblr-tag.stache!'; +import './tumblr-tag.less!'; + +can.Component.extend({ + tag : 'bh-tumblr-tag-service', + template : initView +}); diff --git a/new-app/components/service-forms/tumblr-tag/tumblr-tag.less b/new-app/components/service-forms/tumblr-tag/tumblr-tag.less new file mode 100644 index 0000000..ad9a85c --- /dev/null +++ b/new-app/components/service-forms/tumblr-tag/tumblr-tag.less @@ -0,0 +1,3 @@ +bh-tumblr-tags-service { + display: block; +} diff --git a/new-app/components/service-forms/tumblr-tag/tumblr-tag.stache b/new-app/components/service-forms/tumblr-tag/tumblr-tag.stache new file mode 100644 index 0000000..1074af9 --- /dev/null +++ b/new-app/components/service-forms/tumblr-tag/tumblr-tag.stache @@ -0,0 +1,5 @@ +
+ + + {{{configErrors errors 'tag'}}} +
\ No newline at end of file diff --git a/new-app/components/service-forms/twitter-favorites/twitter-favorites.js b/new-app/components/service-forms/twitter-favorites/twitter-favorites.js new file mode 100644 index 0000000..188d55d --- /dev/null +++ b/new-app/components/service-forms/twitter-favorites/twitter-favorites.js @@ -0,0 +1,8 @@ +import can from "can"; +import initView from './twitter-favorites.stache!'; +import './twitter-favorites.less!'; + +can.Component.extend({ + tag : 'bh-twitter-favorites-service', + template : initView +}); diff --git a/new-app/components/service-forms/twitter-favorites/twitter-favorites.less b/new-app/components/service-forms/twitter-favorites/twitter-favorites.less new file mode 100644 index 0000000..44cdb02 --- /dev/null +++ b/new-app/components/service-forms/twitter-favorites/twitter-favorites.less @@ -0,0 +1,3 @@ +bh-twitter-favorites-service { + display: block; +} diff --git a/new-app/components/service-forms/twitter-favorites/twitter-favorites.stache b/new-app/components/service-forms/twitter-favorites/twitter-favorites.stache new file mode 100644 index 0000000..f1aab0d --- /dev/null +++ b/new-app/components/service-forms/twitter-favorites/twitter-favorites.stache @@ -0,0 +1,9 @@ +
+ +
+ @ + + {{{configErrors errors 'handle'}}} +
+

Enter any Twitter user handle

+
\ No newline at end of file diff --git a/new-app/components/service-forms/twitter-followers/twitter-followers.js b/new-app/components/service-forms/twitter-followers/twitter-followers.js new file mode 100644 index 0000000..1824dba --- /dev/null +++ b/new-app/components/service-forms/twitter-followers/twitter-followers.js @@ -0,0 +1,8 @@ +import can from "can"; +import initView from './twitter-followers.stache!'; +import './twitter-followers.less!'; + +can.Component.extend({ + tag : 'bh-twitter-followers-service', + template : initView +}); diff --git a/new-app/components/service-forms/twitter-followers/twitter-followers.less b/new-app/components/service-forms/twitter-followers/twitter-followers.less new file mode 100644 index 0000000..ac3fc27 --- /dev/null +++ b/new-app/components/service-forms/twitter-followers/twitter-followers.less @@ -0,0 +1,3 @@ +bh-twitter-followers-service { + display: block; +} diff --git a/new-app/components/service-forms/twitter-followers/twitter-followers.stache b/new-app/components/service-forms/twitter-followers/twitter-followers.stache new file mode 100644 index 0000000..72fffc2 --- /dev/null +++ b/new-app/components/service-forms/twitter-followers/twitter-followers.stache @@ -0,0 +1,8 @@ +
+ +
+ @ + + {{{configErrors errors 'handle'}}} +
+
\ No newline at end of file diff --git a/new-app/components/service-forms/twitter-hashtag/twitter-hashtag.js b/new-app/components/service-forms/twitter-hashtag/twitter-hashtag.js new file mode 100644 index 0000000..d69a1ff --- /dev/null +++ b/new-app/components/service-forms/twitter-hashtag/twitter-hashtag.js @@ -0,0 +1,8 @@ +import can from "can"; +import initView from './twitter-hashtag.stache!'; +import './twitter-hashtag.less!'; + +can.Component.extend({ + tag : 'bh-twitter-hashtag-service', + template : initView +}); diff --git a/new-app/components/service-forms/twitter-hashtag/twitter-hashtag.less b/new-app/components/service-forms/twitter-hashtag/twitter-hashtag.less new file mode 100644 index 0000000..d07394d --- /dev/null +++ b/new-app/components/service-forms/twitter-hashtag/twitter-hashtag.less @@ -0,0 +1,3 @@ +bh-twitter-hashtag-service { + display: block; +} diff --git a/new-app/components/service-forms/twitter-hashtag/twitter-hashtag.stache b/new-app/components/service-forms/twitter-hashtag/twitter-hashtag.stache new file mode 100644 index 0000000..43af3c6 --- /dev/null +++ b/new-app/components/service-forms/twitter-hashtag/twitter-hashtag.stache @@ -0,0 +1,8 @@ +
+ +
+ # + + {{{configErrors errors 'hashtag'}}} +
+
\ No newline at end of file diff --git a/new-app/components/service-forms/twitter-term/twitter-term.js b/new-app/components/service-forms/twitter-term/twitter-term.js new file mode 100644 index 0000000..7d79fba --- /dev/null +++ b/new-app/components/service-forms/twitter-term/twitter-term.js @@ -0,0 +1,8 @@ +import can from "can"; +import initView from './twitter-term.stache!'; +import './twitter-term.less!'; + +can.Component.extend({ + tag : 'bh-twitter-term-service', + template : initView +}); diff --git a/new-app/components/service-forms/twitter-term/twitter-term.less b/new-app/components/service-forms/twitter-term/twitter-term.less new file mode 100644 index 0000000..e2f75da --- /dev/null +++ b/new-app/components/service-forms/twitter-term/twitter-term.less @@ -0,0 +1,3 @@ +bh-twitter-term-service { + display: block; +} diff --git a/new-app/components/service-forms/twitter-term/twitter-term.stache b/new-app/components/service-forms/twitter-term/twitter-term.stache new file mode 100644 index 0000000..97829d3 --- /dev/null +++ b/new-app/components/service-forms/twitter-term/twitter-term.stache @@ -0,0 +1,5 @@ +
+ + + {{{configErrors errors 'term'}}} +
\ No newline at end of file diff --git a/new-app/components/service-forms/twitter-user-retweets/twitter-user-retweets.js b/new-app/components/service-forms/twitter-user-retweets/twitter-user-retweets.js new file mode 100644 index 0000000..3cac45d --- /dev/null +++ b/new-app/components/service-forms/twitter-user-retweets/twitter-user-retweets.js @@ -0,0 +1,8 @@ +import can from "can"; +import initView from './twitter-user-retweets.stache!'; +import './twitter-user-retweets.less!'; + +can.Component.extend({ + tag : 'bh-twitter-user-retweets-service', + template : initView +}); diff --git a/new-app/components/service-forms/twitter-user-retweets/twitter-user-retweets.less b/new-app/components/service-forms/twitter-user-retweets/twitter-user-retweets.less new file mode 100644 index 0000000..b796b26 --- /dev/null +++ b/new-app/components/service-forms/twitter-user-retweets/twitter-user-retweets.less @@ -0,0 +1,3 @@ +bh-twitter-user-retweets-service { + display: block; +} diff --git a/new-app/components/service-forms/twitter-user-retweets/twitter-user-retweets.stache b/new-app/components/service-forms/twitter-user-retweets/twitter-user-retweets.stache new file mode 100644 index 0000000..f1aab0d --- /dev/null +++ b/new-app/components/service-forms/twitter-user-retweets/twitter-user-retweets.stache @@ -0,0 +1,9 @@ +
+ +
+ @ + + {{{configErrors errors 'handle'}}} +
+

Enter any Twitter user handle

+
\ No newline at end of file diff --git a/new-app/components/service-forms/twitter-user-timeline/twitter-user-timeline.js b/new-app/components/service-forms/twitter-user-timeline/twitter-user-timeline.js new file mode 100644 index 0000000..87b867f --- /dev/null +++ b/new-app/components/service-forms/twitter-user-timeline/twitter-user-timeline.js @@ -0,0 +1,8 @@ +import can from "can"; +import initView from './twitter-user-timeline.stache!'; +import './twitter-user-timeline.less!'; + +can.Component.extend({ + tag : 'bh-twitter-user-timeline-service', + template : initView +}); diff --git a/new-app/components/service-forms/twitter-user-timeline/twitter-user-timeline.less b/new-app/components/service-forms/twitter-user-timeline/twitter-user-timeline.less new file mode 100644 index 0000000..3be894f --- /dev/null +++ b/new-app/components/service-forms/twitter-user-timeline/twitter-user-timeline.less @@ -0,0 +1,3 @@ +bh-twitter-user-timeline-service { + display: block; +} diff --git a/new-app/components/service-forms/twitter-user-timeline/twitter-user-timeline.stache b/new-app/components/service-forms/twitter-user-timeline/twitter-user-timeline.stache new file mode 100644 index 0000000..f1aab0d --- /dev/null +++ b/new-app/components/service-forms/twitter-user-timeline/twitter-user-timeline.stache @@ -0,0 +1,9 @@ +
+ +
+ @ + + {{{configErrors errors 'handle'}}} +
+

Enter any Twitter user handle

+
\ No newline at end of file diff --git a/new-app/components/service-forms/youtube-channel/youtube-channel.js b/new-app/components/service-forms/youtube-channel/youtube-channel.js new file mode 100644 index 0000000..6c204ac --- /dev/null +++ b/new-app/components/service-forms/youtube-channel/youtube-channel.js @@ -0,0 +1,8 @@ +import can from "can"; +import initView from './youtube-channel.stache!'; +import './youtube-channel.less!'; + +can.Component.extend({ + tag : 'bh-youtube-channel-service', + template : initView +}); diff --git a/new-app/components/service-forms/youtube-channel/youtube-channel.less b/new-app/components/service-forms/youtube-channel/youtube-channel.less new file mode 100644 index 0000000..07aed3d --- /dev/null +++ b/new-app/components/service-forms/youtube-channel/youtube-channel.less @@ -0,0 +1,3 @@ +bh-youtube-channel { + display: block; +} diff --git a/new-app/components/service-forms/youtube-channel/youtube-channel.stache b/new-app/components/service-forms/youtube-channel/youtube-channel.stache new file mode 100644 index 0000000..060d72d --- /dev/null +++ b/new-app/components/service-forms/youtube-channel/youtube-channel.stache @@ -0,0 +1,4 @@ +
+ + {{{configErrors errors 'name'}}} +
diff --git a/new-app/components/service-forms/youtube-playlist/youtube-playlist.js b/new-app/components/service-forms/youtube-playlist/youtube-playlist.js new file mode 100644 index 0000000..909ab32 --- /dev/null +++ b/new-app/components/service-forms/youtube-playlist/youtube-playlist.js @@ -0,0 +1,8 @@ +import can from "can"; +import initView from './youtube-playlist.stache!'; +import './youtube-playlist.less!'; + +can.Component.extend({ + tag : 'bh-youtube-playlist-service', + template : initView +}); diff --git a/new-app/components/service-forms/youtube-playlist/youtube-playlist.less b/new-app/components/service-forms/youtube-playlist/youtube-playlist.less new file mode 100644 index 0000000..874a1e8 --- /dev/null +++ b/new-app/components/service-forms/youtube-playlist/youtube-playlist.less @@ -0,0 +1,3 @@ +bh-youtube-playlist { + display: block; +} diff --git a/new-app/components/service-forms/youtube-playlist/youtube-playlist.stache b/new-app/components/service-forms/youtube-playlist/youtube-playlist.stache new file mode 100644 index 0000000..3d95b81 --- /dev/null +++ b/new-app/components/service-forms/youtube-playlist/youtube-playlist.stache @@ -0,0 +1,4 @@ +
+ + {{{configErrors errors 'name'}}} +
diff --git a/new-app/components/service-forms/youtube-user/youtube-user.js b/new-app/components/service-forms/youtube-user/youtube-user.js new file mode 100644 index 0000000..70180e4 --- /dev/null +++ b/new-app/components/service-forms/youtube-user/youtube-user.js @@ -0,0 +1,8 @@ +import can from "can"; +import initView from './youtube-user.stache!'; +import './youtube-user.less!'; + +can.Component.extend({ + tag : 'bh-youtube-user-service', + template : initView +}); diff --git a/new-app/components/service-forms/youtube-user/youtube-user.less b/new-app/components/service-forms/youtube-user/youtube-user.less new file mode 100644 index 0000000..ddabf7f --- /dev/null +++ b/new-app/components/service-forms/youtube-user/youtube-user.less @@ -0,0 +1,3 @@ +bh-youtube-user { + display: block; +} diff --git a/new-app/components/service-forms/youtube-user/youtube-user.stache b/new-app/components/service-forms/youtube-user/youtube-user.stache new file mode 100644 index 0000000..50a1849 --- /dev/null +++ b/new-app/components/service-forms/youtube-user/youtube-user.stache @@ -0,0 +1,3 @@ +
+ +
diff --git a/new-app/components/services-list/services-list-test.js b/new-app/components/services-list/services-list-test.js new file mode 100644 index 0000000..20c6cd2 --- /dev/null +++ b/new-app/components/services-list/services-list-test.js @@ -0,0 +1,131 @@ +import "./services-list"; +import QUnit from "steal-qunit"; +import F from "funcunit"; +import $ from "jquery"; +import Models from "models/"; + +var template = can.stache(""); + +var renderTemplate = function(data){ + $('#qunit-fixture').html(template(data)); +}; + +var services = [ + new Models.Service({ + "error": null, + "config": { + "display_name": "bitovi", + "term": "bitovi" + }, + "entity_count": 98, + "brand_identity_id": 1, + "type_name": "term", + "feed_name": "twitter", + "id": 4 + }) +]; + +QUnit.module('Services List Test'); + +QUnit.test('Services List is correctly rendered', function(){ + renderTemplate({ + services : new can.List(services), + currentService : new can.compute(), + state : new can.Map({ + hubId: 1, + loadingServices: [] + }) + }); + + F('bh-services-list').exists('Services list is rendered'); + F('bh-services-list tbody tr').size(1, 'Services table is rendered'); +}); + +QUnit.test('Services can be edited', function(){ + renderTemplate({ + services : new can.List(services), + currentService : new can.compute(), + state : new can.Map({ + hubId: 1, + loadingServices: [] + }) + }); + + F('bh-services-list').exists('Services list is rendered'); + F('bh-services-list [can-click=editService]').click(); + F('bh-services-list bh-service-form').exists('Form is rendered'); +}); + +QUnit.test('Services can be destroyed', function(){ + renderTemplate({ + services : new can.List(services), + currentService : new can.compute(), + state : new can.Map({ + hubId: 1, + loadingServices: [] + }) + }); + + F('bh-services-list').exists('Services list is rendered'); + F('bh-services-list [can-click=destroyService]').exists('Destroy confirmation dialog is rendered'); +}); + +QUnit.test('Services can be in loading state', function(){ + var servicesList = new can.List(services); + renderTemplate({ + services : servicesList, + currentService : new can.compute(), + state : new can.Map({ + hubId: 1, + loadingServices: [servicesList[0]] + }) + }); + + F('bh-services-list').exists('Services list is rendered'); + F('bh-services-list tr.loader').exists('Service is in loading state'); + F('bh-services-list tr.loading-service').exists('Service is marked as loading'); +}); + +QUnit.test('Services can have no results', function(){ + var servicesList = new can.List(services); + + renderTemplate({ + services : servicesList, + currentService : new can.compute(), + state : new can.Map({ + hubId: 1, + loadingServices: [] + }) + }); + + servicesList[0].attr('noResults', true); + + F('bh-services-list').exists('Services list is rendered'); + F('bh-services-list .no-data-alert').exists('Service has no data alert is shown'); + F('bh-services-list [can-click=hideNoResults]').click(); + F('bh-services-list .no-data-alert').missing('Service has no data alert can be hidden'); +}); + +QUnit.test('Services can have be in error state', function(){ + var servicesList = new can.List(services); + + renderTemplate({ + services : servicesList, + currentService : new can.compute(), + state : new can.Map({ + hubId: 1, + loadingServices: [] + }) + }); + + servicesList[0].attr('error', { + klass: 'foo', + message: 'bar' + }); + + F('bh-services-list').exists('Services list is rendered'); + F('bh-services-list tr.errored-service').exists('Service is marked as in error state'); + F('bh-services-list .alert-config-error').missing('Errors are not displayed by default'); + F('bh-services-list [can-click=toggleErrorShowing]').click(); + F('bh-services-list .alert-config-error').exists('Errors are displayed'); +}); diff --git a/new-app/components/services-list/services-list.js b/new-app/components/services-list/services-list.js new file mode 100644 index 0000000..e1610f9 --- /dev/null +++ b/new-app/components/services-list/services-list.js @@ -0,0 +1,78 @@ +import can from "can"; +import initView from "./services-list.stache!"; +import "./services-list.less!"; +import "can/map/define/"; +import "components/delete_service_dialog/"; +import "components/service-config-formatter/"; + +can.Component.extend({ + tag : 'bh-services-list', + template : initView, + scope: { + deletingService: null, + init : function(){ + this.attr({ + shownErrors: [], + hiddenNoResults: [] + }); + }, + hideNoResults : function(service){ + this.attr('hiddenNoResults').push(service); + }, + destroyService: function( service, el, ev) { + this.attr('deletingService', service); + }, + editService:function(service){ + this.attr('currentService', service); + }, + toggleErrorShowing : function(service){ + var shownErrors = this.attr('shownErrors'), + index = shownErrors.indexOf(service); + if(index > -1){ + shownErrors.splice(index, 1); + } else { + shownErrors.push(service); + } + } + }, + helpers : { + isCurrentService : function(service, opts){ + var check; + + service = can.isFunction(service) ? service() : service; + + check = service === this.attr('currentService'); + check = check && !service.isNew(); + + return check ? opts.fn(opts.scope.add(service)) : opts.inverse(opts.scope.add(service)); + }, + isServiceCurrentlyLoading : function(service, opts){ + var currentlyLoading = this.attr('state.loadingServices'); + + service = can.isFunction(service) ? service() : service; + + if(service.isLoading() || (currentlyLoading.indexOf(service) !== -1 && !service.attr('error') && !service.attr('noResults'))){ + return opts.fn(); + } + }, + serviceHasNoResults : function(service, opts){ + service = can.isFunction(service) ? service() : service; + this.attr('hiddenNoResults').attr('length'); + if(service.attr('noResults') && this.attr('hiddenNoResults').indexOf(service) === -1){ + return opts.fn(); + } + }, + showErrorsForService : function(service, opts){ + service = can.isFunction(service) ? service() : service; + this.attr('shownErrors').attr('length'); + if(service.attr('error') && this.attr('shownErrors').indexOf(service) !== -1){ + return opts.fn(); + } + } + }, + events : { + '{currentService} created' : function(){ + this.scope.attr('currentService', null); + } + } +}); diff --git a/new-app/components/services-list/services-list.less b/new-app/components/services-list/services-list.less new file mode 100644 index 0000000..4ea5d8e --- /dev/null +++ b/new-app/components/services-list/services-list.less @@ -0,0 +1,83 @@ +bh-services-list { + display: block; + margin: 0 -15px; + border-bottom: 1px solid #ddd; + .destroy-service, .edit-service { + cursor: pointer; + color: #666; + &:hover { + color: #333; + } + } + + table.services-table { + margin-bottom: 0; + > tbody > tr, > thead > tr { + &.service-row td, &.loader td { + border-top-color: #ddd; + } + &.loader td { + background: #97ECFF; + } + &.loading-service td { + border-top: none; + background: #97ECFF; + } + &.errored-service td { + border-top-color: #FFB8B8; + } + th { + border-bottom-color: #ddd; + } + th:first-child, td:first-child { + padding-left: 25px; + } + th:last-child, td:last-child { + padding-right: 25px; + } + th.actions { + width: 70px; + } + td.actions .fa { + display: inline-block; + margin-top: 3px; + + } + th { + color: #f30; + font-size: 16px; + } + .progress { + height: 5px; + margin: 5px 0 0; + } + } + .no-data-alert { + margin: 10px 25px; + } + .alert-config-error { + margin-bottom: 0; + background: white; + } + } + ul.config { + font-size: 12px; + margin: 0; + padding: 0 0 0 16px; + } + .toggle-errors { + cursor: pointer; + float: left; + margin: 3px 5px 0 0; + } + bh-service-config-formatter { + float: left; + } + .table > tbody > tr.current-editing-service > td { + padding-bottom: 0; + padding-top: 25px; + } + .pending-wrap { + padding: 25px; + } +} diff --git a/new-app/components/services-list/services-list.stache b/new-app/components/services-list/services-list.stache new file mode 100644 index 0000000..be11c05 --- /dev/null +++ b/new-app/components/services-list/services-list.stache @@ -0,0 +1,58 @@ +{{#if deletingService}} + +{{/if}} +
+ + + {{#each services}} + {{#isCurrentService this}} + + + + {{else}} + {{#isServiceCurrentlyLoading this}} + + + + {{/isServiceCurrentlyLoading}} + + + + + {{#serviceHasNoResults this}} + + {{/serviceHasNoResults}} + {{#showErrorsForService this}} + + + + {{/showErrorsForService}} + {{/isCurrentService}} + {{/each}} + +
+ +
+
+
+
+
+ {{#if error}} + + {{/if}} + + + + +
+
+ + We couldn't find any data for this service. +
+
+
+ {{ formattedErrorClass }} + {{ formattedError }} +
+
+
diff --git a/new-app/components/services/services.js b/new-app/components/services/services.js new file mode 100644 index 0000000..03f4dce --- /dev/null +++ b/new-app/components/services/services.js @@ -0,0 +1,68 @@ +import can from "can"; +import Models from "models/"; +import initView from "./services.stache!"; + +import "./services.less!"; +import "components/service-form/"; +import "components/services-list/"; + +can.Component.extend({ + tag : 'bh-services', + template : initView, + scope : { + currentService : null, + define : { + services : { + get : function() { + console.log('GET LIST OF SERVICES', this.attr('appState')) + return new Models.Service.List({ + embed_id: this.attr('appState.currentHub.id') + }); + } + } + }, + feeds : Models.Service.feeds, + toggleNewService : function(ctx, el){ + var feed = el.data('feed'); + var currentService = this.attr('currentService'); + var check = currentService && currentService.isNew() && currentService.attr('feed_name') === feed; + + if(check){ + this.attr('currentService', null); + return; + } + + this.attr('currentService', Models.Service.createEmptyService(feed)); + } + }, + events : { + init : function(){ + this.preloadIcons(); + }, + preloadIcons : function(){ + var feeds = this.scope.feeds.attr(); + var img; + for(var k in feeds){ + img = new Image(); + img.src = "/images/social-empty/" + k + '.png'; + } + } + }, + helpers : { + currentServiceIsNewAndHasFeedName : function(feedName, opts){ + var currentService = this.attr('currentService'); + + feedName = can.isFunction(feedName) ? feedName() : feedName; + + if(!currentService){ + return opts.inverse(this); + } + + if(currentService.isNew() && + currentService.attr('feed_name') === feedName){ + return opts.fn(this); + } + return opts.inverse(this); + } + } +}); diff --git a/new-app/components/services/services.less b/new-app/components/services/services.less new file mode 100644 index 0000000..796e8ba --- /dev/null +++ b/new-app/components/services/services.less @@ -0,0 +1,42 @@ +bh-services { + display: block; + .service-slider-outer-wrap { + position: relative; + margin-bottom: 20px; + } + .service-slider-wrap { + padding: 25px 0; + .new-service-picker { + margin-bottom: 0; + li { + float: left; + width: 62px; + height: 63px; + border: 1px solid #dad9d9; + text-align: center; + font-size: 9px; + margin-right: -1px; + margin-top: -1px; + cursor: pointer; + img { + width: 48px; + height: 48px; + display: block; + margin: 5px auto; + } + &.active { + background: white; + color: #249cb8; + } + } + } + } + .alert-error-list { + padding: 5px; + margin-top: 5px; + font-size: 85%; + } + bh-service-form { + margin-bottom: 25px; + } +} diff --git a/new-app/components/services/services.stache b/new-app/components/services/services.stache new file mode 100644 index 0000000..c51fdf9 --- /dev/null +++ b/new-app/components/services/services.stache @@ -0,0 +1,34 @@ +

Connect a service

+ +
+
    + {{#each feeds}} +
  • + {{#currentServiceIsNewAndHasFeedName @key}} + + {{else}} + + {{/currentServiceIsNewAndHasFeedName}} +
  • + {{/each}} +
+
+ +{{#if currentService.isNew}} + {{#ifCanAddService services currentService.feed_name currentService.type_name}} + + {{else}} +
You must upgrade your plan to add this service.
+ {{/ifCanAddService}} +{{/if}} + +{{#if services.isPending}} +
+ Loading ... +
+{{else}} + {{#if services.length}} +

Connected services

+ + {{/if}} +{{/if}} diff --git a/new-app/components/services/services_test.js b/new-app/components/services/services_test.js new file mode 100644 index 0000000..495d950 --- /dev/null +++ b/new-app/components/services/services_test.js @@ -0,0 +1,95 @@ +import "./services"; +import QUnit from "steal-qunit"; +import F from "funcunit"; +import $ from "jquery"; +import fixture from "can/util/fixture/"; +import Models from "models/"; + +import "can/map/define/"; + +var template = can.stache(""); + +var renderTemplate = function(data){ + $('#qunit-fixture').html(template(data)); +}; + +can.stache.registerHelper( + 'ifCanAddService', + function(services, feed, type, opts){ + return opts.fn(); + } +); + +var StateMap = can.Map.extend({ + define : { + services : { + get : function() { + var res = new Models.Service.List({ + embed_id: this.attr('hubId') + }); + console.log(res); + return res; + } + } + } +}); + +QUnit.module('Services Test', { + beforeEach : function(){ + var fixtureData = [ + { + "error": null, + "config": { + "display_name": "bitovi", + "term": "bitovi" + }, + "entity_count": 98, + "brand_identity_id": 1, + "type_name": "term", + "feed_name": "twitter", + "id": 4 + } + ]; + fixture('GET /api/v3/services', function(){ + return fixtureData; + }); + fixture.delay = 1000; + fixture.on = true; + }, + afterEach : function(){ + fixture('GET /api/v3/services', null); + fixture.on = false; + fixture.delay = 100; + } +}); + +QUnit.test('Services are correctly rendered', function(){ + renderTemplate({ + state : new StateMap({ + hubId: 1, + loadingServices: [] + }) + }); + + F('bh-services').exists('Services are rendered'); + F('bh-services .pending-wrap').exists('Loader is rendered'); + F('bh-services bh-services-list').exists('Services list is rendered'); + F('bh-services .service-slider-wrap li').exists('Feed buttons are loaded'); +}); + +QUnit.test('Clicking on a feed button will toggle the service form', function(){ + renderTemplate({ + state : new can.Map({ + hubId: 1, + loadingServices: [] + }) + }); + + F('bh-services li[can-click=toggleNewService]:first').click(); + F('bh-services bh-service-form').exists('Service form is rendered'); + F.wait(1, function(){ + ok(F('bh-services li[can-click=toggleNewService]:first').is('.active'), 'First service button is activated'); + }); + F('bh-services li[can-click=toggleNewService].active').click(); + F('bh-services li[can-click=toggleNewService].active').missing('First service button is deactivated'); +}); diff --git a/new-app/components/suggestions/suggestions.js b/new-app/components/suggestions/suggestions.js new file mode 100644 index 0000000..f9827f7 --- /dev/null +++ b/new-app/components/suggestions/suggestions.js @@ -0,0 +1,61 @@ +import initView from './suggestions.stache!'; +import Models from 'models/'; +import './suggestions.less!'; + +export var SuggestionsVM = can.Map.extend({ + enterYourOwnLabel : 'Enter your own', + pickSuggestionLabel : 'Pick a suggestion', + allowExtra : false, + isLoading : true, + init : function(){ + var self = this; + this.attr('isLoading', true); + Models.Suggestion.findAll({ + service: this.attr('service'), + brandIdentityId: this.attr('brandIdentityId') + }).then(function(data){ + self.attr({ + suggestions: data, + isLoading : false + }); + }); + }, + toggleSuggestion : function(suggestion){ + var currentSuggestion = this.attr('val'); + var newSuggestion = suggestion.attr('id'); + + if(currentSuggestion === newSuggestion){ + this.attr('val', null); + } else { + this.attr('val', suggestion.attr('id')); + } + + }, + hasExtra : function(){ + var suggestions = this.attr('suggestions'); + var length = suggestions.attr('length'); + var val = this.attr('val'); + + for(var i = 0; i < length; i++){ + if(suggestions[i].id === val){ + return false; + } + } + return !!this.attr('allowExtra'); + } +}); + +can.Component.extend({ + tag : 'bh-suggestions', + template : initView, + scope : SuggestionsVM, + helpers : { + isSelected : function(suggestion, opts){ + suggestion = can.isFunction(suggestion) ? suggestion() : suggestion; + if(suggestion.attr('id') === this.attr('val')){ + return opts.fn(); + } + return opts.inverse(); + } + } +}); diff --git a/new-app/components/suggestions/suggestions.less b/new-app/components/suggestions/suggestions.less new file mode 100644 index 0000000..d3cc854 --- /dev/null +++ b/new-app/components/suggestions/suggestions.less @@ -0,0 +1,26 @@ +bh-suggestions { + display: block; + tr { + cursor: pointer; + td:first-child { + padding-left: 15px; + } + &:first-child td { + border-top: none; + } + } + .scroll { + max-height: 215px; + overflow-y: auto; + .table { + margin-bottom: 0; + } + } + .panel { + margin-top: 10px; + } + label.enter-your-own { + display: block; + margin-top: 15px; + } +} \ No newline at end of file diff --git a/new-app/components/suggestions/suggestions.stache b/new-app/components/suggestions/suggestions.stache new file mode 100644 index 0000000..05a1e84 --- /dev/null +++ b/new-app/components/suggestions/suggestions.stache @@ -0,0 +1,35 @@ +{{#if isLoading}} +
+ Loading... +
+{{else}} + {{#if suggestions.length}} +
+
+ {{ pickSuggestionLabel }} +
+
+ + + {{#each suggestions}} + + + + {{/each}} + +
+ + {{ name }} +
+
+
+ {{else}} +
+ We couldn't load any suggestions for this feed. +
+ {{/if}} + {{#if hasExtra}} + + + {{/if}} +{{/if}} diff --git a/new-app/components/suggestions/suggestions_test.js b/new-app/components/suggestions/suggestions_test.js new file mode 100644 index 0000000..22c8aa5 --- /dev/null +++ b/new-app/components/suggestions/suggestions_test.js @@ -0,0 +1,129 @@ +import "./suggestions"; +import QUnit from "steal-qunit"; +import F from "funcunit"; +import $ from "jquery"; + +import fixture from "can/util/fixture/"; + +var template = can.stache(""); + +var renderTemplate = function(data){ + $('#qunit-fixture').html(template(data)); +}; + + +var fixtureUrl = '/api/v3/services/suggestions/repo?brand_identity_id={brandIdentityId}'; + +QUnit.module('Suggestions Tests', { + beforeEach : function(){ + fixture(fixtureUrl, function(req){ + if(req.data.brandIdentityId !== '1'){ + return []; + } + return [ + { + "name": "aljosa/muchi.me", + "id": "aljosa/muchi.me" + }, + { + "name": "retro/apitizer", + "id": "retro/apitizer" + } + ]; + }); + fixture.delay = 100; + fixture.on = true; + }, + afterEach : function(){ + fixture.on = false; + fixture.delay = 0; + fixture(fixtureUrl, null); + } +}); + +QUnit.test("Suggestions are listed", function(){ + renderTemplate({ + brandIdentityId: 1, + service: 'repo' + }); + + F('bh-suggestions .loader').exists('Loader is displayed'); + F('bh-suggestions .panel').exists('Suggestions are loaded'); + F('bh-suggestions td').text(/aljosa\/muchi\.me/, 'First suggestion is rendered'); + F('bh-suggestions td').text(/retro\/apitizer/, 'Secong suggestion is rendered'); + +}); + +QUnit.test("When there are no suggestions, info is shown", function(){ + renderTemplate({ + brandIdentityId: 2, + service: 'repo' + }); + + F('bh-suggestions .panel').missing('Suggestions are not loaded'); + F('bh-suggestions .alert-info').exists('Info panel is shown instead of suggestions'); +}); + +QUnit.test("Allow extra", function(){ + renderTemplate({ + brandIdentityId: 1, + service: 'repo', + allowExtra: true + }); + + F('bh-suggestions [can-value=val]').exists('Input field for extra is shown'); + F('bh-suggestions [can-value=val]').type('foo/bar[\t]'); + F.wait(1, function(){ + QUnit.equal(F('bh-suggestions').scope().attr('val'), 'foo/bar', 'Val is set to extra value'); + }); +}); + +QUnit.test("Selecting suggestion", function(){ + renderTemplate({ + brandIdentityId: 1, + service: 'repo' + }); + + F('bh-suggestions .panel').exists('Suggestions are loaded'); + F('tr:first').click(); + F('tr.info td').text(/aljosa\/muchi\.me/, 'Suggestion is selected'); + F.wait(1, function(){ + QUnit.equal(F('bh-suggestions').scope().attr('val'), 'aljosa/muchi.me', 'Suggestion is set on scope'); + }); +}); + +QUnit.test("Selecting suggestion is possible through the attribute", function(){ + renderTemplate({ + brandIdentityId: 1, + service: 'repo', + val: 'aljosa/muchi.me' + }); + F('tr.info td').text(/aljosa\/muchi\.me/, 'Suggestion is selected'); +}); + +QUnit.test("Clicking on a selected suggestion will hide it", function(){ + renderTemplate({ + brandIdentityId: 1, + service: 'repo', + val: 'aljosa/muchi.me' + }); + + F('tr.info').click(); + F('tr.info').missing('Suggestion is deselected'); +}); + +QUnit.test("Selecting a suggestion from the list will hide the extra input", function(){ + renderTemplate({ + brandIdentityId: 1, + service: 'repo', + allowExtra: true + }); + + F('[can-value=val]').exists('Extra input is shown'); + F('tr:first').click(); + F('tr.info').exists('Suggestion is selected'); + F('[can-value=val]').missing('Extra input is hidden'); + F('tr.info').click(); + F('tr.info').missing('Suggestion is deselected'); + F('[can-value=val]').exists('Extra input is shown'); +}); diff --git a/new-app/components/tag-list/tag-list-tests.js b/new-app/components/tag-list/tag-list-tests.js new file mode 100644 index 0000000..27894fe --- /dev/null +++ b/new-app/components/tag-list/tag-list-tests.js @@ -0,0 +1,66 @@ +import {TagListVM} from "./tag-list"; +import QUnit from "steal-qunit"; +import F from "funcunit"; +import $ from "jquery"; + +var template = can.stache(""); + +var renderTemplate = function(data){ + $('#qunit-fixture').html(template(data)); +}; + +var getTags = function(vm){ + return vm.attr('tags').attr(); +}; + +QUnit.module("Tag List Tests"); + +QUnit.test('Adding tags', function(){ + var tags = new can.List(); + + renderTemplate({tags: tags}); + + F('bh-tag-list').exists(); + F('bh-tag-list').click(); + F('bh-tag-list input').type('FOO '); + F.wait(1, function(){ + QUnit.assert.deepEqual(tags.attr(), ['FOO']); + }); +}); + +QUnit.test('Removing tags', function(){ + var tags = new can.List(['tag1', 'tag2']); + + renderTemplate({tags: tags}); + + F('bh-tag-list input').type('\b'); + + F.wait(1, function(){ + QUnit.assert.deepEqual(tags.attr(), ['tag1']); + }); +}); + +QUnit.test('addTag function', function(){ + var vm = new TagListVM(); + QUnit.assert.deepEqual(getTags(vm), [], 'VM is initalized with empty tag list'); + vm.addTag('foo'); + QUnit.assert.deepEqual(getTags(vm), ['foo'], 'Tag is added'); + vm.addTag('foo'); + QUnit.assert.deepEqual(getTags(vm), ['foo'], 'Duplicate tag entry is prevented'); + vm.addTag(' bar#$'); + QUnit.assert.deepEqual(getTags(vm), ['foo', 'bar'], 'Tags are cleaned before they are added to the list'); + vm.addTag(' bar$$$'); + QUnit.assert.deepEqual(getTags(vm), ['foo', 'bar'], 'Tags are cleaned before checking for duplicates'); +}); + +QUnit.test('removeTag function', function(){ + var vm = new TagListVM({ + tags : ['foo', 'bar', 'baz'] + }); + vm.removeTag(); + QUnit.assert.deepEqual(getTags(vm), ['foo', 'bar'], 'When called without argument removeTag removes last tag from the list'); + vm.removeTag('foo'); + QUnit.assert.deepEqual(getTags(vm), ['bar'], 'When called with argument, removeTag will find the tag in the list and remove it'); + vm.removeTag('foobarbaz'); + QUnit.assert.deepEqual(getTags(vm), ['bar'], 'When called with the non existing tag removeTag function will do nothing'); +}); diff --git a/new-app/components/tag-list/tag-list.js b/new-app/components/tag-list/tag-list.js new file mode 100644 index 0000000..be95fcd --- /dev/null +++ b/new-app/components/tag-list/tag-list.js @@ -0,0 +1,77 @@ +import can from "can"; +import initView from "./tag-list.stache!"; +import "./tag-list.less!"; + +var KEYMAP = { + COMMA : 188, + SPACE : 32, + BACKSPACE : 8, + ENTER : 13 +}; + +export var TagListVM = can.Map.extend({ + init : function(){ + if(!this.attr('tags')){ + this.attr('tags', []); + } + }, + removeTag : function(tag){ + var tags = this.attr('tags'); + var index = tag ? tags.indexOf(tag) : tags.attr('length') - 1; + if(index >= 0){ + tags.splice(index, 1); + } + }, + addTag : function(tag){ + var tags, canAddTag; + + tag = tag.replace(/[^a-zA-Z0-9-_]/g ,""); + tags = this.attr('tags'); + canAddTag = tags.indexOf(tag) === -1; + + if(canAddTag){ + tags.push(tag); + } + } +}); + +can.Component.extend({ + tag : 'bh-tag-list', + template : initView, + scope : TagListVM, + events: { + 'input keydown' : function(el, ev){ + var val = can.trim(el.val()); + if((ev.which === KEYMAP.COMMA || + ev.which === KEYMAP.SPACE || + ev.which === KEYMAP.ENTER) && val !== ''){ + this.scope.addTag(val); + el.val(''); + if(ev.which !== KEYMAP.ENTER){ + ev.preventDefault(); + } + } else if(ev.which === KEYMAP.BACKSPACE && this.__lastSelectionStart === 0){ + this.scope.removeTag(); + } + this.__lastSelectionStart = el[0].selectionStart; + }, + 'input click': function(el){ + this.__lastSelectionStart = el[0].selectionStart; + }, + 'input focus': function(el){ + this.__lastSelectionStart = el[0].selectionStart; + }, + 'input blur' : function(el, ev){ + var val = can.trim(el.val() || ""); + if(val !== ""){ + this.scope.addTag(val); + el.val(""); + } + }, + click : function(el, ev){ + if(ev.target === this.element[0] || $(ev.target).is('.tag-list-wrap')){ + this.element.find('input').focus(); + } + } + } +}); diff --git a/new-app/components/tag-list/tag-list.less b/new-app/components/tag-list/tag-list.less new file mode 100644 index 0000000..bd4b854 --- /dev/null +++ b/new-app/components/tag-list/tag-list.less @@ -0,0 +1,25 @@ +@import "../../node_modules/bootstrap/less/mixins.less"; + +bh-tag-list { + input { + border: none; + outline: none; + box-shadow: none; + float: left; + margin-bottom: 4px; + } + .tag-list-wrap { + padding: 5px 0 0 5px; + height: auto; + } + .label { + float: left; + font-size: 95%; + font-weight: 300; + margin: 0 5px 5px 0; + .remove-tag { + cursor: pointer; + margin-right: 0; + } + } +} diff --git a/new-app/components/tag-list/tag-list.stache b/new-app/components/tag-list/tag-list.stache new file mode 100644 index 0000000..3ce5ffe --- /dev/null +++ b/new-app/components/tag-list/tag-list.stache @@ -0,0 +1,9 @@ +
+ {{#each tags}} + + {{ . }} + + + {{/each}} + +
\ No newline at end of file diff --git a/new-app/index.html b/new-app/index.html new file mode 100644 index 0000000..e69de29 diff --git a/new-app/index.js b/new-app/index.js new file mode 100644 index 0000000..6f1401f --- /dev/null +++ b/new-app/index.js @@ -0,0 +1,12 @@ +import "can/view/autorender/"; +import "bootstrap/less/bootstrap.less!"; +import "style/style.less!"; +import "components/layout/"; +import $ from "jquery"; + +$.ajaxPrefilter(function( options, originalOptions, jqXHR ) { + if(options.type.toLowerCase() !== 'get'){ + options.data = JSON.stringify(originalOptions.data); + options.contentType = 'application/json'; + } +}); diff --git a/new-app/models/account.js b/new-app/models/account.js new file mode 100644 index 0000000..30e50f9 --- /dev/null +++ b/new-app/models/account.js @@ -0,0 +1,37 @@ +import can from "can"; +import Organization from "./organization"; + +import "can/map/define/"; +import "can/construct/super/"; + +export default can.Model.extend({ + findOne : '/api/v3/current/account', + update: 'PUT /api/v3/current/account', + current : function(){ + return this.findOne({}); + } +}, { + define : { + + organizations : { + Type : Organization.List + } + }, + hasMultipleOrganizations : function(){ + var organizations = this.attr('organizations'); + return organizations && organizations.attr('length') > 1; + }, + serialize: function() { + var data = this._super(); + + if(data.current_password && !data.password){ + data.password = ""; + } + + if(data.password && !data.password_confirmation){ + data.password_confirmation = ""; + } + + return { account: data }; + } +}); diff --git a/new-app/models/analytics.js b/new-app/models/analytics.js new file mode 100644 index 0000000..f0a54bf --- /dev/null +++ b/new-app/models/analytics.js @@ -0,0 +1,95 @@ +import can from "can"; +import Service from "./service"; +import moment from "moment"; + +import "can/map/define/"; +import "components/service-config-formatter/"; + +var TOOLTIP = can.stache(''); + +var fillInMissingTimepoints = function(points, length){ + var firstRun = true; + + while(points.length < length){ + if(firstRun){ + points.unshift(0); + firstRun = false; + } else { + points.unshift(null); + } + + } + return points; +}; + +var alphaVersion = function(color){ + return 'rgba' + color.substring(3, color.length - 1) + ', .2)'; +}; + +var Analytics = can.Model.extend({ + findAll : '/api/v3/analytics?source_type={sourceType}&resolution={resolution}&owner_id={ownerId}' +}, { + define : { + source : { + Type: Service + } + } +}); + +Analytics.List = Analytics.List.extend({ + graphData : function(type){ + var length = this.attr('length'); + var serviceTimepoints = {}; + var service; + var timepoints; + var isLongest = false; + var data = []; + var longestPointsLengthLabels = []; + var i; + + for(i = 0; i < length; i++){ + service = this.attr(i + '.source'); + timepoints = this.attr(i + '.timepoints'); + + serviceTimepoints[service.id] = []; + + isLongest = (timepoints.length > longestPointsLengthLabels.length); + + if(isLongest){ + longestPointsLengthLabels = []; + } + + for(var j = 0; j < timepoints.length; j++){ + serviceTimepoints[service.id].push(timepoints[j][type]); + if(isLongest){ + longestPointsLengthLabels.push(moment(timepoints[j].measured_at).fromNow()); + } + + } + } + + for(var k in serviceTimepoints){ + serviceTimepoints[k] = fillInMissingTimepoints(serviceTimepoints[k], longestPointsLengthLabels.length); + } + + for(i = 0; i < length; i++){ + service = this.attr(i + '.source'); + data.push({ + label : can.trim(TOOLTIP(service).firstChild.innerText), + fillColor: alphaVersion(service.attr('graphColor')), + strokeColor: service.attr('graphColor'), + pointColor: service.attr('graphColor'), + pointHighlightFill: "#fff", + pointHighlightStroke: service.attr('graphColor'), + data: serviceTimepoints[service.id] + }); + } + + return { + labels : longestPointsLengthLabels, + datasets: data + }; + } +}); + +export default Analytics; diff --git a/new-app/models/app-state.js b/new-app/models/app-state.js new file mode 100644 index 0000000..5ac5030 --- /dev/null +++ b/new-app/models/app-state.js @@ -0,0 +1,78 @@ +import $ from "jquery"; +import can from "can"; +import Models from "models/"; +import route from "can/route/"; + +import "can/map/define/"; + + +var AppState = can.Map.extend({ + define : { + page : { + set : function(val){ + return val; + } + }, + tab : { + get : function(lastSetVal){ + return lastSetVal || "inbox"; + } + }, + currentBrand : { + serialize: false + }, + currentSubscription : { + serialize: false + }, + currentAccount : { + serialize: false + }, + currentOrganization: { + serialize: false + }, + currentHub: { + serialize: false, + }, + hubs : { + serialize: false + }, + loadingServices : { + serialize : false, + get : function(){ + return []; + } + }, + + }, + isAdmin : function(){ + return true; + }, + resetEmbed : function(){} +}); + +var appState = new AppState(); +route.map(appState); +route("", {page: "moderation"}); +route.ready(); + + +$.when( + Models.Brand.findOne({}), + Models.Subscription.findOne({}), + Models.Account.current(), + Models.Organization.current(), + Models.Hub.findAll({}) +).done(function(brand, subscription, account, organization, hubs){ + + appState.attr({ + currentBrand: brand, + currentSubscription: subscription, + currentAccount: account, + currentOrganization: organization, + hubs: hubs, + currentHub: hubs[0], + }); + +}); + +export default appState; diff --git a/new-app/models/appstate.js b/new-app/models/appstate.js new file mode 100644 index 0000000..601d5d2 --- /dev/null +++ b/new-app/models/appstate.js @@ -0,0 +1,291 @@ +import can from "can"; +import Models from 'models/'; +import _reduce from 'lodash/collection/reduce'; +import connectLiveService from 'connect-liveservice'; +import Communicator from 'communicator/'; +import 'can/map/define/'; +import 'can/construct/proxy/'; +import 'can/map/delegate/'; + +var CURRENT_IFRAME; + +var PAGE_TITLES = { + 'hub-list' : 'Hub List', + 'services' : 'Services', + 'integration' : 'Integration', + 'moderation' : 'Moderation', + 'analytics' : 'Analytics', + 'payments' : 'Payments', + 'organization-settings' : 'Organization Accounts', + 'user-settings' : 'User Settings' +}; + +var getPageTitle = function(val, appState){ + if(val === 'sidebar'){ + val = appState.attr('panel') || 'services'; + } + + return PAGE_TITLES[val]; +}; + +var setTitle = function(val, appState){ + $('title').html('BitHub — ' + getPageTitle(val, appState)); +}; + +export default can.Map.extend({ + define : { + page : { + value : 'hub-list', + set : function(val){ + this.removeAttr('customPreset'); + setTitle(val, this); + return val; + } + }, + panel : { + set : function(val){ + setTitle(val, this); + return val; + } + }, + currentSubscription : { + serialize: false + }, + currentAccount: { + serialize: false + }, + currentOrganization : { + serialize: false + }, + hubId : { + set : function(val){ + var liveService = connectLiveService(val, this.attr('currentBrand').attr('tenant_name')); + var self = this; + + this.attr('bits').splice(0); + + if(liveService){ + + + liveService.on('services', can.proxy(Models.Service.messageFromLiveService, Models.Service)); + + liveService.on('services', function(msg){ + var loadingServices = self.attr('loadingServices'); + var index, service; + if(typeof msg === 'string'){ + msg = JSON.parse(msg); + } + + if(msg.service.empty_results || msg.service.has_errors){ + service = loadingServices.filter(function(s){ + return s.id === msg.service.id; + })[0]; + index = loadingServices.indexOf(service); + if(index > -1){ + loadingServices.splice(index, 1); + } + } + }); + } + + return val; + }, + remove : function(){ + CURRENT_IFRAME = null; + this.attr('bits').splice(0); + } + }, + embedType : { + get : function(){ + if(this.attr('page') === 'sidebar'){ + if(this.attr('panel') === 'integration'){ + return 'preview'; + } + return 'admin'; + } + }, + serialize: false + }, + iframe : { + get : function(){ + var src = this.attr('iframeSrc'); + var iframe; + + if(src){ + if(!CURRENT_IFRAME){ + iframe = $(''); + CURRENT_IFRAME = iframe[0]; + } + + return CURRENT_IFRAME; + } + } + }, + iframeSrc : { + get : function(){ + var currentBrand = this.attr('currentBrand'); + var hubId = this.attr('hubId'); + + if(hubId && currentBrand){ + return this.attr('preset').url(currentBrand.attr('tenant_name'), hubId); + } + }, + serialize: false + }, + adminPreset : { + value : Models.Preset.ADMIN, + serialize: false + }, + defaultPreviewPreset : { + value : Models.Preset.PREVIEW, + serialize: false + }, + preset : { + get : function(){ + var embedType = this.embedType(); + var customPreset; + + if(embedType === 'admin'){ + return this.attr('adminPreset'); + } else { + customPreset = this.attr('customPreset'); + return customPreset || this.attr('defaultPreviewPreset'); + } + }, + set : function(val){ + var embedType = this.embedType(); + var adminPreset = this.attr('adminPreset'); + + if(embedType === 'admin'){ + adminPreset.attr('config').attr(val.attr ? val.attr() : val); + return val; + } + }, + serialize : function(){ + var embedType = this.embedType(); + var adminPreset = this.attr('adminPreset'); + var adminParams; + if(adminPreset){ + adminPreset.attr(); + } + + + if(embedType === 'admin'){ + adminParams = { + order: adminPreset.attr('config.order'), + filter: adminPreset.attr('config.filter') + }; + + if(adminPreset.attr('config.service_id')){ + adminParams.service_id = adminPreset.attr('config.service_id'); + } + + return adminParams; + } + } + }, + customPreset: { + serialize: false + }, + hub : { + serialize : false, + get : function(lastSetValue, setAttrValue){ + Models.Hub.findOne({id: this.attr('hubId')}) + .then(function(hub){ + setAttrValue(hub); + }); + } + }, + services : { + get : function() { + return new Models.Service.List({ + embed_id: this.attr('hubId') + }); + } + }, + sidebarIsExpanded : { + value : true, + serialize: false + }, + loadingServices : { + value : [], + serialize: false + }, + bits : { + Value : Models.Bit.List, + serialize: false + }, + scrollTop : { + value : 0, + serialize: false + }, + scrollHeight: { + value : 0, + serialize: false + }, + currentBrand : { + serialize: false + } + }, + init : function(){ + var self = this; + this.communicator = Communicator.bind(this.compute('iframe'), { + loadedBits : function(payload){ + self.bitsWereLoaded(payload); + } + }); + }, + updateIframeAttrs : function(){ + var preset = this.attr('preset'); + var currentBrand = this.attr('currentBrand'); + var hubId = this.attr('hubId'); + var newAttrs; + + if(preset && currentBrand && hubId){ + newAttrs = preset.embedAttrs(currentBrand.attr('tenant_name'), hubId); + this.communicator.send('updateAttrs', newAttrs); + } + }, + resetEmbed : function(){ + this.communicator.send('reset'); + }, + bitsWereLoaded : function(serviceIds){ + var loadingServices = this.attr('loadingServices'); + var loadingServicesByIds = _reduce(loadingServices, function(acc, service){ + acc[service.attr('id') + ""] = service; + return acc; + }, {}); + var index; + + for(var i = 0; i < serviceIds.length; i++){ + if(loadingServicesByIds[serviceIds[i]]){ + index = loadingServices.indexOf(loadingServicesByIds[serviceIds[i]]); + loadingServices.splice(index, 1); + } + } + }, + isAdminEmbed : function(){ + var preset = this.attr('preset'); + return preset && preset.attr('config.view') === 'admin'; + }, + theme : function(){ + var preset = this.attr('preset'); + return (preset && preset.attr('config.theme')) || 'light'; + }, + isSidebar : function(){ + return this.attr('page') === 'sidebar' && this.attr('hubId'); + }, + embedType : function(){ + return this.attr('embedType'); + }, + embedTypeTitle : function(){ + var titles = { + admin: 'Administration', + preview: 'Preview' + }; + return titles[this.embedType()]; + }, + isAnalyticsPageActive : function(){ + return this.attr('page') === 'analytics'; + }, +}); diff --git a/new-app/models/bit.js b/new-app/models/bit.js new file mode 100644 index 0000000..184bf3f --- /dev/null +++ b/new-app/models/bit.js @@ -0,0 +1,85 @@ +import can from "can"; +import Bit from "bithub-embed/models/bit"; + +import "can/list/promise/"; +import "can/map/define/"; + +var checkIfBitIsBelowCurrentBit = function(bit, currentBit){ + if(!currentBit){ + return false; + } + if(currentBit.is_pinned){ + return true; + } + return bit.thread_updated_ts < currentBit.thread_updated_ts; +}; + +var isFullBit = function(bit){ + return !!bit.created_at; +}; + +var buffer = (function(){ + var _buffer = []; + var _currentSweeper; + + return { + add : function(bit){ + _buffer.push(bit); + if(!_currentSweeper){ + _currentSweeper = setTimeout(function(){ + var localBuffer = _buffer.splice(0).reverse(); + for(var i = 0; i < localBuffer.length; i++){ + can.trigger(Bit, 'lifecycle', [localBuffer[i]]); + } + _currentSweeper = null; + }, 5000); + } + } + }; +})(); + +Bit.messageFromLiveService = function(msg){ + var parsed = JSON.parse(msg); + parsed._isFromLiveService = true; + + if(this.store[parsed.id]){ + this.store[parsed.id].attr(parsed); + } else if(isFullBit(parsed)){ + buffer.add(this.model(parsed)); + } + if(!parsed.is_approved){ + can.trigger(Bit, 'disapproved', [this.store[parsed.id]]); + } +}; + +Bit.List = Bit.List.extend({ + place : function(bit){ + var index = -1; + var currentIndex, currentBit; + + this.attr('length'); + + currentIndex = this.indexOf(bit); + + // if it exists in the list remove it because we are changing the order + if(currentIndex > -1){ + this.splice(currentIndex, 1); + } + + if(bit.attr('is_pinned')){ + do { + index++; + currentBit = this.attr(index); + } while(currentBit && currentBit.attr('is_pinned')); + } else { + do { + index++; + currentBit = this.attr(index); + } while(checkIfBitIsBelowCurrentBit(bit, currentBit)); + } + + this.splice(index, 0, bit); + } +}); + +export default Bit; diff --git a/new-app/models/brand.js b/new-app/models/brand.js new file mode 100644 index 0000000..13cedf6 --- /dev/null +++ b/new-app/models/brand.js @@ -0,0 +1,5 @@ +import can from "can"; + +export default can.Model.extend({ + findOne : '/api/v3/brands/current' +}, {}); diff --git a/new-app/models/embed_appstate.js b/new-app/models/embed_appstate.js new file mode 100644 index 0000000..03ab5c3 --- /dev/null +++ b/new-app/models/embed_appstate.js @@ -0,0 +1,122 @@ +import can from "can"; +import Bit from "models/bit"; +import connectLiveService from "connect-liveservice"; +import "can/map/define/"; + +var addDefaultAttrs = function(params){ + var defaultParams = { + view: 'public', + theme: 'light', + live: false + }; + return can.extend(defaultParams, params); +}; + +var liveService; + +export default can.Map.extend({ + define : { + live : { + set : function(val){ + return (val === true || val === 'true'); + } + }, + hub : { + serialize : false, + }, + bits : { + Value : Bit.List, + serialize: false + }, + currentBrand : { + serialize: false + }, + }, + setAttrs : function(attrs){ + this.attr(addDefaultAttrs(attrs)); + }, + init : function(){ + this.setDefaultParams(); + }, + isLive : function(){ + return this.attr('live'); + }, + isPublic : function(){ + return !this.isAdmin(); + }, + isGroupedByDate : function(){ + return this.attr('order') === 'grouped-by-date'; + }, + showPoweredBy : function(){ + return this.isPublic(); + }, + reset : function(){ + can.batch.start(); + this.setDefaultParams(); + this.bits.splice(0); + can.batch.stop(); + }, + getView : function(){ + if(this.isAdmin()){ + return 'admin'; + } + return 'public'; + }, + connectLiveService : function(){ + + var hubId = this.attr('hubId'); + liveService = connectLiveService(hubId, this.attr('tenant')); + + if(liveService){ + console.log('LIVESERVICE ENTITIES', liveService); + + liveService.on('entities', can.proxy(Bit.messageFromLiveService, Bit)); + } + }, + getParams: function(){ + var hubId = this.attr('hubId'); + var params = {}; + var tenant = this.attr('tenant'); + var isPublic = this.isPublic(); + var filter = this.attr('filter'); + var serviceId = this.attr('service_id'); + var imageOnly = this.attr('image_only'); + + imageOnly = imageOnly === true || imageOnly === 'true'; + + params.view = this.getView(); + + if(isPublic){ + params.tenant_name = tenant; + } else { + params.order = this.attr('order') || "created_at:desc"; + if(params.order === 'grouped-by-date'){ + params.order = 'preview'; + } + if(filter){ + params.show = filter; + } + if(serviceId){ + params.service_id = serviceId; + } + } + + if(imageOnly){ + params.image_only = true; + } + + + params.hubId = hubId; + + return params; + }, + setDefaultParams : function(){ + this.attr('params', { + offset: 0, + limit: 50 + }); + }, + isAdmin : function(){ + return this.attr('hub') && this.attr('view') === 'admin'; + } +}); diff --git a/new-app/models/filter.js b/new-app/models/filter.js new file mode 100644 index 0000000..3c24d08 --- /dev/null +++ b/new-app/models/filter.js @@ -0,0 +1,91 @@ +import can from "can"; +import NatlangQuery from "./natlang-query"; +import "can/map/define/"; +import "can/construct/super/"; + +var ModerationRuleset = can.Model.extend({ + resource : "/api/v3/filters", + destroy : function(id, data){ + return $.ajax({ + url : "/api/v3/filters/" + id + "?embed_id=" + data.filter.embed_id, + type : "DELETE" + }); + } +}, { + define : { + natlang_queries: { + Value : NatlangQuery.List, + set : function(val){ + return new NatlangQuery.List(can.map(val, function(v){ + return NatlangQuery.model(v); + })); + } + }, + }, + addQuery : function(){ + this.natlang_queries.push(new NatlangQuery()); + }, + removeQuery : function(filter){ + var natlang = this.attr('natlang_queries'); + var index = natlang.indexOf(filter); + if(index > -1){ + natlang.splice(index, 1); + } + }, + serialize : function(){ + var data = this._super.apply(this, arguments); + return { + filter: data + }; + }, + markToDestroy : function(){ + this.attr('__shouldDelete', true); + }, + saveOrDestroy : function(){ + if(this.attr('__shouldDelete')){ + return this.destroy(); + } + return this.save(); + } +}); + +ModerationRuleset.List = ModerationRuleset.List.extend({ + blocking : function(){ + return this.filtersByAction('block'); + }, + approving : function(){ + return this.filtersByAction('approve'); + }, + filtersByAction : function(action){ + var list = new this.constructor(); + var length = this.attr('length'); + var current; + for(var i = 0; i < length; i++){ + current = this.attr(i); + if(current.attr('action') === action){ + list.push(current); + } + } + list.attr('action', action); + return list; + }, + addFilter : function(embedId){ + var filter = new ModerationRuleset({action: this.attr('action'), embed_id: embedId}); + filter.addQuery(); + this.push(filter); + }, + removeFilter : function(filter){ + var index = this.indexOf(filter); + + if(index > -1){ + this.splice(index, 1); + } + }, + saveOrDestroy : function(){ + return $.when.apply($, can.map(this, function(f){ + f.saveOrDestroy(); + })); + } +}); + +export default ModerationRuleset; diff --git a/new-app/models/hub.js b/new-app/models/hub.js new file mode 100644 index 0000000..f58241f --- /dev/null +++ b/new-app/models/hub.js @@ -0,0 +1,48 @@ +import can from "can"; +import ServiceModel from './service'; +import 'can/list/promise/'; +import 'can/construct/super/'; +import 'can/map/backup/'; +import 'can/map/define/'; + +var Bit = can.Model.extend({ + resource : '/api/v3/embeds', +}, { + define : { + services : { + get : function(){ + return new ServiceModel.List({embed_id: this.attr('id')}); + } + } + }, + serialize : function(){ + return { + embed : this._super.apply(this, arguments) + }; + }, + moderate : function(){ + return $.ajax({ + type : 'POST', + url : '/api/v3/embeds/' + this.attr('id') + '/moderate' + }); + }, + publish : function(){ + return $.ajax({ + type: 'PUT', + url: '/api/v3/embeds/' + this.attr('id') + '/publish' + }).then(function(data){ + Bit.model(data); + }); + }, + unpublish : function(){ + return $.ajax({ + type: 'PUT', + url: '/api/v3/embeds/' + this.attr('id') + '/unpublish' + }).then(function(data){ + Bit.model(data); + }); + } + +}); + +export default Bit; diff --git a/new-app/models/identity.js b/new-app/models/identity.js new file mode 100644 index 0000000..e9932cf --- /dev/null +++ b/new-app/models/identity.js @@ -0,0 +1,20 @@ +import can from "can"; +import "can/list/promise/"; + +var identities; + +export default can.Model.extend({ + resource : '/api/v3/identities', + getAll : function(){ + return this.reloadAll(); + }, + reloadAll : function(){ + var def = new this.List({}); + + def.then(function(data){ + identities = data; + }); + + return def; + } +}, {}); diff --git a/new-app/models/interaction_event.js b/new-app/models/interaction_event.js new file mode 100644 index 0000000..a015e95 --- /dev/null +++ b/new-app/models/interaction_event.js @@ -0,0 +1,127 @@ +import can from "can"; +import moment from "moment"; +import "can/construct/super/"; + +var wrapCreate = function(data){ + return { + interaction: data + }; +}; + +var InteractionEvent = can.Model.extend({ + create : 'POST /api/v3/interactions', + findAll : 'GET /api/v3/interactions', + + createScrollInteraction : function(tenant_name, hubId){ + return this.create(wrapCreate({ + tenant_name: tenant_name, + primary_source_id: hubId, + primary_source_type: 'Embed', + event_type: 'scroll' + })); + }, + createLinkClickedInteraction : function(tenant_name, hubId, entityId){ + return this.create(wrapCreate({ + tenant_name: tenant_name, + primary_source_id: hubId, + primary_source_type: 'Embed', + secondary_source_id: entityId, + secondary_source_type: 'Entity', + event_type: 'link' + })); + }, + createEntitySharedInteraction : function(tenant_name, hubId, entityId, target){ + return this.create(wrapCreate({ + tenant_name: tenant_name, + primary_source_id: hubId, + primary_source_type: 'Embed', + secondary_source_id: entityId, + secondary_source_type: 'Entity', + event_type: 'share', + event_subtype: target + })); + } +}, {}); + +var fillZeroes = function(data, length){ + while(data.length < length){ + data.unshift(0); + } + return data; +}; + +InteractionEvent.List = InteractionEvent.List.extend({ + totalShareInteractionsGraphData: function(){ + var length = this.attr('length'); + var labels = []; + var data = []; + var i; + for(i = 0; i < length; i++){ + labels.push(moment(this.attr(i + '.created_at')).fromNow()); + data.push(this.attr(i + '.volume')); + } + + return { + datasets: [{ + data: data, + label: "Share count", + strokeColor: '#f30', + fillColor: '#fff' + }], + labels: labels + }; + }, + linkInteractionsGraphData : function(){ + return this.totalShareInteractionsGraphData(); + }, + scrollInteractionsGraphData : function(){ + return this.totalShareInteractionsGraphData(); + }, + perNetworkShareInteractionsGraphData : function(){ + var length = this.attr('length'); + var labels = {}; + var data = {}; + var longestLabels = []; + var datasets = []; + var i, k, current, currentSubtype; + + for(i = 0; i < length; i++){ + current = this.attr(i); + currentSubtype = current.attr('event_subtype'); + if(!data[currentSubtype]){ + data[currentSubtype] = []; + } + if(!labels[currentSubtype]){ + labels[currentSubtype] = []; + } + data[currentSubtype].push(current.attr('volume')); + labels[currentSubtype].push(moment(current.attr('created_at')).fromNow()); + } + + for(k in labels){ + if(labels[k].length > longestLabels.length){ + longestLabels = labels[k]; + } + } + + for(k in data){ + if(data[k].length < longestLabels.length){ + data[k] = fillZeroes(data[k], longestLabels.length); + } + datasets.push({ + label: k, + data: data[k], + strokeColor: '#f30', + fillColor: 'rgba(255,255,255,0)' + }); + } + + return { + labels: longestLabels, + datasets: datasets + }; + + } +}); + +export default InteractionEvent; diff --git a/new-app/models/models.js b/new-app/models/models.js new file mode 100644 index 0000000..9294c5e --- /dev/null +++ b/new-app/models/models.js @@ -0,0 +1,27 @@ +import Hub from './hub'; +import Service from './service'; +import Bit from './bit'; +import Identity from './identity'; +import Suggestion from './suggestion'; +import Brand from './brand'; +import Preset from './preset'; +import Analytics from './analytics'; +import Subscription from './subscription'; +import Filter from './filter'; +import Account from './account'; +import Organization from "./organization"; + +export default { + Hub : Hub, + Service : Service, + Bit : Bit, + Identity : Identity, + Suggestion : Suggestion, + Brand : Brand, + Preset: Preset, + Analytics : Analytics, + Subscription : Subscription, + Filter : Filter, + Account : Account, + Organization: Organization +}; diff --git a/new-app/models/natlang-query.js b/new-app/models/natlang-query.js new file mode 100644 index 0000000..db459d8 --- /dev/null +++ b/new-app/models/natlang-query.js @@ -0,0 +1,36 @@ +import can from "can"; +import "can/map/define/"; + +export default can.Model.extend({}, { + define : { + operation : { + set : function(val){ + var typeAndOp = val.split(":"); + var type = typeAndOp.shift(); + var op = typeAndOp.shift(); + + this.attr({ + is_negated: (type !== 'pos'), + op : op + }); + }, + get : function(){ + var type = this.attr('is_negated') ? 'neg' : 'pos'; + var op = this.attr('op'); + return [type, op].join(':'); + } + }, + attr_name : { + value : 'content' + }, + op : { + value : 'contains_all', + set : function(val){ + return val; + } + }, + is_negated : { + value : false + } + } +}); diff --git a/new-app/models/organization.js b/new-app/models/organization.js new file mode 100644 index 0000000..4a89c30 --- /dev/null +++ b/new-app/models/organization.js @@ -0,0 +1,35 @@ +import can from "can"; + +export default can.Model.extend({ + findOne : '/api/v3/current/organization', + update: 'PUT /api/v3/current/organization', + current : function(){ + return this.findOne({}); + }, + choose : function(id){ + return $.ajax({ + url: '/api/v3/current/organization/choose?id=' + id, + type: 'PUT' + }); + } +}, { + invite : function(email){ + var def = can.Deferred(); + $.post('/api/v3/current/organization/accounts', {account: {email: email}}).then(function(res){ + def.resolve(res.account); + }, function(){ + $.post('/accounts/invitation', {account: {email: email}}).then(function(res){ + def.resolve(res); + }, function(){ + def.reject(); + }); + }); + return def; + }, + addInvitation: function(invitation){ + if(!this.attr('invitations')){ + this.attr('invitations', []); + } + this.attr('invitations').push(invitation); + } +}); diff --git a/new-app/models/preset.js b/new-app/models/preset.js new file mode 100644 index 0000000..b2bf932 --- /dev/null +++ b/new-app/models/preset.js @@ -0,0 +1,82 @@ +/* globals EMBED_ENDPOINT:true */ + +import can from "can"; + +import 'can/construct/super/'; +import 'can/map/define/'; +import 'can/list/promise/'; +import 'can/map/backup/'; + +var EMBED_TEMPLATE = '{hubName} Embed'; + +var Preset = can.Model.extend({ + resource: '/api/v3/presets', +}, { + define : { + config : { + value : function(){ + return { + theme: 'light', + view: 'public' + }; + } + } + }, + embedAttrs : function(tenantName, hubId){ + return can.extend({ + hubId: hubId, + tenant: tenantName + }, this.serialize().preset.config || {}); + }, + url : function(tenantName, hubId){ + var attrs = this.embedAttrs(tenantName, hubId); + return '/embed?' + can.param(attrs); + }, + fullUrl : function(tenantName, hubId){ + return can.sub("http://{embedEndpoint}{embedUrl}", { + embedEndpoint: EMBED_ENDPOINT, + embedUrl: this.url(tenantName, hubId) + }); + }, + embedCode : function(tenantName, hubId, hubName){ + return can.sub(EMBED_TEMPLATE, { + embedEndpoint : EMBED_ENDPOINT, + embedUrl: this.url(tenantName, hubId), + hubName: hubName + }); + }, + serialize : function(){ + var data = this._super.apply(this, arguments); + if(!data.config){ + data.config = {}; + } + if(!data.config.view){ + data.config.view = 'public'; + } + if(!data.config.live){ + delete data.config.live; + } + + return { + preset: data + }; + } +}); + +Preset.ADMIN = new Preset({ + config: { + live: true, + view: 'admin', + order: 'grouped-by-date', + filter: 'all' + } +}); + +Preset.PREVIEW = new Preset({ + name : 'Default Preset', + config: { + live: false + } +}); + +export default Preset; diff --git a/new-app/models/service.js b/new-app/models/service.js new file mode 100644 index 0000000..ba36000 --- /dev/null +++ b/new-app/models/service.js @@ -0,0 +1,350 @@ +import can from "can"; +import _keys from "lodash-amd/modern/object/keys"; + +import 'can/list/promise/'; +import 'can/map/define/'; +import 'can/construct/super/'; + +var RELOAD_TIMEOUTS = {}; + +var isCelluloidError = function(klass){ + return (/celluloid/).test(klass.toLowerCase()); +}; + +var isConfigError = function(klass){ + return (/configerror/).test(klass.toLowerCase()); +}; + +var getErrorMessage = (function(){ + var MESSAGES = { + autherror: "We are unable to authorize with your service credentials. Are you sure you have rights to access this content?", + remoteerror: "Service is currently unavailable. We will try to load data again later.", + unknownerror: "We are so sorry. Unknown error occured when we tried to load data from this service. We have been notified about this error, and we'll try to fix it as soon as possible.", + ratelimiterror: "Due to number of services authorized with the same account we are unable to load data from this service at the moment. We will try again soon." + }; + return function(error){ + var klass = error.klass.toLowerCase(); + return MESSAGES[klass] || error.message; + }; +})(); + + +var convertHexToRgb = function(hex){ + var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + var r, g, b; + if(result){ + r = parseInt(result[1], 16); + g = parseInt(result[2], 16); + b = parseInt(result[3], 16); + var res = 'rgb(' + r + ',' + g + ',' + b + ')'; + return res; + } + return 'rgb(0,0,0)'; +}; + +var GRAPH_COLORS = { + disqus : convertHexToRgb('#ffe842'), + facebook : convertHexToRgb('#80a2bd'), + foursquare : convertHexToRgb('#655557'), + github : convertHexToRgb('#191749'), + instagram : convertHexToRgb('#450d0b'), + meetup : convertHexToRgb('#062233'), + rss : convertHexToRgb('#183a37'), + stackexchange : convertHexToRgb('#95b26e'), + tumblr : convertHexToRgb('#c44900'), + twitter : convertHexToRgb('#432534'), + youtube : convertHexToRgb('#432834') +}; + + +var TYPES = { + disqus : { + forum : 'Forum' + }, + facebook : { + page : 'Page', + public_page : 'Public Page' + }, + foursquare : { + venue : 'Venue' + }, + github : { + org : 'Organization', + repo : 'Repository' + }, + instagram : { + tag : 'Tag', + // location : 'Location', + // geography : 'Geography', + user : 'User' + }, + meetup : { + group : 'Group' + }, + rss : { + site : 'URL' + }, + stackexchange : { + tags : 'Tags' + }, + tumblr : { + blog : 'Blog', + tag : 'Tag' + }, + twitter : { + followers : 'Followers', + hashtag : 'Hashtag', + term : 'Search', + user_timeline : 'User Timeline', + user_retweets: 'User Retweets', + favorites: 'User Favorites' + }, + youtube : { + channel : "Channel", + playlist: "Playlist"/*, + user : "User"*/ + } +}; + +var FEEDS = { + disqus : 'Disqus', + facebook : 'Facebook', + foursquare : 'Foursquare', + github : 'GitHub', + instagram : 'Instagram', + meetup : 'Meetup', + rss : 'RSS', + stackexchange : 'StackExchange', + tumblr : 'Tumblr', + twitter : 'Twitter', + youtube : 'YouTube' +}; + +var NEEDS_OAUTH = { + github : { + types : ['repo', 'org'] + }, + twitter : { + types : ['followers', 'hashtag', 'user_timeline', 'term', 'favorites', 'user_retweets'] + }, + meetup : { + types : ['group'] + }, + facebook : { + types : ['page'] + }, + foursquare : { + types : ['venue'] + }, + disqus : { + types: ['forum'] + }, + instagram : { + types: ['tag', 'user'] + }, + youtube : { + types: ['channel', 'playlist', 'user'] + } +}; + +var formatKey = function(key){ + if(key === 'url'){ + return 'URL'; + } + return can.capitalize(key.replace(/_/g, ' ')); +}; + +var formatConfig = function(config){ + var res = ['
    ']; + for(var k in config){ + res.push('
  • ' + formatKey(k) + ': '); + if(can.isPlainObject(config[k])){ + res.push(formatConfig(config[k])); + } else { + res.push(config[k]); + } + res.push('
  • '); + } + res.push('
'); + return res.join(''); +}; + +var emptyConfigForService = function(feed){ + var config = {}; + + if(feed === 'github'){ + config.tracking = {}; + } + + if(feed === 'stackexchange'){ + config.tags = []; + } + return config; +}; + +var Service = can.Model.extend({ + resource : '/api/v3/services', + feeds : FEEDS, + needsOAuth : NEEDS_OAUTH, + createEmptyService : function(feed){ + + return new this({ + feed_name : feed, + config: emptyConfigForService(feed) + }); + }, + errored : function(service){ + can.trigger(this, 'errored', [this]); + }, + messageFromLiveService : function( msg ) { + var cb = can.noop, + timeout = 1, + self = this, + timeoutKey; + + if(typeof msg === 'string'){ + msg = JSON.parse(msg); + } + + timeoutKey = msg.service.id; + + if(msg.service.empty_results){ + timeoutKey = msg.service.id + '-noResults'; + cb = function(service){ + if(service.attr('entity_count') === 0){ + service.hasNoResults(); + } + }; + timeout = 2000; + } + + clearTimeout(RELOAD_TIMEOUTS[timeoutKey]); + + RELOAD_TIMEOUTS[timeoutKey] = setTimeout(function(){ + self.findOne({id: msg.service.id}).then(cb); + }, timeout); + } +}, { + define : { + feed_name : { + set : function(val){ + var keys = _keys(TYPES[val]); + + this.attr('type_name', keys.length === 1 ? keys[0] : ""); + this.attr('graphColor', GRAPH_COLORS[val]); + + return val; + } + }, + type_name : { + set : function(val){ + this.attr('config', emptyConfigForService(this.attr('feed_name'))); + return val; + } + }, + error : { + set : function(val){ + var klass = val && val.klass; + if(klass && isCelluloidError(klass)){ + return; + } + return val; + } + }, + approved_by_default : { + set : function(val){ + return !!val; + } + } + }, + serialize : function(){ + var data = this._super.apply(this, arguments); + + if(!(data.feed_name === 'instagram' && data.type_name === 'user') && !(data.feed_name === 'facebook' && data.type_name === 'public_page')){ + if(data.config){ + delete data.config.display_name; + } + } + + return { + service : data + }; + }, + typesForFeed : function(){ + var currentFeed = this.attr('feed_name'), + types = TYPES[currentFeed]; + + return types; + }, + hasMultipleTypes : function(){ + var typesForFeed = this.typesForFeed(); + return _keys(typesForFeed || {}).length > 1; + }, + printFeed : function() { + return FEEDS[ this.attr('feed_name') ]; + }, + printType : function() { + return TYPES[ this.attr('feed_name') ][ this.attr('type_name') ]; + }, + printConfig: function() { + var output = [], + config = this.attr('config'); + + config = config ? config.attr() : config; + + if(!config){ + return; + } + + for( var key in config ) { + output.push(key + ': ' + config[key]); + } + + // remove last ', ' + return output.join('
'); + }, + hasNoResults : function(){ + can.batch.start(); + if(this.attr('_isNewlyCreated')){ + this.attr('noResults', true); + } + this.attr({ + error: null + }); + can.batch.stop(); + }, + clearNoResults : function(){ + this.removeAttr('noResults'); + }, + save : function(){ + this.removeAttr('noResults'); + can.trigger(this.constructor, 'saving', [this]); + return this._super.apply(this, arguments); + }, + formattedConfig : function(){ + return formatConfig(this.attr('config').attr()); + }, + formattedError : function(){ + return getErrorMessage(this.attr('error')); + }, + formattedErrorClass : function(){ + var klass = this.attr('error.klass'); + return !isConfigError(klass) ? '' : 'Configuration Error'; + }, + clearErrors : function(){ + this.removeAttr('error'); + }, + isLoading : function(){ + return this.attr('state') === 'loading'; + } +}); + +Service.on('created', function(ev, service){ + service.attr('_isNewlyCreated', true); +}); + +Service.on('updated', function(ev, service){ + service.attr('_isNewlyCreated', true); +}); + +export default Service; diff --git a/new-app/models/subscription.js b/new-app/models/subscription.js new file mode 100644 index 0000000..d78d39a --- /dev/null +++ b/new-app/models/subscription.js @@ -0,0 +1,36 @@ +import can from "can"; + +export default can.Model.extend({ + findOne: '/api/v3/subscriptions/current' +}, { + reload : function(){ + this.constructor.findOne({}); + }, + canAddHub : function(hubs){ + return true; + /*var currentLength = hubs.attr('length'); + var limit = this.attr('plan.limits.embeds_per_brand') || Infinity; + return currentLength < limit;*/ + }, + canAddService : function(services, feed, type){ + return true; + /*var currentLength = services.attr('length'); + var limit = this.attr('plan.limits.services_per_embed') || Infinity; + var currentTypeFeed = [feed, type].join('_'); + var limitCurrentTypeFeed = this.attr('plan.limits').attr(currentTypeFeed) || Infinity; + var servicesWithCurrentTypeFeed = services.filter(function(s){ + return s.attr('feed_name') === feed && s.attr('type_name') === type; + }); + + if(currentLength >= limit){ + return false; + } + if(servicesWithCurrentTypeFeed.attr('length') >= limitCurrentTypeFeed){ + return false; + } + return true;*/ + }, + hasCC : function(){ + return !!this.attr('card'); + } +}); diff --git a/new-app/models/suggestion.js b/new-app/models/suggestion.js new file mode 100644 index 0000000..7e55794 --- /dev/null +++ b/new-app/models/suggestion.js @@ -0,0 +1,4 @@ +import can from "can"; +export default can.Model.extend({ + findAll : '/api/v3/services/suggestions/{service}?brand_identity_id={brandIdentityId}' +}, {}); diff --git a/new-app/package.json b/new-app/package.json new file mode 100644 index 0000000..d8fb6c7 --- /dev/null +++ b/new-app/package.json @@ -0,0 +1,26 @@ +{ + "name": "bithub", + "version": "0.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", + "dependencies": { + "jquery": "^2.1.4", + "can": "^2.3.0-pre.9", + "steal": "^0.12.0-pre.1", + "bootstrap": "^3.3.5", + "steal-tools": "^0.12.0-pre.1", + "lodash-amd": "^3.10.1", + "bit-tabs": "^0.1.3", + "moment": "^2.10.6", + "selectize": "^0.12.1", + "bithub-embed": "bithubapp/bithub-embed#stealable", + "done-component": "^0.2.0", + "iframe-resizer": "^3.3.3", + "jquery.payment": "^1.3.0" + } +} diff --git a/new-app/style/style.less b/new-app/style/style.less new file mode 100644 index 0000000..6f8a638 --- /dev/null +++ b/new-app/style/style.less @@ -0,0 +1,3 @@ +body { + background: #f2f3f5; +} diff --git a/new-bithub-client/.gitignore b/new-bithub-client/.gitignore new file mode 100755 index 0000000..94b6f75 --- /dev/null +++ b/new-bithub-client/.gitignore @@ -0,0 +1,31 @@ +# Logs +logs +*.log +npm-debug.log* + +# Runtime data +pids +*.pid +*.seed + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directory +# https://docs.npmjs.com/misc/faq#should-i-check-my-node-modules-folder-into-git +node_modules + +# DoneJS +docs \ No newline at end of file diff --git a/new-bithub-client/.yo-rc.json b/new-bithub-client/.yo-rc.json new file mode 100755 index 0000000..690bd0b --- /dev/null +++ b/new-bithub-client/.yo-rc.json @@ -0,0 +1,6 @@ +{ + "generator-donejs": { + "folder": "src", + "name": "bithub-client" + } +} \ No newline at end of file diff --git a/new-bithub-client/build.js b/new-bithub-client/build.js new file mode 100755 index 0000000..d184ad9 --- /dev/null +++ b/new-bithub-client/build.js @@ -0,0 +1,7 @@ +var stealTools = require("steal-tools"); + +var buildPromise = stealTools.build({ + config: __dirname + "/package.json!npm" +}, { + bundleAssets: true +}); diff --git a/new-bithub-client/development.html b/new-bithub-client/development.html new file mode 100755 index 0000000..e32dbc8 --- /dev/null +++ b/new-bithub-client/development.html @@ -0,0 +1,9 @@ + + + + bithub-client + + + + + \ No newline at end of file diff --git a/new-bithub-client/documentjs.json b/new-bithub-client/documentjs.json new file mode 100755 index 0000000..a9bc8c0 --- /dev/null +++ b/new-bithub-client/documentjs.json @@ -0,0 +1,14 @@ +{ + "sites": { + "docs": { + "dest": "docs", + "parent": "bithub-client", + "pageConfig": { + "page": "docs" + }, + "glob": { + "pattern": "src/**/*.{js,md}" + } + } + } +} \ No newline at end of file diff --git a/new-bithub-client/images/app-resources-icons-gear-grey.svg b/new-bithub-client/images/app-resources-icons-gear-grey.svg new file mode 100755 index 0000000..f252e85 --- /dev/null +++ b/new-bithub-client/images/app-resources-icons-gear-grey.svg @@ -0,0 +1,51 @@ + + + + + + + + + + +]> + + + + + + + + + + + + diff --git a/new-bithub-client/images/app-resources-icons-gear-white.svg b/new-bithub-client/images/app-resources-icons-gear-white.svg new file mode 100755 index 0000000..05550a9 --- /dev/null +++ b/new-bithub-client/images/app-resources-icons-gear-white.svg @@ -0,0 +1,51 @@ + + + + + + + + + + +]> + + + + + + + + + + + + diff --git a/new-bithub-client/images/app-resources-icons-inbox-grey.svg b/new-bithub-client/images/app-resources-icons-inbox-grey.svg new file mode 100755 index 0000000..96234b8 --- /dev/null +++ b/new-bithub-client/images/app-resources-icons-inbox-grey.svg @@ -0,0 +1,39 @@ + + + + + + + + + + +]> + + + + + + + + + + + + + + + diff --git a/new-bithub-client/images/app-resources-icons-inbox-white.svg b/new-bithub-client/images/app-resources-icons-inbox-white.svg new file mode 100755 index 0000000..f0f3a45 --- /dev/null +++ b/new-bithub-client/images/app-resources-icons-inbox-white.svg @@ -0,0 +1,39 @@ + + + + + + + + + + +]> + + + + + + + + + + + + + + + diff --git a/new-bithub-client/images/app-resources-icons-menu-white.svg b/new-bithub-client/images/app-resources-icons-menu-white.svg new file mode 100755 index 0000000..2215e72 --- /dev/null +++ b/new-bithub-client/images/app-resources-icons-menu-white.svg @@ -0,0 +1,33 @@ + + + + + + + + + + +]> + + + + + + + + + + + + + + diff --git a/new-bithub-client/images/app-resources-icons-plus-blue.svg b/new-bithub-client/images/app-resources-icons-plus-blue.svg new file mode 100755 index 0000000..7e61b15 --- /dev/null +++ b/new-bithub-client/images/app-resources-icons-plus-blue.svg @@ -0,0 +1,34 @@ + + + + + + + + + + +]> + + + + + + + + + + + + diff --git a/new-bithub-client/images/app-resources-icons-plus-white.svg b/new-bithub-client/images/app-resources-icons-plus-white.svg new file mode 100755 index 0000000..5083bdf --- /dev/null +++ b/new-bithub-client/images/app-resources-icons-plus-white.svg @@ -0,0 +1,34 @@ + + + + + + + + + + +]> + + + + + + + + + + + + diff --git a/new-bithub-client/images/app-resources-icons-star-grey.svg b/new-bithub-client/images/app-resources-icons-star-grey.svg new file mode 100755 index 0000000..6693538 --- /dev/null +++ b/new-bithub-client/images/app-resources-icons-star-grey.svg @@ -0,0 +1,32 @@ + + + + + + + + + + +]> + + + + + + + + + + diff --git a/new-bithub-client/images/app-resources-icons-star-white.svg b/new-bithub-client/images/app-resources-icons-star-white.svg new file mode 100755 index 0000000..2779be5 --- /dev/null +++ b/new-bithub-client/images/app-resources-icons-star-white.svg @@ -0,0 +1,32 @@ + + + + + + + + + + +]> + + + + + + + + + + diff --git a/new-bithub-client/images/app-resources-icons-switch-grey.svg b/new-bithub-client/images/app-resources-icons-switch-grey.svg new file mode 100755 index 0000000..aa75a70 --- /dev/null +++ b/new-bithub-client/images/app-resources-icons-switch-grey.svg @@ -0,0 +1,34 @@ + + + + + + + + + + +]> + + + + + + + + + + + + + + + diff --git a/new-bithub-client/images/app-resources-icons-switch-white.svg b/new-bithub-client/images/app-resources-icons-switch-white.svg new file mode 100755 index 0000000..819a8f1 --- /dev/null +++ b/new-bithub-client/images/app-resources-icons-switch-white.svg @@ -0,0 +1,34 @@ + + + + + + + + + + +]> + + + + + + + + + + + + + + + diff --git a/new-bithub-client/images/app-resources-icons-thumbs-up-grey.svg b/new-bithub-client/images/app-resources-icons-thumbs-up-grey.svg new file mode 100755 index 0000000..ed182f5 --- /dev/null +++ b/new-bithub-client/images/app-resources-icons-thumbs-up-grey.svg @@ -0,0 +1,35 @@ + + + + + + + + + + +]> + + + + + + + + + + + + diff --git a/new-bithub-client/images/app-resources-icons-thumbs-up-white.svg b/new-bithub-client/images/app-resources-icons-thumbs-up-white.svg new file mode 100755 index 0000000..15446d9 --- /dev/null +++ b/new-bithub-client/images/app-resources-icons-thumbs-up-white.svg @@ -0,0 +1,35 @@ + + + + + + + + + + +]> + + + + + + + + + + + + diff --git a/new-bithub-client/images/app-resources-icons-trash-grey.svg b/new-bithub-client/images/app-resources-icons-trash-grey.svg new file mode 100755 index 0000000..b057a46 --- /dev/null +++ b/new-bithub-client/images/app-resources-icons-trash-grey.svg @@ -0,0 +1,36 @@ + + + + + + + + + + +]> + + + + + + + + + + + + + + + diff --git a/new-bithub-client/images/app-resources-icons-trash-white.svg b/new-bithub-client/images/app-resources-icons-trash-white.svg new file mode 100755 index 0000000..efed7be --- /dev/null +++ b/new-bithub-client/images/app-resources-icons-trash-white.svg @@ -0,0 +1,36 @@ + + + + + + + + + + +]> + + + + + + + + + + + + + + + diff --git a/new-bithub-client/images/app-resources-icons-x-red.svg b/new-bithub-client/images/app-resources-icons-x-red.svg new file mode 100755 index 0000000..294d568 --- /dev/null +++ b/new-bithub-client/images/app-resources-icons-x-red.svg @@ -0,0 +1,35 @@ + + + + + + + + + + +]> + + + + + + + + + + + + diff --git a/new-bithub-client/images/app-resources-icons-x-white.svg b/new-bithub-client/images/app-resources-icons-x-white.svg new file mode 100755 index 0000000..9238d07 --- /dev/null +++ b/new-bithub-client/images/app-resources-icons-x-white.svg @@ -0,0 +1,35 @@ + + + + + + + + + + +]> + + + + + + + + + + + + diff --git a/new-bithub-client/images/social-empty/500px.png b/new-bithub-client/images/social-empty/500px.png new file mode 100644 index 0000000..73266dd Binary files /dev/null and b/new-bithub-client/images/social-empty/500px.png differ diff --git a/new-bithub-client/images/social-empty/android.png b/new-bithub-client/images/social-empty/android.png new file mode 100644 index 0000000..4979a10 Binary files /dev/null and b/new-bithub-client/images/social-empty/android.png differ diff --git a/new-bithub-client/images/social-empty/apple.png b/new-bithub-client/images/social-empty/apple.png new file mode 100644 index 0000000..1e4e54f Binary files /dev/null and b/new-bithub-client/images/social-empty/apple.png differ diff --git a/new-bithub-client/images/social-empty/appnet.png b/new-bithub-client/images/social-empty/appnet.png new file mode 100644 index 0000000..ec789ed Binary files /dev/null and b/new-bithub-client/images/social-empty/appnet.png differ diff --git a/new-bithub-client/images/social-empty/bebo.png b/new-bithub-client/images/social-empty/bebo.png new file mode 100644 index 0000000..3bbdb61 Binary files /dev/null and b/new-bithub-client/images/social-empty/bebo.png differ diff --git a/new-bithub-client/images/social-empty/behance.png b/new-bithub-client/images/social-empty/behance.png new file mode 100644 index 0000000..e54849f Binary files /dev/null and b/new-bithub-client/images/social-empty/behance.png differ diff --git a/new-bithub-client/images/social-empty/blogger.png b/new-bithub-client/images/social-empty/blogger.png new file mode 100644 index 0000000..76b4379 Binary files /dev/null and b/new-bithub-client/images/social-empty/blogger.png differ diff --git a/new-bithub-client/images/social-empty/buffer.png b/new-bithub-client/images/social-empty/buffer.png new file mode 100644 index 0000000..59e452b Binary files /dev/null and b/new-bithub-client/images/social-empty/buffer.png differ diff --git a/new-bithub-client/images/social-empty/chimein.png b/new-bithub-client/images/social-empty/chimein.png new file mode 100644 index 0000000..f9ee78a Binary files /dev/null and b/new-bithub-client/images/social-empty/chimein.png differ diff --git a/new-bithub-client/images/social-empty/coderwall.png b/new-bithub-client/images/social-empty/coderwall.png new file mode 100644 index 0000000..963ee86 Binary files /dev/null and b/new-bithub-client/images/social-empty/coderwall.png differ diff --git a/new-bithub-client/images/social-empty/dailymotion.png b/new-bithub-client/images/social-empty/dailymotion.png new file mode 100644 index 0000000..e878939 Binary files /dev/null and b/new-bithub-client/images/social-empty/dailymotion.png differ diff --git a/new-bithub-client/images/social-empty/delicious.png b/new-bithub-client/images/social-empty/delicious.png new file mode 100644 index 0000000..edfc408 Binary files /dev/null and b/new-bithub-client/images/social-empty/delicious.png differ diff --git a/new-bithub-client/images/social-empty/deviantart.png b/new-bithub-client/images/social-empty/deviantart.png new file mode 100644 index 0000000..02d26dc Binary files /dev/null and b/new-bithub-client/images/social-empty/deviantart.png differ diff --git a/new-bithub-client/images/social-empty/digg.png b/new-bithub-client/images/social-empty/digg.png new file mode 100644 index 0000000..8266383 Binary files /dev/null and b/new-bithub-client/images/social-empty/digg.png differ diff --git a/new-bithub-client/images/social-empty/disqus.png b/new-bithub-client/images/social-empty/disqus.png new file mode 100644 index 0000000..db112ba Binary files /dev/null and b/new-bithub-client/images/social-empty/disqus.png differ diff --git a/new-bithub-client/images/social-empty/dribbble.png b/new-bithub-client/images/social-empty/dribbble.png new file mode 100644 index 0000000..b3f1102 Binary files /dev/null and b/new-bithub-client/images/social-empty/dribbble.png differ diff --git a/new-bithub-client/images/social-empty/drupal.png b/new-bithub-client/images/social-empty/drupal.png new file mode 100644 index 0000000..7263329 Binary files /dev/null and b/new-bithub-client/images/social-empty/drupal.png differ diff --git a/new-bithub-client/images/social-empty/envato.png b/new-bithub-client/images/social-empty/envato.png new file mode 100644 index 0000000..2bbde2b Binary files /dev/null and b/new-bithub-client/images/social-empty/envato.png differ diff --git a/new-bithub-client/images/social-empty/facebook.png b/new-bithub-client/images/social-empty/facebook.png new file mode 100644 index 0000000..b06ccb5 Binary files /dev/null and b/new-bithub-client/images/social-empty/facebook.png differ diff --git a/new-bithub-client/images/social-empty/feedburner.png b/new-bithub-client/images/social-empty/feedburner.png new file mode 100644 index 0000000..e57af06 Binary files /dev/null and b/new-bithub-client/images/social-empty/feedburner.png differ diff --git a/new-bithub-client/images/social-empty/flattr.png b/new-bithub-client/images/social-empty/flattr.png new file mode 100644 index 0000000..511f24d Binary files /dev/null and b/new-bithub-client/images/social-empty/flattr.png differ diff --git a/new-bithub-client/images/social-empty/flickr.png b/new-bithub-client/images/social-empty/flickr.png new file mode 100644 index 0000000..0cedf44 Binary files /dev/null and b/new-bithub-client/images/social-empty/flickr.png differ diff --git a/new-bithub-client/images/social-empty/forrst.png b/new-bithub-client/images/social-empty/forrst.png new file mode 100644 index 0000000..72bda7f Binary files /dev/null and b/new-bithub-client/images/social-empty/forrst.png differ diff --git a/new-bithub-client/images/social-empty/foursquare.png b/new-bithub-client/images/social-empty/foursquare.png new file mode 100644 index 0000000..7802c6b Binary files /dev/null and b/new-bithub-client/images/social-empty/foursquare.png differ diff --git a/new-bithub-client/images/social-empty/friendfeed.png b/new-bithub-client/images/social-empty/friendfeed.png new file mode 100644 index 0000000..0daaaa9 Binary files /dev/null and b/new-bithub-client/images/social-empty/friendfeed.png differ diff --git a/new-bithub-client/images/social-empty/github.png b/new-bithub-client/images/social-empty/github.png new file mode 100644 index 0000000..4f33508 Binary files /dev/null and b/new-bithub-client/images/social-empty/github.png differ diff --git a/new-bithub-client/images/social-empty/goodreads.png b/new-bithub-client/images/social-empty/goodreads.png new file mode 100644 index 0000000..9aa233f Binary files /dev/null and b/new-bithub-client/images/social-empty/goodreads.png differ diff --git a/new-bithub-client/images/social-empty/google.png b/new-bithub-client/images/social-empty/google.png new file mode 100644 index 0000000..5ef8afd Binary files /dev/null and b/new-bithub-client/images/social-empty/google.png differ diff --git a/new-bithub-client/images/social-empty/grooveshark.png b/new-bithub-client/images/social-empty/grooveshark.png new file mode 100644 index 0000000..acdcd69 Binary files /dev/null and b/new-bithub-client/images/social-empty/grooveshark.png differ diff --git a/new-bithub-client/images/social-empty/houzz.png b/new-bithub-client/images/social-empty/houzz.png new file mode 100644 index 0000000..5438183 Binary files /dev/null and b/new-bithub-client/images/social-empty/houzz.png differ diff --git a/new-bithub-client/images/social-empty/identica.png b/new-bithub-client/images/social-empty/identica.png new file mode 100644 index 0000000..3bfb3af Binary files /dev/null and b/new-bithub-client/images/social-empty/identica.png differ diff --git a/new-bithub-client/images/social-empty/instagram.png b/new-bithub-client/images/social-empty/instagram.png new file mode 100644 index 0000000..098d0e5 Binary files /dev/null and b/new-bithub-client/images/social-empty/instagram.png differ diff --git a/new-bithub-client/images/social-empty/lanyrd.png b/new-bithub-client/images/social-empty/lanyrd.png new file mode 100644 index 0000000..529e6d6 Binary files /dev/null and b/new-bithub-client/images/social-empty/lanyrd.png differ diff --git a/new-bithub-client/images/social-empty/lastfm.png b/new-bithub-client/images/social-empty/lastfm.png new file mode 100644 index 0000000..ac87052 Binary files /dev/null and b/new-bithub-client/images/social-empty/lastfm.png differ diff --git a/new-bithub-client/images/social-empty/linkedin.png b/new-bithub-client/images/social-empty/linkedin.png new file mode 100644 index 0000000..1879697 Binary files /dev/null and b/new-bithub-client/images/social-empty/linkedin.png differ diff --git a/new-bithub-client/images/social-empty/mail.png b/new-bithub-client/images/social-empty/mail.png new file mode 100644 index 0000000..ad02588 Binary files /dev/null and b/new-bithub-client/images/social-empty/mail.png differ diff --git a/new-bithub-client/images/social-empty/meetup.png b/new-bithub-client/images/social-empty/meetup.png new file mode 100644 index 0000000..7147566 Binary files /dev/null and b/new-bithub-client/images/social-empty/meetup.png differ diff --git a/new-bithub-client/images/social-empty/myspace.png b/new-bithub-client/images/social-empty/myspace.png new file mode 100644 index 0000000..a67eac7 Binary files /dev/null and b/new-bithub-client/images/social-empty/myspace.png differ diff --git a/new-bithub-client/images/social-empty/newsvine.png b/new-bithub-client/images/social-empty/newsvine.png new file mode 100644 index 0000000..2dec0c3 Binary files /dev/null and b/new-bithub-client/images/social-empty/newsvine.png differ diff --git a/new-bithub-client/images/social-empty/odnoklassniki.png b/new-bithub-client/images/social-empty/odnoklassniki.png new file mode 100644 index 0000000..cfdd6ce Binary files /dev/null and b/new-bithub-client/images/social-empty/odnoklassniki.png differ diff --git a/new-bithub-client/images/social-empty/outlook.png b/new-bithub-client/images/social-empty/outlook.png new file mode 100644 index 0000000..60967cc Binary files /dev/null and b/new-bithub-client/images/social-empty/outlook.png differ diff --git a/new-bithub-client/images/social-empty/patreon.png b/new-bithub-client/images/social-empty/patreon.png new file mode 100644 index 0000000..2e51a71 Binary files /dev/null and b/new-bithub-client/images/social-empty/patreon.png differ diff --git a/new-bithub-client/images/social-empty/paypal.png b/new-bithub-client/images/social-empty/paypal.png new file mode 100644 index 0000000..bf0d6cc Binary files /dev/null and b/new-bithub-client/images/social-empty/paypal.png differ diff --git a/new-bithub-client/images/social-empty/persona.png b/new-bithub-client/images/social-empty/persona.png new file mode 100644 index 0000000..a597f8d Binary files /dev/null and b/new-bithub-client/images/social-empty/persona.png differ diff --git a/new-bithub-client/images/social-empty/pinterest.png b/new-bithub-client/images/social-empty/pinterest.png new file mode 100644 index 0000000..151c944 Binary files /dev/null and b/new-bithub-client/images/social-empty/pinterest.png differ diff --git a/new-bithub-client/images/social-empty/play.png b/new-bithub-client/images/social-empty/play.png new file mode 100644 index 0000000..33453f2 Binary files /dev/null and b/new-bithub-client/images/social-empty/play.png differ diff --git a/new-bithub-client/images/social-empty/playstation.png b/new-bithub-client/images/social-empty/playstation.png new file mode 100644 index 0000000..e88bd9d Binary files /dev/null and b/new-bithub-client/images/social-empty/playstation.png differ diff --git a/new-bithub-client/images/social-empty/reddit.png b/new-bithub-client/images/social-empty/reddit.png new file mode 100644 index 0000000..1974382 Binary files /dev/null and b/new-bithub-client/images/social-empty/reddit.png differ diff --git a/new-bithub-client/images/social-empty/rss.png b/new-bithub-client/images/social-empty/rss.png new file mode 100644 index 0000000..cb04482 Binary files /dev/null and b/new-bithub-client/images/social-empty/rss.png differ diff --git a/new-bithub-client/images/social-empty/skype.png b/new-bithub-client/images/social-empty/skype.png new file mode 100644 index 0000000..c6103c4 Binary files /dev/null and b/new-bithub-client/images/social-empty/skype.png differ diff --git a/new-bithub-client/images/social-empty/slideshare.png b/new-bithub-client/images/social-empty/slideshare.png new file mode 100644 index 0000000..da943ed Binary files /dev/null and b/new-bithub-client/images/social-empty/slideshare.png differ diff --git a/new-bithub-client/images/social-empty/smugmug.png b/new-bithub-client/images/social-empty/smugmug.png new file mode 100644 index 0000000..5436075 Binary files /dev/null and b/new-bithub-client/images/social-empty/smugmug.png differ diff --git a/new-bithub-client/images/social-empty/soundcloud.png b/new-bithub-client/images/social-empty/soundcloud.png new file mode 100644 index 0000000..e02067f Binary files /dev/null and b/new-bithub-client/images/social-empty/soundcloud.png differ diff --git a/new-bithub-client/images/social-empty/spotify.png b/new-bithub-client/images/social-empty/spotify.png new file mode 100644 index 0000000..c798065 Binary files /dev/null and b/new-bithub-client/images/social-empty/spotify.png differ diff --git a/new-bithub-client/images/social-empty/stackexchange.png b/new-bithub-client/images/social-empty/stackexchange.png new file mode 100644 index 0000000..07c976e Binary files /dev/null and b/new-bithub-client/images/social-empty/stackexchange.png differ diff --git a/new-bithub-client/images/social-empty/steam.png b/new-bithub-client/images/social-empty/steam.png new file mode 100644 index 0000000..b485fc6 Binary files /dev/null and b/new-bithub-client/images/social-empty/steam.png differ diff --git a/new-bithub-client/images/social-empty/stumbleupon.png b/new-bithub-client/images/social-empty/stumbleupon.png new file mode 100644 index 0000000..0a0466e Binary files /dev/null and b/new-bithub-client/images/social-empty/stumbleupon.png differ diff --git a/new-bithub-client/images/social-empty/swarm.png b/new-bithub-client/images/social-empty/swarm.png new file mode 100644 index 0000000..1c260b0 Binary files /dev/null and b/new-bithub-client/images/social-empty/swarm.png differ diff --git a/new-bithub-client/images/social-empty/technorati.png b/new-bithub-client/images/social-empty/technorati.png new file mode 100644 index 0000000..becc826 Binary files /dev/null and b/new-bithub-client/images/social-empty/technorati.png differ diff --git a/new-bithub-client/images/social-empty/tripadvisor.png b/new-bithub-client/images/social-empty/tripadvisor.png new file mode 100644 index 0000000..dcdc86f Binary files /dev/null and b/new-bithub-client/images/social-empty/tripadvisor.png differ diff --git a/new-bithub-client/images/social-empty/tripit.png b/new-bithub-client/images/social-empty/tripit.png new file mode 100644 index 0000000..e7594e9 Binary files /dev/null and b/new-bithub-client/images/social-empty/tripit.png differ diff --git a/new-bithub-client/images/social-empty/triplej.png b/new-bithub-client/images/social-empty/triplej.png new file mode 100644 index 0000000..3730197 Binary files /dev/null and b/new-bithub-client/images/social-empty/triplej.png differ diff --git a/new-bithub-client/images/social-empty/tumblr.png b/new-bithub-client/images/social-empty/tumblr.png new file mode 100644 index 0000000..6c84612 Binary files /dev/null and b/new-bithub-client/images/social-empty/tumblr.png differ diff --git a/new-bithub-client/images/social-empty/twitter.png b/new-bithub-client/images/social-empty/twitter.png new file mode 100644 index 0000000..d363692 Binary files /dev/null and b/new-bithub-client/images/social-empty/twitter.png differ diff --git a/new-bithub-client/images/social-empty/viadeo.png b/new-bithub-client/images/social-empty/viadeo.png new file mode 100644 index 0000000..2eab032 Binary files /dev/null and b/new-bithub-client/images/social-empty/viadeo.png differ diff --git a/new-bithub-client/images/social-empty/vimeo.png b/new-bithub-client/images/social-empty/vimeo.png new file mode 100644 index 0000000..d028086 Binary files /dev/null and b/new-bithub-client/images/social-empty/vimeo.png differ diff --git a/new-bithub-client/images/social-empty/vine.png b/new-bithub-client/images/social-empty/vine.png new file mode 100644 index 0000000..79ebe0d Binary files /dev/null and b/new-bithub-client/images/social-empty/vine.png differ diff --git a/new-bithub-client/images/social-empty/vkontakte.png b/new-bithub-client/images/social-empty/vkontakte.png new file mode 100644 index 0000000..10159a4 Binary files /dev/null and b/new-bithub-client/images/social-empty/vkontakte.png differ diff --git a/new-bithub-client/images/social-empty/wikipedia.png b/new-bithub-client/images/social-empty/wikipedia.png new file mode 100644 index 0000000..7c90a19 Binary files /dev/null and b/new-bithub-client/images/social-empty/wikipedia.png differ diff --git a/new-bithub-client/images/social-empty/windows.png b/new-bithub-client/images/social-empty/windows.png new file mode 100644 index 0000000..354e785 Binary files /dev/null and b/new-bithub-client/images/social-empty/windows.png differ diff --git a/new-bithub-client/images/social-empty/wordpress.png b/new-bithub-client/images/social-empty/wordpress.png new file mode 100644 index 0000000..737a7cb Binary files /dev/null and b/new-bithub-client/images/social-empty/wordpress.png differ diff --git a/new-bithub-client/images/social-empty/xbox.png b/new-bithub-client/images/social-empty/xbox.png new file mode 100644 index 0000000..1768fd1 Binary files /dev/null and b/new-bithub-client/images/social-empty/xbox.png differ diff --git a/new-bithub-client/images/social-empty/xing.png b/new-bithub-client/images/social-empty/xing.png new file mode 100644 index 0000000..f364cff Binary files /dev/null and b/new-bithub-client/images/social-empty/xing.png differ diff --git a/new-bithub-client/images/social-empty/yahoo.png b/new-bithub-client/images/social-empty/yahoo.png new file mode 100644 index 0000000..376ee5f Binary files /dev/null and b/new-bithub-client/images/social-empty/yahoo.png differ diff --git a/new-bithub-client/images/social-empty/yammer.png b/new-bithub-client/images/social-empty/yammer.png new file mode 100644 index 0000000..60f3cdb Binary files /dev/null and b/new-bithub-client/images/social-empty/yammer.png differ diff --git a/new-bithub-client/images/social-empty/yelp.png b/new-bithub-client/images/social-empty/yelp.png new file mode 100644 index 0000000..23e3ad1 Binary files /dev/null and b/new-bithub-client/images/social-empty/yelp.png differ diff --git a/new-bithub-client/images/social-empty/youtube.png b/new-bithub-client/images/social-empty/youtube.png new file mode 100644 index 0000000..3f2cbaa Binary files /dev/null and b/new-bithub-client/images/social-empty/youtube.png differ diff --git a/new-bithub-client/images/social-empty/zerply.png b/new-bithub-client/images/social-empty/zerply.png new file mode 100644 index 0000000..43054f3 Binary files /dev/null and b/new-bithub-client/images/social-empty/zerply.png differ diff --git a/new-bithub-client/images/social-empty/zynga.png b/new-bithub-client/images/social-empty/zynga.png new file mode 100644 index 0000000..d80f6c3 Binary files /dev/null and b/new-bithub-client/images/social-empty/zynga.png differ diff --git a/new-bithub-client/images/social-grey/500px.png b/new-bithub-client/images/social-grey/500px.png new file mode 100644 index 0000000..70a373a Binary files /dev/null and b/new-bithub-client/images/social-grey/500px.png differ diff --git a/new-bithub-client/images/social-grey/android.png b/new-bithub-client/images/social-grey/android.png new file mode 100644 index 0000000..8873929 Binary files /dev/null and b/new-bithub-client/images/social-grey/android.png differ diff --git a/new-bithub-client/images/social-grey/apple.png b/new-bithub-client/images/social-grey/apple.png new file mode 100644 index 0000000..3be24cd Binary files /dev/null and b/new-bithub-client/images/social-grey/apple.png differ diff --git a/new-bithub-client/images/social-grey/appnet.png b/new-bithub-client/images/social-grey/appnet.png new file mode 100644 index 0000000..a0692e9 Binary files /dev/null and b/new-bithub-client/images/social-grey/appnet.png differ diff --git a/new-bithub-client/images/social-grey/bebo.png b/new-bithub-client/images/social-grey/bebo.png new file mode 100644 index 0000000..cda2140 Binary files /dev/null and b/new-bithub-client/images/social-grey/bebo.png differ diff --git a/new-bithub-client/images/social-grey/behance.png b/new-bithub-client/images/social-grey/behance.png new file mode 100644 index 0000000..32e826f Binary files /dev/null and b/new-bithub-client/images/social-grey/behance.png differ diff --git a/new-bithub-client/images/social-grey/blogger.png b/new-bithub-client/images/social-grey/blogger.png new file mode 100644 index 0000000..e5c578a Binary files /dev/null and b/new-bithub-client/images/social-grey/blogger.png differ diff --git a/new-bithub-client/images/social-grey/buffer.png b/new-bithub-client/images/social-grey/buffer.png new file mode 100644 index 0000000..6459b72 Binary files /dev/null and b/new-bithub-client/images/social-grey/buffer.png differ diff --git a/new-bithub-client/images/social-grey/chimein.png b/new-bithub-client/images/social-grey/chimein.png new file mode 100644 index 0000000..8ef164e Binary files /dev/null and b/new-bithub-client/images/social-grey/chimein.png differ diff --git a/new-bithub-client/images/social-grey/coderwall.png b/new-bithub-client/images/social-grey/coderwall.png new file mode 100644 index 0000000..e33921a Binary files /dev/null and b/new-bithub-client/images/social-grey/coderwall.png differ diff --git a/new-bithub-client/images/social-grey/dailymotion.png b/new-bithub-client/images/social-grey/dailymotion.png new file mode 100644 index 0000000..21ebbc5 Binary files /dev/null and b/new-bithub-client/images/social-grey/dailymotion.png differ diff --git a/new-bithub-client/images/social-grey/delicious.png b/new-bithub-client/images/social-grey/delicious.png new file mode 100644 index 0000000..95cc3b7 Binary files /dev/null and b/new-bithub-client/images/social-grey/delicious.png differ diff --git a/new-bithub-client/images/social-grey/deviantart.png b/new-bithub-client/images/social-grey/deviantart.png new file mode 100644 index 0000000..402ee08 Binary files /dev/null and b/new-bithub-client/images/social-grey/deviantart.png differ diff --git a/new-bithub-client/images/social-grey/digg.png b/new-bithub-client/images/social-grey/digg.png new file mode 100644 index 0000000..ec6b626 Binary files /dev/null and b/new-bithub-client/images/social-grey/digg.png differ diff --git a/new-bithub-client/images/social-grey/disqus.png b/new-bithub-client/images/social-grey/disqus.png new file mode 100644 index 0000000..05e62f4 Binary files /dev/null and b/new-bithub-client/images/social-grey/disqus.png differ diff --git a/new-bithub-client/images/social-grey/dribbble.png b/new-bithub-client/images/social-grey/dribbble.png new file mode 100644 index 0000000..0ebb563 Binary files /dev/null and b/new-bithub-client/images/social-grey/dribbble.png differ diff --git a/new-bithub-client/images/social-grey/drupal.png b/new-bithub-client/images/social-grey/drupal.png new file mode 100644 index 0000000..664ec75 Binary files /dev/null and b/new-bithub-client/images/social-grey/drupal.png differ diff --git a/new-bithub-client/images/social-grey/envato.png b/new-bithub-client/images/social-grey/envato.png new file mode 100644 index 0000000..e7d08ff Binary files /dev/null and b/new-bithub-client/images/social-grey/envato.png differ diff --git a/new-bithub-client/images/social-grey/facebook.png b/new-bithub-client/images/social-grey/facebook.png new file mode 100644 index 0000000..7e9dec0 Binary files /dev/null and b/new-bithub-client/images/social-grey/facebook.png differ diff --git a/new-bithub-client/images/social-grey/feedburner.png b/new-bithub-client/images/social-grey/feedburner.png new file mode 100644 index 0000000..c62cf94 Binary files /dev/null and b/new-bithub-client/images/social-grey/feedburner.png differ diff --git a/new-bithub-client/images/social-grey/flattr.png b/new-bithub-client/images/social-grey/flattr.png new file mode 100644 index 0000000..692d1da Binary files /dev/null and b/new-bithub-client/images/social-grey/flattr.png differ diff --git a/new-bithub-client/images/social-grey/flickr.png b/new-bithub-client/images/social-grey/flickr.png new file mode 100644 index 0000000..6b305ed Binary files /dev/null and b/new-bithub-client/images/social-grey/flickr.png differ diff --git a/new-bithub-client/images/social-grey/forrst.png b/new-bithub-client/images/social-grey/forrst.png new file mode 100644 index 0000000..1f4937d Binary files /dev/null and b/new-bithub-client/images/social-grey/forrst.png differ diff --git a/new-bithub-client/images/social-grey/foursquare.png b/new-bithub-client/images/social-grey/foursquare.png new file mode 100644 index 0000000..10b7df6 Binary files /dev/null and b/new-bithub-client/images/social-grey/foursquare.png differ diff --git a/new-bithub-client/images/social-grey/friendfeed.png b/new-bithub-client/images/social-grey/friendfeed.png new file mode 100644 index 0000000..9c9844f Binary files /dev/null and b/new-bithub-client/images/social-grey/friendfeed.png differ diff --git a/new-bithub-client/images/social-grey/github.png b/new-bithub-client/images/social-grey/github.png new file mode 100644 index 0000000..a0762eb Binary files /dev/null and b/new-bithub-client/images/social-grey/github.png differ diff --git a/new-bithub-client/images/social-grey/goodreads.png b/new-bithub-client/images/social-grey/goodreads.png new file mode 100644 index 0000000..aff201a Binary files /dev/null and b/new-bithub-client/images/social-grey/goodreads.png differ diff --git a/new-bithub-client/images/social-grey/google.png b/new-bithub-client/images/social-grey/google.png new file mode 100644 index 0000000..26421d1 Binary files /dev/null and b/new-bithub-client/images/social-grey/google.png differ diff --git a/new-bithub-client/images/social-grey/grooveshark.png b/new-bithub-client/images/social-grey/grooveshark.png new file mode 100644 index 0000000..f2db683 Binary files /dev/null and b/new-bithub-client/images/social-grey/grooveshark.png differ diff --git a/new-bithub-client/images/social-grey/houzz.png b/new-bithub-client/images/social-grey/houzz.png new file mode 100644 index 0000000..58ed314 Binary files /dev/null and b/new-bithub-client/images/social-grey/houzz.png differ diff --git a/new-bithub-client/images/social-grey/identica.png b/new-bithub-client/images/social-grey/identica.png new file mode 100644 index 0000000..6d49b4c Binary files /dev/null and b/new-bithub-client/images/social-grey/identica.png differ diff --git a/new-bithub-client/images/social-grey/instagram.png b/new-bithub-client/images/social-grey/instagram.png new file mode 100644 index 0000000..c6cf5e8 Binary files /dev/null and b/new-bithub-client/images/social-grey/instagram.png differ diff --git a/new-bithub-client/images/social-grey/lanyrd.png b/new-bithub-client/images/social-grey/lanyrd.png new file mode 100644 index 0000000..e849cec Binary files /dev/null and b/new-bithub-client/images/social-grey/lanyrd.png differ diff --git a/new-bithub-client/images/social-grey/lastfm.png b/new-bithub-client/images/social-grey/lastfm.png new file mode 100644 index 0000000..6fdb091 Binary files /dev/null and b/new-bithub-client/images/social-grey/lastfm.png differ diff --git a/new-bithub-client/images/social-grey/linkedin.png b/new-bithub-client/images/social-grey/linkedin.png new file mode 100644 index 0000000..35c2641 Binary files /dev/null and b/new-bithub-client/images/social-grey/linkedin.png differ diff --git a/new-bithub-client/images/social-grey/mail.png b/new-bithub-client/images/social-grey/mail.png new file mode 100644 index 0000000..e4f65c3 Binary files /dev/null and b/new-bithub-client/images/social-grey/mail.png differ diff --git a/new-bithub-client/images/social-grey/meetup.png b/new-bithub-client/images/social-grey/meetup.png new file mode 100644 index 0000000..231bfaa Binary files /dev/null and b/new-bithub-client/images/social-grey/meetup.png differ diff --git a/new-bithub-client/images/social-grey/myspace.png b/new-bithub-client/images/social-grey/myspace.png new file mode 100644 index 0000000..2b31bde Binary files /dev/null and b/new-bithub-client/images/social-grey/myspace.png differ diff --git a/new-bithub-client/images/social-grey/newsvine.png b/new-bithub-client/images/social-grey/newsvine.png new file mode 100644 index 0000000..38e93f2 Binary files /dev/null and b/new-bithub-client/images/social-grey/newsvine.png differ diff --git a/new-bithub-client/images/social-grey/odnoklassniki.png b/new-bithub-client/images/social-grey/odnoklassniki.png new file mode 100644 index 0000000..800e3c5 Binary files /dev/null and b/new-bithub-client/images/social-grey/odnoklassniki.png differ diff --git a/new-bithub-client/images/social-grey/outlook.png b/new-bithub-client/images/social-grey/outlook.png new file mode 100644 index 0000000..cf67521 Binary files /dev/null and b/new-bithub-client/images/social-grey/outlook.png differ diff --git a/new-bithub-client/images/social-grey/patreon.png b/new-bithub-client/images/social-grey/patreon.png new file mode 100644 index 0000000..4f1fa82 Binary files /dev/null and b/new-bithub-client/images/social-grey/patreon.png differ diff --git a/new-bithub-client/images/social-grey/paypal.png b/new-bithub-client/images/social-grey/paypal.png new file mode 100644 index 0000000..a6677c1 Binary files /dev/null and b/new-bithub-client/images/social-grey/paypal.png differ diff --git a/new-bithub-client/images/social-grey/persona.png b/new-bithub-client/images/social-grey/persona.png new file mode 100644 index 0000000..eb65912 Binary files /dev/null and b/new-bithub-client/images/social-grey/persona.png differ diff --git a/new-bithub-client/images/social-grey/pinterest.png b/new-bithub-client/images/social-grey/pinterest.png new file mode 100644 index 0000000..1e984c4 Binary files /dev/null and b/new-bithub-client/images/social-grey/pinterest.png differ diff --git a/new-bithub-client/images/social-grey/play.png b/new-bithub-client/images/social-grey/play.png new file mode 100644 index 0000000..773c8f3 Binary files /dev/null and b/new-bithub-client/images/social-grey/play.png differ diff --git a/new-bithub-client/images/social-grey/playstation.png b/new-bithub-client/images/social-grey/playstation.png new file mode 100644 index 0000000..95f7ff0 Binary files /dev/null and b/new-bithub-client/images/social-grey/playstation.png differ diff --git a/new-bithub-client/images/social-grey/reddit.png b/new-bithub-client/images/social-grey/reddit.png new file mode 100644 index 0000000..fe097a2 Binary files /dev/null and b/new-bithub-client/images/social-grey/reddit.png differ diff --git a/new-bithub-client/images/social-grey/rss.png b/new-bithub-client/images/social-grey/rss.png new file mode 100644 index 0000000..e2513f1 Binary files /dev/null and b/new-bithub-client/images/social-grey/rss.png differ diff --git a/new-bithub-client/images/social-grey/skype.png b/new-bithub-client/images/social-grey/skype.png new file mode 100644 index 0000000..ca14f90 Binary files /dev/null and b/new-bithub-client/images/social-grey/skype.png differ diff --git a/new-bithub-client/images/social-grey/slideshare.png b/new-bithub-client/images/social-grey/slideshare.png new file mode 100644 index 0000000..5695875 Binary files /dev/null and b/new-bithub-client/images/social-grey/slideshare.png differ diff --git a/new-bithub-client/images/social-grey/smugmug.png b/new-bithub-client/images/social-grey/smugmug.png new file mode 100644 index 0000000..2d61ea1 Binary files /dev/null and b/new-bithub-client/images/social-grey/smugmug.png differ diff --git a/new-bithub-client/images/social-grey/soundcloud.png b/new-bithub-client/images/social-grey/soundcloud.png new file mode 100644 index 0000000..1b7437b Binary files /dev/null and b/new-bithub-client/images/social-grey/soundcloud.png differ diff --git a/new-bithub-client/images/social-grey/spotify.png b/new-bithub-client/images/social-grey/spotify.png new file mode 100644 index 0000000..542d941 Binary files /dev/null and b/new-bithub-client/images/social-grey/spotify.png differ diff --git a/new-bithub-client/images/social-grey/stackexchange.png b/new-bithub-client/images/social-grey/stackexchange.png new file mode 100644 index 0000000..938ab25 Binary files /dev/null and b/new-bithub-client/images/social-grey/stackexchange.png differ diff --git a/new-bithub-client/images/social-grey/steam.png b/new-bithub-client/images/social-grey/steam.png new file mode 100644 index 0000000..3fcd67d Binary files /dev/null and b/new-bithub-client/images/social-grey/steam.png differ diff --git a/new-bithub-client/images/social-grey/stumbleupon.png b/new-bithub-client/images/social-grey/stumbleupon.png new file mode 100644 index 0000000..962b416 Binary files /dev/null and b/new-bithub-client/images/social-grey/stumbleupon.png differ diff --git a/new-bithub-client/images/social-grey/swarm.png b/new-bithub-client/images/social-grey/swarm.png new file mode 100644 index 0000000..ca31acb Binary files /dev/null and b/new-bithub-client/images/social-grey/swarm.png differ diff --git a/new-bithub-client/images/social-grey/technorati.png b/new-bithub-client/images/social-grey/technorati.png new file mode 100644 index 0000000..df12d4a Binary files /dev/null and b/new-bithub-client/images/social-grey/technorati.png differ diff --git a/new-bithub-client/images/social-grey/tripadvisor.png b/new-bithub-client/images/social-grey/tripadvisor.png new file mode 100644 index 0000000..84b66a7 Binary files /dev/null and b/new-bithub-client/images/social-grey/tripadvisor.png differ diff --git a/new-bithub-client/images/social-grey/tripit.png b/new-bithub-client/images/social-grey/tripit.png new file mode 100644 index 0000000..6c994ab Binary files /dev/null and b/new-bithub-client/images/social-grey/tripit.png differ diff --git a/new-bithub-client/images/social-grey/triplej.png b/new-bithub-client/images/social-grey/triplej.png new file mode 100644 index 0000000..304f650 Binary files /dev/null and b/new-bithub-client/images/social-grey/triplej.png differ diff --git a/new-bithub-client/images/social-grey/tumblr.png b/new-bithub-client/images/social-grey/tumblr.png new file mode 100644 index 0000000..e5fa06d Binary files /dev/null and b/new-bithub-client/images/social-grey/tumblr.png differ diff --git a/new-bithub-client/images/social-grey/twitter.png b/new-bithub-client/images/social-grey/twitter.png new file mode 100644 index 0000000..77e27f6 Binary files /dev/null and b/new-bithub-client/images/social-grey/twitter.png differ diff --git a/new-bithub-client/images/social-grey/viadeo.png b/new-bithub-client/images/social-grey/viadeo.png new file mode 100644 index 0000000..1e4fc65 Binary files /dev/null and b/new-bithub-client/images/social-grey/viadeo.png differ diff --git a/new-bithub-client/images/social-grey/vimeo.png b/new-bithub-client/images/social-grey/vimeo.png new file mode 100644 index 0000000..38e7706 Binary files /dev/null and b/new-bithub-client/images/social-grey/vimeo.png differ diff --git a/new-bithub-client/images/social-grey/vine.png b/new-bithub-client/images/social-grey/vine.png new file mode 100644 index 0000000..d300d35 Binary files /dev/null and b/new-bithub-client/images/social-grey/vine.png differ diff --git a/new-bithub-client/images/social-grey/vkontakte.png b/new-bithub-client/images/social-grey/vkontakte.png new file mode 100644 index 0000000..b7172d3 Binary files /dev/null and b/new-bithub-client/images/social-grey/vkontakte.png differ diff --git a/new-bithub-client/images/social-grey/wikipedia.png b/new-bithub-client/images/social-grey/wikipedia.png new file mode 100644 index 0000000..2a0af7d Binary files /dev/null and b/new-bithub-client/images/social-grey/wikipedia.png differ diff --git a/new-bithub-client/images/social-grey/windows.png b/new-bithub-client/images/social-grey/windows.png new file mode 100644 index 0000000..25e0f86 Binary files /dev/null and b/new-bithub-client/images/social-grey/windows.png differ diff --git a/new-bithub-client/images/social-grey/wordpress.png b/new-bithub-client/images/social-grey/wordpress.png new file mode 100644 index 0000000..7e0ecee Binary files /dev/null and b/new-bithub-client/images/social-grey/wordpress.png differ diff --git a/new-bithub-client/images/social-grey/xbox.png b/new-bithub-client/images/social-grey/xbox.png new file mode 100644 index 0000000..11599a7 Binary files /dev/null and b/new-bithub-client/images/social-grey/xbox.png differ diff --git a/new-bithub-client/images/social-grey/xing.png b/new-bithub-client/images/social-grey/xing.png new file mode 100644 index 0000000..8c84a10 Binary files /dev/null and b/new-bithub-client/images/social-grey/xing.png differ diff --git a/new-bithub-client/images/social-grey/yahoo.png b/new-bithub-client/images/social-grey/yahoo.png new file mode 100644 index 0000000..a543542 Binary files /dev/null and b/new-bithub-client/images/social-grey/yahoo.png differ diff --git a/new-bithub-client/images/social-grey/yammer.png b/new-bithub-client/images/social-grey/yammer.png new file mode 100644 index 0000000..d554e9c Binary files /dev/null and b/new-bithub-client/images/social-grey/yammer.png differ diff --git a/new-bithub-client/images/social-grey/yelp.png b/new-bithub-client/images/social-grey/yelp.png new file mode 100644 index 0000000..c8821e9 Binary files /dev/null and b/new-bithub-client/images/social-grey/yelp.png differ diff --git a/new-bithub-client/images/social-grey/youtube.png b/new-bithub-client/images/social-grey/youtube.png new file mode 100644 index 0000000..95fa497 Binary files /dev/null and b/new-bithub-client/images/social-grey/youtube.png differ diff --git a/new-bithub-client/images/social-grey/zerply.png b/new-bithub-client/images/social-grey/zerply.png new file mode 100644 index 0000000..cb087b2 Binary files /dev/null and b/new-bithub-client/images/social-grey/zerply.png differ diff --git a/new-bithub-client/images/social-grey/zynga.png b/new-bithub-client/images/social-grey/zynga.png new file mode 100644 index 0000000..a2dc735 Binary files /dev/null and b/new-bithub-client/images/social-grey/zynga.png differ diff --git a/new-bithub-client/images/social/500px.png b/new-bithub-client/images/social/500px.png new file mode 100755 index 0000000..c7e9841 Binary files /dev/null and b/new-bithub-client/images/social/500px.png differ diff --git a/new-bithub-client/images/social/android.png b/new-bithub-client/images/social/android.png new file mode 100755 index 0000000..412c2f8 Binary files /dev/null and b/new-bithub-client/images/social/android.png differ diff --git a/new-bithub-client/images/social/apple.png b/new-bithub-client/images/social/apple.png new file mode 100755 index 0000000..ebc9119 Binary files /dev/null and b/new-bithub-client/images/social/apple.png differ diff --git a/new-bithub-client/images/social/appnet.png b/new-bithub-client/images/social/appnet.png new file mode 100755 index 0000000..1251fd3 Binary files /dev/null and b/new-bithub-client/images/social/appnet.png differ diff --git a/new-bithub-client/images/social/bebo.png b/new-bithub-client/images/social/bebo.png new file mode 100755 index 0000000..65c19e8 Binary files /dev/null and b/new-bithub-client/images/social/bebo.png differ diff --git a/new-bithub-client/images/social/behance.png b/new-bithub-client/images/social/behance.png new file mode 100755 index 0000000..7c933f6 Binary files /dev/null and b/new-bithub-client/images/social/behance.png differ diff --git a/new-bithub-client/images/social/blogger.png b/new-bithub-client/images/social/blogger.png new file mode 100755 index 0000000..274664b Binary files /dev/null and b/new-bithub-client/images/social/blogger.png differ diff --git a/new-bithub-client/images/social/buffer.png b/new-bithub-client/images/social/buffer.png new file mode 100755 index 0000000..3e05e29 Binary files /dev/null and b/new-bithub-client/images/social/buffer.png differ diff --git a/new-bithub-client/images/social/chimein.png b/new-bithub-client/images/social/chimein.png new file mode 100755 index 0000000..0c33ff1 Binary files /dev/null and b/new-bithub-client/images/social/chimein.png differ diff --git a/new-bithub-client/images/social/coderwall.png b/new-bithub-client/images/social/coderwall.png new file mode 100755 index 0000000..ee02af6 Binary files /dev/null and b/new-bithub-client/images/social/coderwall.png differ diff --git a/new-bithub-client/images/social/dailymotion.png b/new-bithub-client/images/social/dailymotion.png new file mode 100755 index 0000000..52a25ac Binary files /dev/null and b/new-bithub-client/images/social/dailymotion.png differ diff --git a/new-bithub-client/images/social/delicious.png b/new-bithub-client/images/social/delicious.png new file mode 100755 index 0000000..7039143 Binary files /dev/null and b/new-bithub-client/images/social/delicious.png differ diff --git a/new-bithub-client/images/social/deviantart.png b/new-bithub-client/images/social/deviantart.png new file mode 100755 index 0000000..8c22886 Binary files /dev/null and b/new-bithub-client/images/social/deviantart.png differ diff --git a/new-bithub-client/images/social/digg.png b/new-bithub-client/images/social/digg.png new file mode 100755 index 0000000..8a0ebcc Binary files /dev/null and b/new-bithub-client/images/social/digg.png differ diff --git a/new-bithub-client/images/social/disqus.png b/new-bithub-client/images/social/disqus.png new file mode 100755 index 0000000..70f7f08 Binary files /dev/null and b/new-bithub-client/images/social/disqus.png differ diff --git a/new-bithub-client/images/social/dribbble.png b/new-bithub-client/images/social/dribbble.png new file mode 100755 index 0000000..b6172fd Binary files /dev/null and b/new-bithub-client/images/social/dribbble.png differ diff --git a/new-bithub-client/images/social/drupal.png b/new-bithub-client/images/social/drupal.png new file mode 100755 index 0000000..9027f59 Binary files /dev/null and b/new-bithub-client/images/social/drupal.png differ diff --git a/new-bithub-client/images/social/envato.png b/new-bithub-client/images/social/envato.png new file mode 100755 index 0000000..d7882fc Binary files /dev/null and b/new-bithub-client/images/social/envato.png differ diff --git a/new-bithub-client/images/social/facebook.png b/new-bithub-client/images/social/facebook.png new file mode 100755 index 0000000..d24d130 Binary files /dev/null and b/new-bithub-client/images/social/facebook.png differ diff --git a/new-bithub-client/images/social/feedburner.png b/new-bithub-client/images/social/feedburner.png new file mode 100755 index 0000000..05b6a38 Binary files /dev/null and b/new-bithub-client/images/social/feedburner.png differ diff --git a/new-bithub-client/images/social/flattr.png b/new-bithub-client/images/social/flattr.png new file mode 100755 index 0000000..9cf4410 Binary files /dev/null and b/new-bithub-client/images/social/flattr.png differ diff --git a/new-bithub-client/images/social/flickr.png b/new-bithub-client/images/social/flickr.png new file mode 100755 index 0000000..5fbbef5 Binary files /dev/null and b/new-bithub-client/images/social/flickr.png differ diff --git a/new-bithub-client/images/social/forrst.png b/new-bithub-client/images/social/forrst.png new file mode 100755 index 0000000..f53f423 Binary files /dev/null and b/new-bithub-client/images/social/forrst.png differ diff --git a/new-bithub-client/images/social/foursquare.png b/new-bithub-client/images/social/foursquare.png new file mode 100755 index 0000000..33b9206 Binary files /dev/null and b/new-bithub-client/images/social/foursquare.png differ diff --git a/new-bithub-client/images/social/friendfeed.png b/new-bithub-client/images/social/friendfeed.png new file mode 100755 index 0000000..1c404c3 Binary files /dev/null and b/new-bithub-client/images/social/friendfeed.png differ diff --git a/new-bithub-client/images/social/github.png b/new-bithub-client/images/social/github.png new file mode 100755 index 0000000..085af7d Binary files /dev/null and b/new-bithub-client/images/social/github.png differ diff --git a/new-bithub-client/images/social/goodreads.png b/new-bithub-client/images/social/goodreads.png new file mode 100755 index 0000000..9d123a6 Binary files /dev/null and b/new-bithub-client/images/social/goodreads.png differ diff --git a/new-bithub-client/images/social/google.png b/new-bithub-client/images/social/google.png new file mode 100755 index 0000000..664c9fb Binary files /dev/null and b/new-bithub-client/images/social/google.png differ diff --git a/new-bithub-client/images/social/grooveshark.png b/new-bithub-client/images/social/grooveshark.png new file mode 100755 index 0000000..2196b12 Binary files /dev/null and b/new-bithub-client/images/social/grooveshark.png differ diff --git a/new-bithub-client/images/social/houzz.png b/new-bithub-client/images/social/houzz.png new file mode 100755 index 0000000..0d89cd0 Binary files /dev/null and b/new-bithub-client/images/social/houzz.png differ diff --git a/new-bithub-client/images/social/identica.png b/new-bithub-client/images/social/identica.png new file mode 100755 index 0000000..db9c160 Binary files /dev/null and b/new-bithub-client/images/social/identica.png differ diff --git a/new-bithub-client/images/social/instagram.png b/new-bithub-client/images/social/instagram.png new file mode 100755 index 0000000..4673f7a Binary files /dev/null and b/new-bithub-client/images/social/instagram.png differ diff --git a/new-bithub-client/images/social/lanyrd.png b/new-bithub-client/images/social/lanyrd.png new file mode 100755 index 0000000..d68b6d0 Binary files /dev/null and b/new-bithub-client/images/social/lanyrd.png differ diff --git a/new-bithub-client/images/social/lastfm.png b/new-bithub-client/images/social/lastfm.png new file mode 100755 index 0000000..40f4012 Binary files /dev/null and b/new-bithub-client/images/social/lastfm.png differ diff --git a/new-bithub-client/images/social/linkedin.png b/new-bithub-client/images/social/linkedin.png new file mode 100755 index 0000000..02e5296 Binary files /dev/null and b/new-bithub-client/images/social/linkedin.png differ diff --git a/new-bithub-client/images/social/mail.png b/new-bithub-client/images/social/mail.png new file mode 100755 index 0000000..62f1288 Binary files /dev/null and b/new-bithub-client/images/social/mail.png differ diff --git a/new-bithub-client/images/social/meetup.png b/new-bithub-client/images/social/meetup.png new file mode 100755 index 0000000..bfd7924 Binary files /dev/null and b/new-bithub-client/images/social/meetup.png differ diff --git a/new-bithub-client/images/social/myspace.png b/new-bithub-client/images/social/myspace.png new file mode 100755 index 0000000..550b125 Binary files /dev/null and b/new-bithub-client/images/social/myspace.png differ diff --git a/new-bithub-client/images/social/newsvine.png b/new-bithub-client/images/social/newsvine.png new file mode 100755 index 0000000..8dd4ed8 Binary files /dev/null and b/new-bithub-client/images/social/newsvine.png differ diff --git a/new-bithub-client/images/social/odnoklassniki.png b/new-bithub-client/images/social/odnoklassniki.png new file mode 100755 index 0000000..9a912f8 Binary files /dev/null and b/new-bithub-client/images/social/odnoklassniki.png differ diff --git a/new-bithub-client/images/social/outlook.png b/new-bithub-client/images/social/outlook.png new file mode 100755 index 0000000..6d60dda Binary files /dev/null and b/new-bithub-client/images/social/outlook.png differ diff --git a/new-bithub-client/images/social/patreon.png b/new-bithub-client/images/social/patreon.png new file mode 100755 index 0000000..122a9ef Binary files /dev/null and b/new-bithub-client/images/social/patreon.png differ diff --git a/new-bithub-client/images/social/paypal.png b/new-bithub-client/images/social/paypal.png new file mode 100755 index 0000000..21d888e Binary files /dev/null and b/new-bithub-client/images/social/paypal.png differ diff --git a/new-bithub-client/images/social/persona.png b/new-bithub-client/images/social/persona.png new file mode 100755 index 0000000..6adbed8 Binary files /dev/null and b/new-bithub-client/images/social/persona.png differ diff --git a/new-bithub-client/images/social/pinterest.png b/new-bithub-client/images/social/pinterest.png new file mode 100755 index 0000000..26a6b65 Binary files /dev/null and b/new-bithub-client/images/social/pinterest.png differ diff --git a/new-bithub-client/images/social/play.png b/new-bithub-client/images/social/play.png new file mode 100755 index 0000000..fb5d28c Binary files /dev/null and b/new-bithub-client/images/social/play.png differ diff --git a/new-bithub-client/images/social/playstation.png b/new-bithub-client/images/social/playstation.png new file mode 100755 index 0000000..355fe47 Binary files /dev/null and b/new-bithub-client/images/social/playstation.png differ diff --git a/new-bithub-client/images/social/reddit.png b/new-bithub-client/images/social/reddit.png new file mode 100755 index 0000000..893a5ed Binary files /dev/null and b/new-bithub-client/images/social/reddit.png differ diff --git a/new-bithub-client/images/social/rss.png b/new-bithub-client/images/social/rss.png new file mode 100755 index 0000000..3835c16 Binary files /dev/null and b/new-bithub-client/images/social/rss.png differ diff --git a/new-bithub-client/images/social/skype.png b/new-bithub-client/images/social/skype.png new file mode 100755 index 0000000..bcd9036 Binary files /dev/null and b/new-bithub-client/images/social/skype.png differ diff --git a/new-bithub-client/images/social/slideshare.png b/new-bithub-client/images/social/slideshare.png new file mode 100755 index 0000000..b8757b3 Binary files /dev/null and b/new-bithub-client/images/social/slideshare.png differ diff --git a/new-bithub-client/images/social/smugmug.png b/new-bithub-client/images/social/smugmug.png new file mode 100755 index 0000000..327d7aa Binary files /dev/null and b/new-bithub-client/images/social/smugmug.png differ diff --git a/new-bithub-client/images/social/soundcloud.png b/new-bithub-client/images/social/soundcloud.png new file mode 100755 index 0000000..74030b4 Binary files /dev/null and b/new-bithub-client/images/social/soundcloud.png differ diff --git a/new-bithub-client/images/social/spotify.png b/new-bithub-client/images/social/spotify.png new file mode 100755 index 0000000..df73ed1 Binary files /dev/null and b/new-bithub-client/images/social/spotify.png differ diff --git a/new-bithub-client/images/social/stackexchange.png b/new-bithub-client/images/social/stackexchange.png new file mode 100755 index 0000000..af011f3 Binary files /dev/null and b/new-bithub-client/images/social/stackexchange.png differ diff --git a/new-bithub-client/images/social/stackoverflow.png b/new-bithub-client/images/social/stackoverflow.png new file mode 100755 index 0000000..0c76cc9 Binary files /dev/null and b/new-bithub-client/images/social/stackoverflow.png differ diff --git a/new-bithub-client/images/social/steam.png b/new-bithub-client/images/social/steam.png new file mode 100755 index 0000000..920660b Binary files /dev/null and b/new-bithub-client/images/social/steam.png differ diff --git a/new-bithub-client/images/social/stumbleupon.png b/new-bithub-client/images/social/stumbleupon.png new file mode 100755 index 0000000..a844d8d Binary files /dev/null and b/new-bithub-client/images/social/stumbleupon.png differ diff --git a/new-bithub-client/images/social/swarm.png b/new-bithub-client/images/social/swarm.png new file mode 100755 index 0000000..fa9c4de Binary files /dev/null and b/new-bithub-client/images/social/swarm.png differ diff --git a/new-bithub-client/images/social/technorati.png b/new-bithub-client/images/social/technorati.png new file mode 100755 index 0000000..e8f6fa8 Binary files /dev/null and b/new-bithub-client/images/social/technorati.png differ diff --git a/new-bithub-client/images/social/tripadvisor.png b/new-bithub-client/images/social/tripadvisor.png new file mode 100755 index 0000000..ee30ffd Binary files /dev/null and b/new-bithub-client/images/social/tripadvisor.png differ diff --git a/new-bithub-client/images/social/tripit.png b/new-bithub-client/images/social/tripit.png new file mode 100755 index 0000000..c5428b0 Binary files /dev/null and b/new-bithub-client/images/social/tripit.png differ diff --git a/new-bithub-client/images/social/triplej.png b/new-bithub-client/images/social/triplej.png new file mode 100755 index 0000000..5756a81 Binary files /dev/null and b/new-bithub-client/images/social/triplej.png differ diff --git a/new-bithub-client/images/social/tumblr.png b/new-bithub-client/images/social/tumblr.png new file mode 100755 index 0000000..e95fbd2 Binary files /dev/null and b/new-bithub-client/images/social/tumblr.png differ diff --git a/new-bithub-client/images/social/twitter.png b/new-bithub-client/images/social/twitter.png new file mode 100755 index 0000000..9d61895 Binary files /dev/null and b/new-bithub-client/images/social/twitter.png differ diff --git a/new-bithub-client/images/social/viadeo.png b/new-bithub-client/images/social/viadeo.png new file mode 100755 index 0000000..b446887 Binary files /dev/null and b/new-bithub-client/images/social/viadeo.png differ diff --git a/new-bithub-client/images/social/vimeo.png b/new-bithub-client/images/social/vimeo.png new file mode 100755 index 0000000..a187938 Binary files /dev/null and b/new-bithub-client/images/social/vimeo.png differ diff --git a/new-bithub-client/images/social/vine.png b/new-bithub-client/images/social/vine.png new file mode 100755 index 0000000..8e09e9d Binary files /dev/null and b/new-bithub-client/images/social/vine.png differ diff --git a/new-bithub-client/images/social/vkontakte.png b/new-bithub-client/images/social/vkontakte.png new file mode 100755 index 0000000..ea2bcef Binary files /dev/null and b/new-bithub-client/images/social/vkontakte.png differ diff --git a/new-bithub-client/images/social/wikipedia.png b/new-bithub-client/images/social/wikipedia.png new file mode 100755 index 0000000..4e351bd Binary files /dev/null and b/new-bithub-client/images/social/wikipedia.png differ diff --git a/new-bithub-client/images/social/windows.png b/new-bithub-client/images/social/windows.png new file mode 100755 index 0000000..72ff8ac Binary files /dev/null and b/new-bithub-client/images/social/windows.png differ diff --git a/new-bithub-client/images/social/wordpress.png b/new-bithub-client/images/social/wordpress.png new file mode 100755 index 0000000..9970380 Binary files /dev/null and b/new-bithub-client/images/social/wordpress.png differ diff --git a/new-bithub-client/images/social/xbox.png b/new-bithub-client/images/social/xbox.png new file mode 100755 index 0000000..d1b77df Binary files /dev/null and b/new-bithub-client/images/social/xbox.png differ diff --git a/new-bithub-client/images/social/xing.png b/new-bithub-client/images/social/xing.png new file mode 100755 index 0000000..01e3f2b Binary files /dev/null and b/new-bithub-client/images/social/xing.png differ diff --git a/new-bithub-client/images/social/yahoo.png b/new-bithub-client/images/social/yahoo.png new file mode 100755 index 0000000..d330229 Binary files /dev/null and b/new-bithub-client/images/social/yahoo.png differ diff --git a/new-bithub-client/images/social/yammer.png b/new-bithub-client/images/social/yammer.png new file mode 100755 index 0000000..990d819 Binary files /dev/null and b/new-bithub-client/images/social/yammer.png differ diff --git a/new-bithub-client/images/social/yelp.png b/new-bithub-client/images/social/yelp.png new file mode 100755 index 0000000..0b9e3a9 Binary files /dev/null and b/new-bithub-client/images/social/yelp.png differ diff --git a/new-bithub-client/images/social/youtube.png b/new-bithub-client/images/social/youtube.png new file mode 100755 index 0000000..cad5c27 Binary files /dev/null and b/new-bithub-client/images/social/youtube.png differ diff --git a/new-bithub-client/images/social/zerply.png b/new-bithub-client/images/social/zerply.png new file mode 100755 index 0000000..66a76a1 Binary files /dev/null and b/new-bithub-client/images/social/zerply.png differ diff --git a/new-bithub-client/images/social/zynga.png b/new-bithub-client/images/social/zynga.png new file mode 100755 index 0000000..a1bbf00 Binary files /dev/null and b/new-bithub-client/images/social/zynga.png differ diff --git a/new-bithub-client/images/spinner.gif b/new-bithub-client/images/spinner.gif new file mode 100644 index 0000000..0435861 Binary files /dev/null and b/new-bithub-client/images/spinner.gif differ diff --git a/new-bithub-client/package.json b/new-bithub-client/package.json new file mode 100644 index 0000000..7f2d5a3 --- /dev/null +++ b/new-bithub-client/package.json @@ -0,0 +1,80 @@ +{ + "name": "bithub-client", + "version": "0.0.0", + "description": "", + "homepage": "", + "author": { + "name": "Mihael Konjevic", + "email": "konjevic@gmail.com", + "url": "" + }, + "scripts": { + "test": "testee src/test.html --browsers firefox --reporter Spec", + "start": "BITHUB_HOST=http://dev.bithub.com can-serve --port 3030", + "develop": "BITHUB_HOST=http://dev.bithub.com node server --develop --port 3030", + "document": "documentjs", + "build": "node build" + }, + "main": "bithub-client/index.stache!done-autorender", + "files": [ + "src" + ], + "keywords": [], + "system": { + "main": "bithub-client/index.stache!done-autorender", + "directories": { + "lib": "src" + }, + "configDependencies": [ + "live-reload" + ], + "envs": { + "server-development": { + "map": { + "slideout/dist/slideout": "@empty" + } + }, + "server-production": { + "map": { + "slideout/dist/slideout": "@empty" + } + } + }, + "npmIgnore": [ + "documentjs", + "testee", + "donejs-deploy", + "generator-donejs", + "donejs-cli" + ] + }, + "dependencies": { + "can": "2.3.9", + "can-connect": "^0.3.1", + "can-ssr": "^0.10.1", + "done-autorender": "^0.4.3", + "done-component": "^0.3.0", + "done-css": "^1.1.15", + "donejs": "0.6.0", + "generator-donejs": "^0.3.4", + "jquery": "2.1.4", + "lodash-amd": "^3.10.1", + "moment": "^2.10.6", + "selectize": "^0.12.1", + "bootstrap": "^3.3.5", + "slideout": "0.1.11", + "font-awesome": "^4.4.0", + "cookies": "^0.5.1", + "commander": "^2.9.0", + "infanticide": "^1.0.1", + "js-cookie": "^2.0.4", + "steal-qunit": "^0.1.1", + "can-fixture": "0.0.1", + "funcunit": "^3.0.0", + "testee": "^0.2.2", + "donejs-deploy": "^0.3.1", + "donejs-cli": "^0.5.4", + "steal-tools": "0.13.2", + "steal": "0.13.0" + } +} diff --git a/new-bithub-client/production.html b/new-bithub-client/production.html new file mode 100644 index 0000000..2f46017 --- /dev/null +++ b/new-bithub-client/production.html @@ -0,0 +1,9 @@ + + + + bithub-client + + + + + \ No newline at end of file diff --git a/new-bithub-client/readme.md b/new-bithub-client/readme.md new file mode 100644 index 0000000..ac440f4 --- /dev/null +++ b/new-bithub-client/readme.md @@ -0,0 +1 @@ +# bithub-client diff --git a/new-bithub-client/server.js b/new-bithub-client/server.js new file mode 100644 index 0000000..fb7c563 --- /dev/null +++ b/new-bithub-client/server.js @@ -0,0 +1,94 @@ +#!/usr/bin/env node +var fs = require('fs'); +var path = require("path"); +var program = require('commander'); + +var pkg = require('can-ssr/package.json'); +var server = require('can-ssr/lib/server'); +var exec = require('child_process').exec; +var Cookies = require('cookies'); +var http = require('http'); + +program.version(pkg.version) + .usage('[options]') + .description(pkg.description) + .option('-d, --develop', 'Enable development mode (live-reload)') + .option('-p, --port ', 'The server port') + .option('-r, --proxy ', 'A URL to an API that should be proxied') + .option('-t, --proxy-to ', 'The path to proxy to (default: /api)') + .option('-l, --no-live-reload', 'Turn off live-reload') + .option('--live-reload-port ', 'Port to use for live-reload') + .option('--steal-tools-path ', 'Location of your steal-tools') + .parse(process.argv); + +var options = { + path: process.cwd(), + liveReload: program.liveReload, + configure: function(app){ + app.use(function(req, res, next){ + var cookies = new Cookies(req, res); + var sessionId = cookies.get('_session_id'); + if(sessionId){ + global.__railsSessionId = sessionId; + } + next(); + }); + } +}; + +if(program.proxy) { + options.proxy = program.proxy; + options.proxyTo = program.proxyTo; +} + +// Spawn a child process in development mode +if(program.develop) { + var stealToolsPath = program.stealToolsPath || + path.join("node_modules", ".bin", "steal-tools"); + if(!fs.existsSync(stealToolsPath)) { + console.error('live-reload not available: ' + + 'No local steal-tools binary found. ' + + 'Run `npm install steal-tools --save-dev`.'); + } else { + var cmd = stealToolsPath + ' live-reload'; + if(program.liveReloadPort) { + cmd += ' --live-reload-port ' + program.liveReloadPort; + } + var child = exec(cmd, { + cwd: process.cwd() + }); + + child.stdout.pipe(process.stdout); + child.stderr.pipe(process.stderr); + + var killOnExit = require('infanticide'); + killOnExit(child); + } +} + +var app = server(options); +var port = program.port || process.env.PORT || 3030; +var server = app.listen(port); + +// We should never hit this if the user is logged in +app.use(function(req, res, next){ + res.redirect(process.env.BITHUB_HOST + '/accounts/sign_in'); +}); + +server.on('error', function(e) { + if(e.code === 'EADDRINUSE') { + console.error('ERROR: Can not start can-serve on port ' + port + + '.\nAnother application is already using it.'); + } else { + console.error(e); + console.error(e.stack); + } +}); + +server.on('listening', function() { + var address = server.address(); + var url = 'http://' + (address.address === '::' ? + 'localhost' : address.address) + ':' + address.port; + + console.log('can-serve starting on ' + url); +}); diff --git a/new-bithub-client/src/app.js b/new-bithub-client/src/app.js new file mode 100755 index 0000000..124e68c --- /dev/null +++ b/new-bithub-client/src/app.js @@ -0,0 +1,351 @@ +/* globals process */ +/* globals global */ +/* globals setTimeout */ + +import AppMap from "can-ssr/app-map"; +import 'can/map/define/'; +import 'can/route/pushstate/'; +import Account from 'src/models/account'; +import Hub from 'src/models/hub'; +import Organization from 'src/models/organization'; +import Bit from 'src/models/bit'; +import EntityDecision from 'src/models/entity-decision'; +import Service from 'src/models/service'; +import $ from "jquery"; +import Cookie from "js-cookie"; +import connectLiveService from "./connect-liveservice"; + +can.route.bindings.pushstate.root = "/new-bithub/"; +can.baseURL = '/new-bithub/'; + +var NODE_ENV = ""; +var BITHUB_HOST = "http://dev.bithub.com"; + +if(process){ + NODE_ENV = (process.env && process.env.NODE_ENV) || ""; + BITHUB_HOST = (process.env && process.env.BITHUB_HOST) || BITHUB_HOST; + + console.log('BITHUB_HOST', BITHUB_HOST) + +} + +if(NODE_ENV.substr(0, 6) !== 'window'){ + // Hacking in session stuff (should be gone in next version) + $.ajaxSettings.xhr = function(){ + try { + var req = new global.XMLHttpRequest(); + var oldOpen = req.open; + req.open = function(){ + if((arguments[1] || "").substr(0, 5) === '/api/'){ + arguments[1] = BITHUB_HOST + arguments[1]; + } + var res = oldOpen.apply(this, arguments); + + console.log('AJAX CALL', global.__railsSessionId) + + if(this.setDisableHeaderCheck && global && global.__railsSessionId){ + this.setDisableHeaderCheck(true); + this.setRequestHeader('Cookie', '_session_id=' + global.__railsSessionId); + } + + return res; + }; + return req; + } catch( e ) {} + }; +} + + +const TAB_TO_FILTER = { + pending: 'pending', + approved: 'approved', + starred: 'starred', + deleted: 'deleted' +}; + +var getCurrentDecision = function(decisions, current){ + decisions = decisions || []; + for(var i = 0; i < decisions.length; i++){ + if(decisions[i].id === current){ + return decisions[i]; + } + } +}; + +const AppViewModel = AppMap.extend({ + define : { + page : { + set : function(val){ + return val; + } + }, + isSlideoutOpen : { + serialize: false, + value: false, + set : function(val){ + if(val){ + this.attr('wasSlideoutOpen', true); + } + return val; + } + }, + wasSlideoutOpen : { + value: false, + serialize: false + }, + tab : { + get : function(lastSetVal){ + return lastSetVal || "pending"; + } + }, + currentBrand : { + serialize: false + }, + currentSubscription : { + serialize: false + }, + currentAccount : { + serialize: false + }, + isChangingOrganization : { + value: false, + serialize: false + }, + currentOrganizationId : { + set : function(newVal, setVal){ + var self = this; + if(newVal){ + Organization.choose(newVal).then(function(){ + self.attr('organizationsOpen', false); + window.location.href = "/new-bithub/"; + }); + } + }, + get : function(lastValue, setter){ + if(!lastValue){ + this.waitFor(Organization.current()).then(function(organization){ + setter(organization.id); + }); + } + return lastValue; + } + }, + currentOrganization: { + serialize: false, + get : function(lastValue, setter){ + var organizations = this.attr('currentAccount.organizations'); + var currentOrganizationId = parseInt(this.attr('currentOrganizationId'), 10); + var length; + if(organizations && currentOrganizationId){ + length = organizations.attr('length'); + for(var i = 0; i < length; i++){ + if(organizations[i].id === currentOrganizationId){ + return organizations[i]; + } + } + } + } + }, + currentHubIdAsString: { + get: function(){ + return this.attr("currentHubId") ? ""+this.attr("currentHubId") : undefined; + }, + set: function(newVal){ + this.attr("currentHubId", parseInt(newVal,10)); + }, + serialize: true, + }, + currentHubId: { + set: function(newVal, resolve){ + if(newVal){ + return newVal; + } + }, + get: function(lastSet, resolve){ + if(!lastSet && resolve) { + Hub.findAll({limit: 1}).then((hubs) => { + this.attr("currentHub",hubs[0] ); + resolve(hubs[0].attr("id")); + }); + } else { + return lastSet; + } + } + }, + currentHub: { + serialize: false, + get : function(lastSetVal, setter){ + var currentHubId = this.attr('currentHubId'); + if(currentHubId) { + if(lastSetVal && lastSetVal.attr("id") === currentHubId ) { + return lastSetVal; + } else { + + Hub.findOne({id: currentHubId}).then(setter); + return null; + } + } else { + return null; + } + } + }, + hubs : { + serialize: false, + get : function(){ + return new Hub.List({}); + } + }, + loadingServices : { + serialize : false, + get : function(){ + return []; + } + }, + title : { + serialize : false, + value : 'BitHub' + }, + entityDecisions : { + get : function(){ + var currentHub = this.attr('currentHub'); + var deferred, list; + if(currentHub){ + deferred = can.Deferred(); + list = new EntityDecision.List({hubId: currentHub.id}); + this.waitFor(deferred); + list.then(function(){ + deferred.resolve(); + }, function(){ + deferred.reject(); + }); + return list; + } + } + }, + services : { + get : function(){ + var currentHub = this.attr('currentHub'); + var deferred, list; + if(currentHub){ + deferred = can.Deferred(); + list = new Service.List({embed_id: currentHub.id}); + this.waitFor(deferred); + list.then(function(){ + deferred.resolve(); + }, function(){ + deferred.reject(); + }); + return list; + } + } + }, + // Creates an empty list, returns it, but in next turn, + // calls `loadNextPage` to populate list. + bits : { + get : function(){ + var tab = this.attr('moderationTab'); + var currentHub = this.attr('currentHubId'); + var list = new Bit.List(); + var deferred = can.Deferred(); + var self = this; + + clearTimeout(this.__listRefreshTimeout); + + if(tab && currentHub){ + list.__loadingParams = { + hubId: currentHub, + decision: TAB_TO_FILTER[tab], + limit: 50, + offset: 0 + }; + setTimeout(function(){ + + var req = list.loadNextPage(); + if(req){ + req.then(function(){ + self.refreshBits(); + deferred.resolve(); + }); + } else { + deferred.resolve(); + } + }); + //this.waitFor(deferred); + return list; + } + } + }, + organizationsOpen : { + serialize: false, + value: false + } + }, + init : function(){ + $("html").data("viewModel",this); + var self = this; + can.on.call(Bit, 'decision', this.handleDecision.bind(this)); + Account.current().then(function(acc){ + //console.log('ACCOUNT', acc); + self.attr('currentAccount', acc); + }, function(){ + //console.log('ACCOUNT REQ', arguments); + window.location.href = "/"; + }); + }, + refreshBits : function(){ + var self = this; + this.__listRefreshTimeout = setTimeout(function(){ + self.attr('bits').refresh(function(newCount){ + var currentDecision = getCurrentDecision(self.attr('entityDecisions'), self.attr('moderationTab')); + if(currentDecision){ + currentDecision.attr('count', currentDecision.attr('count') + newCount); + } + }); + self.refreshBits(); + }, 30000); + }, + toggleOrganizations: function(){ + this.attr('organizationsOpen', !this.attr('organizationsOpen')); + }, + handleDecision: function(ev, oldDecision, newDecision){ + var entityDecisions = this.attr('entityDecisions'); + if(entityDecisions.isResolved()){ + can.batch.start(); + entityDecisions.getById(oldDecision).dec(); + entityDecisions.getById(newDecision).inc(); + can.batch.stop(); + } + }, + isAdmin : function(){ + return true; + }, + resetEmbed : function(){}, + changeCurrentOrganizationId : function(id){ + this.attr('currentOrganizationId', id); + }, + isLoaded : function(){ + var services = this.attr('services'); + + if(!this.attr('currentAccount')){ + return false; + } + if(this.attr('isChangingOrganization')){ + return false; + } + if(!services || (services && services.isPending())){ + return false; + } + return true; + }, + redirectToDesktop : function(ctx, el, ev){ + ev.preventDefault(); + Cookie.set('redirected-from-new-ui', 1); + window.location.href = el.attr('href'); + } +}); + +can.route("/:currentHubIdAsString", {page: 'moderation', moderationTab: 'pending'}); +can.route('/:currentHubIdAsString/:page', {moderationTab: 'pending'}); +can.route('/:currentHubIdAsString/:page/:moderationTab'); + +export default AppViewModel; diff --git a/new-bithub-client/src/card-body-wrap/card-body-wrap.js b/new-bithub-client/src/card-body-wrap/card-body-wrap.js new file mode 100644 index 0000000..21ea467 --- /dev/null +++ b/new-bithub-client/src/card-body-wrap/card-body-wrap.js @@ -0,0 +1,66 @@ +import can from "can/"; +import initView from "./card-body-wrap.stache!"; +import "./card-body-wrap.less!"; +import "can/construct/proxy/"; + +var calculateRatioPercentage = function(width, height){ + return (height/width) * 100; +}; + +var getIframeRatioClass = function(width, height){ + var ratioPercentage = calculateRatioPercentage(width, height); + if(ratioPercentage - 56 < 5){ + return 'iframe-16-9'; + } + return 'iframe-4-3'; +}; + +can.Component.extend({ + tag: 'bh-card-body-wrap', + template : initView, + scope : { + toggleExpanded : function(){ + this.attr('isExpanded', !this.attr('isExpanded')); + } + }, + events : { + inserted : function(){ + this.wrapImages(); + this.wrapIframes(); + setTimeout(this.proxy('recalculateHeight'), 1); + }, + wrapImages : function(){ + var imgs = this.element.find('img'); + imgs.each(function(){ + var $img = $(this); + if(!$img.parent().is('.img-wrap')){ + $img.wrap('
'); + } + }); + imgs.on('load', this.proxy('recalculateHeight')); + }, + wrapIframes : function(){ + var iframes = this.element.find('iframe'); + iframes.each(function(){ + var $iframe = $(this); + var height = $iframe.attr('height'); + var width = $iframe.attr('width'); + var iframeRatioClass = getIframeRatioClass(width, height); + if(!$iframe.parent().is('.iframe-wrap')){ + $iframe.wrap('
'); + } + }); + }, + recalculateHeight : function(){ + if(this.scope.attr('isExpanded') || !this.element){ + return; + } + + var wrap = this.element.find('.body-wrap'); + var scrollHeight = wrap[0].scrollHeight; + var height = wrap.height(); + + this.scope.attr('isTooTall', scrollHeight > 150 && height < scrollHeight); + } + } +}); diff --git a/new-bithub-client/src/card-body-wrap/card-body-wrap.less b/new-bithub-client/src/card-body-wrap/card-body-wrap.less new file mode 100644 index 0000000..32df6c3 --- /dev/null +++ b/new-bithub-client/src/card-body-wrap/card-body-wrap.less @@ -0,0 +1,43 @@ +bh-card-body-wrap { + display: block; + .body-wrap { + overflow: hidden; + padding: 15px; + } + .collapsed { + max-height: 150px; + } + .expand-collapse { + text-align: center; + color: #666; + cursor: pointer; + padding: 10px 0; + box-shadow: 0 0 20px 10px #fff; + position: relative; + z-index: 10; + &:hover { + color: #000; + } + } + .no-gradient { + box-shadow: none; + } + .iframe-wrap { + position: relative; + height: 0; + overflow: hidden; + iframe { + position: absolute; + top:0; + left: 0; + width: 100%; + height: 100%; + } + } + .iframe-4-3 { + padding-bottom: 75%; + } + .iframe-16-9 { + padding-bottom: 56.25%; + } +} diff --git a/new-bithub-client/src/card-body-wrap/card-body-wrap.stache b/new-bithub-client/src/card-body-wrap/card-body-wrap.stache new file mode 100644 index 0000000..90f344a --- /dev/null +++ b/new-bithub-client/src/card-body-wrap/card-body-wrap.stache @@ -0,0 +1,8 @@ +
+ +
+{{#if isTooTall}} +
+ +
+{{/if}} diff --git a/new-bithub-client/src/card-image-gallery/card-image-gallery.js b/new-bithub-client/src/card-image-gallery/card-image-gallery.js new file mode 100644 index 0000000..48c1994 --- /dev/null +++ b/new-bithub-client/src/card-image-gallery/card-image-gallery.js @@ -0,0 +1,28 @@ +import can from "can/"; +import initView from "./card-image-gallery.stache!"; +import "./card-image-gallery.less!"; + +can.Component.extend({ + tag: 'bh-card-image-gallery', + template: initView, + scope: { + init : function(){ + this.attr('currentImage', this.attr('images.0')); + }, + setCurrent : function(img){ + this.attr('currentImage', img); + }, + hasGallery : function(){ + var images = this.attr('images'); + return images && images.attr('length') > 1; + } + }, + helpers : { + isCurrent : function(img, opts){ + img = can.isFunction(img) ? img() : img; + if(img === this.attr('currentImage')){ + return opts.fn(); + } + } + } +}); diff --git a/new-bithub-client/src/card-image-gallery/card-image-gallery.less b/new-bithub-client/src/card-image-gallery/card-image-gallery.less new file mode 100644 index 0000000..6eed477 --- /dev/null +++ b/new-bithub-client/src/card-image-gallery/card-image-gallery.less @@ -0,0 +1,54 @@ +@import "../../node_modules/bootstrap/less/mixins/clearfix.less"; + +bh-card-image-gallery { + display: block; + .clearfix; + .current-image-wrap { + position: relative; + img { + max-width: 100%; + max-height: 150px; + margin: 0 auto; + display: block; + } + p.caption { + background: rgba(0,0,0,0.5); + top: 0; + left: 0; + right: 0; + position: absolute; + } + } + .image-list { + margin: 0; + margin-right: -1px; + margin-bottom: -1px; + border-top: 2px solid #fff; + li { + float: left; + width: 25%; + height: 50px; + overflow: hidden; + position: relative; + cursor: pointer; + border-right: 1px solid #fff; + border-bottom: 1px solid #fff; + &.current { + img { + opacity: 1; + } + } + } + img { + min-width: 100%; + min-height: 100%; + max-width: 100%; + max-height: 100%; + top: 0; + left: 0; + display: block; + position: absolute; + opacity: 0.5; + } + } +} diff --git a/new-bithub-client/src/card-image-gallery/card-image-gallery.stache b/new-bithub-client/src/card-image-gallery/card-image-gallery.stache new file mode 100644 index 0000000..f40f222 --- /dev/null +++ b/new-bithub-client/src/card-image-gallery/card-image-gallery.stache @@ -0,0 +1,13 @@ +
+ + {{#if currentImage.caption}} +

{{ currentImage.caption }}

+ {{/if}} +
+{{#if hasGallery}} +
    + {{#each images}} +
  • + {{/each}} +
+{{/if}} diff --git a/new-bithub-client/src/connect-liveservice.js b/new-bithub-client/src/connect-liveservice.js new file mode 100644 index 0000000..70827f5 --- /dev/null +++ b/new-bithub-client/src/connect-liveservice.js @@ -0,0 +1,48 @@ +/* globals io:true */ + +import $ from 'jquery'; + +var currentSocket; + +if(window){ + $(window).on('beforeunload', function(){ + if(currentSocket && currentSocket.close){ + currentSocket.close(); + } + }); +} + +var url = '/?embed_id={embedId}'; +var publicUrl = '/?embed_id={embedId}&tenant_name={tenantName}'; + +export default function(hubId, tenantName){ + + if(currentSocket && currentSocket.close){ + currentSocket.close(); + } + + if(typeof io !== 'undefined'){ + console.log(can.sub((tenantName ? publicUrl : url), { + embedId : hubId, + tenantName : tenantName + })) + currentSocket = io(can.sub((tenantName ? publicUrl : url), { + embedId : hubId, + tenantName : tenantName + }), { multiplex: false }); + + currentSocket.on('connect', function() { + console.log('CONNECTED!', currentSocket.id); + }); + + currentSocket.on('connect_error', function( err ) { + console.log('CONNECTION ERROR!', err.description, err.message, err.type); + }); + + currentSocket.on('disconnect', function( msg ) { + console.log('DISCONNECTION!', msg); + }); + + return currentSocket; + } +} diff --git a/new-bithub-client/src/edit_hub_name/edit_hub_name.js b/new-bithub-client/src/edit_hub_name/edit_hub_name.js new file mode 100644 index 0000000..845c560 --- /dev/null +++ b/new-bithub-client/src/edit_hub_name/edit_hub_name.js @@ -0,0 +1,66 @@ +import can from "can"; +import initView from "./edit_hub_name.stache!"; +import "./edit_hub_name.less!"; + +var KEYMAP = { + 13 : 'ENTER', + 27 : 'ESC' +}; + +export var EditHubNameVM = can.Map.extend({ + isEditing: false, + toggleHubEditing : function(val){ + val = (typeof val === 'undefined') ? !this.attr('isEditing') : val; + this.attr('isEditing', val); + }, + commitNewHubName : function(val){ + var hub = this.attr('hub'); + var name = hub.attr('name'); + if(name !== val){ + hub.attr('name', val); + hub.save(); + } + } +}); + +can.Component.extend({ + tag: 'bh-edit-hub-name', + template: initView, + scope: EditHubNameVM, + events : { + '{scope} isEditing' : function(scope, ev, newVal){ + var self = this; + if(newVal){ + setTimeout(function(){ + if(self.element){ + self.element.find('.hub-name').select().focus(); + } + }, 100); + } + }, + click : function(){ + this.scope.toggleHubEditing(); + }, + "input click" : function(el, ev){ + ev.stopImmediatePropagation(); + }, + "input keyup" : function(el, ev){ + var key = KEYMAP[ev.which]; + if(key === 'ENTER'){ + this.scope.commitNewHubName(el.val()); + } + if(key){ + this.__preventBlur = true; + this.scope.toggleHubEditing(); + } + }, + "input blur" : function(el, ev){ + if(this.__preventBlur){ + delete this.__preventBlur; + } else { + this.scope.commitNewHubName(el.val()); + this.scope.toggleHubEditing(); + } + } + } +}); diff --git a/new-bithub-client/src/edit_hub_name/edit_hub_name.less b/new-bithub-client/src/edit_hub_name/edit_hub_name.less new file mode 100644 index 0000000..169fe6b --- /dev/null +++ b/new-bithub-client/src/edit_hub_name/edit_hub_name.less @@ -0,0 +1,12 @@ +bh-edit-hub-name { + display: block; + h2 { + margin: 0; + font-size: 20px; + } + input.hub-name { + diplay: block; + margin-top: -6px; + } +} + diff --git a/new-bithub-client/src/edit_hub_name/edit_hub_name.stache b/new-bithub-client/src/edit_hub_name/edit_hub_name.stache new file mode 100644 index 0000000..4806c01 --- /dev/null +++ b/new-bithub-client/src/edit_hub_name/edit_hub_name.stache @@ -0,0 +1,9 @@ +
+ {{#if isEditing}} + + {{else}} +

{{ hub.name }}

+ + {{/if}} +
+ diff --git a/new-bithub-client/src/edit_hub_name/edit_hub_name_test.js b/new-bithub-client/src/edit_hub_name/edit_hub_name_test.js new file mode 100644 index 0000000..e117de9 --- /dev/null +++ b/new-bithub-client/src/edit_hub_name/edit_hub_name_test.js @@ -0,0 +1,77 @@ +import {EditHubNameVM} from "./edit_hub_name"; +import QUnit from "steal-qunit"; +import F from "funcunit"; +import $ from "jquery"; + +var template = can.stache(""); + +var Hub = can.Map.extend({ + save : function(){ + QUnit.ok(true, 'Save Called'); + } +}); + +var renderTemplate = function(data){ + $('#qunit-fixture').html(template(data)); +}; + +var renderTemplateAndCheckIfHubNameIsShown = function(){ + renderTemplate({ + hub : new Hub({name: 'Hub Name'}) + }); + F('bh-edit-hub-name h2').text('Hub Name', 'Hub Name is shown'); +}; + +var renderTemplateAndEnterEditingState = function(){ + renderTemplateAndCheckIfHubNameIsShown(); + F('bh-edit-hub-name').click(); +}; + +QUnit.module("Edit Hub Name Tests"); + +QUnit.test("Hub Name will be shown by default", function(){ + renderTemplateAndCheckIfHubNameIsShown(); +}); + +QUnit.test("Clicking on a component will toggle editing state", function(){ + renderTemplateAndEnterEditingState(); + F('bh-edit-hub-name input').exists('Input field is shown'); +}); + +QUnit.test("Pressing escape inside the input field will exit the editing state and revert the changes", 3, function(){ + renderTemplateAndEnterEditingState(); + F('bh-edit-hub-name input').click().type('aaa[escape]'); + F('bh-edit-hub-name input').missing('Exiting edit state'); + F('bh-edit-hub-name h2').text('Hub Name', 'Name is reverted'); +}); + +QUnit.test("Pressing enter inside the input field will save changes and exit the editing state", 4, function(){ + renderTemplateAndEnterEditingState(); + F('bh-edit-hub-name input').click().type('[\b][\b]foo[enter]'); + F('bh-edit-hub-name input').missing('Exited edit state'); + F('bh-edit-hub-name h2').text('foo', 'Hub name is updated'); +}); + +QUnit.test('Bluring the input field will save changes and exit the editing state', 4, function(){ + renderTemplateAndEnterEditingState(); + F('bh-edit-hub-name input').click().type('[\b][\b]foo'); + F('bh-edit-hub-name input').type('[\t][\t]'); + F('body').click(); + F('bh-edit-hub-name input').missing('Exited edit state'); + F('bh-edit-hub-name h2').text('foo', 'Hub name is updated'); +}); + +QUnit.test('Committing the same name will not trigger save', 0, function(){ + var editVM = new EditHubNameVM({hub: new Hub({name: 'Hub Name'})}); + editVM.commitNewHubName('Hub Name'); +}); + +QUnit.test('Toggling edit state works', function(){ + var editVM = new EditHubNameVM({hub: new Hub({name: 'Hub Name'})}); + editVM.toggleHubEditing(); + ok(editVM.attr('isEditing'), 'Editing State'); + editVM.toggleHubEditing(); + ok(!editVM.attr('isEditing'), 'Exited editing state'); + editVM.toggleHubEditing(false); + ok(!editVM.attr('isEditing'), 'Did not enter editing state'); +}); diff --git a/new-bithub-client/src/index.md b/new-bithub-client/src/index.md new file mode 100755 index 0000000..19f89ea --- /dev/null +++ b/new-bithub-client/src/index.md @@ -0,0 +1,5 @@ +@page bithub-client + +# bithub-client + +This is the documentation for bithub-client \ No newline at end of file diff --git a/new-bithub-client/src/index.stache b/new-bithub-client/src/index.stache new file mode 100755 index 0000000..8380f65 --- /dev/null +++ b/new-bithub-client/src/index.stache @@ -0,0 +1,85 @@ + + + {{title}} + + {{#switch env.NODE_ENV}} + {{#case "production"}} + + {{/case}} + + {{#default}} + {{asset "css"}} + {{/default}} + {{/switch}} + + {{asset "html5shiv"}} + + + + + + + + + + + + {{#if isLoaded}} + + + +
+
+ +

{{currentHub.name}}

+
+ {{#if services.length}} + + + {{else}} +
+
Currently you don't have any services set up. Please use the desktop interface to set them up.
+
+ {{/if}} +
+ +
+
+
+ Organizations +
+
    + {{#each currentAccount.organizations}} +
  • {{name}} {{#eq id currentOrganizationId}}{{/eq}}
  • + {{/each}} +
+
+ {{else}} +
+ +
+ {{/if}} + {{asset "inline-cache"}} + + {{#switch env.NODE_ENV}} + {{#case "production"}} + + {{/case}} + {{#default}} + + {{/default}} + {{/switch}} + + diff --git a/new-bithub-client/src/mobile-menu/mobile-menu.js b/new-bithub-client/src/mobile-menu/mobile-menu.js new file mode 100644 index 0000000..e395425 --- /dev/null +++ b/new-bithub-client/src/mobile-menu/mobile-menu.js @@ -0,0 +1,9 @@ +import can from "can"; +import template from "./mobile-menu.stache!"; + +import "./mobile-menu.less!"; + +export default can.Component.extend({ + tag : 'bh-mobile-menu', + template: template +}); diff --git a/new-bithub-client/src/mobile-menu/mobile-menu.less b/new-bithub-client/src/mobile-menu/mobile-menu.less new file mode 100644 index 0000000..5abb5e1 --- /dev/null +++ b/new-bithub-client/src/mobile-menu/mobile-menu.less @@ -0,0 +1,33 @@ +bh-mobile-menu { + ul { + li { + font-size: 14px; + border-bottom: 1px solid #576a74; + &:last-child { + border-bottom: none; + } + } + a { + color: white; + line-height: 20px; + padding: 15px 20px; + display: block; + &:hover { + color: white; + background: rgba(0,0,0,0.2); + } + } + &:before { + content: ""; + float: left; + width: 1px; + margin-left: -1px; + height: calc(100% + 1px); + } + &:after { + content: ""; + display: block; + clear: both; + } + } +} diff --git a/new-bithub-client/src/mobile-menu/mobile-menu.stache b/new-bithub-client/src/mobile-menu/mobile-menu.stache new file mode 100644 index 0000000..c6f0bd3 --- /dev/null +++ b/new-bithub-client/src/mobile-menu/mobile-menu.stache @@ -0,0 +1,8 @@ +
+ +
diff --git a/new-bithub-client/src/models/account.js b/new-bithub-client/src/models/account.js new file mode 100644 index 0000000..30e50f9 --- /dev/null +++ b/new-bithub-client/src/models/account.js @@ -0,0 +1,37 @@ +import can from "can"; +import Organization from "./organization"; + +import "can/map/define/"; +import "can/construct/super/"; + +export default can.Model.extend({ + findOne : '/api/v3/current/account', + update: 'PUT /api/v3/current/account', + current : function(){ + return this.findOne({}); + } +}, { + define : { + + organizations : { + Type : Organization.List + } + }, + hasMultipleOrganizations : function(){ + var organizations = this.attr('organizations'); + return organizations && organizations.attr('length') > 1; + }, + serialize: function() { + var data = this._super(); + + if(data.current_password && !data.password){ + data.password = ""; + } + + if(data.password && !data.password_confirmation){ + data.password_confirmation = ""; + } + + return { account: data }; + } +}); diff --git a/new-bithub-client/src/models/analytics.js b/new-bithub-client/src/models/analytics.js new file mode 100644 index 0000000..cbb19e7 --- /dev/null +++ b/new-bithub-client/src/models/analytics.js @@ -0,0 +1,95 @@ +import can from "can"; +import Service from "./service"; +import moment from "moment"; + +import "can/map/define/"; +//import "components/service-config-formatter/"; + +var TOOLTIP = can.stache(''); + +var fillInMissingTimepoints = function(points, length){ + var firstRun = true; + + while(points.length < length){ + if(firstRun){ + points.unshift(0); + firstRun = false; + } else { + points.unshift(null); + } + + } + return points; +}; + +var alphaVersion = function(color){ + return 'rgba' + color.substring(3, color.length - 1) + ', .2)'; +}; + +var Analytics = can.Model.extend({ + findAll : '/api/v3/analytics?source_type={sourceType}&resolution={resolution}&owner_id={ownerId}' +}, { + define : { + source : { + Type: Service + } + } +}); + +Analytics.List = Analytics.List.extend({ + graphData : function(type){ + var length = this.attr('length'); + var serviceTimepoints = {}; + var service; + var timepoints; + var isLongest = false; + var data = []; + var longestPointsLengthLabels = []; + var i; + + for(i = 0; i < length; i++){ + service = this.attr(i + '.source'); + timepoints = this.attr(i + '.timepoints'); + + serviceTimepoints[service.id] = []; + + isLongest = (timepoints.length > longestPointsLengthLabels.length); + + if(isLongest){ + longestPointsLengthLabels = []; + } + + for(var j = 0; j < timepoints.length; j++){ + serviceTimepoints[service.id].push(timepoints[j][type]); + if(isLongest){ + longestPointsLengthLabels.push(moment(timepoints[j].measured_at).fromNow()); + } + + } + } + + for(var k in serviceTimepoints){ + serviceTimepoints[k] = fillInMissingTimepoints(serviceTimepoints[k], longestPointsLengthLabels.length); + } + + for(i = 0; i < length; i++){ + service = this.attr(i + '.source'); + data.push({ + label : can.trim(TOOLTIP(service).firstChild.innerText), + fillColor: alphaVersion(service.attr('graphColor')), + strokeColor: service.attr('graphColor'), + pointColor: service.attr('graphColor'), + pointHighlightFill: "#fff", + pointHighlightStroke: service.attr('graphColor'), + data: serviceTimepoints[service.id] + }); + } + + return { + labels : longestPointsLengthLabels, + datasets: data + }; + } +}); + +export default Analytics; diff --git a/new-bithub-client/src/models/app-state.js b/new-bithub-client/src/models/app-state.js new file mode 100644 index 0000000..5ac5030 --- /dev/null +++ b/new-bithub-client/src/models/app-state.js @@ -0,0 +1,78 @@ +import $ from "jquery"; +import can from "can"; +import Models from "models/"; +import route from "can/route/"; + +import "can/map/define/"; + + +var AppState = can.Map.extend({ + define : { + page : { + set : function(val){ + return val; + } + }, + tab : { + get : function(lastSetVal){ + return lastSetVal || "inbox"; + } + }, + currentBrand : { + serialize: false + }, + currentSubscription : { + serialize: false + }, + currentAccount : { + serialize: false + }, + currentOrganization: { + serialize: false + }, + currentHub: { + serialize: false, + }, + hubs : { + serialize: false + }, + loadingServices : { + serialize : false, + get : function(){ + return []; + } + }, + + }, + isAdmin : function(){ + return true; + }, + resetEmbed : function(){} +}); + +var appState = new AppState(); +route.map(appState); +route("", {page: "moderation"}); +route.ready(); + + +$.when( + Models.Brand.findOne({}), + Models.Subscription.findOne({}), + Models.Account.current(), + Models.Organization.current(), + Models.Hub.findAll({}) +).done(function(brand, subscription, account, organization, hubs){ + + appState.attr({ + currentBrand: brand, + currentSubscription: subscription, + currentAccount: account, + currentOrganization: organization, + hubs: hubs, + currentHub: hubs[0], + }); + +}); + +export default appState; diff --git a/new-bithub-client/src/models/appstate.js b/new-bithub-client/src/models/appstate.js new file mode 100644 index 0000000..601d5d2 --- /dev/null +++ b/new-bithub-client/src/models/appstate.js @@ -0,0 +1,291 @@ +import can from "can"; +import Models from 'models/'; +import _reduce from 'lodash/collection/reduce'; +import connectLiveService from 'connect-liveservice'; +import Communicator from 'communicator/'; +import 'can/map/define/'; +import 'can/construct/proxy/'; +import 'can/map/delegate/'; + +var CURRENT_IFRAME; + +var PAGE_TITLES = { + 'hub-list' : 'Hub List', + 'services' : 'Services', + 'integration' : 'Integration', + 'moderation' : 'Moderation', + 'analytics' : 'Analytics', + 'payments' : 'Payments', + 'organization-settings' : 'Organization Accounts', + 'user-settings' : 'User Settings' +}; + +var getPageTitle = function(val, appState){ + if(val === 'sidebar'){ + val = appState.attr('panel') || 'services'; + } + + return PAGE_TITLES[val]; +}; + +var setTitle = function(val, appState){ + $('title').html('BitHub — ' + getPageTitle(val, appState)); +}; + +export default can.Map.extend({ + define : { + page : { + value : 'hub-list', + set : function(val){ + this.removeAttr('customPreset'); + setTitle(val, this); + return val; + } + }, + panel : { + set : function(val){ + setTitle(val, this); + return val; + } + }, + currentSubscription : { + serialize: false + }, + currentAccount: { + serialize: false + }, + currentOrganization : { + serialize: false + }, + hubId : { + set : function(val){ + var liveService = connectLiveService(val, this.attr('currentBrand').attr('tenant_name')); + var self = this; + + this.attr('bits').splice(0); + + if(liveService){ + + + liveService.on('services', can.proxy(Models.Service.messageFromLiveService, Models.Service)); + + liveService.on('services', function(msg){ + var loadingServices = self.attr('loadingServices'); + var index, service; + if(typeof msg === 'string'){ + msg = JSON.parse(msg); + } + + if(msg.service.empty_results || msg.service.has_errors){ + service = loadingServices.filter(function(s){ + return s.id === msg.service.id; + })[0]; + index = loadingServices.indexOf(service); + if(index > -1){ + loadingServices.splice(index, 1); + } + } + }); + } + + return val; + }, + remove : function(){ + CURRENT_IFRAME = null; + this.attr('bits').splice(0); + } + }, + embedType : { + get : function(){ + if(this.attr('page') === 'sidebar'){ + if(this.attr('panel') === 'integration'){ + return 'preview'; + } + return 'admin'; + } + }, + serialize: false + }, + iframe : { + get : function(){ + var src = this.attr('iframeSrc'); + var iframe; + + if(src){ + if(!CURRENT_IFRAME){ + iframe = $(''); + CURRENT_IFRAME = iframe[0]; + } + + return CURRENT_IFRAME; + } + } + }, + iframeSrc : { + get : function(){ + var currentBrand = this.attr('currentBrand'); + var hubId = this.attr('hubId'); + + if(hubId && currentBrand){ + return this.attr('preset').url(currentBrand.attr('tenant_name'), hubId); + } + }, + serialize: false + }, + adminPreset : { + value : Models.Preset.ADMIN, + serialize: false + }, + defaultPreviewPreset : { + value : Models.Preset.PREVIEW, + serialize: false + }, + preset : { + get : function(){ + var embedType = this.embedType(); + var customPreset; + + if(embedType === 'admin'){ + return this.attr('adminPreset'); + } else { + customPreset = this.attr('customPreset'); + return customPreset || this.attr('defaultPreviewPreset'); + } + }, + set : function(val){ + var embedType = this.embedType(); + var adminPreset = this.attr('adminPreset'); + + if(embedType === 'admin'){ + adminPreset.attr('config').attr(val.attr ? val.attr() : val); + return val; + } + }, + serialize : function(){ + var embedType = this.embedType(); + var adminPreset = this.attr('adminPreset'); + var adminParams; + if(adminPreset){ + adminPreset.attr(); + } + + + if(embedType === 'admin'){ + adminParams = { + order: adminPreset.attr('config.order'), + filter: adminPreset.attr('config.filter') + }; + + if(adminPreset.attr('config.service_id')){ + adminParams.service_id = adminPreset.attr('config.service_id'); + } + + return adminParams; + } + } + }, + customPreset: { + serialize: false + }, + hub : { + serialize : false, + get : function(lastSetValue, setAttrValue){ + Models.Hub.findOne({id: this.attr('hubId')}) + .then(function(hub){ + setAttrValue(hub); + }); + } + }, + services : { + get : function() { + return new Models.Service.List({ + embed_id: this.attr('hubId') + }); + } + }, + sidebarIsExpanded : { + value : true, + serialize: false + }, + loadingServices : { + value : [], + serialize: false + }, + bits : { + Value : Models.Bit.List, + serialize: false + }, + scrollTop : { + value : 0, + serialize: false + }, + scrollHeight: { + value : 0, + serialize: false + }, + currentBrand : { + serialize: false + } + }, + init : function(){ + var self = this; + this.communicator = Communicator.bind(this.compute('iframe'), { + loadedBits : function(payload){ + self.bitsWereLoaded(payload); + } + }); + }, + updateIframeAttrs : function(){ + var preset = this.attr('preset'); + var currentBrand = this.attr('currentBrand'); + var hubId = this.attr('hubId'); + var newAttrs; + + if(preset && currentBrand && hubId){ + newAttrs = preset.embedAttrs(currentBrand.attr('tenant_name'), hubId); + this.communicator.send('updateAttrs', newAttrs); + } + }, + resetEmbed : function(){ + this.communicator.send('reset'); + }, + bitsWereLoaded : function(serviceIds){ + var loadingServices = this.attr('loadingServices'); + var loadingServicesByIds = _reduce(loadingServices, function(acc, service){ + acc[service.attr('id') + ""] = service; + return acc; + }, {}); + var index; + + for(var i = 0; i < serviceIds.length; i++){ + if(loadingServicesByIds[serviceIds[i]]){ + index = loadingServices.indexOf(loadingServicesByIds[serviceIds[i]]); + loadingServices.splice(index, 1); + } + } + }, + isAdminEmbed : function(){ + var preset = this.attr('preset'); + return preset && preset.attr('config.view') === 'admin'; + }, + theme : function(){ + var preset = this.attr('preset'); + return (preset && preset.attr('config.theme')) || 'light'; + }, + isSidebar : function(){ + return this.attr('page') === 'sidebar' && this.attr('hubId'); + }, + embedType : function(){ + return this.attr('embedType'); + }, + embedTypeTitle : function(){ + var titles = { + admin: 'Administration', + preview: 'Preview' + }; + return titles[this.embedType()]; + }, + isAnalyticsPageActive : function(){ + return this.attr('page') === 'analytics'; + }, +}); diff --git a/new-bithub-client/src/models/bit.js b/new-bithub-client/src/models/bit.js new file mode 100644 index 0000000..3218197 --- /dev/null +++ b/new-bithub-client/src/models/bit.js @@ -0,0 +1,202 @@ +import can from "can"; +import moment from "moment"; + +import "can/list/promise/"; +import "can/map/define/"; + +var Bit = can.Model.extend({ + resource : '/api/v4/embeds/{hubId}/entities', +}, { + define : { + thread_updated_at: { + set : function(val){ + var momentThreadUpdatedAt = moment(val); + this.attr({ + formattedThreadUpdatedAt: momentThreadUpdatedAt.format('LL'), + formattedThreadUpdatedAtDate: momentThreadUpdatedAt.format('YYYY-MM-DD') + }); + return val; + } + } + }, + isTumblrImage : function(){ + return this.isPhoto() && this.isTumblr(); + }, + isInstagramImage : function(){ + return this.isPhoto() && this.attr('feed_name') === 'instagram'; + }, + isPhoto : function(){ + return this.attr('type_name') === 'photo'; + }, + isTumblr : function(){ + return this.attr('feed_name') === 'tumblr'; + }, + isTwitterFollow : function(){ + return this.attr('feed_name') === 'twitter' && this.attr('type_name') === 'follow'; + }, + isYoutube : function(){ + return this.attr('feed_name') === 'youtube'; + }, + youtubeEmbedURL : function(){ + return this.attr('url').replace(/watch\?v=/, 'embed/'); + } +}); + + +Bit.DECISIONS = ['pending', 'starred', 'deleted', 'approved']; + +var makeBitAction = function(decision){ + var templateUrl = '/api/v4/embeds/{hubId}/entities/{id}/decide/?decision={decision}'; + return function(hubId){ + var realDecision = decision; + var currentDecision = this.attr('decision'); + + if(decision === currentDecision){ + realDecision = 'pending'; + } + + var url = can.sub(templateUrl, { + hubId : hubId, + id : this.attr('id'), + decision: realDecision + }); + + return $.ajax(url, { + dataType: 'json', + type: 'PUT' + }).then(function(data){ + can.trigger(Bit, 'decision', [currentDecision, realDecision]); + var bit = Bit.model(data); + bit.updated(); + }); + }; +}; + +for(var i = 0; i < Bit.DECISIONS.length; i++){ + Bit.prototype['decide' + can.capitalize(Bit.DECISIONS[i])] = makeBitAction(Bit.DECISIONS[i]); +} + +var checkIfBitIsBelowCurrentBit = function(bit, currentBit){ + if(!currentBit){ + return false; + } + if(currentBit.is_pinned){ + return true; + } + return bit.thread_updated_ts < currentBit.thread_updated_ts; +}; + +var isFullBit = function(bit){ + return !!bit.created_at; +}; + +var buffer = (function(){ + var _buffer = []; + var _currentSweeper; + + return { + add : function(bit){ + _buffer.push(bit); + if(!_currentSweeper){ + _currentSweeper = setTimeout(function(){ + var localBuffer = _buffer.splice(0).reverse(); + for(var i = 0; i < localBuffer.length; i++){ + can.trigger(Bit, 'lifecycle', [localBuffer[i]]); + } + _currentSweeper = null; + }, 5000); + } + } + }; +})(); + +Bit.messageFromLiveService = function(msg){ + var parsed = JSON.parse(msg); + parsed._isFromLiveService = true; + + if(this.store[parsed.id]){ + this.store[parsed.id].attr(parsed); + } else if(isFullBit(parsed)){ + buffer.add(this.model(parsed)); + } + if(!parsed.is_approved){ + can.trigger(Bit, 'disapproved', [this.store[parsed.id]]); + } +}; + +Bit.List = Bit.List.extend({ + place : function(bit){ + var index = -1; + var currentIndex, currentBit; + + this.attr('length'); + + currentIndex = this.indexOf(bit); + + // if it exists in the list remove it because we are changing the order + if(currentIndex > -1){ + this.splice(currentIndex, 1); + } + + if(bit.attr('is_pinned')){ + do { + index++; + currentBit = this.attr(index); + } while(currentBit && currentBit.attr('is_pinned')); + } else { + do { + index++; + currentBit = this.attr(index); + } while(checkIfBitIsBelowCurrentBit(bit, currentBit)); + } + + this.splice(index, 0, bit); + }, + remove : function(bit){ + var index = this.indexOf(bit); + if(index > -1){ + this.splice(index, 1); + } + }, + loadNextPage: function(){ + var length = this.attr('length'); + var count = this.__totalCount; + var self = this; + + if(typeof count !== 'undefined' || length < this.__totalCount){ + this.__loadingParams.offset = length; + } + if(!this.attr('isCurrentlyLoading') && (!this.__totalCount || length < this.__totalCount)){ + this.attr('isCurrentlyLoading', true); + return Bit.findAll(this.__loadingParams).then(function(data){ + self.__totalCount = data.count; + self.push.apply(self, data); + setTimeout(function(){ + self.attr('isCurrentlyLoading', false); + }); + }); + } + }, + refresh : function(cb){ + var params = this.__loadingParams; + var self = this; + Bit.findAll(params).then(function(data){ + var current; + var counter = 0; + for(var i = 0; i < data.length; i++){ + current = data[i]; + if(self.indexOf(current) === -1){ + self.unshift(current); + counter++; + } + } + cb(counter); + }); + + }, + isLoading : function(){ + return this.attr('length') === 0 && this.attr('isCurrentlyLoading'); + } +}); + +export default Bit; diff --git a/new-bithub-client/src/models/brand.js b/new-bithub-client/src/models/brand.js new file mode 100644 index 0000000..13cedf6 --- /dev/null +++ b/new-bithub-client/src/models/brand.js @@ -0,0 +1,5 @@ +import can from "can"; + +export default can.Model.extend({ + findOne : '/api/v3/brands/current' +}, {}); diff --git a/new-bithub-client/src/models/embed_appstate.js b/new-bithub-client/src/models/embed_appstate.js new file mode 100644 index 0000000..03ab5c3 --- /dev/null +++ b/new-bithub-client/src/models/embed_appstate.js @@ -0,0 +1,122 @@ +import can from "can"; +import Bit from "models/bit"; +import connectLiveService from "connect-liveservice"; +import "can/map/define/"; + +var addDefaultAttrs = function(params){ + var defaultParams = { + view: 'public', + theme: 'light', + live: false + }; + return can.extend(defaultParams, params); +}; + +var liveService; + +export default can.Map.extend({ + define : { + live : { + set : function(val){ + return (val === true || val === 'true'); + } + }, + hub : { + serialize : false, + }, + bits : { + Value : Bit.List, + serialize: false + }, + currentBrand : { + serialize: false + }, + }, + setAttrs : function(attrs){ + this.attr(addDefaultAttrs(attrs)); + }, + init : function(){ + this.setDefaultParams(); + }, + isLive : function(){ + return this.attr('live'); + }, + isPublic : function(){ + return !this.isAdmin(); + }, + isGroupedByDate : function(){ + return this.attr('order') === 'grouped-by-date'; + }, + showPoweredBy : function(){ + return this.isPublic(); + }, + reset : function(){ + can.batch.start(); + this.setDefaultParams(); + this.bits.splice(0); + can.batch.stop(); + }, + getView : function(){ + if(this.isAdmin()){ + return 'admin'; + } + return 'public'; + }, + connectLiveService : function(){ + + var hubId = this.attr('hubId'); + liveService = connectLiveService(hubId, this.attr('tenant')); + + if(liveService){ + console.log('LIVESERVICE ENTITIES', liveService); + + liveService.on('entities', can.proxy(Bit.messageFromLiveService, Bit)); + } + }, + getParams: function(){ + var hubId = this.attr('hubId'); + var params = {}; + var tenant = this.attr('tenant'); + var isPublic = this.isPublic(); + var filter = this.attr('filter'); + var serviceId = this.attr('service_id'); + var imageOnly = this.attr('image_only'); + + imageOnly = imageOnly === true || imageOnly === 'true'; + + params.view = this.getView(); + + if(isPublic){ + params.tenant_name = tenant; + } else { + params.order = this.attr('order') || "created_at:desc"; + if(params.order === 'grouped-by-date'){ + params.order = 'preview'; + } + if(filter){ + params.show = filter; + } + if(serviceId){ + params.service_id = serviceId; + } + } + + if(imageOnly){ + params.image_only = true; + } + + + params.hubId = hubId; + + return params; + }, + setDefaultParams : function(){ + this.attr('params', { + offset: 0, + limit: 50 + }); + }, + isAdmin : function(){ + return this.attr('hub') && this.attr('view') === 'admin'; + } +}); diff --git a/new-bithub-client/src/models/entity-decision.js b/new-bithub-client/src/models/entity-decision.js new file mode 100644 index 0000000..742fbf5 --- /dev/null +++ b/new-bithub-client/src/models/entity-decision.js @@ -0,0 +1,26 @@ +import can from "can"; +import "can/list/promise/"; + +var EntityDecision = can.Model.extend({ + findAll : '/api/v4/embeds/{hubId}/entities/stats' +}, { + dec: function(){ + this.attr('count', this.attr('count') - 1); + }, + inc: function(){ + this.attr('count', this.attr('count') + 1); + } +}); + +EntityDecision.List = EntityDecision.List.extend({ + getById : function(id){ + var length = this.attr('length'); + for(var i = 0; i < length; i++){ + if(this[i].id === id){ + return this[i]; + } + } + } +}); + +export default EntityDecision; diff --git a/new-bithub-client/src/models/filter.js b/new-bithub-client/src/models/filter.js new file mode 100644 index 0000000..3c24d08 --- /dev/null +++ b/new-bithub-client/src/models/filter.js @@ -0,0 +1,91 @@ +import can from "can"; +import NatlangQuery from "./natlang-query"; +import "can/map/define/"; +import "can/construct/super/"; + +var ModerationRuleset = can.Model.extend({ + resource : "/api/v3/filters", + destroy : function(id, data){ + return $.ajax({ + url : "/api/v3/filters/" + id + "?embed_id=" + data.filter.embed_id, + type : "DELETE" + }); + } +}, { + define : { + natlang_queries: { + Value : NatlangQuery.List, + set : function(val){ + return new NatlangQuery.List(can.map(val, function(v){ + return NatlangQuery.model(v); + })); + } + }, + }, + addQuery : function(){ + this.natlang_queries.push(new NatlangQuery()); + }, + removeQuery : function(filter){ + var natlang = this.attr('natlang_queries'); + var index = natlang.indexOf(filter); + if(index > -1){ + natlang.splice(index, 1); + } + }, + serialize : function(){ + var data = this._super.apply(this, arguments); + return { + filter: data + }; + }, + markToDestroy : function(){ + this.attr('__shouldDelete', true); + }, + saveOrDestroy : function(){ + if(this.attr('__shouldDelete')){ + return this.destroy(); + } + return this.save(); + } +}); + +ModerationRuleset.List = ModerationRuleset.List.extend({ + blocking : function(){ + return this.filtersByAction('block'); + }, + approving : function(){ + return this.filtersByAction('approve'); + }, + filtersByAction : function(action){ + var list = new this.constructor(); + var length = this.attr('length'); + var current; + for(var i = 0; i < length; i++){ + current = this.attr(i); + if(current.attr('action') === action){ + list.push(current); + } + } + list.attr('action', action); + return list; + }, + addFilter : function(embedId){ + var filter = new ModerationRuleset({action: this.attr('action'), embed_id: embedId}); + filter.addQuery(); + this.push(filter); + }, + removeFilter : function(filter){ + var index = this.indexOf(filter); + + if(index > -1){ + this.splice(index, 1); + } + }, + saveOrDestroy : function(){ + return $.when.apply($, can.map(this, function(f){ + f.saveOrDestroy(); + })); + } +}); + +export default ModerationRuleset; diff --git a/new-bithub-client/src/models/fixtures/fixtures.js b/new-bithub-client/src/models/fixtures/fixtures.js new file mode 100755 index 0000000..424b956 --- /dev/null +++ b/new-bithub-client/src/models/fixtures/fixtures.js @@ -0,0 +1 @@ +import fixture from 'can-fixture'; diff --git a/new-bithub-client/src/models/hub.js b/new-bithub-client/src/models/hub.js new file mode 100644 index 0000000..f58241f --- /dev/null +++ b/new-bithub-client/src/models/hub.js @@ -0,0 +1,48 @@ +import can from "can"; +import ServiceModel from './service'; +import 'can/list/promise/'; +import 'can/construct/super/'; +import 'can/map/backup/'; +import 'can/map/define/'; + +var Bit = can.Model.extend({ + resource : '/api/v3/embeds', +}, { + define : { + services : { + get : function(){ + return new ServiceModel.List({embed_id: this.attr('id')}); + } + } + }, + serialize : function(){ + return { + embed : this._super.apply(this, arguments) + }; + }, + moderate : function(){ + return $.ajax({ + type : 'POST', + url : '/api/v3/embeds/' + this.attr('id') + '/moderate' + }); + }, + publish : function(){ + return $.ajax({ + type: 'PUT', + url: '/api/v3/embeds/' + this.attr('id') + '/publish' + }).then(function(data){ + Bit.model(data); + }); + }, + unpublish : function(){ + return $.ajax({ + type: 'PUT', + url: '/api/v3/embeds/' + this.attr('id') + '/unpublish' + }).then(function(data){ + Bit.model(data); + }); + } + +}); + +export default Bit; diff --git a/new-bithub-client/src/models/identity.js b/new-bithub-client/src/models/identity.js new file mode 100644 index 0000000..e9932cf --- /dev/null +++ b/new-bithub-client/src/models/identity.js @@ -0,0 +1,20 @@ +import can from "can"; +import "can/list/promise/"; + +var identities; + +export default can.Model.extend({ + resource : '/api/v3/identities', + getAll : function(){ + return this.reloadAll(); + }, + reloadAll : function(){ + var def = new this.List({}); + + def.then(function(data){ + identities = data; + }); + + return def; + } +}, {}); diff --git a/new-bithub-client/src/models/interaction_event.js b/new-bithub-client/src/models/interaction_event.js new file mode 100644 index 0000000..a015e95 --- /dev/null +++ b/new-bithub-client/src/models/interaction_event.js @@ -0,0 +1,127 @@ +import can from "can"; +import moment from "moment"; +import "can/construct/super/"; + +var wrapCreate = function(data){ + return { + interaction: data + }; +}; + +var InteractionEvent = can.Model.extend({ + create : 'POST /api/v3/interactions', + findAll : 'GET /api/v3/interactions', + + createScrollInteraction : function(tenant_name, hubId){ + return this.create(wrapCreate({ + tenant_name: tenant_name, + primary_source_id: hubId, + primary_source_type: 'Embed', + event_type: 'scroll' + })); + }, + createLinkClickedInteraction : function(tenant_name, hubId, entityId){ + return this.create(wrapCreate({ + tenant_name: tenant_name, + primary_source_id: hubId, + primary_source_type: 'Embed', + secondary_source_id: entityId, + secondary_source_type: 'Entity', + event_type: 'link' + })); + }, + createEntitySharedInteraction : function(tenant_name, hubId, entityId, target){ + return this.create(wrapCreate({ + tenant_name: tenant_name, + primary_source_id: hubId, + primary_source_type: 'Embed', + secondary_source_id: entityId, + secondary_source_type: 'Entity', + event_type: 'share', + event_subtype: target + })); + } +}, {}); + +var fillZeroes = function(data, length){ + while(data.length < length){ + data.unshift(0); + } + return data; +}; + +InteractionEvent.List = InteractionEvent.List.extend({ + totalShareInteractionsGraphData: function(){ + var length = this.attr('length'); + var labels = []; + var data = []; + var i; + for(i = 0; i < length; i++){ + labels.push(moment(this.attr(i + '.created_at')).fromNow()); + data.push(this.attr(i + '.volume')); + } + + return { + datasets: [{ + data: data, + label: "Share count", + strokeColor: '#f30', + fillColor: '#fff' + }], + labels: labels + }; + }, + linkInteractionsGraphData : function(){ + return this.totalShareInteractionsGraphData(); + }, + scrollInteractionsGraphData : function(){ + return this.totalShareInteractionsGraphData(); + }, + perNetworkShareInteractionsGraphData : function(){ + var length = this.attr('length'); + var labels = {}; + var data = {}; + var longestLabels = []; + var datasets = []; + var i, k, current, currentSubtype; + + for(i = 0; i < length; i++){ + current = this.attr(i); + currentSubtype = current.attr('event_subtype'); + if(!data[currentSubtype]){ + data[currentSubtype] = []; + } + if(!labels[currentSubtype]){ + labels[currentSubtype] = []; + } + data[currentSubtype].push(current.attr('volume')); + labels[currentSubtype].push(moment(current.attr('created_at')).fromNow()); + } + + for(k in labels){ + if(labels[k].length > longestLabels.length){ + longestLabels = labels[k]; + } + } + + for(k in data){ + if(data[k].length < longestLabels.length){ + data[k] = fillZeroes(data[k], longestLabels.length); + } + datasets.push({ + label: k, + data: data[k], + strokeColor: '#f30', + fillColor: 'rgba(255,255,255,0)' + }); + } + + return { + labels: longestLabels, + datasets: datasets + }; + + } +}); + +export default InteractionEvent; diff --git a/new-bithub-client/src/models/models.js b/new-bithub-client/src/models/models.js new file mode 100644 index 0000000..9294c5e --- /dev/null +++ b/new-bithub-client/src/models/models.js @@ -0,0 +1,27 @@ +import Hub from './hub'; +import Service from './service'; +import Bit from './bit'; +import Identity from './identity'; +import Suggestion from './suggestion'; +import Brand from './brand'; +import Preset from './preset'; +import Analytics from './analytics'; +import Subscription from './subscription'; +import Filter from './filter'; +import Account from './account'; +import Organization from "./organization"; + +export default { + Hub : Hub, + Service : Service, + Bit : Bit, + Identity : Identity, + Suggestion : Suggestion, + Brand : Brand, + Preset: Preset, + Analytics : Analytics, + Subscription : Subscription, + Filter : Filter, + Account : Account, + Organization: Organization +}; diff --git a/new-bithub-client/src/models/natlang-query.js b/new-bithub-client/src/models/natlang-query.js new file mode 100644 index 0000000..db459d8 --- /dev/null +++ b/new-bithub-client/src/models/natlang-query.js @@ -0,0 +1,36 @@ +import can from "can"; +import "can/map/define/"; + +export default can.Model.extend({}, { + define : { + operation : { + set : function(val){ + var typeAndOp = val.split(":"); + var type = typeAndOp.shift(); + var op = typeAndOp.shift(); + + this.attr({ + is_negated: (type !== 'pos'), + op : op + }); + }, + get : function(){ + var type = this.attr('is_negated') ? 'neg' : 'pos'; + var op = this.attr('op'); + return [type, op].join(':'); + } + }, + attr_name : { + value : 'content' + }, + op : { + value : 'contains_all', + set : function(val){ + return val; + } + }, + is_negated : { + value : false + } + } +}); diff --git a/new-bithub-client/src/models/organization.js b/new-bithub-client/src/models/organization.js new file mode 100644 index 0000000..4a89c30 --- /dev/null +++ b/new-bithub-client/src/models/organization.js @@ -0,0 +1,35 @@ +import can from "can"; + +export default can.Model.extend({ + findOne : '/api/v3/current/organization', + update: 'PUT /api/v3/current/organization', + current : function(){ + return this.findOne({}); + }, + choose : function(id){ + return $.ajax({ + url: '/api/v3/current/organization/choose?id=' + id, + type: 'PUT' + }); + } +}, { + invite : function(email){ + var def = can.Deferred(); + $.post('/api/v3/current/organization/accounts', {account: {email: email}}).then(function(res){ + def.resolve(res.account); + }, function(){ + $.post('/accounts/invitation', {account: {email: email}}).then(function(res){ + def.resolve(res); + }, function(){ + def.reject(); + }); + }); + return def; + }, + addInvitation: function(invitation){ + if(!this.attr('invitations')){ + this.attr('invitations', []); + } + this.attr('invitations').push(invitation); + } +}); diff --git a/new-bithub-client/src/models/preset.js b/new-bithub-client/src/models/preset.js new file mode 100644 index 0000000..b2bf932 --- /dev/null +++ b/new-bithub-client/src/models/preset.js @@ -0,0 +1,82 @@ +/* globals EMBED_ENDPOINT:true */ + +import can from "can"; + +import 'can/construct/super/'; +import 'can/map/define/'; +import 'can/list/promise/'; +import 'can/map/backup/'; + +var EMBED_TEMPLATE = '{hubName} Embed'; + +var Preset = can.Model.extend({ + resource: '/api/v3/presets', +}, { + define : { + config : { + value : function(){ + return { + theme: 'light', + view: 'public' + }; + } + } + }, + embedAttrs : function(tenantName, hubId){ + return can.extend({ + hubId: hubId, + tenant: tenantName + }, this.serialize().preset.config || {}); + }, + url : function(tenantName, hubId){ + var attrs = this.embedAttrs(tenantName, hubId); + return '/embed?' + can.param(attrs); + }, + fullUrl : function(tenantName, hubId){ + return can.sub("http://{embedEndpoint}{embedUrl}", { + embedEndpoint: EMBED_ENDPOINT, + embedUrl: this.url(tenantName, hubId) + }); + }, + embedCode : function(tenantName, hubId, hubName){ + return can.sub(EMBED_TEMPLATE, { + embedEndpoint : EMBED_ENDPOINT, + embedUrl: this.url(tenantName, hubId), + hubName: hubName + }); + }, + serialize : function(){ + var data = this._super.apply(this, arguments); + if(!data.config){ + data.config = {}; + } + if(!data.config.view){ + data.config.view = 'public'; + } + if(!data.config.live){ + delete data.config.live; + } + + return { + preset: data + }; + } +}); + +Preset.ADMIN = new Preset({ + config: { + live: true, + view: 'admin', + order: 'grouped-by-date', + filter: 'all' + } +}); + +Preset.PREVIEW = new Preset({ + name : 'Default Preset', + config: { + live: false + } +}); + +export default Preset; diff --git a/new-bithub-client/src/models/service.js b/new-bithub-client/src/models/service.js new file mode 100644 index 0000000..ba36000 --- /dev/null +++ b/new-bithub-client/src/models/service.js @@ -0,0 +1,350 @@ +import can from "can"; +import _keys from "lodash-amd/modern/object/keys"; + +import 'can/list/promise/'; +import 'can/map/define/'; +import 'can/construct/super/'; + +var RELOAD_TIMEOUTS = {}; + +var isCelluloidError = function(klass){ + return (/celluloid/).test(klass.toLowerCase()); +}; + +var isConfigError = function(klass){ + return (/configerror/).test(klass.toLowerCase()); +}; + +var getErrorMessage = (function(){ + var MESSAGES = { + autherror: "We are unable to authorize with your service credentials. Are you sure you have rights to access this content?", + remoteerror: "Service is currently unavailable. We will try to load data again later.", + unknownerror: "We are so sorry. Unknown error occured when we tried to load data from this service. We have been notified about this error, and we'll try to fix it as soon as possible.", + ratelimiterror: "Due to number of services authorized with the same account we are unable to load data from this service at the moment. We will try again soon." + }; + return function(error){ + var klass = error.klass.toLowerCase(); + return MESSAGES[klass] || error.message; + }; +})(); + + +var convertHexToRgb = function(hex){ + var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + var r, g, b; + if(result){ + r = parseInt(result[1], 16); + g = parseInt(result[2], 16); + b = parseInt(result[3], 16); + var res = 'rgb(' + r + ',' + g + ',' + b + ')'; + return res; + } + return 'rgb(0,0,0)'; +}; + +var GRAPH_COLORS = { + disqus : convertHexToRgb('#ffe842'), + facebook : convertHexToRgb('#80a2bd'), + foursquare : convertHexToRgb('#655557'), + github : convertHexToRgb('#191749'), + instagram : convertHexToRgb('#450d0b'), + meetup : convertHexToRgb('#062233'), + rss : convertHexToRgb('#183a37'), + stackexchange : convertHexToRgb('#95b26e'), + tumblr : convertHexToRgb('#c44900'), + twitter : convertHexToRgb('#432534'), + youtube : convertHexToRgb('#432834') +}; + + +var TYPES = { + disqus : { + forum : 'Forum' + }, + facebook : { + page : 'Page', + public_page : 'Public Page' + }, + foursquare : { + venue : 'Venue' + }, + github : { + org : 'Organization', + repo : 'Repository' + }, + instagram : { + tag : 'Tag', + // location : 'Location', + // geography : 'Geography', + user : 'User' + }, + meetup : { + group : 'Group' + }, + rss : { + site : 'URL' + }, + stackexchange : { + tags : 'Tags' + }, + tumblr : { + blog : 'Blog', + tag : 'Tag' + }, + twitter : { + followers : 'Followers', + hashtag : 'Hashtag', + term : 'Search', + user_timeline : 'User Timeline', + user_retweets: 'User Retweets', + favorites: 'User Favorites' + }, + youtube : { + channel : "Channel", + playlist: "Playlist"/*, + user : "User"*/ + } +}; + +var FEEDS = { + disqus : 'Disqus', + facebook : 'Facebook', + foursquare : 'Foursquare', + github : 'GitHub', + instagram : 'Instagram', + meetup : 'Meetup', + rss : 'RSS', + stackexchange : 'StackExchange', + tumblr : 'Tumblr', + twitter : 'Twitter', + youtube : 'YouTube' +}; + +var NEEDS_OAUTH = { + github : { + types : ['repo', 'org'] + }, + twitter : { + types : ['followers', 'hashtag', 'user_timeline', 'term', 'favorites', 'user_retweets'] + }, + meetup : { + types : ['group'] + }, + facebook : { + types : ['page'] + }, + foursquare : { + types : ['venue'] + }, + disqus : { + types: ['forum'] + }, + instagram : { + types: ['tag', 'user'] + }, + youtube : { + types: ['channel', 'playlist', 'user'] + } +}; + +var formatKey = function(key){ + if(key === 'url'){ + return 'URL'; + } + return can.capitalize(key.replace(/_/g, ' ')); +}; + +var formatConfig = function(config){ + var res = ['
    ']; + for(var k in config){ + res.push('
  • ' + formatKey(k) + ': '); + if(can.isPlainObject(config[k])){ + res.push(formatConfig(config[k])); + } else { + res.push(config[k]); + } + res.push('
  • '); + } + res.push('
'); + return res.join(''); +}; + +var emptyConfigForService = function(feed){ + var config = {}; + + if(feed === 'github'){ + config.tracking = {}; + } + + if(feed === 'stackexchange'){ + config.tags = []; + } + return config; +}; + +var Service = can.Model.extend({ + resource : '/api/v3/services', + feeds : FEEDS, + needsOAuth : NEEDS_OAUTH, + createEmptyService : function(feed){ + + return new this({ + feed_name : feed, + config: emptyConfigForService(feed) + }); + }, + errored : function(service){ + can.trigger(this, 'errored', [this]); + }, + messageFromLiveService : function( msg ) { + var cb = can.noop, + timeout = 1, + self = this, + timeoutKey; + + if(typeof msg === 'string'){ + msg = JSON.parse(msg); + } + + timeoutKey = msg.service.id; + + if(msg.service.empty_results){ + timeoutKey = msg.service.id + '-noResults'; + cb = function(service){ + if(service.attr('entity_count') === 0){ + service.hasNoResults(); + } + }; + timeout = 2000; + } + + clearTimeout(RELOAD_TIMEOUTS[timeoutKey]); + + RELOAD_TIMEOUTS[timeoutKey] = setTimeout(function(){ + self.findOne({id: msg.service.id}).then(cb); + }, timeout); + } +}, { + define : { + feed_name : { + set : function(val){ + var keys = _keys(TYPES[val]); + + this.attr('type_name', keys.length === 1 ? keys[0] : ""); + this.attr('graphColor', GRAPH_COLORS[val]); + + return val; + } + }, + type_name : { + set : function(val){ + this.attr('config', emptyConfigForService(this.attr('feed_name'))); + return val; + } + }, + error : { + set : function(val){ + var klass = val && val.klass; + if(klass && isCelluloidError(klass)){ + return; + } + return val; + } + }, + approved_by_default : { + set : function(val){ + return !!val; + } + } + }, + serialize : function(){ + var data = this._super.apply(this, arguments); + + if(!(data.feed_name === 'instagram' && data.type_name === 'user') && !(data.feed_name === 'facebook' && data.type_name === 'public_page')){ + if(data.config){ + delete data.config.display_name; + } + } + + return { + service : data + }; + }, + typesForFeed : function(){ + var currentFeed = this.attr('feed_name'), + types = TYPES[currentFeed]; + + return types; + }, + hasMultipleTypes : function(){ + var typesForFeed = this.typesForFeed(); + return _keys(typesForFeed || {}).length > 1; + }, + printFeed : function() { + return FEEDS[ this.attr('feed_name') ]; + }, + printType : function() { + return TYPES[ this.attr('feed_name') ][ this.attr('type_name') ]; + }, + printConfig: function() { + var output = [], + config = this.attr('config'); + + config = config ? config.attr() : config; + + if(!config){ + return; + } + + for( var key in config ) { + output.push(key + ': ' + config[key]); + } + + // remove last ', ' + return output.join('
'); + }, + hasNoResults : function(){ + can.batch.start(); + if(this.attr('_isNewlyCreated')){ + this.attr('noResults', true); + } + this.attr({ + error: null + }); + can.batch.stop(); + }, + clearNoResults : function(){ + this.removeAttr('noResults'); + }, + save : function(){ + this.removeAttr('noResults'); + can.trigger(this.constructor, 'saving', [this]); + return this._super.apply(this, arguments); + }, + formattedConfig : function(){ + return formatConfig(this.attr('config').attr()); + }, + formattedError : function(){ + return getErrorMessage(this.attr('error')); + }, + formattedErrorClass : function(){ + var klass = this.attr('error.klass'); + return !isConfigError(klass) ? '' : 'Configuration Error'; + }, + clearErrors : function(){ + this.removeAttr('error'); + }, + isLoading : function(){ + return this.attr('state') === 'loading'; + } +}); + +Service.on('created', function(ev, service){ + service.attr('_isNewlyCreated', true); +}); + +Service.on('updated', function(ev, service){ + service.attr('_isNewlyCreated', true); +}); + +export default Service; diff --git a/new-bithub-client/src/models/subscription.js b/new-bithub-client/src/models/subscription.js new file mode 100644 index 0000000..d78d39a --- /dev/null +++ b/new-bithub-client/src/models/subscription.js @@ -0,0 +1,36 @@ +import can from "can"; + +export default can.Model.extend({ + findOne: '/api/v3/subscriptions/current' +}, { + reload : function(){ + this.constructor.findOne({}); + }, + canAddHub : function(hubs){ + return true; + /*var currentLength = hubs.attr('length'); + var limit = this.attr('plan.limits.embeds_per_brand') || Infinity; + return currentLength < limit;*/ + }, + canAddService : function(services, feed, type){ + return true; + /*var currentLength = services.attr('length'); + var limit = this.attr('plan.limits.services_per_embed') || Infinity; + var currentTypeFeed = [feed, type].join('_'); + var limitCurrentTypeFeed = this.attr('plan.limits').attr(currentTypeFeed) || Infinity; + var servicesWithCurrentTypeFeed = services.filter(function(s){ + return s.attr('feed_name') === feed && s.attr('type_name') === type; + }); + + if(currentLength >= limit){ + return false; + } + if(servicesWithCurrentTypeFeed.attr('length') >= limitCurrentTypeFeed){ + return false; + } + return true;*/ + }, + hasCC : function(){ + return !!this.attr('card'); + } +}); diff --git a/new-bithub-client/src/models/suggestion.js b/new-bithub-client/src/models/suggestion.js new file mode 100644 index 0000000..7e55794 --- /dev/null +++ b/new-bithub-client/src/models/suggestion.js @@ -0,0 +1,4 @@ +import can from "can"; +export default can.Model.extend({ + findAll : '/api/v3/services/suggestions/{service}?brand_identity_id={brandIdentityId}' +}, {}); diff --git a/new-bithub-client/src/models/test.js b/new-bithub-client/src/models/test.js new file mode 100755 index 0000000..8b78254 --- /dev/null +++ b/new-bithub-client/src/models/test.js @@ -0,0 +1 @@ +import './fixtures/'; diff --git a/new-bithub-client/src/moderation-card/moderation-card.js b/new-bithub-client/src/moderation-card/moderation-card.js new file mode 100644 index 0000000..b2e42ea --- /dev/null +++ b/new-bithub-client/src/moderation-card/moderation-card.js @@ -0,0 +1,64 @@ +import can from "can"; +import template from "./moderation-card.stache!"; +import "./moderation-card.less!"; + +const DECISION_ICON_MAP = { + approved : 'thumbs-up', + deleted : 'trash', + starred : 'star' +}; + +var removeHtmlTags = function(html){ + return (html || "").replace(/<[^>]+>/ig, ""); +}; + +export default can.Component.extend({ + tag: 'bh-moderation-card', + template: template, + scope : { + iconUrl : function(decision){ + var icon = DECISION_ICON_MAP[decision] || decision; + var color = 'white'; + + if(decision === this.attr('bit.decision')){ + color = 'grey'; + } + + return "images/app-resources-icons-" + icon + '-' + color + '.svg'; + }, + feedIconUrl : function(feedName){ + return "images/social-grey/" + feedName + ".png"; + }, + shouldBeColumns : function(){ + var bit = this.attr('bit'); + var hasImages = !!bit.attr('images').attr('length'); + var bodyLength = removeHtmlTags(bit.attr('body')).length; + var titleLength = removeHtmlTags(bit.attr('title')).length; + if(hasImages){ + if(bodyLength + titleLength > 300){ + return false; + } + return true; + } + return false; + } + }, + helpers : { + formattedTitle : function(title){ + title = can.isFunction(title) ? title() : title; + if(title && title !== 'undefined'){ + return title; + } + return ""; + }, + formattedQuotedTweetDate : function(date){ + date = can.isFunction(date) ? date() : date; + return moment(date, 'dd MMM DD HH:mm:ss ZZ YYYY').format('LL'); + } + }, + events : { + inserted : function(){ + this.element.find('.content-column--title-body img').wrap('
'); + } + } +}); diff --git a/new-bithub-client/src/moderation-card/moderation-card.less b/new-bithub-client/src/moderation-card/moderation-card.less new file mode 100644 index 0000000..adcd821 --- /dev/null +++ b/new-bithub-client/src/moderation-card/moderation-card.less @@ -0,0 +1,120 @@ +bh-moderation-card { + display: block; + background: white; + box-shadow: 0 0 20px rgba(0,0,0,0.2); + border-radius: 5px; + border: 2px solid white; + overflow: hidden; + .content-wrap { + } + .columns-2 { + .content-column { + float: left; + width: 50%; + } + bh-card-image-gallery .current-image-wrap img { + width: 100%; + max-height: none; + } + } + .content-column--title-body { + padding: 15px; + .content-image-wrap { + margin: 0 -15px; + } + img { + width: 100%; + } + :last-child { + margin-bottom: 0; + } + bh-card-body-wrap, bh-card-body-wrap:last-child { + margin: -15px; + } + } + .moderation-bar { + background: #d2d7da; + height: 40px; + ul { + text-align: center; + li { + display: inline-block; + height: 30px; + margin: 5px 0; + border-left: 1px solid #dce2e2; + &:last-child { + border-right: 1px solid #dce2e2; + } + a { + display: block; + padding: 0 20px; + } + img { + height: 20px; + margin: 5px; + } + } + } + } + bh-card-image-gallery { + max-width: 100%; + } + .author-date-wrap { + border-top: 2px solid #f3f3f3; + padding: 5px 15px; + position: relative; + z-index: 1000; + } + .bit-author-name { + font-weight: bold; + font-size: 110%; + margin-bottom: -5px; + margin-top: 2px; + } + .social-icon { + width: 16px; + height: 16px; + float: left; + img { + width: 16px; + height: 16px; + display: block; + position: relative; + top: 2px; + } + } + .bit-created-at { + color: #7b7f80; + } + .bit-avatar { + float: left; + width: 40px; + height: 40px; + border-radius: 20px; + overflow: hidden; + margin-right: 10px; + a { + display: block; + width: 40px; + height: 40px; + img { + width: 40px; + height: 40px; + } + } + } + .youtube-embed-container { + margin: -15px -15px 15px; + position: relative; + padding-bottom: 56.25%; + height: 0; + overflow: hidden; + iframe, object, embed { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + } + } +} diff --git a/new-bithub-client/src/moderation-card/moderation-card.stache b/new-bithub-client/src/moderation-card/moderation-card.stache new file mode 100644 index 0000000..247203d --- /dev/null +++ b/new-bithub-client/src/moderation-card/moderation-card.stache @@ -0,0 +1,61 @@ + + + +{{#bit}} + +
+
+ {{#if images.length}} + + {{/if}} +
+
+ {{#if isYoutube}} +
+ +
+

{{{formattedTitle title }}}

+ {{else}} + {{#if shouldBeColumns}} + {{{formattedTitle title }}} + {{{ body }}} + {{else}} + + {{{formattedTitle title }}} + {{{ body }}} + + {{/if}} + {{/if}} +
+
+ +
+
    +
  • +
  • +
  • +
+
+{{/bit}} diff --git a/new-bithub-client/src/moderation-panel/moderation-panel.js b/new-bithub-client/src/moderation-panel/moderation-panel.js new file mode 100644 index 0000000..14cb052 --- /dev/null +++ b/new-bithub-client/src/moderation-panel/moderation-panel.js @@ -0,0 +1,47 @@ +import can from "can"; +import template from "./moderation-panel.stache!"; +import Bit from "src/models/bit"; +import "./moderation-panel.less!"; + +export default can.Component.extend({ + tag: 'bh-moderation-panel', + template: template, + scope : { + Bit: Bit + }, + events : { + init : function(){ + this.__timeouts = {}; + }, + scroll : function(){ + var self = this; + clearTimeout(this.__scrollTimeout); + if(this.scope.bits.length){ + this.__scrollTimeout = setTimeout(function(){ + var scrollTop = self.element.scrollTop(); + var scrollHeight = self.element[0].scrollHeight; + var height = self.element.outerHeight(); + if(scrollHeight - height - scrollTop < 200){ + self.scope.bits.loadNextPage(); + } + }, 200); + } + + }, + "{scope.Bit} updated" : function(Bit, ev, bit){ + var bitDecision = bit.attr('decision'); + var activeDecision = this.scope.attr('activeDecision'); + var id = bit.id; + var bits = this.scope.attr('bits'); + var bitElement = this.element.find('[data-bit-id=' + id + ']'); + if(bitDecision !== activeDecision){ + clearTimeout(this.__timeouts[id]); + this.__timeouts[id] = setTimeout(function(){ + bitElement.slideUp(300, function(){ + bits.remove(bit); + }); + }, 1000); + } + } + } +}); diff --git a/new-bithub-client/src/moderation-panel/moderation-panel.less b/new-bithub-client/src/moderation-panel/moderation-panel.less new file mode 100644 index 0000000..452c80d --- /dev/null +++ b/new-bithub-client/src/moderation-panel/moderation-panel.less @@ -0,0 +1,18 @@ +bh-moderation-panel { + overflow-y: scroll; + -webkit-overflow-scrolling: touch; + display: block; + padding: 15px 15px 0; + bh-moderation-card { + margin-bottom: 15px; + } + .loading-wrap { + text-align: center; + } + .alert-no-bits { + background: #4c94a3; + color: white; + text-align: center; + padding: 10px; + } +} diff --git a/new-bithub-client/src/moderation-panel/moderation-panel.stache b/new-bithub-client/src/moderation-panel/moderation-panel.stache new file mode 100644 index 0000000..50ae8d1 --- /dev/null +++ b/new-bithub-client/src/moderation-panel/moderation-panel.stache @@ -0,0 +1,14 @@ + +{{#if bits.isLoading}} +
+ +
+{{else}} + {{#if bits.length}} + {{#each bits}} + + {{/each}} + {{else}} +
There are no bits in this group.
+ {{/if}} +{{/if}} diff --git a/new-bithub-client/src/moderation-tabs/moderation-tabs.js b/new-bithub-client/src/moderation-tabs/moderation-tabs.js new file mode 100644 index 0000000..f7169a8 --- /dev/null +++ b/new-bithub-client/src/moderation-tabs/moderation-tabs.js @@ -0,0 +1,37 @@ +import can from "can"; +import template from "./moderation-tabs.stache!"; + +import "./moderation-tabs.less!"; +import "can/route/"; + +const ICON_MAPPINGS = { + pending: 'inbox', + approved: 'thumbs-up', + starred: 'star', + deleted: 'trash' +}; + + +export default can.Component.extend({ + tag: 'bh-moderation-tabs', + template: template, + scope : { + icon : function(icon){ + var color = this.attr('activeTab') === icon ? "white" : "grey"; + return "images/app-resources-icons-" + (ICON_MAPPINGS[icon] || icon) + "-" + color + ".svg"; + }, + countFor : function(decision){ + var entityDecisions = this.attr('entityDecisions'); + if(entityDecisions.isResolved()){ + return "(" + entityDecisions.getById(decision).attr('count') + ")"; + } + } + }, + helpers : { + moderationUrl : function(tab){ + tab = can.isFunction(tab) ? tab() : tab; + return can.route.url({moderationTab: tab}, true); + } + } +}); + diff --git a/new-bithub-client/src/moderation-tabs/moderation-tabs.less b/new-bithub-client/src/moderation-tabs/moderation-tabs.less new file mode 100644 index 0000000..98ab4f4 --- /dev/null +++ b/new-bithub-client/src/moderation-tabs/moderation-tabs.less @@ -0,0 +1,30 @@ +bh-moderation-tabs { + display: block; + ul { + width: 100%; + background: white; + height: 50px; + margin: 0; + box-shadow: 0 0 20px 0 rgba(0,0,0,0.05); + li { + width: 25%; + float: left; + height: 50px; + border-right: 1px solid #eee; + a { + display: block; + height: 50px; + line-height: 50px; + text-align: center; + color: #767f82; + &.active { + background: #4c94a3; + color: white; + } + img { + height: 20px; + } + } + } + } +} diff --git a/new-bithub-client/src/moderation-tabs/moderation-tabs.stache b/new-bithub-client/src/moderation-tabs/moderation-tabs.stache new file mode 100644 index 0000000..2722ab4 --- /dev/null +++ b/new-bithub-client/src/moderation-tabs/moderation-tabs.stache @@ -0,0 +1,14 @@ + diff --git a/new-bithub-client/src/slideout.js b/new-bithub-client/src/slideout.js new file mode 100644 index 0000000..dd05ab9 --- /dev/null +++ b/new-bithub-client/src/slideout.js @@ -0,0 +1,28 @@ +import can from "can"; +import Slideout from "slideout/dist/slideout"; + +can.Component.extend({ + tag: 'bh-slideout', + events: { + inserted : function(){ + setTimeout(()=> this.initSlideout(), 1); + }, + '.toggle-button click' : function(){ + if(this.slideout){ + this.scope.attr('isOpen', !this.scope.attr('isOpen')); + this.slideout.toggle(); + } + }, + initSlideout : function(){ + var self = this; + if(Slideout && self.element){ + self.slideout = new Slideout({ + 'panel': self.element.find('#panel')[0], + 'menu': self.element.find('#menu')[0], + 'padding': 256, + 'tolerance': 70 + }); + } + } + } +}); diff --git a/new-bithub-client/src/styles.less b/new-bithub-client/src/styles.less new file mode 100755 index 0000000..be98d73 --- /dev/null +++ b/new-bithub-client/src/styles.less @@ -0,0 +1,170 @@ +@import url('https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,700,700italic,400italic'); +@import "../node_modules/font-awesome/less/font-awesome.less"; + +@fa-font-path: "/new-bithub-client/node_modules/font-awesome/fonts"; + + +html { + height: 100%; +} + +body { + font-family: "Source Sans Pro","Helvetica Neue",Helvetica,Arial,"Lucida Grande",sans-serif; + font-weight: 400; + width: 100%; + height: 100%; + font-size: 14px; + background: #f2f3f5; +} + +.slideout-menu { + position: absolute; + left: 0; + top: 0; + bottom: 0; + right: 0; + z-index: 0; + width: 256px; + display: none; + background: #354c58; + bh-mobile-menu { + display: block; + position: absolute; + left: 0; + right: 0; + bottom: 90px; + top: 0; + overflow: hidden; + .list-wrap { + height: 100%; + overflow-x: hidden; + overflow-y: scroll !important; + -webkit-overflow-scrolling: touch; + } + ul { + } + } + .btn-switch-org, .btn-logout { + height: 45px; + color: white; + display: block; + line-height: 45px; + text-align: center; + position: absolute; + width: 256px; + } + .btn-switch-org { + bottom: 45px; + background: #354c58; + } + .btn-logout { + font-weight: 700; + bottom: 0; + background: #ae362c; + } +} + +.slideout-panel { + position:relative; + z-index: 1; + background: #f2f3f5; + height: 100%; + box-shadow: 0 0 20px 0 rgba(0,0,0,0.2); + overflow: hidden; + header { + background: #af372c; + height: 50px; + .toggle-button { + width: 60px; + float: left; + border: none; + border-right: 1px solid #dc4a41; + background: transparent; + color: white; + height: 50px; + line-height: 45px; + font-size: 18px; + } + h1 { + color: white; + margin: 0; + font-size: 20px; + float: left; + padding-left: 10px; + line-height: 50px; + } + } + bh-moderation-tabs { + position: absolute; + bottom: 0; + width: 100%; + box-shadow: 0 0 20px 0 rgba(0,0,0,0.2); + } + bh-moderation-panel { + position: absolute; + top: 50px; + bottom: 50px; + left: 0; + right: 0; + } +} + +.slideout-open, +.slideout-open body, +.slideout-open .slideout-panel { + overflow: hidden; +} + +.slideout-open .slideout-menu { + display: block; +} +.content-padding { + padding: 10px; +} +.organizations-wrap { + background: #f2f3f4; + position: fixed; + top: 0; + left: 0; + right: 0; + bottom: 0; + z-index: 1000; + transition: all 0.3s; + -webkit-transform: translateX(100%); + transform: translateX(100%); + header { + background: white; + height: 50px; + line-height: 50px; + position: relative; + color: #827f82; + font-size: 16px; + .fa-chevron-left { + position: absolute; + color: #4493a5; + top: 17px; + left: 15px; + + } + } + .list-organizations { + margin-top: 15px; + li { + line-height: 50px; + padding: 0 40px; + border-bottom: 1px solid white; + color: #827f82; + font-size: 16px; + position: relative; + .fa-check { + position: absolute; + right: 30px; + top: 17px; + } + } + } +} +.organizations-wrap--open { + -webkit-transform: translateX(0); + transform: translateX(0); +} diff --git a/new-bithub-client/src/test.html b/new-bithub-client/src/test.html new file mode 100755 index 0000000..27a3d6b --- /dev/null +++ b/new-bithub-client/src/test.html @@ -0,0 +1,4 @@ +bithub-client tests + + +
diff --git a/new-bithub-client/src/test/functional.js b/new-bithub-client/src/test/functional.js new file mode 100755 index 0000000..15cc0e4 --- /dev/null +++ b/new-bithub-client/src/test/functional.js @@ -0,0 +1,14 @@ +import F from 'funcunit'; +import QUnit from 'steal-qunit'; + +F.attach(QUnit); + +QUnit.module('bithub-client functional smoke test', { + beforeEach() { + F.open('../development.html'); + } +}); + +QUnit.test('bithub-client main page shows up', function() { + F('title').text('bithub-client', 'Title is set'); +}); diff --git a/new-bithub-client/src/test/test.js b/new-bithub-client/src/test/test.js new file mode 100755 index 0000000..9852dfe --- /dev/null +++ b/new-bithub-client/src/test/test.js @@ -0,0 +1,4 @@ +import QUnit from 'steal-qunit'; + +import 'bithub-client/models/test'; +import 'bithub-client/test/functional'; \ No newline at end of file diff --git a/package.json b/package.json new file mode 100644 index 0000000..219ca37 --- /dev/null +++ b/package.json @@ -0,0 +1,39 @@ +{ + "name": "bithub-admin", + "version": "0.1.0", + "description": "", + "main": "bithub-social.js", + "scripts": { + "test": "./node_modules/.bin/testee --browsers firefox tests.html" + }, + "author": "", + "license": "ISC", + "dependencies": { + "bithub-embed": "^0.1.0", + "bootstrap": "3.3.0", + "can": "^2.3.0", + "chart.js": "1.0.2", + "font-awesome": "~4.4.0", + "jquery": "2.2.1", + "jquery.payment": "1.2.3", + "js-cookie": "^2.1.0", + "lodash-amd": "3.10.1", + "moment": "2.10.3", + "randomcolor": "0.4.3", + "selectize": "0.12.0", + "steal": "0.16.0", + "system-json": "^0.1.0" + }, + "devDependencies": { + "steal-tools": "0.16.0", + "funcunit": "3.1.0-pre.1", + "steal-qunit": "0.1.1", + "testee": "0.2.5" + }, + "system": { + "npmAlgorithm": "flat", + "configDependencies": [ + "live-reload" + ] + } +} diff --git a/robots.txt b/robots.txt new file mode 100644 index 0000000..085187f --- /dev/null +++ b/robots.txt @@ -0,0 +1,5 @@ +# See http://www.robotstxt.org/wc/norobots.html for documentation on how to use the robots.txt file +# +# To ban all spiders from the entire site uncomment the next two lines: +# User-Agent: * +# Disallow: / diff --git a/site/fonts/bootstrap/glyphicons-halflings-regular.eot b/site/fonts/bootstrap/glyphicons-halflings-regular.eot new file mode 100644 index 0000000..b93a495 Binary files /dev/null and b/site/fonts/bootstrap/glyphicons-halflings-regular.eot differ diff --git a/site/fonts/bootstrap/glyphicons-halflings-regular.svg b/site/fonts/bootstrap/glyphicons-halflings-regular.svg new file mode 100644 index 0000000..94fb549 --- /dev/null +++ b/site/fonts/bootstrap/glyphicons-halflings-regular.svg @@ -0,0 +1,288 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/site/fonts/bootstrap/glyphicons-halflings-regular.ttf b/site/fonts/bootstrap/glyphicons-halflings-regular.ttf new file mode 100644 index 0000000..1413fc6 Binary files /dev/null and b/site/fonts/bootstrap/glyphicons-halflings-regular.ttf differ diff --git a/site/fonts/bootstrap/glyphicons-halflings-regular.woff b/site/fonts/bootstrap/glyphicons-halflings-regular.woff new file mode 100644 index 0000000..9e61285 Binary files /dev/null and b/site/fonts/bootstrap/glyphicons-halflings-regular.woff differ diff --git a/site/fonts/bootstrap/glyphicons-halflings-regular.woff2 b/site/fonts/bootstrap/glyphicons-halflings-regular.woff2 new file mode 100644 index 0000000..64539b5 Binary files /dev/null and b/site/fonts/bootstrap/glyphicons-halflings-regular.woff2 differ diff --git a/site/images/approve_block.png b/site/images/approve_block.png new file mode 100644 index 0000000..0046974 Binary files /dev/null and b/site/images/approve_block.png differ diff --git a/site/images/bithub-connect-moderate-embed.mp4 b/site/images/bithub-connect-moderate-embed.mp4 new file mode 100644 index 0000000..e98f0e6 Binary files /dev/null and b/site/images/bithub-connect-moderate-embed.mp4 differ diff --git a/site/images/bithub-connect-moderate-embed.webm b/site/images/bithub-connect-moderate-embed.webm new file mode 100644 index 0000000..213d9fe Binary files /dev/null and b/site/images/bithub-connect-moderate-embed.webm differ diff --git a/site/images/bithub-white.png b/site/images/bithub-white.png new file mode 100644 index 0000000..b3aec88 Binary files /dev/null and b/site/images/bithub-white.png differ diff --git a/site/images/bithub_converted.mp4 b/site/images/bithub_converted.mp4 new file mode 100644 index 0000000..04a6156 Binary files /dev/null and b/site/images/bithub_converted.mp4 differ diff --git a/site/images/bithub_converted.webm b/site/images/bithub_converted.webm new file mode 100644 index 0000000..19d32fb Binary files /dev/null and b/site/images/bithub_converted.webm differ diff --git a/site/images/checkmark.png b/site/images/checkmark.png new file mode 100644 index 0000000..1ea4a87 Binary files /dev/null and b/site/images/checkmark.png differ diff --git a/site/images/connect-moderate-embed-cover.png b/site/images/connect-moderate-embed-cover.png new file mode 100644 index 0000000..c60e5c3 Binary files /dev/null and b/site/images/connect-moderate-embed-cover.png differ diff --git a/site/images/connect.png b/site/images/connect.png new file mode 100644 index 0000000..235d688 Binary files /dev/null and b/site/images/connect.png differ diff --git a/site/images/design_embed.png b/site/images/design_embed.png new file mode 100644 index 0000000..36471ed Binary files /dev/null and b/site/images/design_embed.png differ diff --git a/site/images/embed.png b/site/images/embed.png new file mode 100644 index 0000000..debe71d Binary files /dev/null and b/site/images/embed.png differ diff --git a/site/images/embed_preview_bg.png b/site/images/embed_preview_bg.png new file mode 100644 index 0000000..7efc1e9 Binary files /dev/null and b/site/images/embed_preview_bg.png differ diff --git a/site/images/illustration.png b/site/images/illustration.png new file mode 100644 index 0000000..6a539b2 Binary files /dev/null and b/site/images/illustration.png differ diff --git a/site/images/lego/agency.png b/site/images/lego/agency.png new file mode 100644 index 0000000..0a99317 Binary files /dev/null and b/site/images/lego/agency.png differ diff --git a/site/images/lego/brand.png b/site/images/lego/brand.png new file mode 100644 index 0000000..b73ab7e Binary files /dev/null and b/site/images/lego/brand.png differ diff --git a/site/images/lego/startup.png b/site/images/lego/startup.png new file mode 100644 index 0000000..8e129b8 Binary files /dev/null and b/site/images/lego/startup.png differ diff --git a/site/images/logo.png b/site/images/logo.png new file mode 100644 index 0000000..cb04d9b Binary files /dev/null and b/site/images/logo.png differ diff --git a/site/images/moderate.png b/site/images/moderate.png new file mode 100644 index 0000000..c401792 Binary files /dev/null and b/site/images/moderate.png differ diff --git a/site/images/networks.png b/site/images/networks.png new file mode 100644 index 0000000..fae8c9c Binary files /dev/null and b/site/images/networks.png differ diff --git a/site/images/video_poster.png b/site/images/video_poster.png new file mode 100644 index 0000000..87d2d24 Binary files /dev/null and b/site/images/video_poster.png differ diff --git a/site/index.html b/site/index.html new file mode 100644 index 0000000..631d143 --- /dev/null +++ b/site/index.html @@ -0,0 +1,372 @@ + + + + + + + + + + BitHub - Real time, embeddable, social hubs + + + + + + + +
+
+
+
+ +

+ Real time, embeddable, social hubs +

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

Capitalize your social proof now!

+

+ Your social network activity gives you a direct connection to your fans. Time spent preparing the interesting content and posting it to Facebook, Twitter or Instagram pays off, resulting in a steady growth of your reach and influence. But, what do you do with all these retweets and likes? +

+
+

+ What if you could leverage the power of your social proof
to convert your visitors into your customers? +

+
+

+ With BitHub you can unify all your social media content in one place. Use the wisdom of crowds to strengthen your brand image and extend your influence. +

+

+ BitHub provides you with an embeddable social hub that gathers and displays all the content produced by you and your fans. Place it on your site, landing page or an interactive event wall. Whatever needs you have, BitHub has you covered. +

+

+ Check out our pricing and features! Every plan comes with a 45 ‐ day trial. +

+
+

Start using BitHub in three easy steps:

+
+
+
+
+
+
+
+ +
+ +

Connect

+

Connect the content that you produce accross multiple networks.

+
+ +
+ +

Moderate

+

Set up the moderation rules to keep your content focused.

+
+ +
+ +

Embed

+

Easily embed your customized feed on any website.

+
+ +
+
+

Start your 45 ‐ day trial »

+
+
+
+
+
+ +

Example embed used by the StealJS project.

+
+
+
+
+
+
+

Your context, your rules

+

How many times did you see your perfectly crafted post buried under a pile of irrelevant content? But, that's the nature of the social networks. What if you could avoid that problem altogether? What if you could have a place where you control the context? One place where it's everything about you.

+ +

Truth be told, you already have it ‐ it's your own site. With BitHub, you can move the conversation from social networks to your own site, a place where your visitors can became your customers.

+

And you know what you can also put on your site? +

+
+

+ Ninety-two percent of consumers around the world say they trust earned media, such as word-of-mouth and recommendations from friends and family, above all other forms of advertising… +

+ Nielsen Survey 2012. +
+

Studies show that social proof is one of the most important factors in consumers' decision‐making (Nielsen Survey 2012., CompUSA and an iPerceptions study). + +

BitHub enables you to gather all your dispersed content in one place and present it as your unified social proof. And the best part? Your content is not mixed with a bunch of other, irellevant posts, tweets and pictures.

+

BitHub puts you in control of your brand image, content and context.

+
+ +
+

Some of the features we built for you:

+
    +
  • Pull in any content - Twitter, Facebook, Instagram, RSS - all of them are just a click away
  • +
  • Moderate and organize the content - pin posts and block irrelevance
  • +
  • Live Embeds - for any type of event, you can use live version that updates content in near real time
  • +
+
+

You already spend all this time to produce the right content.
Now take the next step and start converting!

+
+
+
+
+

So, how does it work?

+
+
+
+
+ +
+
+

Connect

+

Aggregate everything!

+

+ BitHub has a powerful aggregation engine which allows you to collect all your content. +

+

+ Twitter, Facebook and Tumblr are just some of the content sources we support. No matter what the content is (text, image or video), we can display it in your feed. All of this works in real time. +

+
+ + +
+
+
+
+
+
+

Moderate

+

Your content, your rules.

+

+ Every item we collect is automatically moderated based on the rules you set up. +

+

+ You can block profanities or filter the data related to some subject. BitHub puts you in control of the data. +

+

+ Besides the automatic moderation, you can manually moderate any item. +

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

Embed

+

Embed on any page.

+

+ BitHub allows you to adjust its design so it fits your branding. +

+

+ All content cards are designed to work in both full page and small area context which allow you to reuse your embeds across your site. +

+

+ Pick your layout and theme, paste the code into your HTML page and you’re ready to go. +

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

Usage examples

+

BitHub is designed and developed for brands and companies that already have a vibrant community. Some of the ways people use it are:

+
+
+
+
+
+
    +
  • Media wall for your event
  • +
  • Activity stream for your open‐source project
  • +
  • Hashtag contest
  • +
  • Buzz collector for your festival or concert
  • +
+
    +
  • Topic stream for your news portal
  • +
  • Showcase of your app users
  • +
  • Community showcase
  • +
  • Landing page for your app, album or ebook
  • +
+
+ +
+
+
+
+
+
+

StealJS is using BitHub to display the activity stream on its homepage

+ +
+
+
+
+
+
+

Start your trial today!

+

All of our plans come with a 45 ‐ day trial, and can be cancelled at any time.

+ +
+

FAQ

+

How long does the contract last?

+

After your free trial period expires, we will charge you on a monthly basis.

+ +

How do I sign up?

+

By clicking on any of the links above, you will start your 45 ‐ day trial. When the trial expires, we will remind you to provide us with your credit card information.

+ +

I want to switch plans. Can I do it?

+

You can switch your plans at any time. If you have more hubs than the plan permits, we'll archive some of them and you won't lose any data. In case you want to start using them later on, upgrade your plan, and start collecting your data again (archived hubs are not publicly accessible and they don't collect the data).

+ +

Do you have any more questions? Feel free to contact us, and we'll get back to you ASAP!

+
+ +
+
+
+
+ + + + + \ No newline at end of file diff --git a/site/javascripts/all.js b/site/javascripts/all.js new file mode 100644 index 0000000..f075665 --- /dev/null +++ b/site/javascripts/all.js @@ -0,0 +1,10290 @@ +/*! + * jQuery JavaScript Library v1.10.2 + * http://jquery.com/ + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * + * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2013-07-03T13:48Z + */ + + (function( window, undefined ) { + +// Can't do this because several apps including ASP.NET trace +// the stack via arguments.caller.callee and Firefox dies if +// you try to trace through "use strict" call chains. (#13335) +// Support: Firefox 18+ +//"use strict"; +var + // The deferred used on DOM ready + readyList, + + // A central reference to the root jQuery(document) + rootjQuery, + + // Support: IE<10 + // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` + core_strundefined = typeof undefined, + + // Use the correct document accordingly with window argument (sandbox) + location = window.location, + document = window.document, + docElem = document.documentElement, + + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + + // Map over the $ in case of overwrite + _$ = window.$, + + // [[Class]] -> type pairs + class2type = {}, + + // List of deleted data cache ids, so we can reuse them + core_deletedIds = [], + + core_version = "1.10.2", + + // Save a reference to some core methods + core_concat = core_deletedIds.concat, + core_push = core_deletedIds.push, + core_slice = core_deletedIds.slice, + core_indexOf = core_deletedIds.indexOf, + core_toString = class2type.toString, + core_hasOwn = class2type.hasOwnProperty, + core_trim = core_version.trim, + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context, rootjQuery ); + }, + + // Used for matching numbers + core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, + + // Used for splitting on whitespace + core_rnotwhite = /\S+/g, + + // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, + + // JSON RegExp + rvalidchars = /^[\],:{}\s]*$/, + rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, + rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, + rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([\da-z])/gi, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }, + + // The ready event handler + completed = function( event ) { + + // readyState === "complete" is good enough for us to call the dom ready in oldIE + if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { + detach(); + jQuery.ready(); + } + }, + // Clean-up method for dom ready events + detach = function() { + if ( document.addEventListener ) { + document.removeEventListener( "DOMContentLoaded", completed, false ); + window.removeEventListener( "load", completed, false ); + + } else { + document.detachEvent( "onreadystatechange", completed ); + window.detachEvent( "onload", completed ); + } + }; + + jQuery.fn = jQuery.prototype = { + // The current version of jQuery being used + jquery: core_version, + + constructor: jQuery, + init: function( selector, context, rootjQuery ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + + // scripts is true for back-compat + jQuery.merge( this, jQuery.parseHTML( + match[1], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); +}, + + // Start with an empty selector + selector: "", + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return core_slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == null ? + + // Return a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + ret.context = this.context; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) +each: function( callback, args ) { + return jQuery.each( this, callback, args ); +}, + +ready: function( fn ) { + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; + }, + + slice: function() { + return this.pushStack( core_slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: core_push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + var src, copyIsArray, copy, name, options, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } +} + + // Return the modified object + return target; +}; + +jQuery.extend({ + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), + + noConflict: function( deep ) { + if ( window.$ === jQuery ) { + window.$ = _$; + } + + if ( deep && window.jQuery === jQuery ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.trigger ) { + jQuery( document ).trigger("ready").off("ready"); + } + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + isWindow: function( obj ) { + /* jshint eqeqeq: false */ + return obj != null && obj == obj.window; + }, + + isNumeric: function( obj ) { + return !isNaN( parseFloat(obj) ) && isFinite( obj ); + }, + + type: function( obj ) { + if ( obj == null ) { + return String( obj ); + } + return typeof obj === "object" || typeof obj === "function" ? + class2type[ core_toString.call(obj) ] || "object" : + typeof obj; + }, + + isPlainObject: function( obj ) { + var key; + + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !core_hasOwn.call(obj, "constructor") && + !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Support: IE<9 + // Handle iteration over inherited properties before own properties. + if ( jQuery.support.ownLast ) { + for ( key in obj ) { + return core_hasOwn.call( obj, key ); + } + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + for ( key in obj ) {} + + return key === undefined || core_hasOwn.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw new Error( msg ); + }, + + // data: string of html + // context (optional): If specified, the fragment will be created in this context, defaults to document + // keepScripts (optional): If true, will include scripts passed in the html string + parseHTML: function( data, context, keepScripts ) { + if ( !data || typeof data !== "string" ) { + return null; + } + if ( typeof context === "boolean" ) { + keepScripts = context; + context = false; + } + context = context || document; + + var parsed = rsingleTag.exec( data ), + scripts = !keepScripts && []; + + // Single tag + if ( parsed ) { + return [ context.createElement( parsed[1] ) ]; + } + + parsed = jQuery.buildFragment( [ data ], context, scripts ); + if ( scripts ) { + jQuery( scripts ).remove(); + } + return jQuery.merge( [], parsed.childNodes ); + }, + + parseJSON: function( data ) { + // Attempt to parse using the native JSON parser first + if ( window.JSON && window.JSON.parse ) { + return window.JSON.parse( data ); + } + + if ( data === null ) { + return data; + } + + if ( typeof data === "string" ) { + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); + + if ( data ) { + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( rvalidchars.test( data.replace( rvalidescape, "@" ) + .replace( rvalidtokens, "]" ) + .replace( rvalidbraces, "")) ) { + + return ( new Function( "return " + data ) )(); + } + } + } + + jQuery.error( "Invalid JSON: " + data ); +}, + + // Cross-browser xml parsing + parseXML: function( data ) { + var xml, tmp; + if ( !data || typeof data !== "string" ) { + return null; + } + try { + if ( window.DOMParser ) { // Standard + tmp = new DOMParser(); + xml = tmp.parseFromString( data , "text/xml" ); + } else { // IE + xml = new ActiveXObject( "Microsoft.XMLDOM" ); + xml.async = "false"; + xml.loadXML( data ); + } + } catch( e ) { + xml = undefined; + } + if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; + }, + + noop: function() {}, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && jQuery.trim( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + // args is for internal usage only + each: function( obj, callback, args ) { + var value, + i = 0, + length = obj.length, + isArray = isArraylike( obj ); + + if ( args ) { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } + } + + return obj; +}, + + // Use native String.trim function wherever possible + trim: core_trim && !core_trim.call("\uFEFF\xA0") ? + function( text ) { + return text == null ? + "" : + core_trim.call( text ); + } : + + // Otherwise use our own trimming functionality + function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArraylike( Object(arr) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + core_push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + var len; + + if ( arr ) { + if ( core_indexOf ) { + return core_indexOf.call( arr, elem, i ); + } + + len = arr.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in arr && arr[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge: function( first, second ) { + var l = second.length, + i = first.length, + j = 0; + + if ( typeof l === "number" ) { + for ( ; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var retVal, + ret = [], + i = 0, + length = elems.length; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, + i = 0, + length = elems.length, + isArray = isArraylike( elems ), + ret = []; + + // Go through the array, translating each of the items to their + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + } + + // Flatten any nested arrays + return core_concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var args, proxy, tmp; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = core_slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + // Multifunctional method to get and set values of a collection + // The value/s can optionally be executed if it's a function + access: function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + length = elems.length, + bulk = key == null; + + // Sets many values + if ( jQuery.type( key ) === "object" ) { + chainable = true; + for ( i in key ) { + jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !jQuery.isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < length; i++ ) { + fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); + } + } + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + length ? fn( elems[0], key ) : emptyGet; + }, + + now: function() { + return ( new Date() ).getTime(); + }, + + // A method for quickly swapping in/out CSS properties to get correct calculations. + // Note: this method belongs to the css module but it's needed here for the support module. + // If support gets modularized, this method should be moved back to the css module. + swap: function( elem, options, callback, args ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.apply( elem, args || [] ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; + } +}); + +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { + + readyList = jQuery.Deferred(); + + // Catch cases where $(document).ready() is called after the browser event has already occurred. + // we once tried to use readyState "interactive" here, but it caused issues like the one + // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + setTimeout( jQuery.ready ); + + // Standards-based browsers support DOMContentLoaded + } else if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed, false ); + + // If IE event model is used + } else { + // Ensure firing before onload, maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", completed ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", completed ); + + // If IE and not a frame + // continually check to see if the document is ready + var top = false; + + try { + top = window.frameElement == null && document.documentElement; + } catch(e) {} + + if ( top && top.doScroll ) { + (function doScrollCheck() { + if ( !jQuery.isReady ) { + + try { + // Use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + top.doScroll("left"); + } catch(e) { + return setTimeout( doScrollCheck, 50 ); + } + + // detach all dom ready events + detach(); + + // and execute any waiting functions + jQuery.ready(); + } + })(); + } + } + } + return readyList.promise( obj ); +}; + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +function isArraylike( obj ) { + var length = obj.length, + type = jQuery.type( obj ); + + if ( jQuery.isWindow( obj ) ) { + return false; + } + + if ( obj.nodeType === 1 && length ) { + return true; + } + + return type === "array" || type !== "function" && + ( length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj ); +} + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); +/*! + * Sizzle CSS Selector Engine v1.10.2 + * http://sizzlejs.com/ + * + * Copyright 2013 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2013-07-03 + */ + (function( window, undefined ) { + + var i, + support, + cachedruns, + Expr, + getText, + isXML, + compile, + outermostContext, + sortInput, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + -(new Date()), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + hasDuplicate = false, + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + return 0; + } + return 0; + }, + + // General-purpose constants + strundefined = typeof undefined, + MAX_NEGATIVE = 1 << 31, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf if we can't use a native one + indexOf = arr.indexOf || function( elem ) { + var i = 0, + len = this.length; + for ( ; i < len; i++ ) { + if ( this[i] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + // http://www.w3.org/TR/css3-syntax/#characters + characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + + // Loosely modeled on CSS identifier characters + // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors + // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = characterEncoding.replace( "w", "w#" ), + + // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", + + // Prefer arguments quoted, + // then not containing pseudos/brackets, + // then attribute selectors/non-parenthetical expressions, + // then anything else + // These preferences are here to reduce the number of selectors + // needing tokenize in the PSEUDO preFilter + pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), + + rsibling = new RegExp( whitespace + "*[+~]" ), + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + characterEncoding + ")" ), + "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), + "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rescape = /'|\\/g, + + // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + // BMP codepoint + high < 0 ? + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }; + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var match, elem, m, nodeType, + // QSA vars + i, groups, old, nid, newContext, newSelector; + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + + context = context || document; + results = results || []; + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { + return []; + } + + if ( documentIsHTML && !seed ) { + + // Shortcuts + if ( (match = rquickExpr.exec( selector )) ) { + // Speed-up: Sizzle("#ID") + if ( (m = match[1]) ) { + if ( nodeType === 9 ) { + elem = context.getElementById( m ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE, Opera, and Webkit return items + // by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + } else { + // Context is not a document + if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && + contains( context, elem ) && elem.id === m ) { + results.push( elem ); + return results; + } + } + + // Speed-up: Sizzle("TAG") + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // QSA path + if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + nid = old = expando; + newContext = context; + newSelector = nodeType === 9 && selector; + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + groups = tokenize( selector ); + + if ( (old = context.getAttribute("id")) ) { + nid = old.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", nid ); + } + nid = "[id='" + nid + "'] "; + + i = groups.length; + while ( i-- ) { + groups[i] = nid + toSelector( groups[i] ); + } + newContext = rsibling.test( selector ) && context.parentNode || context; + newSelector = groups.join(","); + } + + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch(qsaError) { + } finally { + if ( !old ) { + context.removeAttribute("id"); + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {Function(string, Object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ + function createCache() { + var keys = []; + + function cache( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key += " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key ] = value); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ + function markFunction( fn ) { + fn[ expando ] = true; + return fn; + } + +/** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ + function assert( fn ) { + var div = document.createElement("div"); + + try { + return !!fn( div ); + } catch (e) { + return false; + } finally { + // Remove from its parent by default + if ( div.parentNode ) { + div.parentNode.removeChild( div ); + } + // release memory in IE + div = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ + function addHandle( attrs, handler ) { + var arr = attrs.split("|"), + i = attrs.length; + + while ( i-- ) { + Expr.attrHandle[ arr[i] ] = handler; + } + } + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ + function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + ( ~b.sourceIndex || MAX_NEGATIVE ) - + ( ~a.sourceIndex || MAX_NEGATIVE ); + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ + function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; + } + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ + function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; + } + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ + function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); + } + +/** + * Detect xml + * @param {Element|Object} elem An element or a document + */ + isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ + setDocument = Sizzle.setDocument = function( node ) { + var doc = node ? node.ownerDocument || node : preferredDoc, + parent = doc.defaultView; + + // If no document and documentElement is available, return + if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Set our document + document = doc; + docElem = doc.documentElement; + + // Support tests + documentIsHTML = !isXML( doc ); + + // Support: IE>8 + // If iframe document is assigned to "document" variable and if iframe has been reloaded, + // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 + // IE6-8 do not support the defaultView property so parent will be undefined + if ( parent && parent.attachEvent && parent !== parent.top ) { + parent.attachEvent( "onbeforeunload", function() { + setDocument(); + }); + } + + /* Attributes + ---------------------------------------------------------------------- */ + + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) + support.attributes = assert(function( div ) { + div.className = "i"; + return !div.getAttribute("className"); + }); + + /* getElement(s)By* + ---------------------------------------------------------------------- */ + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert(function( div ) { + div.appendChild( doc.createComment("") ); + return !div.getElementsByTagName("*").length; + }); + + // Check if getElementsByClassName can be trusted + support.getElementsByClassName = assert(function( div ) { + div.innerHTML = "
"; + + // Support: Safari<4 + // Catch class over-caching + div.firstChild.className = "i"; + // Support: Opera<10 + // Catch gEBCN failure to find non-leading classes + return div.getElementsByClassName("i").length === 2; + }); + + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert(function( div ) { + docElem.appendChild( div ).id = expando; + return !doc.getElementsByName || !doc.getElementsByName( expando ).length; + }); + + // ID find and filter + if ( support.getById ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && documentIsHTML ) { + var m = context.getElementById( id ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + // Support: IE6/7 + // getElementById is not reliable as a find shortcut + delete Expr.find["ID"]; + + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); + return node && node.value === attrId; + }; + }; + } + + // Tag + Expr.find["TAG"] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== strundefined ) { + return context.getElementsByTagName( tag ); + } + } : + function( tag, context ) { + var elem, + tmp = [], + i = 0, + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Class + Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; + + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See http://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + div.innerHTML = ""; + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + }); + + assert(function( div ) { + + // Support: Opera 10-12/IE8 + // ^= $= *= and empty values + // Should not select anything + // Support: Windows 8 Native Apps + // The type attribute is restricted during .innerHTML assignment + var input = doc.createElement("input"); + input.setAttribute( "type", "hidden" ); + div.appendChild( input ).setAttribute( "t", "" ); + + if ( div.querySelectorAll("[t^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Opera 10-11 does not throw on post-comma invalid pseudos + div.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } + + if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { + + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( div, "div" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( div, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); +} + +rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); +rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); + + /* Contains + ---------------------------------------------------------------------- */ + + // Element contains another + // Purposefully does not implement inclusive descendent + // As in, an element does not contain itself + contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = docElem.compareDocumentPosition ? + function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); + + if ( compare ) { + // Disconnected nodes + if ( compare & 1 || + (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === doc || contains(preferredDoc, a) ) { + return -1; + } + if ( b === doc || contains(preferredDoc, b) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } + + // Not directly comparable, sort on existence of method + return a.compareDocumentPosition ? -1 : 1; + } : + function( a, b ) { + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Parentless nodes are either documents or disconnected + } else if ( !aup || !bup ) { + return a === doc ? -1 : + b === doc ? 1 : + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + return doc; + }; + + Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); + }; + + Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + if ( support.matchesSelector && documentIsHTML && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch(e) {} +} + +return Sizzle( expr, document, null, [elem] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val === undefined ? + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + (val = elem.getAttributeNode(name)) && val.specified ? + val.value : + null : + val; + }; + + Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); + }; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ + Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + return results; +}; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ + getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + for ( ; (node = elem[i]); i++ ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (see #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[5] && match[2]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[3] && match[4] !== undefined ) { + match[2] = match[4]; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { return true; } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, outerCache, node, diff, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + // Seek `elem` from a previously-cached index + outerCache = parent[ expando ] || (parent[ expando ] = {}); + cache = outerCache[ type ] || []; + nodeIndex = cache[0] === dirruns && cache[1]; + diff = cache[0] === dirruns && cache[2]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + // Use previously-cached element index if available + } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { + diff = cache[1]; + + // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) + } else { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { + // Cache the index of each encountered element + if ( useCache ) { + (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf.call( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), + // not comment, processing instructions, or others + // Thanks to Diego Perini for the nodeName shortcut + // Greater than "@" means alpha characters (specifically not starting with "#" or "?") + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +function tokenize( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( tokens = [] ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push({ + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + }); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push({ + value: matched, + type: type, + matches: match + }); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } +} + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); + } + + function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; + } + + function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && dir === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var data, cache, outerCache, + dirkey = dirruns + " " + doneName; + + // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { + if ( (data = cache[1]) === true || data === cachedruns ) { + return data === true; + } + } else { + cache = outerCache[ dir ] = [ dirkey ]; + cache[1] = matcher( elem, context, xml ) || cachedruns; + if ( cache[1] === true ) { + return true; + } + } + } + } + } + }; + } + + function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; + } + + function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; + } + + function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } +}); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf.call( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + // A counter to specify which element is currently being matched + var matcherCachedRuns = 0, + bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, expandContext ) { + var elem, j, matcher, + setMatched = [], + matchedCount = 0, + i = "0", + unmatched = seed && [], + outermost = expandContext != null, + contextBackup = outermostContext, + // We must always have either seed elements or context + elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); + + if ( outermost ) { + outermostContext = context !== document && context; + cachedruns = matcherCachedRuns; + } + + // Add elements passing elementMatchers directly to results + // Keep `i` a string if there are no elements so `matchedCount` will be "00" below + for ( ; (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + cachedruns = ++matcherCachedRuns; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // Apply set filters to unmatched elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; + } + + compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !group ) { + group = tokenize( selector ); + } + i = group.length; + while ( i-- ) { + cached = matcherFromTokens( group[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + } + return cached; +}; + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function select( selector, context, results, seed ) { + var i, tokens, token, type, find, + match = tokenize( selector ); + + if ( !seed ) { + // Try to minimize operations if there is only one group + if ( match.length === 1 ) { + + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + support.getById && context.nodeType === 9 && documentIsHTML && + Expr.relative[ tokens[1].type ] ) { + + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; + } + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && context.parentNode || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } +} + + // Compile and execute a filtering function + // Provide `match` to avoid retokenization if we modified the selector above + compile( selector, match )( + seed, + context, + !documentIsHTML, + results, + rsibling.test( selector ) + ); + return results; +} + +// One-time assignments + +// Sort stability +support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; + +// Support: Chrome<14 +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = hasDuplicate; + +// Initialize against the default document +setDocument(); + +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert(function( div1 ) { + // Should return 1, but returns 4 (following) + return div1.compareDocumentPosition( document.createElement("div") ) & 1; +}); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert(function( div ) { + div.innerHTML = ""; + return div.firstChild.getAttribute("href") === "#" ; +}) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + }); +} + +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert(function( div ) { + div.innerHTML = ""; + div.firstChild.setAttribute( "value", "" ); + return div.firstChild.getAttribute( "value" ) === ""; +}) ) { + addHandle( "value", function( elem, name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + }); +} + +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert(function( div ) { + return div.getAttribute("disabled") == null; +}) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return (val = elem.getAttributeNode( name )) && val.specified ? + val.value : + elem[ name ] === true ? name.toLowerCase() : null; + } + }); +} + +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.pseudos; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + +})( window ); +// String to Object options format cache +var optionsCache = {}; + +// Convert String-formatted options into Object-formatted ones and store in cache +function createOptions( options ) { + var object = optionsCache[ options ] = {}; + jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { + object[ flag ] = true; + }); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ + jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + ( optionsCache[ options ] || createOptions( options ) ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list was already fired + fired, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // First callback to fire (used internally by add and fireWith) + firingStart, + // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = !options.once && [], + // Fire callbacks + fire = function( data ) { + memory = options.memory && data; + fired = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + firing = true; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { + memory = false; // To prevent further calls using add + break; + } + } + firing = false; + if ( list ) { + if ( stack ) { + if ( stack.length ) { + fire( stack.shift() ); + } + } else if ( memory ) { + list = []; + } else { + self.disable(); + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + // First, we save the current length + var start = list.length; + (function add( args ) { + jQuery.each( args, function( _, arg ) { + var type = jQuery.type( arg ); + if ( type === "function" ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && type !== "string" ) { + // Inspect recursively + add( arg ); + } + }); + })( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away + } else if ( memory ) { + firingStart = start; + fire( memory ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + jQuery.each( arguments, function( _, arg ) { + var index; + while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + // Handle firing indexes + if ( firing ) { + if ( index <= firingLength ) { + firingLength--; + } + if ( index <= firingIndex ) { + firingIndex--; + } + } + } + }); + } + return this; + }, + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); + }, + // Remove all callbacks from the list + empty: function() { + list = []; + firingLength = 0; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( list && ( !fired || stack ) ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + if ( firing ) { + stack.push( args ); + } else { + fire( args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; + }; + jQuery.extend({ + + Deferred: function( func ) { + var tuples = [ + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], + [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], + [ "notify", "progress", jQuery.Callbacks("memory") ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred(function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var action = tuple[ 0 ], + fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[1] ](function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .done( newDefer.resolve ) + .fail( newDefer.reject ) + .progress( newDefer.notify ); + } else { + newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); + } + }); + }); + fns = null; + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Keep pipe for back-compat + promise.pipe = promise.then; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; + + // promise[ done | fail | progress ] = list.add + promise[ tuple[1] ] = list.add; + + // Handle state + if ( stateString ) { + list.add(function() { + // state = [ resolved | rejected ] + state = stateString; + + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); + } + + // deferred[ resolve | reject | notify ] + deferred[ tuple[0] ] = function() { + deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); + return this; + }; + deferred[ tuple[0] + "With" ] = list.fireWith; + }); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = core_slice.call( arguments ), + length = resolveValues.length, + + // the count of uncompleted subordinates + remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; + if( values === progressValues ) { + deferred.notifyWith( contexts, values ); + } else if ( !( --remaining ) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, + + progressValues, progressContexts, resolveContexts; + + // add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ) + .progress( updateFunc( i, progressContexts, progressValues ) ); + } else { + --remaining; + } + } + } + + // if we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); + } + + return deferred.promise(); + } +}); +jQuery.support = (function( support ) { + + var all, a, input, select, fragment, opt, eventName, isSupported, i, + div = document.createElement("div"); + + // Setup + div.setAttribute( "className", "t" ); + div.innerHTML = "
a"; + + // Finish early in limited (non-browser) environments + all = div.getElementsByTagName("*") || []; + a = div.getElementsByTagName("a")[ 0 ]; + if ( !a || !a.style || !all.length ) { + return support; + } + + // First batch of tests + select = document.createElement("select"); + opt = select.appendChild( document.createElement("option") ); + input = div.getElementsByTagName("input")[ 0 ]; + + a.style.cssText = "top:1px;float:left;opacity:.5"; + + // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) + support.getSetAttribute = div.className !== "t"; + + // IE strips leading whitespace when .innerHTML is used + support.leadingWhitespace = div.firstChild.nodeType === 3; + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + support.tbody = !div.getElementsByTagName("tbody").length; + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + support.htmlSerialize = !!div.getElementsByTagName("link").length; + + // Get the style information from getAttribute + // (IE uses .cssText instead) + support.style = /top/.test( a.getAttribute("style") ); + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + support.hrefNormalized = a.getAttribute("href") === "/a"; + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + support.opacity = /^0.5/.test( a.style.opacity ); + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + support.cssFloat = !!a.style.cssFloat; + + // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) + support.checkOn = !!input.value; + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + support.optSelected = opt.selected; + + // Tests for enctype support on a form (#6743) + support.enctype = !!document.createElement("form").enctype; + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>"; + + // Will be defined later + support.inlineBlockNeedsLayout = false; + support.shrinkWrapBlocks = false; + support.pixelPosition = false; + support.deleteExpando = true; + support.noCloneEvent = true; + support.reliableMarginRight = true; + support.boxSizingReliable = true; + + // Make sure checked status is properly cloned + input.checked = true; + support.noCloneChecked = input.cloneNode( true ).checked; + + // Make sure that the options inside disabled selects aren't marked as disabled + // (WebKit marks them as disabled) + select.disabled = true; + support.optDisabled = !opt.disabled; + + // Support: IE<9 + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + + // Check if we can trust getAttribute("value") + input = document.createElement("input"); + input.setAttribute( "value", "" ); + support.input = input.getAttribute( "value" ) === ""; + + // Check if an input maintains its value after becoming a radio + input.value = "t"; + input.setAttribute( "type", "radio" ); + support.radioValue = input.value === "t"; + + // #11217 - WebKit loses check when the name is after the checked attribute + input.setAttribute( "checked", "t" ); + input.setAttribute( "name", "t" ); + + fragment = document.createDocumentFragment(); + fragment.appendChild( input ); + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + support.appendChecked = input.checked; + + // WebKit doesn't clone checked state correctly in fragments + support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE<9 + // Opera does not clone events (and typeof div.attachEvent === undefined). + // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() + if ( div.attachEvent ) { + div.attachEvent( "onclick", function() { + support.noCloneEvent = false; + }); + + div.cloneNode( true ).click(); + } + + // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) + // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) + for ( i in { submit: true, change: true, focusin: true }) { + div.setAttribute( eventName = "on" + i, "t" ); + + support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; + } + + div.style.backgroundClip = "content-box"; + div.cloneNode( true ).style.backgroundClip = ""; + support.clearCloneStyle = div.style.backgroundClip === "content-box"; + + // Support: IE<9 + // Iteration over object's inherited properties before its own. + for ( i in jQuery( support ) ) { + break; + } + support.ownLast = i !== "0"; + + // Run tests that need a body at doc ready + jQuery(function() { + var container, marginDiv, tds, + divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", + body = document.getElementsByTagName("body")[0]; + + if ( !body ) { + // Return for frameset docs that don't have a body + return; + } + + container = document.createElement("div"); + container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; + + body.appendChild( container ).appendChild( div ); + + // Support: IE8 + // Check if table cells still have offsetWidth/Height when they are set + // to display:none and there are still other visible table cells in a + // table row; if so, offsetWidth/Height are not reliable for use when + // determining if an element has been hidden directly using + // display:none (it is still safe to use offsets if a parent element is + // hidden; don safety goggles and see bug #4512 for more information). +div.innerHTML = "
t
"; +tds = div.getElementsByTagName("td"); +tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; +isSupported = ( tds[ 0 ].offsetHeight === 0 ); + +tds[ 0 ].style.display = ""; +tds[ 1 ].style.display = "none"; + + // Support: IE8 + // Check if empty table cells still have offsetWidth/Height + support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + + // Check box-sizing and margin behavior. + div.innerHTML = ""; + div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; + + // Workaround failing boxSizing test due to offsetWidth returning wrong value + // with some non-1 values of body zoom, ticket #13543 + jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { + support.boxSizing = div.offsetWidth === 4; + }); + + // Use window.getComputedStyle because jsdom on node.js will break without it. + if ( window.getComputedStyle ) { + support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; + support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; + + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. (#3333) + // Fails in WebKit before Feb 2011 nightlies + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + marginDiv = div.appendChild( document.createElement("div") ); + marginDiv.style.cssText = div.style.cssText = divReset; + marginDiv.style.marginRight = marginDiv.style.width = "0"; + div.style.width = "1px"; + + support.reliableMarginRight = + !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); + } + + if ( typeof div.style.zoom !== core_strundefined ) { + // Support: IE<8 + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + div.innerHTML = ""; + div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; + support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); + + // Support: IE6 + // Check if elements with layout shrink-wrap their children + div.style.display = "block"; + div.innerHTML = "
"; + div.firstChild.style.width = "5px"; + support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); + + if ( support.inlineBlockNeedsLayout ) { + // Prevent IE 6 from affecting layout for positioned elements #11048 + // Prevent IE from shrinking the body in IE 7 mode #12869 + // Support: IE<8 + body.style.zoom = 1; + } + } + + body.removeChild( container ); + + // Null elements to avoid leaks in IE + container = div = tds = marginDiv = null; + }); + + // Null elements to avoid leaks in IE + all = select = fragment = opt = a = input = null; + + return support; +})({}); + +var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, +rmultiDash = /([A-Z])/g; + +function internalData( elem, name, data, pvt /* Internal Use Only */ ){ + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var ret, thisCache, + internalKey = jQuery.expando, + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + // Avoid exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( typeof name === "string" ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; +} + +function internalRemoveData( elem, name, pvt ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, i, + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + id = isNode ? elem[ jQuery.expando ] : jQuery.expando; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split(" "); + } + } + } else { + // If "name" is an array of keys... + // When data is initially created, via ("key", "val") signature, + // keys will be converted to camelCase. + // Since there is no way to tell _how_ a key was added, remove + // both plain key and camelCase key. #12786 + // This will only penalize the array argument path. + name = name.concat( jQuery.map( name, jQuery.camelCase ) ); + } + + i = name.length; + while ( i-- ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject( cache[ id ] ) ) { + return; + } + } + + // Destroy the cache + if ( isNode ) { + jQuery.cleanData( [ elem ], true ); + + // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) + /* jshint eqeqeq: false */ +} else if ( jQuery.support.deleteExpando || cache != cache.window ) { + /* jshint eqeqeq: true */ + delete cache[ id ]; + + // When all else fails, null +} else { + cache[ id ] = null; +} +} + +jQuery.extend({ + cache: {}, + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "applet": true, + "embed": true, + // Ban all objects except for Flash (which handle expandos) + "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data ) { + return internalData( elem, name, data ); + }, + + removeData: function( elem, name ) { + return internalRemoveData( elem, name ); + }, + + // For internal use only. + _data: function( elem, name, data ) { + return internalData( elem, name, data, true ); + }, + + _removeData: function( elem, name ) { + return internalRemoveData( elem, name, true ); + }, + + // A method for determining if a DOM node can handle the data expando + acceptData: function( elem ) { + // Do not set data on non-element because it will not be cleared (#8335). + if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { + return false; + } + + var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; + + // nodes accept data unless otherwise specified; rejection can be conditional + return !noData || noData !== true && elem.getAttribute("classid") === noData; + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var attrs, name, + data = null, + i = 0, + elem = this[0]; + + // Special expections of .data basically thwart jQuery.access, + // so implement the relevant behavior ourselves + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = jQuery.data( elem ); + + if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { + attrs = elem.attributes; + for ( ; i < attrs.length; i++ ) { + name = attrs[i].name; + + if ( name.indexOf("data-") === 0 ) { + name = jQuery.camelCase( name.slice(5) ); + + dataAttr( elem, name, data[ name ] ); + } + } + jQuery._data( elem, "parsedAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + return arguments.length > 1 ? + + // Sets one value + this.each(function() { + jQuery.data( this, key, value ); + }) : + + // Gets one value + // Try to fetch any internally stored data first + elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } + }); + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + var name; + for ( name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} +jQuery.extend({ + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray(data) ) { + queue = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // not intended for public consumption - generates a queueHooks object, or returns the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return jQuery._data( elem, key ) || jQuery._data( elem, key, { + empty: jQuery.Callbacks("once memory").add(function() { + jQuery._removeData( elem, type + "queue" ); + jQuery._removeData( elem, key ); + }) + }); + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[0], type ); + } + + return data === undefined ? + this : + this.each(function() { + var queue = jQuery.queue( this, type, data ); + + // ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay: function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = setTimeout( next, time ); + hooks.stop = function() { + clearTimeout( timeout ); + }; + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while( i-- ) { + tmp = jQuery._data( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +}); +var nodeHook, boolHook, +rclass = /[\t\r\n\f]/g, +rreturn = /\r/g, +rfocusable = /^(?:input|select|textarea|button|object)$/i, +rclickable = /^(?:a|area)$/i, +ruseDefault = /^(?:checked|selected)$/i, +getSetAttribute = jQuery.support.getSetAttribute, +getSetInput = jQuery.support.input; + +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each(function() { + jQuery.removeAttr( this, name ); + }); + }, + + prop: function( name, value ) { + return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + name = jQuery.propFix[ name ] || name; + return this.each(function() { + // try/catch handles cases where IE balks (such as removing a property on window) + try { + this[ name ] = undefined; + delete this[ name ]; + } catch( e ) {} + }); + }, + + addClass: function( value ) { + var classes, elem, cur, clazz, j, + i = 0, + len = this.length, + proceed = typeof value === "string" && value; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).addClass( value.call( this, j, this.className ) ); + }); + } + + if ( proceed ) { + // The disjunction here is for better compressibility (see removeClass) + classes = ( value || "" ).match( core_rnotwhite ) || []; + + for ( ; i < len; i++ ) { + elem = this[ i ]; + cur = elem.nodeType === 1 && ( elem.className ? + ( " " + elem.className + " " ).replace( rclass, " " ) : + " " + ); + + if ( cur ) { + j = 0; + while ( (clazz = classes[j++]) ) { + if ( cur.indexOf( " " + clazz + " " ) < 0 ) { + cur += clazz + " "; + } + } + elem.className = jQuery.trim( cur ); + + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classes, elem, cur, clazz, j, + i = 0, + len = this.length, + proceed = arguments.length === 0 || typeof value === "string" && value; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).removeClass( value.call( this, j, this.className ) ); + }); + } + if ( proceed ) { + classes = ( value || "" ).match( core_rnotwhite ) || []; + + for ( ; i < len; i++ ) { + elem = this[ i ]; + // This expression is here for better compressibility (see addClass) + cur = elem.nodeType === 1 && ( elem.className ? + ( " " + elem.className + " " ).replace( rclass, " " ) : + "" + ); + + if ( cur ) { + j = 0; + while ( (clazz = classes[j++]) ) { + // Remove *all* instances + while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { + cur = cur.replace( " " + clazz + " ", " " ); + } + } + elem.className = value ? jQuery.trim( cur ) : ""; + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value; + + if ( typeof stateVal === "boolean" && type === "string" ) { + return stateVal ? this.addClass( value ) : this.removeClass( value ); + } + + if ( jQuery.isFunction( value ) ) { + return this.each(function( i ) { + jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); + }); + } + + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, + i = 0, + self = jQuery( this ), + classNames = value.match( core_rnotwhite ) || []; + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space separated list + if ( self.hasClass( className ) ) { + self.removeClass( className ); + } else { + self.addClass( className ); + } + } + + // Toggle whole class name + } else if ( type === core_strundefined || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); + } + + // If the element has a class name or if we're passed "false", + // then remove the whole classname (if there was one, the above saved it). + // Otherwise bring back whatever was previously saved (if anything), + // falling back to the empty string if nothing was stored. + this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; + } + }); +}, + +hasClass: function( selector ) { + var className = " " + selector + " ", + i = 0, + l = this.length; + for ( ; i < l; i++ ) { + if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { + return true; + } + } + + return false; +}, + +val: function( value ) { + var ret, hooks, isFunction, + elem = this[0]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { + return ret; + } + + ret = elem.value; + + return typeof ret === "string" ? + // handle most common string cases + ret.replace(rreturn, "") : + // handle cases where value is null/undef or number + ret == null ? "" : ret; + } + + return; + } + + isFunction = jQuery.isFunction( value ); + + return this.each(function( i ) { + var val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, jQuery( this ).val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + } else if ( typeof val === "number" ) { + val += ""; + } else if ( jQuery.isArray( val ) ) { + val = jQuery.map(val, function ( value ) { + return value == null ? "" : value + ""; + }); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + }); + } + }); + +jQuery.extend({ + valHooks: { + option: { + get: function( elem ) { + // Use proper attribute retrieval(#6932, #12072) + var val = jQuery.find.attr( elem, "value" ); + return val != null ? + val : + elem.text; + } + }, + select: { + get: function( elem ) { + var value, option, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one" || index < 0, + values = one ? null : [], + max = one ? index + 1 : options.length, + i = index < 0 ? + max : + one ? index : 0; + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // oldIE doesn't update selected after form reset (#2551) + if ( ( option.selected || i === index ) && + // Don't return options that are disabled or in a disabled optgroup + ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && + ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var optionSet, option, + options = elem.options, + values = jQuery.makeArray( value ), + i = options.length; + + while ( i-- ) { + option = options[ i ]; + if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { + optionSet = true; + } + } + + // force browsers to behave consistently when non-matching value is set + if ( !optionSet ) { + elem.selectedIndex = -1; + } + return values; + } + } + }, + + attr: function( elem, name, value ) { + var hooks, ret, + nType = elem.nodeType; + + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === core_strundefined ) { + return jQuery.prop( elem, name, value ); + } + + // All attributes are lowercase + // Grab necessary hook if one is defined + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + name = name.toLowerCase(); + hooks = jQuery.attrHooks[ name ] || + ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); + } + + if ( value !== undefined ) { + + if ( value === null ) { + jQuery.removeAttr( elem, name ); + + } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + elem.setAttribute( name, value + "" ); + return value; + } + + } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + ret = jQuery.find.attr( elem, name ); + + // Non-existent attributes return null, we normalize to undefined + return ret == null ? + undefined : + ret; + } + }, + + removeAttr: function( elem, value ) { + var name, propName, + i = 0, + attrNames = value && value.match( core_rnotwhite ); + + if ( attrNames && elem.nodeType === 1 ) { + while ( (name = attrNames[i++]) ) { + propName = jQuery.propFix[ name ] || name; + + // Boolean attributes get special treatment (#10870) + if ( jQuery.expr.match.bool.test( name ) ) { + // Set corresponding property to false + if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { + elem[ propName ] = false; + // Support: IE<9 + // Also clear defaultChecked/defaultSelected (if appropriate) + } else { + elem[ jQuery.camelCase( "default-" + name ) ] = + elem[ propName ] = false; + } + + // See #9699 for explanation of this approach (setting first, then removal) + } else { + jQuery.attr( elem, name, "" ); + } + + elem.removeAttribute( getSetAttribute ? name : propName ); + } + } +}, + +attrHooks: { + type: { + set: function( elem, value ) { + if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { + // Setting the type on a radio button after the value resets the value in IE6-9 + // Reset value to default in case type is set after value during creation + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + } + }, + + propFix: { + "for": "htmlFor", + "class": "className" + }, + + prop: function( elem, name, value ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set properties on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + if ( notxml ) { + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? + ret : + ( elem[ name ] = value ); + + } else { + return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? + ret : + elem[ name ]; + } + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + // Use proper attribute retrieval(#12072) + var tabindex = jQuery.find.attr( elem, "tabindex" ); + + return tabindex ? + parseInt( tabindex, 10 ) : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + -1; + } + } + } +}); + +// Hooks for boolean attributes +boolHook = { + set: function( elem, value, name ) { + if ( value === false ) { + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { + // IE<8 needs the *property* name + elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); + + // Use defaultChecked and defaultSelected for oldIE + } else { + elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; + } + + return name; +} +}; +jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { + var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; + + jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? + function( elem, name, isXML ) { + var fn = jQuery.expr.attrHandle[ name ], + ret = isXML ? + undefined : + /* jshint eqeqeq: false */ + (jQuery.expr.attrHandle[ name ] = undefined) != + getter( elem, name, isXML ) ? + + name.toLowerCase() : + null; + jQuery.expr.attrHandle[ name ] = fn; + return ret; + } : + function( elem, name, isXML ) { + return isXML ? + undefined : + elem[ jQuery.camelCase( "default-" + name ) ] ? + name.toLowerCase() : + null; + }; +}); + +// fix oldIE attroperties +if ( !getSetInput || !getSetAttribute ) { + jQuery.attrHooks.value = { + set: function( elem, value, name ) { + if ( jQuery.nodeName( elem, "input" ) ) { + // Does not return so that setAttribute is also used + elem.defaultValue = value; + } else { + // Use nodeHook if defined (#1954); otherwise setAttribute is fine + return nodeHook && nodeHook.set( elem, value, name ); + } + } + }; +} + +// IE6/7 do not support getting/setting some attributes with get/setAttribute +if ( !getSetAttribute ) { + + // Use this for any attribute in IE6/7 + // This fixes almost every IE6/7 issue + nodeHook = { + set: function( elem, value, name ) { + // Set the existing or create a new attribute node + var ret = elem.getAttributeNode( name ); + if ( !ret ) { + elem.setAttributeNode( + (ret = elem.ownerDocument.createAttribute( name )) + ); + } + + ret.value = value += ""; + + // Break association with cloned elements by also using setAttribute (#9646) + return name === "value" || value === elem.getAttribute( name ) ? + value : + undefined; + } + }; + jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords = + // Some attributes are constructed with empty-string values when not defined + function( elem, name, isXML ) { + var ret; + return isXML ? + undefined : + (ret = elem.getAttributeNode( name )) && ret.value !== "" ? + ret.value : + null; + }; + jQuery.valHooks.button = { + get: function( elem, name ) { + var ret = elem.getAttributeNode( name ); + return ret && ret.specified ? + ret.value : + undefined; + }, + set: nodeHook.set + }; + + // Set contenteditable to false on removals(#10429) + // Setting to empty string throws an error as an invalid value + jQuery.attrHooks.contenteditable = { + set: function( elem, value, name ) { + nodeHook.set( elem, value === "" ? false : value, name ); + } + }; + + // Set width and height to auto instead of 0 on empty string( Bug #8150 ) + // This is for removals + jQuery.each([ "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = { + set: function( elem, value ) { + if ( value === "" ) { + elem.setAttribute( name, "auto" ); + return value; + } + } + }; + }); +} + + +// Some attributes require a special call on IE +// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !jQuery.support.hrefNormalized ) { + // href/src property should get the full normalized URL (#10299/#12915) + jQuery.each([ "href", "src" ], function( i, name ) { + jQuery.propHooks[ name ] = { + get: function( elem ) { + return elem.getAttribute( name, 4 ); + } + }; + }); +} + +if ( !jQuery.support.style ) { + jQuery.attrHooks.style = { + get: function( elem ) { + // Return undefined in the case of empty string + // Note: IE uppercases css property names, but if we were to .toLowerCase() + // .cssText, that would destroy case senstitivity in URL's, like in "background" + return elem.style.cssText || undefined; + }, + set: function( elem, value ) { + return ( elem.style.cssText = value + "" ); + } + }; +} + +// Safari mis-reports the default selected property of an option +// Accessing the parent's selectedIndex property fixes it +if ( !jQuery.support.optSelected ) { + jQuery.propHooks.selected = { + get: function( elem ) { + var parent = elem.parentNode; + + if ( parent ) { + parent.selectedIndex; + + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + return null; + } + }; +} + +jQuery.each([ + "tabIndex", + "readOnly", + "maxLength", + "cellSpacing", + "cellPadding", + "rowSpan", + "colSpan", + "useMap", + "frameBorder", + "contentEditable" + ], function() { + jQuery.propFix[ this.toLowerCase() ] = this; + }); + +// IE6/7 call enctype encoding +if ( !jQuery.support.enctype ) { + jQuery.propFix.enctype = "encoding"; +} + +// Radios and checkboxes getter/setter +jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); + } + } + }; + if ( !jQuery.support.checkOn ) { + jQuery.valHooks[ this ].get = function( elem ) { + // Support: Webkit + // "" is returned instead of "on" if a value isn't specified + return elem.getAttribute("value") === null ? "on" : elem.value; + }; + } +}); +var rformElems = /^(?:input|select|textarea)$/i, +rkeyEvent = /^key/, +rmouseEvent = /^(?:mouse|contextmenu)|click/, +rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, +rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ + jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + var tmp, events, t, handleObjIn, + special, eventHandle, handleObj, + handlers, type, namespaces, origType, + elemData = jQuery._data( elem ); + + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !(events = elemData.events) ) { + events = elemData.events = {}; + } + if ( !(eventHandle = elemData.handle) ) { + eventHandle = elemData.handle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( core_rnotwhite ) || [""]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !(handlers = events[ type ]) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + var j, handleObj, tmp, + origCount, t, events, + special, handlers, type, + namespaces, origType, + elemData = jQuery.hasData( elem ) && jQuery._data( elem ); + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( core_rnotwhite ) || [""]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + delete elemData.handle; + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery._removeData( elem, "events" ); + } + }, + + trigger: function( event, data, elem, onlyHandlers ) { + var handle, ontype, cur, + bubbleType, special, tmp, i, + eventPath = [ elem || document ], + type = core_hasOwn.call( event, "type" ) ? event.type : event, + namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; + + cur = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf(".") >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf(":") < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join("."); + event.namespace_re = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === (elem.ownerDocument || document) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { + + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { + event.preventDefault(); + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && + jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + try { + elem[ type ](); + } catch ( e ) { + // IE<9 dies on focus/blur to hidden element (#1486,#12518) + // only reproducible on winXP IE8 native, not IE9 in IE8 mode + } + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event ); + + var i, ret, handleObj, matched, j, + handlerQueue = [], + args = core_slice.call( arguments ), + handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { + + // Triggered event must either 1) have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). +if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( (event.result = ret) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } +} +} +} + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var sel, handleObj, matches, i, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + // Black-hole SVG instance trees (#13180) + // Avoid non-left-click bubbling in Firefox (#3861) + if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { + + /* jshint eqeqeq: false */ + for ( ; cur != this; cur = cur.parentNode || this ) { + /* jshint eqeqeq: true */ + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matches[ sel ] === undefined ) { + matches[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) >= 0 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matches[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, handlers: matches }); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( delegateCount < handlers.length ) { + handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); + } + + return handlerQueue; + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, copy, + type = event.type, + originalEvent = event, + fixHook = this.fixHooks[ type ]; + + if ( !fixHook ) { + this.fixHooks[ type ] = fixHook = + rmouseEvent.test( type ) ? this.mouseHooks : + rkeyEvent.test( type ) ? this.keyHooks : + {}; + } + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = new jQuery.Event( originalEvent ); + + i = copy.length; + while ( i-- ) { + prop = copy[ i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Support: IE<9 + // Fix target property (#1925) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Support: Chrome 23+, Safari? + // Target should not be a text node (#504, #13143) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // Support: IE<9 + // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) + event.metaKey = !!event.metaKey; + + return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var body, eventDoc, doc, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + special: { + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + focus: { + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== safeActiveElement() && this.focus ) { + try { + this.focus(); + return false; + } catch ( e ) { + // Support: IE<9 + // If we error on focus to hidden element (#1486, #12518), + // let .trigger() run the handlers + } + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === safeActiveElement() && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + click: { + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { + this.click(); + return false; + } + }, + + // For cross-browser consistency, don't fire native .click() on links + _default: function( event ) { + return jQuery.nodeName( event.target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Even when returnValue equals to undefined Firefox will still show alert + if ( event.result !== undefined ) { + event.originalEvent.returnValue = event.result; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +jQuery.removeEvent = document.removeEventListener ? +function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } +} : +function( elem, type, handle ) { + var name = "on" + type; + + if ( elem.detachEvent ) { + + // #8545, #7054, preventing memory leaks for custom events in IE6-8 + // detachEvent needed property on element, by name of that event, to properly expose it to GC + if ( typeof elem[ name ] === core_strundefined ) { + elem[ name ] = null; + } + + elem.detachEvent( name, handle ); + } + }; + + jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || + src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; + + // Event type +} else { + this.type = src; +} + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + if ( !e ) { + return; + } + + // If preventDefault exists, run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // Support: IE + // Otherwise set the returnValue property of the original event to false + } else { + e.returnValue = false; + } +}, +stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + if ( !e ) { + return; + } + // If stopPropagation exists, run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + + // Support: IE + // Set the cancelBubble property of the original event to true + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + } +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// IE submit delegation +if ( !jQuery.support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !jQuery._data( form, "submitBubbles" ) ) { + jQuery.event.add( form, "submit._submit", function( event ) { + event._submit_bubble = true; + }); + jQuery._data( form, "submitBubbles", true ); + } + }); + // return undefined since we don't need an event listener + }, + + postDispatch: function( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( event._submit_bubble ) { + delete event._submit_bubble; + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + } + }, + + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; +} + +// IE change delegation and checkbox/radio fix +if ( !jQuery.support.changeBubbles ) { + + jQuery.event.special.change = { + + setup: function() { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + } + // Allow triggered, simulated change events (#11500) + jQuery.event.simulate( "change", this, event, true ); + }); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + jQuery._data( elem, "changeBubbles", true ); + } + }); + }, + + handle: function( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown: function() { + jQuery.event.remove( this, "._change" ); + + return !rformElems.test( this.nodeName ); + } + }; +} + +// Create "bubbling" focus and blur events +if ( !jQuery.support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler while someone wants focusin/focusout + var attaches = 0, + handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + if ( attaches++ === 0 ) { + document.addEventListener( orig, handler, true ); + } + }, + teardown: function() { + if ( --attaches === 0 ) { + document.removeEventListener( orig, handler, true ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var type, origFn; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on( types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + var elem = this[0]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +}); +var isSimple = /^.[^:#\[\.,]*$/, +rparentsprev = /^(?:parents|prev(?:Until|All))/, +rneedsContext = jQuery.expr.match.needsContext, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + + jQuery.fn.extend({ + find: function( selector ) { + var i, + ret = [], + self = this, + len = self.length; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }) ); + } + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + // Needed because $( selector, context ) becomes $( context ).find( selector ) + ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); + ret.selector = this.selector ? this.selector + " " + selector : selector; + return ret; + }, + + has: function( target ) { + var i, + targets = jQuery( target, this ), + len = targets.length; + + return this.filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector || [], true) ); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector || [], false) ); + }, + + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + ret = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( ; i < l; i++ ) { + for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { + // Always skip document fragments + if ( cur.nodeType < 11 && (pos ? + pos.index(cur) > -1 : + + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector(cur, selectors)) ) { + + cur = ret.push( cur ); + break; + } + } + } + + return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); +}, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( jQuery.unique(all) ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter(selector) + ); + } +}); + +function sibling( cur, dir ) { + do { + cur = cur[ dir ]; + } while ( cur && cur.nodeType !== 1 ); + + return cur; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + if ( this.length > 1 ) { + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + ret = jQuery.unique( ret ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + } + + return this.pushStack( ret ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 && elem.nodeType === 1 ? + jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : + jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + })); + }, + + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + /* jshint -W018 */ + return !!qualifier.call( elem, i, elem ) !== not; + }); + + } + + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + }); + + } + + if ( typeof qualifier === "string" ) { + if ( isSimple.test( qualifier ) ) { + return jQuery.filter( qualifier, elements, not ); + } + + qualifier = jQuery.filter( qualifier, elements ); + } + + return jQuery.grep( elements, function( elem ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; + }); +} +function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); + + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } + } + return safeFrag; +} + +var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + +"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", +rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, +rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), +rleadingWhitespace = /^\s+/, +rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, +rtagName = /<([\w:]+)/, +rtbody = /\s*$/g, + + // We have to close these tags to support XHTML (#13200) + wrapMap = { + option: [ 1, "" ], + legend: [ 1, "
", "
" ], + area: [ 1, "", "" ], + param: [ 1, "", "" ], + thead: [ 1, "", "
" ], + tr: [ 2, "", "
" ], + col: [ 2, "", "
" ], + td: [ 3, "", "
" ], + + // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, + // unless wrapped in a div with non-breaking characters in front of it. + _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X
", "
" ] + }, + safeFragment = createSafeFragment( document ), + fragmentDiv = safeFragment.appendChild( document.createElement("div") ); + + wrapMap.optgroup = wrapMap.option; + wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; + wrapMap.th = wrapMap.td; + + jQuery.fn.extend({ + text: function( value ) { + return jQuery.access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); + }, null, value, arguments.length ); + }, + + append: function() { + return this.domManip( arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip( arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + }); + }, + + before: function() { + return this.domManip( arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + }); + }, + + after: function() { + return this.domManip( arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + }); + }, + + // keepData is for internal use only--do not document + remove: function( selector, keepData ) { + var elem, + elems = selector ? jQuery.filter( selector, this ) : this, + i = 0; + + for ( ; (elem = elems[i]) != null; i++ ) { + + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem ) ); + } + + if ( elem.parentNode ) { + if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { + setGlobalEval( getAll( elem, "script" ) ); + } + elem.parentNode.removeChild( elem ); + } + } + + return this; + }, + + empty: function() { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + } + + // Remove any remaining nodes + while ( elem.firstChild ) { + elem.removeChild( elem.firstChild ); + } + + // If this is a select, ensure that it displays empty (#12336) + // Support: IE<9 + if ( elem.options && jQuery.nodeName( elem, "select" ) ) { + elem.options.length = 0; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function () { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + }); + }, + + html: function( value ) { + return jQuery.access( this, function( value ) { + var elem = this[0] || {}, + i = 0, + l = this.length; + + if ( value === undefined ) { + return elem.nodeType === 1 ? + elem.innerHTML.replace( rinlinejQuery, "" ) : + undefined; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && + ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && + !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { + + value = value.replace( rxhtmlTag, "<$1>" ); + + try { + for (; i < l; i++ ) { + // Remove element nodes and prevent memory leaks + elem = this[i] || {}; + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch(e) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); +}, + +replaceWith: function() { + var + // Snapshot the DOM in case .domManip sweeps something relevant into its fragment + args = jQuery.map( this, function( elem ) { + return [ elem.nextSibling, elem.parentNode ]; + }), + i = 0; + + // Make the changes, replacing each context element with the new content + this.domManip( arguments, function( elem ) { + var next = args[ i++ ], + parent = args[ i++ ]; + + if ( parent ) { + // Don't use the snapshot next if it has moved (#13810) + if ( next && next.parentNode !== parent ) { + next = this.nextSibling; + } + jQuery( this ).remove(); + parent.insertBefore( elem, next ); + } + // Allow new content to include elements from the context set + }, true ); + + // Force removal if there was no new content (e.g., from empty arguments) + return i ? this : this.remove(); + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, callback, allowIntersection ) { + + // Flatten any nested arrays + args = core_concat.apply( [], args ); + + var first, node, hasScripts, + scripts, doc, fragment, + i = 0, + l = this.length, + set = this, + iNoClone = l - 1, + value = args[0], + isFunction = jQuery.isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { + return this.each(function( index ) { + var self = set.eq( index ); + if ( isFunction ) { + args[0] = value.call( this, index, self.html() ); + } + self.domManip( args, callback, allowIntersection ); + }); + } + + if ( l ) { + fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + if ( first ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( this[i], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { + + if ( node.src ) { + // Hope ajax is available... + jQuery._evalUrl( node.src ); + } else { + jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); + } + } + } + } + + // Fix #11809: Avoid leaking memory + fragment = first = null; + } + } + + return this; + } +}); + +// Support: IE<8 +// Manipulating tables requires a tbody +function manipulationTarget( elem, content ) { + return jQuery.nodeName( elem, "table" ) && + jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? + + elem.getElementsByTagName("tbody")[0] || + elem.appendChild( elem.ownerDocument.createElement("tbody") ) : + elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + var match = rscriptTypeMasked.exec( elem.type ); + if ( match ) { + elem.type = match[1]; + } else { + elem.removeAttribute("type"); + } + return elem; +} + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var elem, + i = 0; + for ( ; (elem = elems[i]) != null; i++ ) { + jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); + } +} + +function cloneCopyEvent( src, dest ) { + + if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { + return; + } + + var type, i, l, + oldData = jQuery._data( src ), + curData = jQuery._data( dest, oldData ), + events = oldData.events; + + if ( events ) { + delete curData.handle; + curData.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + + // make the cloned public data object a copy from the original + if ( curData.data ) { + curData.data = jQuery.extend( {}, curData.data ); + } +} + +function fixCloneNodeIssues( src, dest ) { + var nodeName, e, data; + + // We do not need to do anything for non-Elements + if ( dest.nodeType !== 1 ) { + return; + } + + nodeName = dest.nodeName.toLowerCase(); + + // IE6-8 copies events bound via attachEvent when using cloneNode. + if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { + data = jQuery._data( dest ); + + for ( e in data.events ) { + jQuery.removeEvent( dest, e, data.handle ); + } + + // Event data gets referenced instead of copied if the expando gets copied too + dest.removeAttribute( jQuery.expando ); + } + + // IE blanks contents when cloning scripts, and tries to evaluate newly-set text + if ( nodeName === "script" && dest.text !== src.text ) { + disableScript( dest ).text = src.text; + restoreScript( dest ); + + // IE6-10 improperly clones children of object elements using classid. + // IE10 throws NoModificationAllowedError if parent is null, #12132. +} else if ( nodeName === "object" ) { + if ( dest.parentNode ) { + dest.outerHTML = src.outerHTML; + } + + // This path appears unavoidable for IE9. When cloning an object + // element in IE9, the outerHTML strategy above is not sufficient. + // If the src has innerHTML and the destination does not, + // copy the src.innerHTML into the dest.innerHTML. #10324 + if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { + dest.innerHTML = src.innerHTML; + } + + } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { + // IE6-8 fails to persist the checked state of a cloned checkbox + // or radio button. Worse, IE6-7 fail to give the cloned element + // a checked appearance if the defaultChecked value isn't also set + + dest.defaultChecked = dest.checked = src.checked; + + // IE6-7 get confused and end up setting the value of a cloned + // checkbox/radio button to an empty string instead of "on" + if ( dest.value !== src.value ) { + dest.value = src.value; + } + + // IE6-8 fails to return the selected option to the default selected + // state when cloning options +} else if ( nodeName === "option" ) { + dest.defaultSelected = dest.selected = src.defaultSelected; + + // IE6-8 fails to set the defaultValue to the correct value when + // cloning other types of input fields +} else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; +} +} + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + i = 0, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone(true); + jQuery( insert[i] )[ original ]( elems ); + + // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() + core_push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +}); + +function getAll( context, tag ) { + var elems, elem, + i = 0, + found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : + typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : + undefined; + + if ( !found ) { + for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { + if ( !tag || jQuery.nodeName( elem, tag ) ) { + found.push( elem ); + } else { + jQuery.merge( found, getAll( elem, tag ) ); + } + } + } + + return tag === undefined || tag && jQuery.nodeName( context, tag ) ? + jQuery.merge( [ context ], found ) : + found; +} + +// Used in buildFragment, fixes the defaultChecked property +function fixDefaultChecked( elem ) { + if ( manipulation_rcheckableType.test( elem.type ) ) { + elem.defaultChecked = elem.checked; + } +} + +jQuery.extend({ + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var destElements, node, clone, i, srcElements, + inPage = jQuery.contains( elem.ownerDocument, elem ); + + if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { + clone = elem.cloneNode( true ); + + // IE<=8 does not properly clone detached, unknown element nodes + } else { + fragmentDiv.innerHTML = elem.outerHTML; + fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); + } + + if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && + (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { + + // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + // Fix all IE cloning issues + for ( i = 0; (node = srcElements[i]) != null; ++i ) { + // Ensure that the destination node is not null; Fixes #9587 + if ( destElements[i] ) { + fixCloneNodeIssues( node, destElements[i] ); + } + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0; (node = srcElements[i]) != null; i++ ) { + cloneCopyEvent( node, destElements[i] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + destElements = srcElements = node = null; + + // Return the cloned set + return clone; + }, + + buildFragment: function( elems, context, scripts, selection ) { + var j, elem, contains, + tmp, tag, tbody, wrap, + l = elems.length, + + // Ensure a safe fragment + safe = createSafeFragment( context ), + + nodes = [], + i = 0; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( jQuery.type( elem ) === "object" ) { + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || safe.appendChild( context.createElement("div") ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + + tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[2]; + + // Descend through wrappers to the right content + j = wrap[0]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Manually add leading whitespace removed by IE + if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { + nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); + } + + // Remove IE's autoinserted from table fragments + if ( !jQuery.support.tbody ) { + + // String was a , *may* have spurious + elem = tag === "table" && !rtbody.test( elem ) ? + tmp.firstChild : + + // String was a bare or + wrap[1] === "
" && !rtbody.test( elem ) ? + tmp : + 0; + + j = elem && elem.childNodes.length; + while ( j-- ) { + if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { + elem.removeChild( tbody ); + } + } + } + + jQuery.merge( nodes, tmp.childNodes ); + + // Fix #12392 for WebKit and IE > 9 + tmp.textContent = ""; + + // Fix #12392 for oldIE + while ( tmp.firstChild ) { + tmp.removeChild( tmp.firstChild ); + } + + // Remember the top-level container for proper cleanup + tmp = safe.lastChild; + } + } + } + + // Fix #11356: Clear elements from fragment + if ( tmp ) { + safe.removeChild( tmp ); + } + + // Reset defaultChecked for any radios and checkboxes + // about to be appended to the DOM in IE 6/7 (#8060) + if ( !jQuery.support.appendChecked ) { + jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); + } + + i = 0; + while ( (elem = nodes[ i++ ]) ) { + + // #4087 - If origin and destination elements are the same, and this is + // that element, do not do anything + if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { + continue; + } + + contains = jQuery.contains( elem.ownerDocument, elem ); + + // Append to fragment + tmp = getAll( safe.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( (elem = tmp[ j++ ]) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + tmp = null; + + return safe; + }, + + cleanData: function( elems, /* internal */ acceptData ) { + var elem, type, id, data, + i = 0, + internalKey = jQuery.expando, + cache = jQuery.cache, + deleteExpando = jQuery.support.deleteExpando, + special = jQuery.event.special; + + for ( ; (elem = elems[i]) != null; i++ ) { + + if ( acceptData || jQuery.acceptData( elem ) ) { + + id = elem[ internalKey ]; + data = id && cache[ id ]; + + if ( data ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Remove cache only if it was not already removed by jQuery.event.remove + if ( cache[ id ] ) { + + delete cache[ id ]; + + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( deleteExpando ) { + delete elem[ internalKey ]; + + } else if ( typeof elem.removeAttribute !== core_strundefined ) { + elem.removeAttribute( internalKey ); + + } else { + elem[ internalKey ] = null; + } + + core_deletedIds.push( id ); + } + } + } + } + }, + + _evalUrl: function( url ) { + return jQuery.ajax({ + url: url, + type: "GET", + dataType: "script", + async: false, + global: false, + "throws": true + }); + } +}); +jQuery.fn.extend({ + wrapAll: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapAll( html.call(this, i) ); + }); + } + + if ( this[0] ) { + // The elements to wrap the target around + var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); + + if ( this[0].parentNode ) { + wrap.insertBefore( this[0] ); + } + + wrap.map(function() { + var elem = this; + + while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { + elem = elem.firstChild; + } + + return elem; + }).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapInner( html.call(this, i) ); + }); + } + + return this.each(function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + }); + }, + + wrap: function( html ) { + var isFunction = jQuery.isFunction( html ); + + return this.each(function(i) { + jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); + }); + }, + + unwrap: function() { + return this.parent().each(function() { + if ( !jQuery.nodeName( this, "body" ) ) { + jQuery( this ).replaceWith( this.childNodes ); + } + }).end(); + } +}); +var iframe, getStyles, curCSS, +ralpha = /alpha\([^)]*\)/i, +ropacity = /opacity\s*=\s*([^)]*)/, +rposition = /^(top|right|bottom|left)$/, + // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" + // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + rmargin = /^margin/, + rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), + rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), + rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), + elemdisplay = { BODY: "block" }, + + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: 0, + fontWeight: 400 + }, + + cssExpand = [ "Top", "Right", "Bottom", "Left" ], + cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; + +// return a css property mapped to a potentially vendor prefixed property +function vendorPropName( style, name ) { + + // shortcut for names that are not vendor prefixed + if ( name in style ) { + return name; + } + + // check for vendor prefixed names + var capName = name.charAt(0).toUpperCase() + name.slice(1), + origName = name, + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in style ) { + return name; + } + } + + return origName; +} + +function isHidden( elem, el ) { + // isHidden might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); +} + +function showHide( elements, show ) { + var display, elem, hidden, + values = [], + index = 0, + length = elements.length; + + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + + values[ index ] = jQuery._data( elem, "olddisplay" ); + display = elem.style.display; + if ( show ) { + // Reset the inline display of this element to learn if it is + // being hidden by cascaded rules or not + if ( !values[ index ] && display === "none" ) { + elem.style.display = ""; + } + + // Set elements which have been overridden with display: none + // in a stylesheet to whatever the default browser style is + // for such an element + if ( elem.style.display === "" && isHidden( elem ) ) { + values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); + } + } else { + + if ( !values[ index ] ) { + hidden = isHidden( elem ); + + if ( display && display !== "none" || !hidden ) { + jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); + } + } + } + } + + // Set the display of most of the elements in a second loop + // to avoid the constant reflow + for ( index = 0; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + if ( !show || elem.style.display === "none" || elem.style.display === "" ) { + elem.style.display = show ? values[ index ] || "" : "none"; + } + } + + return elements; +} + +jQuery.fn.extend({ + css: function( name, value ) { + return jQuery.access( this, function( elem, name, value ) { + var len, styles, + map = {}, + i = 0; + + if ( jQuery.isArray( name ) ) { + styles = getStyles( elem ); + len = name.length; + + for ( ; i < len; i++ ) { + map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); + } + + return map; + } + + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + }, + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state ) { + if ( typeof state === "boolean" ) { + return state ? this.show() : this.hide(); + } + + return this.each(function() { + if ( isHidden( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + }); + } +}); + +jQuery.extend({ + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity" ); + return ret === "" ? "1" : ret; + } + } + } + }, + + // Don't automatically add "px" to these possibly-unitless properties + cssNumber: { + "columnCount": true, + "fillOpacity": true, + "fontWeight": true, + "lineHeight": true, + "opacity": true, + "order": true, + "orphans": true, + "widows": true, + "zIndex": true, + "zoom": true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: { + // normalize float css property + "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" + }, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = jQuery.camelCase( name ), + style = elem.style; + + name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); + + // gets hook for the prefixed version + // followed by the unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // convert relative number strings (+= or -=) to relative numbers. #7345 + if ( type === "string" && (ret = rrelNum.exec( value )) ) { + value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); + // Fixes bug #9237 + type = "number"; + } + + // Make sure that NaN and null values aren't set. See: #7116 + if ( value == null || type === "number" && isNaN( value ) ) { + return; + } + + // If a number was passed in, add 'px' to the (except for certain CSS properties) + if ( type === "number" && !jQuery.cssNumber[ origName ] ) { + value += "px"; + } + + // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, + // but it would mean to define eight (for every problematic property) identical functions + if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { + style[ name ] = "inherit"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { + + // Wrapped to prevent IE from throwing errors when 'invalid' values are provided + // Fixes bug #5509 + try { + style[ name ] = value; + } catch(e) {} + } + + } else { + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra, styles ) { + var num, val, hooks, + origName = jQuery.camelCase( name ); + + // Make sure that we're working with the right name + name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); + + // gets hook for the prefixed version + // followed by the unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name, styles ); + } + + //convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Return, converting to number if forced or a qualifier was provided and val looks numeric + if ( extra === "" || extra ) { + num = parseFloat( val ); + return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; + } + return val; + } +}); + +// NOTE: we've included the "window" in window.getComputedStyle +// because jsdom on node.js will break without it. +if ( window.getComputedStyle ) { + getStyles = function( elem ) { + return window.getComputedStyle( elem, null ); + }; + + curCSS = function( elem, name, _computed ) { + var width, minWidth, maxWidth, + computed = _computed || getStyles( elem ), + + // getPropertyValue is only needed for .css('filter') in IE9, see #12537 + ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, + style = elem.style; + + if ( computed ) { + + if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { + ret = jQuery.style( elem, name ); + } + + // A tribute to the "awesome hack by Dean Edwards" + // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right + // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels + // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values + if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { + + // Remember the original values + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + // Put in the new values to get a computed value out + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + // Revert the changed values + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret; + }; +} else if ( document.documentElement.currentStyle ) { + getStyles = function( elem ) { + return elem.currentStyle; + }; + + curCSS = function( elem, name, _computed ) { + var left, rs, rsLeft, + computed = _computed || getStyles( elem ), + ret = computed ? computed[ name ] : undefined, + style = elem.style; + + // Avoid setting ret to empty string here + // so we don't default to auto + if ( ret == null && style && style[ name ] ) { + ret = style[ name ]; + } + + // From the awesome hack by Dean Edwards + // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 + + // If we're not dealing with a regular pixel number + // but a number that has a weird ending, we need to convert it to pixels + // but not position css attributes, as those are proportional to the parent element instead + // and we can't measure the parent instead because it might trigger a "stacking dolls" problem + if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { + + // Remember the original values + left = style.left; + rs = elem.runtimeStyle; + rsLeft = rs && rs.left; + + // Put in the new values to get a computed value out + if ( rsLeft ) { + rs.left = elem.currentStyle.left; + } + style.left = name === "fontSize" ? "1em" : ret; + ret = style.pixelLeft + "px"; + + // Revert the changed values + style.left = left; + if ( rsLeft ) { + rs.left = rsLeft; + } + } + + return ret === "" ? "auto" : ret; + }; +} + +function setPositiveNumber( elem, value, subtract ) { + var matches = rnumsplit.exec( value ); + return matches ? + // Guard against undefined "subtract", e.g., when used as in cssHooks + Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : + value; + } + + function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { + var i = extra === ( isBorderBox ? "border" : "content" ) ? + // If we already have the right measurement, avoid augmentation + 4 : + // Otherwise initialize for horizontal or vertical properties + name === "width" ? 1 : 0, + + val = 0; + + for ( ; i < 4; i += 2 ) { + // both box models exclude margin, so add it if we want it + if ( extra === "margin" ) { + val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); + } + + if ( isBorderBox ) { + // border-box includes padding, so remove it if we want content + if ( extra === "content" ) { + val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } + + // at this point, extra isn't border nor margin, so remove border + if ( extra !== "margin" ) { + val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } else { + // at this point, extra isn't content, so add padding + val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + + // at this point, extra isn't content nor padding, so add border + if ( extra !== "padding" ) { + val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } + } + + return val; +} + +function getWidthOrHeight( elem, name, extra ) { + + // Start with offset property, which is equivalent to the border-box value + var valueIsBorderBox = true, + val = name === "width" ? elem.offsetWidth : elem.offsetHeight, + styles = getStyles( elem ), + isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + + // some non-html elements return undefined for offsetWidth, so check for null/undefined + // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 + // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 + if ( val <= 0 || val == null ) { + // Fall back to computed then uncomputed css if necessary + val = curCSS( elem, name, styles ); + if ( val < 0 || val == null ) { + val = elem.style[ name ]; + } + + // Computed unit is not pixels. Stop here and return. + if ( rnumnonpx.test(val) ) { + return val; + } + + // we need the check for style in case a browser which returns unreliable values + // for getComputedStyle silently falls back to the reliable elem.style + valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); + + // Normalize "", auto, and prepare for extra + val = parseFloat( val ) || 0; + } + + // use the active box-sizing model to add/subtract irrelevant styles + return ( val + + augmentWidthOrHeight( + elem, + name, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox, + styles + ) + ) + "px"; +} + +// Try to determine the default display value of an element +function css_defaultDisplay( nodeName ) { + var doc = document, + display = elemdisplay[ nodeName ]; + + if ( !display ) { + display = actualDisplay( nodeName, doc ); + + // If the simple way fails, read from inside an iframe + if ( display === "none" || !display ) { + // Use the already-created iframe if possible + iframe = ( iframe || + jQuery("